SemaAttr.cpp revision 0942e31e6c3725b57c5093ab339dd86031454cfc
1//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for non-trivial attributes and
11// pragmas.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/SemaInternal.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/Preprocessor.h"
21using namespace clang;
22
23//===----------------------------------------------------------------------===//
24// Pragma 'pack' and 'options align'
25//===----------------------------------------------------------------------===//
26
27namespace {
28  struct PackStackEntry {
29    // We just use a sentinel to represent when the stack is set to mac68k
30    // alignment.
31    static const unsigned kMac68kAlignmentSentinel = ~0U;
32
33    unsigned Alignment;
34    IdentifierInfo *Name;
35  };
36
37  /// PragmaPackStack - Simple class to wrap the stack used by #pragma
38  /// pack.
39  class PragmaPackStack {
40    typedef std::vector<PackStackEntry> stack_ty;
41
42    /// Alignment - The current user specified alignment.
43    unsigned Alignment;
44
45    /// Stack - Entries in the #pragma pack stack, consisting of saved
46    /// alignments and optional names.
47    stack_ty Stack;
48
49  public:
50    PragmaPackStack() : Alignment(0) {}
51
52    void setAlignment(unsigned A) { Alignment = A; }
53    unsigned getAlignment() { return Alignment; }
54
55    /// push - Push the current alignment onto the stack, optionally
56    /// using the given \arg Name for the record, if non-zero.
57    void push(IdentifierInfo *Name) {
58      PackStackEntry PSE = { Alignment, Name };
59      Stack.push_back(PSE);
60    }
61
62    /// pop - Pop a record from the stack and restore the current
63    /// alignment to the previous value. If \arg Name is non-zero then
64    /// the first such named record is popped, otherwise the top record
65    /// is popped. Returns true if the pop succeeded.
66    bool pop(IdentifierInfo *Name, bool IsReset);
67  };
68}  // end anonymous namespace.
69
70bool PragmaPackStack::pop(IdentifierInfo *Name, bool IsReset) {
71  // If name is empty just pop top.
72  if (!Name) {
73    // An empty stack is a special case...
74    if (Stack.empty()) {
75      // If this isn't a reset, it is always an error.
76      if (!IsReset)
77        return false;
78
79      // Otherwise, it is an error only if some alignment has been set.
80      if (!Alignment)
81        return false;
82
83      // Otherwise, reset to the default alignment.
84      Alignment = 0;
85    } else {
86      Alignment = Stack.back().Alignment;
87      Stack.pop_back();
88    }
89
90    return true;
91  }
92
93  // Otherwise, find the named record.
94  for (unsigned i = Stack.size(); i != 0; ) {
95    --i;
96    if (Stack[i].Name == Name) {
97      // Found it, pop up to and including this record.
98      Alignment = Stack[i].Alignment;
99      Stack.erase(Stack.begin() + i, Stack.end());
100      return true;
101    }
102  }
103
104  return false;
105}
106
107
108/// FreePackedContext - Deallocate and null out PackContext.
109void Sema::FreePackedContext() {
110  delete static_cast<PragmaPackStack*>(PackContext);
111  PackContext = 0;
112}
113
114void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
115  // If there is no pack context, we don't need any attributes.
116  if (!PackContext)
117    return;
118
119  PragmaPackStack *Stack = static_cast<PragmaPackStack*>(PackContext);
120
121  // Otherwise, check to see if we need a max field alignment attribute.
122  if (unsigned Alignment = Stack->getAlignment()) {
123    if (Alignment == PackStackEntry::kMac68kAlignmentSentinel)
124      RD->addAttr(::new (Context) AlignMac68kAttr(SourceLocation(), Context));
125    else
126      RD->addAttr(::new (Context) MaxFieldAlignmentAttr(SourceLocation(),
127                                                        Context,
128                                                        Alignment * 8));
129  }
130}
131
132void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
133                                   SourceLocation PragmaLoc,
134                                   SourceLocation KindLoc) {
135  if (PackContext == 0)
136    PackContext = new PragmaPackStack();
137
138  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
139
140  // Reset just pops the top of the stack, or resets the current alignment to
141  // default.
142  if (Kind == Action::POAK_Reset) {
143    if (!Context->pop(0, /*IsReset=*/true)) {
144      Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
145        << "stack empty";
146    }
147    return;
148  }
149
150  switch (Kind) {
151    // For all targets we support native and natural are the same.
152    //
153    // FIXME: This is not true on Darwin/PPC.
154  case POAK_Native:
155  case POAK_Power:
156  case POAK_Natural:
157    Context->push(0);
158    Context->setAlignment(0);
159    break;
160
161    // Note that '#pragma options align=packed' is not equivalent to attribute
162    // packed, it has a different precedence relative to attribute aligned.
163  case POAK_Packed:
164    Context->push(0);
165    Context->setAlignment(1);
166    break;
167
168  case POAK_Mac68k:
169    // Check if the target supports this.
170    if (!PP.getTargetInfo().hasAlignMac68kSupport()) {
171      Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
172      return;
173    }
174    Context->push(0);
175    Context->setAlignment(PackStackEntry::kMac68kAlignmentSentinel);
176    break;
177
178  default:
179    Diag(PragmaLoc, diag::warn_pragma_options_align_unsupported_option)
180      << KindLoc;
181    break;
182  }
183}
184
185void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
186                           ExprTy *alignment, SourceLocation PragmaLoc,
187                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
188  Expr *Alignment = static_cast<Expr *>(alignment);
189
190  // If specified then alignment must be a "small" power of two.
191  unsigned AlignmentVal = 0;
192  if (Alignment) {
193    llvm::APSInt Val;
194
195    // pack(0) is like pack(), which just works out since that is what
196    // we use 0 for in PackAttr.
197    if (Alignment->isTypeDependent() ||
198        Alignment->isValueDependent() ||
199        !Alignment->isIntegerConstantExpr(Val, Context) ||
200        !(Val == 0 || Val.isPowerOf2()) ||
201        Val.getZExtValue() > 16) {
202      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
203      return; // Ignore
204    }
205
206    AlignmentVal = (unsigned) Val.getZExtValue();
207  }
208
209  if (PackContext == 0)
210    PackContext = new PragmaPackStack();
211
212  PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext);
213
214  switch (Kind) {
215  case Action::PPK_Default: // pack([n])
216    Context->setAlignment(AlignmentVal);
217    break;
218
219  case Action::PPK_Show: // pack(show)
220    // Show the current alignment, making sure to show the right value
221    // for the default.
222    AlignmentVal = Context->getAlignment();
223    // FIXME: This should come from the target.
224    if (AlignmentVal == 0)
225      AlignmentVal = 8;
226    if (AlignmentVal == PackStackEntry::kMac68kAlignmentSentinel)
227      Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
228    else
229      Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
230    break;
231
232  case Action::PPK_Push: // pack(push [, id] [, [n])
233    Context->push(Name);
234    // Set the new alignment if specified.
235    if (Alignment)
236      Context->setAlignment(AlignmentVal);
237    break;
238
239  case Action::PPK_Pop: // pack(pop [, id] [,  n])
240    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
241    // "#pragma pack(pop, identifier, n) is undefined"
242    if (Alignment && Name)
243      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
244
245    // Do the pop.
246    if (!Context->pop(Name, /*IsReset=*/false)) {
247      // If a name was specified then failure indicates the name
248      // wasn't found. Otherwise failure indicates the stack was
249      // empty.
250      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
251        << (Name ? "no record matching name" : "stack empty");
252
253      // FIXME: Warn about popping named records as MSVC does.
254    } else {
255      // Pop succeeded, set the new alignment if specified.
256      if (Alignment)
257        Context->setAlignment(AlignmentVal);
258    }
259    break;
260
261  default:
262    assert(0 && "Invalid #pragma pack kind.");
263  }
264}
265
266void Sema::ActOnPragmaUnused(const Token *Identifiers, unsigned NumIdentifiers,
267                             Scope *curScope,
268                             SourceLocation PragmaLoc,
269                             SourceLocation LParenLoc,
270                             SourceLocation RParenLoc) {
271
272  for (unsigned i = 0; i < NumIdentifiers; ++i) {
273    const Token &Tok = Identifiers[i];
274    IdentifierInfo *Name = Tok.getIdentifierInfo();
275    LookupResult Lookup(*this, Name, Tok.getLocation(), LookupOrdinaryName);
276    LookupParsedName(Lookup, curScope, NULL, true);
277
278    if (Lookup.empty()) {
279      Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
280        << Name << SourceRange(Tok.getLocation());
281      continue;
282    }
283
284    VarDecl *VD = Lookup.getAsSingle<VarDecl>();
285    if (!VD || !VD->hasLocalStorage()) {
286      Diag(PragmaLoc, diag::warn_pragma_unused_expected_localvar)
287        << Name << SourceRange(Tok.getLocation());
288      continue;
289    }
290
291    VD->addAttr(::new (Context) UnusedAttr(Tok.getLocation(), Context));
292  }
293}
294
295typedef std::vector<std::pair<VisibilityAttr::VisibilityType,
296                              SourceLocation> > VisStack;
297
298void Sema::AddPushedVisibilityAttribute(Decl *D) {
299  if (!VisContext)
300    return;
301
302  if (D->hasAttr<VisibilityAttr>())
303    return;
304
305  VisStack *Stack = static_cast<VisStack*>(VisContext);
306  VisibilityAttr::VisibilityType type = Stack->back().first;
307  SourceLocation loc = Stack->back().second;
308
309  D->addAttr(::new (Context) VisibilityAttr(loc, Context, type));
310}
311
312/// FreeVisContext - Deallocate and null out VisContext.
313void Sema::FreeVisContext() {
314  delete static_cast<VisStack*>(VisContext);
315  VisContext = 0;
316}
317
318static void PushPragmaVisibility(Sema &S, VisibilityAttr::VisibilityType type,
319                                 SourceLocation loc) {
320  // Put visibility on stack.
321  if (!S.VisContext)
322    S.VisContext = new VisStack;
323
324  VisStack *Stack = static_cast<VisStack*>(S.VisContext);
325  Stack->push_back(std::make_pair(type, loc));
326}
327
328void Sema::ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
329                                 SourceLocation PragmaLoc) {
330  if (IsPush) {
331    // Compute visibility to use.
332    VisibilityAttr::VisibilityType type;
333    if (VisType->isStr("default"))
334      type = VisibilityAttr::Default;
335    else if (VisType->isStr("hidden"))
336      type = VisibilityAttr::Hidden;
337    else if (VisType->isStr("internal"))
338      type = VisibilityAttr::Hidden; // FIXME
339    else if (VisType->isStr("protected"))
340      type = VisibilityAttr::Protected;
341    else {
342      Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) <<
343        VisType->getName();
344      return;
345    }
346    PushPragmaVisibility(*this, type, PragmaLoc);
347  } else {
348    PopPragmaVisibility();
349  }
350}
351
352void Sema::PushVisibilityAttr(const VisibilityAttr *Attr) {
353  PushPragmaVisibility(*this, Attr->getVisibility(), Attr->getLocation());
354}
355
356void Sema::PopPragmaVisibility() {
357  // Pop visibility from stack, if there is one on the stack.
358  if (VisContext) {
359    VisStack *Stack = static_cast<VisStack*>(VisContext);
360
361    Stack->pop_back();
362    // To simplify the implementation, never keep around an empty stack.
363    if (Stack->empty())
364      FreeVisContext();
365  }
366  // FIXME: Add diag for pop without push.
367}
368