1193326Sed//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements semantic analysis for non-trivial attributes and
11193326Sed// pragmas.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15212904Sdim#include "clang/Sema/SemaInternal.h"
16263508Sdim#include "clang/AST/ASTConsumer.h"
17212904Sdim#include "clang/AST/Attr.h"
18193326Sed#include "clang/AST/Expr.h"
19208600Srdivacky#include "clang/Basic/TargetInfo.h"
20208600Srdivacky#include "clang/Lex/Preprocessor.h"
21249423Sdim#include "clang/Sema/Lookup.h"
22193326Sedusing namespace clang;
23193326Sed
24193326Sed//===----------------------------------------------------------------------===//
25208600Srdivacky// Pragma 'pack' and 'options align'
26193326Sed//===----------------------------------------------------------------------===//
27193326Sed
28193326Sednamespace {
29208600Srdivacky  struct PackStackEntry {
30208600Srdivacky    // We just use a sentinel to represent when the stack is set to mac68k
31208600Srdivacky    // alignment.
32208600Srdivacky    static const unsigned kMac68kAlignmentSentinel = ~0U;
33208600Srdivacky
34208600Srdivacky    unsigned Alignment;
35208600Srdivacky    IdentifierInfo *Name;
36208600Srdivacky  };
37208600Srdivacky
38193326Sed  /// PragmaPackStack - Simple class to wrap the stack used by #pragma
39193326Sed  /// pack.
40193326Sed  class PragmaPackStack {
41208600Srdivacky    typedef std::vector<PackStackEntry> stack_ty;
42193326Sed
43193326Sed    /// Alignment - The current user specified alignment.
44193326Sed    unsigned Alignment;
45193326Sed
46193326Sed    /// Stack - Entries in the #pragma pack stack, consisting of saved
47193326Sed    /// alignments and optional names.
48193326Sed    stack_ty Stack;
49198092Srdivacky
50198092Srdivacky  public:
51193326Sed    PragmaPackStack() : Alignment(0) {}
52193326Sed
53193326Sed    void setAlignment(unsigned A) { Alignment = A; }
54193326Sed    unsigned getAlignment() { return Alignment; }
55193326Sed
56193326Sed    /// push - Push the current alignment onto the stack, optionally
57193326Sed    /// using the given \arg Name for the record, if non-zero.
58193326Sed    void push(IdentifierInfo *Name) {
59208600Srdivacky      PackStackEntry PSE = { Alignment, Name };
60208600Srdivacky      Stack.push_back(PSE);
61193326Sed    }
62193326Sed
63193326Sed    /// pop - Pop a record from the stack and restore the current
64193326Sed    /// alignment to the previous value. If \arg Name is non-zero then
65193326Sed    /// the first such named record is popped, otherwise the top record
66193326Sed    /// is popped. Returns true if the pop succeeded.
67212904Sdim    bool pop(IdentifierInfo *Name, bool IsReset);
68193326Sed  };
69193326Sed}  // end anonymous namespace.
70193326Sed
71212904Sdimbool PragmaPackStack::pop(IdentifierInfo *Name, bool IsReset) {
72193326Sed  // If name is empty just pop top.
73193326Sed  if (!Name) {
74212904Sdim    // An empty stack is a special case...
75212904Sdim    if (Stack.empty()) {
76212904Sdim      // If this isn't a reset, it is always an error.
77212904Sdim      if (!IsReset)
78212904Sdim        return false;
79212904Sdim
80212904Sdim      // Otherwise, it is an error only if some alignment has been set.
81212904Sdim      if (!Alignment)
82212904Sdim        return false;
83212904Sdim
84212904Sdim      // Otherwise, reset to the default alignment.
85212904Sdim      Alignment = 0;
86212904Sdim    } else {
87212904Sdim      Alignment = Stack.back().Alignment;
88212904Sdim      Stack.pop_back();
89212904Sdim    }
90212904Sdim
91193326Sed    return true;
92198092Srdivacky  }
93198092Srdivacky
94193326Sed  // Otherwise, find the named record.
95193326Sed  for (unsigned i = Stack.size(); i != 0; ) {
96193326Sed    --i;
97208600Srdivacky    if (Stack[i].Name == Name) {
98193326Sed      // Found it, pop up to and including this record.
99208600Srdivacky      Alignment = Stack[i].Alignment;
100193326Sed      Stack.erase(Stack.begin() + i, Stack.end());
101193326Sed      return true;
102193326Sed    }
103193326Sed  }
104198092Srdivacky
105193326Sed  return false;
106193326Sed}
107193326Sed
108193326Sed
109193326Sed/// FreePackedContext - Deallocate and null out PackContext.
110193326Sedvoid Sema::FreePackedContext() {
111193326Sed  delete static_cast<PragmaPackStack*>(PackContext);
112193326Sed  PackContext = 0;
113193326Sed}
114193326Sed
115208600Srdivackyvoid Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
116208600Srdivacky  // If there is no pack context, we don't need any attributes.
117208600Srdivacky  if (!PackContext)
118208600Srdivacky    return;
119208600Srdivacky
120208600Srdivacky  PragmaPackStack *Stack = static_cast<PragmaPackStack*>(PackContext);
121208600Srdivacky
122208600Srdivacky  // Otherwise, check to see if we need a max field alignment attribute.
123208600Srdivacky  if (unsigned Alignment = Stack->getAlignment()) {
124208600Srdivacky    if (Alignment == PackStackEntry::kMac68kAlignmentSentinel)
125212904Sdim      RD->addAttr(::new (Context) AlignMac68kAttr(SourceLocation(), Context));
126208600Srdivacky    else
127212904Sdim      RD->addAttr(::new (Context) MaxFieldAlignmentAttr(SourceLocation(),
128212904Sdim                                                        Context,
129212904Sdim                                                        Alignment * 8));
130208600Srdivacky  }
131193326Sed}
132193326Sed
133221345Sdimvoid Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
134221345Sdim  if (!MSStructPragmaOn)
135221345Sdim    return;
136221345Sdim  RD->addAttr(::new (Context) MsStructAttr(SourceLocation(), Context));
137221345Sdim}
138221345Sdim
139208600Srdivackyvoid Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
140243830Sdim                                   SourceLocation PragmaLoc) {
141208600Srdivacky  if (PackContext == 0)
142208600Srdivacky    PackContext = new PragmaPackStack();
143208600Srdivacky
144208600Srdivacky  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
145208600Srdivacky
146208600Srdivacky  switch (Kind) {
147210299Sed    // For all targets we support native and natural are the same.
148210299Sed    //
149210299Sed    // FIXME: This is not true on Darwin/PPC.
150210299Sed  case POAK_Native:
151210299Sed  case POAK_Power:
152208600Srdivacky  case POAK_Natural:
153208600Srdivacky    Context->push(0);
154208600Srdivacky    Context->setAlignment(0);
155208600Srdivacky    break;
156208600Srdivacky
157210299Sed    // Note that '#pragma options align=packed' is not equivalent to attribute
158210299Sed    // packed, it has a different precedence relative to attribute aligned.
159210299Sed  case POAK_Packed:
160210299Sed    Context->push(0);
161210299Sed    Context->setAlignment(1);
162210299Sed    break;
163210299Sed
164208600Srdivacky  case POAK_Mac68k:
165208600Srdivacky    // Check if the target supports this.
166208600Srdivacky    if (!PP.getTargetInfo().hasAlignMac68kSupport()) {
167208600Srdivacky      Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
168208600Srdivacky      return;
169208600Srdivacky    }
170208600Srdivacky    Context->push(0);
171208600Srdivacky    Context->setAlignment(PackStackEntry::kMac68kAlignmentSentinel);
172208600Srdivacky    break;
173208600Srdivacky
174243830Sdim  case POAK_Reset:
175243830Sdim    // Reset just pops the top of the stack, or resets the current alignment to
176243830Sdim    // default.
177243830Sdim    if (!Context->pop(0, /*IsReset=*/true)) {
178243830Sdim      Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
179243830Sdim        << "stack empty";
180243830Sdim    }
181208600Srdivacky    break;
182208600Srdivacky  }
183208600Srdivacky}
184208600Srdivacky
185198092Srdivackyvoid Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
186226633Sdim                           Expr *alignment, SourceLocation PragmaLoc,
187193326Sed                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
188193326Sed  Expr *Alignment = static_cast<Expr *>(alignment);
189193326Sed
190193326Sed  // If specified then alignment must be a "small" power of two.
191193326Sed  unsigned AlignmentVal = 0;
192193326Sed  if (Alignment) {
193193326Sed    llvm::APSInt Val;
194198092Srdivacky
195193326Sed    // pack(0) is like pack(), which just works out since that is what
196193326Sed    // we use 0 for in PackAttr.
197208600Srdivacky    if (Alignment->isTypeDependent() ||
198208600Srdivacky        Alignment->isValueDependent() ||
199208600Srdivacky        !Alignment->isIntegerConstantExpr(Val, Context) ||
200193326Sed        !(Val == 0 || Val.isPowerOf2()) ||
201193326Sed        Val.getZExtValue() > 16) {
202193326Sed      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
203193326Sed      return; // Ignore
204193326Sed    }
205193326Sed
206193326Sed    AlignmentVal = (unsigned) Val.getZExtValue();
207193326Sed  }
208198092Srdivacky
209193326Sed  if (PackContext == 0)
210193326Sed    PackContext = new PragmaPackStack();
211198092Srdivacky
212193326Sed  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
213198092Srdivacky
214193326Sed  switch (Kind) {
215212904Sdim  case Sema::PPK_Default: // pack([n])
216193326Sed    Context->setAlignment(AlignmentVal);
217193326Sed    break;
218193326Sed
219212904Sdim  case Sema::PPK_Show: // pack(show)
220193326Sed    // Show the current alignment, making sure to show the right value
221193326Sed    // for the default.
222193326Sed    AlignmentVal = Context->getAlignment();
223193326Sed    // FIXME: This should come from the target.
224193326Sed    if (AlignmentVal == 0)
225193326Sed      AlignmentVal = 8;
226208600Srdivacky    if (AlignmentVal == PackStackEntry::kMac68kAlignmentSentinel)
227208600Srdivacky      Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
228208600Srdivacky    else
229208600Srdivacky      Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
230193326Sed    break;
231193326Sed
232212904Sdim  case Sema::PPK_Push: // pack(push [, id] [, [n])
233193326Sed    Context->push(Name);
234193326Sed    // Set the new alignment if specified.
235193326Sed    if (Alignment)
236198092Srdivacky      Context->setAlignment(AlignmentVal);
237193326Sed    break;
238193326Sed
239212904Sdim  case Sema::PPK_Pop: // pack(pop [, id] [,  n])
240193326Sed    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
241193326Sed    // "#pragma pack(pop, identifier, n) is undefined"
242193326Sed    if (Alignment && Name)
243198092Srdivacky      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
244198092Srdivacky
245193326Sed    // Do the pop.
246212904Sdim    if (!Context->pop(Name, /*IsReset=*/false)) {
247193326Sed      // If a name was specified then failure indicates the name
248193326Sed      // wasn't found. Otherwise failure indicates the stack was
249193326Sed      // empty.
250193326Sed      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
251193326Sed        << (Name ? "no record matching name" : "stack empty");
252193326Sed
253193326Sed      // FIXME: Warn about popping named records as MSVC does.
254193326Sed    } else {
255193326Sed      // Pop succeeded, set the new alignment if specified.
256193326Sed      if (Alignment)
257193326Sed        Context->setAlignment(AlignmentVal);
258193326Sed    }
259193326Sed    break;
260193326Sed  }
261193326Sed}
262193326Sed
263221345Sdimvoid Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
264221345Sdim  MSStructPragmaOn = (Kind == PMSST_ON);
265221345Sdim}
266221345Sdim
267263508Sdimvoid Sema::ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg) {
268263508Sdim  // FIXME: Serialize this.
269263508Sdim  switch (Kind) {
270263508Sdim  case PCK_Unknown:
271263508Sdim    llvm_unreachable("unexpected pragma comment kind");
272263508Sdim  case PCK_Linker:
273263508Sdim    Consumer.HandleLinkerOptionPragma(Arg);
274263508Sdim    return;
275263508Sdim  case PCK_Lib:
276263508Sdim    Consumer.HandleDependentLibrary(Arg);
277263508Sdim    return;
278263508Sdim  case PCK_Compiler:
279263508Sdim  case PCK_ExeStr:
280263508Sdim  case PCK_User:
281263508Sdim    return;  // We ignore all of these.
282263508Sdim  }
283263508Sdim  llvm_unreachable("invalid pragma comment kind");
284263508Sdim}
285263508Sdim
286263508Sdimvoid Sema::ActOnPragmaDetectMismatch(StringRef Name, StringRef Value) {
287263508Sdim  // FIXME: Serialize this.
288263508Sdim  Consumer.HandleDetectMismatch(Name, Value);
289263508Sdim}
290263508Sdim
291218893Sdimvoid Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
292218893Sdim                             SourceLocation PragmaLoc) {
293198092Srdivacky
294218893Sdim  IdentifierInfo *Name = IdTok.getIdentifierInfo();
295218893Sdim  LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
296218893Sdim  LookupParsedName(Lookup, curScope, NULL, true);
297198092Srdivacky
298218893Sdim  if (Lookup.empty()) {
299218893Sdim    Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
300218893Sdim      << Name << SourceRange(IdTok.getLocation());
301218893Sdim    return;
302218893Sdim  }
303193326Sed
304218893Sdim  VarDecl *VD = Lookup.getAsSingle<VarDecl>();
305218893Sdim  if (!VD) {
306218893Sdim    Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
307218893Sdim      << Name << SourceRange(IdTok.getLocation());
308218893Sdim    return;
309218893Sdim  }
310193326Sed
311218893Sdim  // Warn if this was used before being marked unused.
312218893Sdim  if (VD->isUsed())
313218893Sdim    Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
314218893Sdim
315218893Sdim  VD->addAttr(::new (Context) UnusedAttr(IdTok.getLocation(), Context));
316193326Sed}
317212904Sdim
318226633Sdimvoid Sema::AddCFAuditedAttribute(Decl *D) {
319226633Sdim  SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
320226633Sdim  if (!Loc.isValid()) return;
321226633Sdim
322226633Sdim  // Don't add a redundant or conflicting attribute.
323226633Sdim  if (D->hasAttr<CFAuditedTransferAttr>() ||
324226633Sdim      D->hasAttr<CFUnknownTransferAttr>())
325226633Sdim    return;
326226633Sdim
327226633Sdim  D->addAttr(::new (Context) CFAuditedTransferAttr(Loc, Context));
328226633Sdim}
329226633Sdim
330218893Sdimtypedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
331218893Sdimenum { NoVisibility = (unsigned) -1 };
332212904Sdim
333212904Sdimvoid Sema::AddPushedVisibilityAttribute(Decl *D) {
334212904Sdim  if (!VisContext)
335212904Sdim    return;
336212904Sdim
337249423Sdim  NamedDecl *ND = dyn_cast<NamedDecl>(D);
338249423Sdim  if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
339212904Sdim    return;
340212904Sdim
341212904Sdim  VisStack *Stack = static_cast<VisStack*>(VisContext);
342218893Sdim  unsigned rawType = Stack->back().first;
343218893Sdim  if (rawType == NoVisibility) return;
344218893Sdim
345218893Sdim  VisibilityAttr::VisibilityType type
346218893Sdim    = (VisibilityAttr::VisibilityType) rawType;
347212904Sdim  SourceLocation loc = Stack->back().second;
348212904Sdim
349212904Sdim  D->addAttr(::new (Context) VisibilityAttr(loc, Context, type));
350212904Sdim}
351212904Sdim
352212904Sdim/// FreeVisContext - Deallocate and null out VisContext.
353212904Sdimvoid Sema::FreeVisContext() {
354212904Sdim  delete static_cast<VisStack*>(VisContext);
355212904Sdim  VisContext = 0;
356212904Sdim}
357212904Sdim
358218893Sdimstatic void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
359212904Sdim  // Put visibility on stack.
360212904Sdim  if (!S.VisContext)
361212904Sdim    S.VisContext = new VisStack;
362212904Sdim
363212904Sdim  VisStack *Stack = static_cast<VisStack*>(S.VisContext);
364212904Sdim  Stack->push_back(std::make_pair(type, loc));
365212904Sdim}
366212904Sdim
367234353Sdimvoid Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
368212904Sdim                                 SourceLocation PragmaLoc) {
369234353Sdim  if (VisType) {
370212904Sdim    // Compute visibility to use.
371263508Sdim    VisibilityAttr::VisibilityType T;
372263508Sdim    if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
373263508Sdim      Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
374212904Sdim      return;
375212904Sdim    }
376263508Sdim    PushPragmaVisibility(*this, T, PragmaLoc);
377212904Sdim  } else {
378234353Sdim    PopPragmaVisibility(false, PragmaLoc);
379212904Sdim  }
380212904Sdim}
381212904Sdim
382218893Sdimvoid Sema::ActOnPragmaFPContract(tok::OnOffSwitch OOS) {
383218893Sdim  switch (OOS) {
384218893Sdim  case tok::OOS_ON:
385218893Sdim    FPFeatures.fp_contract = 1;
386218893Sdim    break;
387218893Sdim  case tok::OOS_OFF:
388218893Sdim    FPFeatures.fp_contract = 0;
389218893Sdim    break;
390218893Sdim  case tok::OOS_DEFAULT:
391234353Sdim    FPFeatures.fp_contract = getLangOpts().DefaultFPContract;
392218893Sdim    break;
393218893Sdim  }
394212904Sdim}
395212904Sdim
396234353Sdimvoid Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
397234353Sdim                                       SourceLocation Loc) {
398218893Sdim  // Visibility calculations will consider the namespace's visibility.
399218893Sdim  // Here we just want to note that we're in a visibility context
400218893Sdim  // which overrides any enclosing #pragma context, but doesn't itself
401218893Sdim  // contribute visibility.
402234353Sdim  PushPragmaVisibility(*this, NoVisibility, Loc);
403218893Sdim}
404218893Sdim
405234353Sdimvoid Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
406234353Sdim  if (!VisContext) {
407234353Sdim    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
408234353Sdim    return;
409234353Sdim  }
410212904Sdim
411234353Sdim  // Pop visibility from stack
412234353Sdim  VisStack *Stack = static_cast<VisStack*>(VisContext);
413234353Sdim
414234353Sdim  const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
415234353Sdim  bool StartsWithPragma = Back->first != NoVisibility;
416234353Sdim  if (StartsWithPragma && IsNamespaceEnd) {
417234353Sdim    Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
418234353Sdim    Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
419234353Sdim
420234353Sdim    // For better error recovery, eat all pushes inside the namespace.
421234353Sdim    do {
422234353Sdim      Stack->pop_back();
423234353Sdim      Back = &Stack->back();
424234353Sdim      StartsWithPragma = Back->first != NoVisibility;
425234353Sdim    } while (StartsWithPragma);
426234353Sdim  } else if (!StartsWithPragma && !IsNamespaceEnd) {
427234353Sdim    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
428234353Sdim    Diag(Back->second, diag::note_surrounding_namespace_starts_here);
429234353Sdim    return;
430212904Sdim  }
431234353Sdim
432234353Sdim  Stack->pop_back();
433234353Sdim  // To simplify the implementation, never keep around an empty stack.
434234353Sdim  if (Stack->empty())
435234353Sdim    FreeVisContext();
436212904Sdim}
437