SemaDecl.cpp revision 8bcfc5bef434d7052e28d0ce45182855659ebd3d
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/DenseSet.h"
33using namespace clang;
34
35Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38  if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
39    return IIDecl;
40  return 0;
41}
42
43void Sema::PushDeclContext(DeclContext *CD) {
44  assert(CD->getParent() == CurContext &&
45      "The next DeclContext should be directly contained in the current one.");
46  CurContext = CD;
47}
48
49void Sema::PopDeclContext() {
50  assert(CurContext && "DeclContext imbalance!");
51  CurContext = CurContext->getParent();
52}
53
54void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
55  if (S->decl_empty()) return;
56  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
58  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59       I != E; ++I) {
60    Decl *TmpD = static_cast<Decl*>(*I);
61    assert(TmpD && "This decl didn't get pushed??");
62    ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63    assert(D && "This decl isn't a ScopedDecl?");
64
65    IdentifierInfo *II = D->getIdentifier();
66    if (!II) continue;
67
68    // Unlink this decl from the identifier.  Because the scope contains decls
69    // in an unordered collection, and because we have multiple identifier
70    // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
71    if (II->getFETokenInfo<Decl>() == D) {
72      // Normal case, no multiple decls in different namespaces.
73      II->setFETokenInfo(D->getNext());
74    } else {
75      // Scan ahead.  There are only three namespaces in C, so this loop can
76      // never execute more than 3 times.
77      ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
78      while (SomeDecl->getNext() != D) {
79        SomeDecl = SomeDecl->getNext();
80        assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
81      }
82      SomeDecl->setNext(D->getNext());
83    }
84
85    // This will have to be revisited for C++: there we want to nest stuff in
86    // namespace decls etc.  Even for C, we might want a top-level translation
87    // unit decl or something.
88    if (!CurFunctionDecl)
89      continue;
90
91    // Chain this decl to the containing function, it now owns the memory for
92    // the decl.
93    D->setNext(CurFunctionDecl->getDeclChain());
94    CurFunctionDecl->setDeclChain(D);
95  }
96}
97
98/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
99/// return 0 if one not found.
100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
101  // The third "scope" argument is 0 since we aren't enabling lazy built-in
102  // creation from this context.
103  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
104
105  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
106}
107
108/// LookupDecl - Look up the inner-most declaration in the specified
109/// namespace.
110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
111                       Scope *S, bool enableLazyBuiltinCreation) {
112  if (II == 0) return 0;
113  Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
114
115  // Scan up the scope chain looking for a decl that matches this identifier
116  // that is in the appropriate namespace.  This search should not take long, as
117  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
118  for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
119    if (D->getIdentifierNamespace() == NS)
120      return D;
121
122  // If we didn't find a use of this identifier, and if the identifier
123  // corresponds to a compiler builtin, create the decl object for the builtin
124  // now, injecting it into translation unit scope, and return it.
125  if (NS == Decl::IDNS_Ordinary) {
126    if (enableLazyBuiltinCreation) {
127      // If this is a builtin on this (or all) targets, create the decl.
128      if (unsigned BuiltinID = II->getBuiltinID())
129        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
130    }
131    if (getLangOptions().ObjC1) {
132      // @interface and @compatibility_alias introduce typedef-like names.
133      // Unlike typedef's, they can only be introduced at file-scope (and are
134      // therefore not scoped decls). They can, however, be shadowed by
135      // other names in IDNS_Ordinary.
136      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
137      if (IDI != ObjCInterfaceDecls.end())
138        return IDI->second;
139      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
140      if (I != ObjCAliasDecls.end())
141        return I->second->getClassInterface();
142    }
143  }
144  return 0;
145}
146
147void Sema::InitBuiltinVaListType()
148{
149  if (!Context.getBuiltinVaListType().isNull())
150    return;
151
152  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
153  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
154  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
155  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
156}
157
158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
159/// lazily create a decl for it.
160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
161                                      Scope *S) {
162  Builtin::ID BID = (Builtin::ID)bid;
163
164  if (BID == Builtin::BI__builtin_va_start ||
165       BID == Builtin::BI__builtin_va_copy ||
166       BID == Builtin::BI__builtin_va_end)
167    InitBuiltinVaListType();
168
169  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
170  FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
171                                           SourceLocation(), II, R,
172                                           FunctionDecl::Extern, false, 0);
173
174  // Find translation-unit scope to insert this function into.
175  if (Scope *FnS = S->getFnParent())
176    S = FnS->getParent();   // Skip all scopes in a function at once.
177  while (S->getParent())
178    S = S->getParent();
179  S->AddDecl(New);
180
181  // Add this decl to the end of the identifier info.
182  if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
183    // Scan until we find the last (outermost) decl in the id chain.
184    while (LastDecl->getNext())
185      LastDecl = LastDecl->getNext();
186    // Insert before (outside) it.
187    LastDecl->setNext(New);
188  } else {
189    II->setFETokenInfo(New);
190  }
191  return New;
192}
193
194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
195/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
199  // Verify the old decl was also a typedef.
200  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
201  if (!Old) {
202    Diag(New->getLocation(), diag::err_redefinition_different_kind,
203         New->getName());
204    Diag(OldD->getLocation(), diag::err_previous_definition);
205    return New;
206  }
207
208  // Allow multiple definitions for ObjC built-in typedefs.
209  // FIXME: Verify the underlying types are equivalent!
210  if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
211    return Old;
212
213  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
214  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
215  // *either* declaration is in a system header. The code below implements
216  // this adhoc compatibility rule. FIXME: The following code will not
217  // work properly when compiling ".i" files (containing preprocessed output).
218  SourceManager &SrcMgr = Context.getSourceManager();
219  const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
220  const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
221  HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
222  DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
223  DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
224
225  // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
226  if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
227       NewDirType != DirectoryLookup::NormalHeaderDir) ||
228      getLangOptions().Microsoft)
229    return New;
230
231  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232  // TODO: This is totally simplistic.  It should handle merging functions
233  // together etc, merging extern int X; int X; ...
234  Diag(New->getLocation(), diag::err_redefinition, New->getName());
235  Diag(Old->getLocation(), diag::err_previous_definition);
236  return New;
237}
238
239/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
240static bool DeclHasAttr(const Decl *decl, const Attr *target) {
241  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
242    if (attr->getKind() == target->getKind())
243      return true;
244
245  return false;
246}
247
248/// MergeAttributes - append attributes from the Old decl to the New one.
249static void MergeAttributes(Decl *New, Decl *Old) {
250  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
251
252// FIXME: fix this code to cleanup the Old attrs correctly
253  while (attr) {
254     tmp = attr;
255     attr = attr->getNext();
256
257    if (!DeclHasAttr(New, tmp)) {
258       New->addAttr(tmp);
259    } else {
260       tmp->setNext(0);
261       delete(tmp);
262    }
263  }
264}
265
266/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
267/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
268/// situation, merging decls or emitting diagnostics as appropriate.
269///
270FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
271  // Verify the old decl was also a function.
272  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
273  if (!Old) {
274    Diag(New->getLocation(), diag::err_redefinition_different_kind,
275         New->getName());
276    Diag(OldD->getLocation(), diag::err_previous_definition);
277    return New;
278  }
279
280  MergeAttributes(New, Old);
281
282
283  QualType OldQType = Context.getCanonicalType(Old->getType());
284  QualType NewQType = Context.getCanonicalType(New->getType());
285
286  // Function types need to be compatible, not identical. This handles
287  // duplicate function decls like "void f(int); void f(enum X);" properly.
288  if (Context.functionTypesAreCompatible(OldQType, NewQType))
289    return New;
290
291  // A function that has already been declared has been redeclared or defined
292  // with a different type- show appropriate diagnostic
293  diag::kind PrevDiag;
294  if (Old->getBody())
295    PrevDiag = diag::err_previous_definition;
296  else if (Old->isImplicit())
297    PrevDiag = diag::err_previous_implicit_declaration;
298  else
299    PrevDiag = diag::err_previous_declaration;
300
301  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
302  // TODO: This is totally simplistic.  It should handle merging functions
303  // together etc, merging extern int X; int X; ...
304  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
305  Diag(Old->getLocation(), PrevDiag);
306  return New;
307}
308
309/// equivalentArrayTypes - Used to determine whether two array types are
310/// equivalent.
311/// We need to check this explicitly as an incomplete array definition is
312/// considered a VariableArrayType, so will not match a complete array
313/// definition that would be otherwise equivalent.
314static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
315  const ArrayType *NewAT = NewQType->getAsArrayType();
316  const ArrayType *OldAT = OldQType->getAsArrayType();
317
318  if (!NewAT || !OldAT)
319    return false;
320
321  // If either (or both) array types in incomplete we need to strip off the
322  // outer VariableArrayType.  Once the outer VAT is removed the remaining
323  // types must be identical if the array types are to be considered
324  // equivalent.
325  // eg. int[][1] and int[1][1] become
326  //     VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
327  // removing the outermost VAT gives
328  //     CAT(1, int) and CAT(1, int)
329  // which are equal, therefore the array types are equivalent.
330  if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
331    if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
332      return false;
333    NewQType = NewAT->getElementType().getCanonicalType();
334    OldQType = OldAT->getElementType().getCanonicalType();
335  }
336
337  return NewQType == OldQType;
338}
339
340/// MergeVarDecl - We just parsed a variable 'New' which has the same name
341/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
342/// situation, merging decls or emitting diagnostics as appropriate.
343///
344/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
345/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
346///
347VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
348  // Verify the old decl was also a variable.
349  VarDecl *Old = dyn_cast<VarDecl>(OldD);
350  if (!Old) {
351    Diag(New->getLocation(), diag::err_redefinition_different_kind,
352         New->getName());
353    Diag(OldD->getLocation(), diag::err_previous_definition);
354    return New;
355  }
356
357  MergeAttributes(New, Old);
358
359  // Verify the types match.
360  QualType OldCType = Context.getCanonicalType(Old->getType());
361  QualType NewCType = Context.getCanonicalType(New->getType());
362  if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
363    Diag(New->getLocation(), diag::err_redefinition, New->getName());
364    Diag(Old->getLocation(), diag::err_previous_definition);
365    return New;
366  }
367  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
368  if (New->getStorageClass() == VarDecl::Static &&
369      (Old->getStorageClass() == VarDecl::None ||
370       Old->getStorageClass() == VarDecl::Extern)) {
371    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
372    Diag(Old->getLocation(), diag::err_previous_definition);
373    return New;
374  }
375  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
376  if (New->getStorageClass() != VarDecl::Static &&
377      Old->getStorageClass() == VarDecl::Static) {
378    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
379    Diag(Old->getLocation(), diag::err_previous_definition);
380    return New;
381  }
382  // We've verified the types match, now handle "tentative" definitions.
383  FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
384  FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
385
386  if (OldFSDecl && NewFSDecl) {
387    // Handle C "tentative" external object definitions (C99 6.9.2).
388    bool OldIsTentative = false;
389    bool NewIsTentative = false;
390
391    if (!OldFSDecl->getInit() &&
392        (OldFSDecl->getStorageClass() == VarDecl::None ||
393         OldFSDecl->getStorageClass() == VarDecl::Static))
394      OldIsTentative = true;
395
396    // FIXME: this check doesn't work (since the initializer hasn't been
397    // attached yet). This check should be moved to FinalizeDeclaratorGroup.
398    // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
399    // thrown out the old decl.
400    if (!NewFSDecl->getInit() &&
401        (NewFSDecl->getStorageClass() == VarDecl::None ||
402         NewFSDecl->getStorageClass() == VarDecl::Static))
403      ; // change to NewIsTentative = true; once the code is moved.
404
405    if (NewIsTentative || OldIsTentative)
406      return New;
407  }
408  if (Old->getStorageClass() != VarDecl::Extern &&
409      New->getStorageClass() != VarDecl::Extern) {
410    Diag(New->getLocation(), diag::err_redefinition, New->getName());
411    Diag(Old->getLocation(), diag::err_previous_definition);
412  }
413  return New;
414}
415
416/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
417/// no declarator (e.g. "struct foo;") is parsed.
418Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
419  // TODO: emit error on 'int;' or 'const enum foo;'.
420  // TODO: emit error on 'typedef int;'
421  // if (!DS.isMissingDeclaratorOk()) Diag(...);
422
423  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
424}
425
426bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
427  // Get the type before calling CheckSingleAssignmentConstraints(), since
428  // it can promote the expression.
429  QualType InitType = Init->getType();
430
431  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
432  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
433                                  InitType, Init, "initializing");
434}
435
436bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
437                         QualType ElementType) {
438  Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
439  if (CheckSingleInitializer(expr, ElementType))
440    return true; // types weren't compatible.
441
442  if (savExpr != expr) // The type was promoted, update initializer list.
443    IList->setInit(slot, expr);
444  return false;
445}
446
447bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
448  if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
449    // C99 6.7.8p14. We have an array of character type with unknown size
450    // being initialized to a string literal.
451    llvm::APSInt ConstVal(32);
452    ConstVal = strLiteral->getByteLength() + 1;
453    // Return a new array type (C99 6.7.8p22).
454    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
455                                         ArrayType::Normal, 0);
456  } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
457    // C99 6.7.8p14. We have an array of character type with known size.
458    if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
459      Diag(strLiteral->getSourceRange().getBegin(),
460           diag::warn_initializer_string_for_char_array_too_long,
461           strLiteral->getSourceRange());
462  } else {
463    assert(0 && "HandleStringLiteralInit(): Invalid array type");
464  }
465  // Set type from "char *" to "constant array of char".
466  strLiteral->setType(DeclT);
467  // For now, we always return false (meaning success).
468  return false;
469}
470
471StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
472  const ArrayType *AT = DeclType->getAsArrayType();
473  if (AT && AT->getElementType()->isCharType()) {
474    return dyn_cast<StringLiteral>(Init);
475  }
476  return 0;
477}
478
479// CheckInitializerListTypes - Checks the types of elements of an initializer
480// list. This function is recursive: it calls itself to initialize subelements
481// of aggregate types.  Note that the topLevel parameter essentially refers to
482// whether this expression "owns" the initializer list passed in, or if this
483// initialization is taking elements out of a parent initializer.  Each
484// call to this function adds zero or more to startIndex, reports any errors,
485// and returns true if it found any inconsistent types.
486bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
487                                     bool topLevel, unsigned& startIndex) {
488  bool hadError = false;
489
490  if (DeclType->isScalarType()) {
491    // The simplest case: initializing a single scalar
492    if (topLevel) {
493      Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
494           IList->getSourceRange());
495    }
496    if (startIndex < IList->getNumInits()) {
497      Expr* expr = IList->getInit(startIndex);
498      if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
499        // FIXME: Should an error be reported here instead?
500        unsigned newIndex = 0;
501        CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
502      } else {
503        hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
504      }
505      ++startIndex;
506    }
507    // FIXME: Should an error be reported for empty initializer list + scalar?
508  } else if (DeclType->isVectorType()) {
509    if (startIndex < IList->getNumInits()) {
510      const VectorType *VT = DeclType->getAsVectorType();
511      int maxElements = VT->getNumElements();
512      QualType elementType = VT->getElementType();
513
514      for (int i = 0; i < maxElements; ++i) {
515        // Don't attempt to go past the end of the init list
516        if (startIndex >= IList->getNumInits())
517          break;
518        Expr* expr = IList->getInit(startIndex);
519        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
520          unsigned newIndex = 0;
521          hadError |= CheckInitializerListTypes(SubInitList, elementType,
522                                                true, newIndex);
523          ++startIndex;
524        } else {
525          hadError |= CheckInitializerListTypes(IList, elementType,
526                                                false, startIndex);
527        }
528      }
529    }
530  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
531    if (DeclType->isStructureType() || DeclType->isUnionType()) {
532      if (startIndex < IList->getNumInits() && !topLevel &&
533          Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
534                                     DeclType)) {
535        // We found a compatible struct; per the standard, this initializes the
536        // struct.  (The C standard technically says that this only applies for
537        // initializers for declarations with automatic scope; however, this
538        // construct is unambiguous anyway because a struct cannot contain
539        // a type compatible with itself. We'll output an error when we check
540        // if the initializer is constant.)
541        // FIXME: Is a call to CheckSingleInitializer required here?
542        ++startIndex;
543      } else {
544        RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
545
546        // If the record is invalid, some of it's members are invalid. To avoid
547        // confusion, we forgo checking the intializer for the entire record.
548        if (structDecl->isInvalidDecl())
549          return true;
550
551        // If structDecl is a forward declaration, this loop won't do anything;
552        // That's okay, because an error should get printed out elsewhere. It
553        // might be worthwhile to skip over the rest of the initializer, though.
554        int numMembers = structDecl->getNumMembers() -
555                         structDecl->hasFlexibleArrayMember();
556        for (int i = 0; i < numMembers; i++) {
557          // Don't attempt to go past the end of the init list
558          if (startIndex >= IList->getNumInits())
559            break;
560          FieldDecl * curField = structDecl->getMember(i);
561          if (!curField->getIdentifier()) {
562            // Don't initialize unnamed fields, e.g. "int : 20;"
563            continue;
564          }
565          QualType fieldType = curField->getType();
566          Expr* expr = IList->getInit(startIndex);
567          if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
568            unsigned newStart = 0;
569            hadError |= CheckInitializerListTypes(SubInitList, fieldType,
570                                                  true, newStart);
571            ++startIndex;
572          } else {
573            hadError |= CheckInitializerListTypes(IList, fieldType,
574                                                  false, startIndex);
575          }
576          if (DeclType->isUnionType())
577            break;
578        }
579        // FIXME: Implement flexible array initialization GCC extension (it's a
580        // really messy extension to implement, unfortunately...the necessary
581        // information isn't actually even here!)
582      }
583    } else if (DeclType->isArrayType()) {
584      // Check for the special-case of initializing an array with a string.
585      if (startIndex < IList->getNumInits()) {
586        if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
587                                                     DeclType)) {
588          CheckStringLiteralInit(lit, DeclType);
589          ++startIndex;
590          if (topLevel && startIndex < IList->getNumInits()) {
591            // We have leftover initializers; warn
592            Diag(IList->getInit(startIndex)->getLocStart(),
593                 diag::err_excess_initializers_in_char_array_initializer,
594                 IList->getInit(startIndex)->getSourceRange());
595          }
596          return false;
597        }
598      }
599      int maxElements;
600      if (DeclType->isIncompleteArrayType()) {
601        // FIXME: use a proper constant
602        maxElements = 0x7FFFFFFF;
603      } else if (const VariableArrayType *VAT =
604                                DeclType->getAsVariableArrayType()) {
605        // Check for VLAs; in standard C it would be possible to check this
606        // earlier, but I don't know where clang accepts VLAs (gcc accepts
607        // them in all sorts of strange places).
608        Diag(VAT->getSizeExpr()->getLocStart(),
609             diag::err_variable_object_no_init,
610             VAT->getSizeExpr()->getSourceRange());
611        hadError = true;
612        maxElements = 0x7FFFFFFF;
613      } else {
614        const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
615        maxElements = static_cast<int>(CAT->getSize().getZExtValue());
616      }
617      QualType elementType = DeclType->getAsArrayType()->getElementType();
618      int numElements = 0;
619      for (int i = 0; i < maxElements; ++i, ++numElements) {
620        // Don't attempt to go past the end of the init list
621        if (startIndex >= IList->getNumInits())
622          break;
623        Expr* expr = IList->getInit(startIndex);
624        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
625          unsigned newIndex = 0;
626          hadError |= CheckInitializerListTypes(SubInitList, elementType,
627                                                true, newIndex);
628          ++startIndex;
629        } else {
630          hadError |= CheckInitializerListTypes(IList, elementType,
631                                                false, startIndex);
632        }
633      }
634      if (DeclType->isIncompleteArrayType()) {
635        // If this is an incomplete array type, the actual type needs to
636        // be calculated here
637        if (numElements == 0) {
638          // Sizing an array implicitly to zero is not allowed
639          // (It could in theory be allowed, but it doesn't really matter.)
640          Diag(IList->getLocStart(),
641               diag::err_at_least_one_initializer_needed_to_size_array);
642          hadError = true;
643        } else {
644          llvm::APSInt ConstVal(32);
645          ConstVal = numElements;
646          DeclType = Context.getConstantArrayType(elementType, ConstVal,
647                                                  ArrayType::Normal, 0);
648        }
649      }
650    } else {
651      assert(0 && "Aggregate that isn't a function or array?!");
652    }
653  } else {
654    // In C, all types are either scalars or aggregates, but
655    // additional handling is needed here for C++ (and possibly others?).
656    assert(0 && "Unsupported initializer type");
657  }
658
659  // If this init list is a base list, we set the type; an initializer doesn't
660  // fundamentally have a type, but this makes the ASTs a bit easier to read
661  if (topLevel)
662    IList->setType(DeclType);
663
664  if (topLevel && startIndex < IList->getNumInits()) {
665    // We have leftover initializers; warn
666    Diag(IList->getInit(startIndex)->getLocStart(),
667         diag::warn_excess_initializers,
668         IList->getInit(startIndex)->getSourceRange());
669  }
670  return hadError;
671}
672
673bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
674  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
675  // of unknown size ("[]") or an object type that is not a variable array type.
676  if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
677    return Diag(VAT->getSizeExpr()->getLocStart(),
678                diag::err_variable_object_no_init,
679                VAT->getSizeExpr()->getSourceRange());
680
681  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
682  if (!InitList) {
683    // FIXME: Handle wide strings
684    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
685      return CheckStringLiteralInit(strLiteral, DeclType);
686
687    if (DeclType->isArrayType())
688      return Diag(Init->getLocStart(),
689                  diag::err_array_init_list_required,
690                  Init->getSourceRange());
691
692    return CheckSingleInitializer(Init, DeclType);
693  }
694  unsigned newIndex = 0;
695  return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
696}
697
698Sema::DeclTy *
699Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
700  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
701  IdentifierInfo *II = D.getIdentifier();
702
703  // All of these full declarators require an identifier.  If it doesn't have
704  // one, the ParsedFreeStandingDeclSpec action should be used.
705  if (II == 0) {
706    Diag(D.getDeclSpec().getSourceRange().getBegin(),
707         diag::err_declarator_need_ident,
708         D.getDeclSpec().getSourceRange(), D.getSourceRange());
709    return 0;
710  }
711
712  // The scope passed in may not be a decl scope.  Zip up the scope tree until
713  // we find one that is.
714  while ((S->getFlags() & Scope::DeclScope) == 0)
715    S = S->getParent();
716
717  // See if this is a redefinition of a variable in the same scope.
718  Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
719  ScopedDecl *New;
720  bool InvalidDecl = false;
721
722  QualType R = GetTypeForDeclarator(D, S);
723  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
724
725  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
726    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
727    if (!NewTD) return 0;
728
729    // Handle attributes prior to checking for duplicates in MergeVarDecl
730    HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
731                         D.getAttributes());
732    // Merge the decl with the existing one if appropriate. If the decl is
733    // in an outer scope, it isn't the same thing.
734    if (PrevDecl && S->isDeclScope(PrevDecl)) {
735      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
736      if (NewTD == 0) return 0;
737    }
738    New = NewTD;
739    if (S->getParent() == 0) {
740      // C99 6.7.7p2: If a typedef name specifies a variably modified type
741      // then it shall have block scope.
742      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
743        // FIXME: Diagnostic needs to be fixed.
744        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
745        InvalidDecl = true;
746      }
747    }
748  } else if (R.getTypePtr()->isFunctionType()) {
749    FunctionDecl::StorageClass SC = FunctionDecl::None;
750    switch (D.getDeclSpec().getStorageClassSpec()) {
751      default: assert(0 && "Unknown storage class!");
752      case DeclSpec::SCS_auto:
753      case DeclSpec::SCS_register:
754        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
755             R.getAsString());
756        InvalidDecl = true;
757        break;
758      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
759      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
760      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
761      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
762    }
763
764    bool isInline = D.getDeclSpec().isInlineSpecified();
765    FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
766                                               D.getIdentifierLoc(),
767                                               II, R, SC, isInline,
768                                               LastDeclarator);
769    // Handle attributes.
770    HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
771                         D.getAttributes());
772
773    // Merge the decl with the existing one if appropriate. Since C functions
774    // are in a flat namespace, make sure we consider decls in outer scopes.
775    if (PrevDecl) {
776      NewFD = MergeFunctionDecl(NewFD, PrevDecl);
777      if (NewFD == 0) return 0;
778    }
779    New = NewFD;
780  } else {
781    if (R.getTypePtr()->isObjCInterfaceType()) {
782      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
783           D.getIdentifier()->getName());
784      InvalidDecl = true;
785    }
786
787    VarDecl *NewVD;
788    VarDecl::StorageClass SC;
789    switch (D.getDeclSpec().getStorageClassSpec()) {
790    default: assert(0 && "Unknown storage class!");
791    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
792    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
793    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
794    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
795    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
796    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
797    }
798    if (S->getParent() == 0) {
799      // C99 6.9p2: The storage-class specifiers auto and register shall not
800      // appear in the declaration specifiers in an external declaration.
801      if (SC == VarDecl::Auto || SC == VarDecl::Register) {
802        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
803             R.getAsString());
804        InvalidDecl = true;
805      }
806      NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
807                                  II, R, SC,
808                                  LastDeclarator);
809    } else {
810      NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
811                                   II, R, SC,
812                                   LastDeclarator);
813    }
814    // Handle attributes prior to checking for duplicates in MergeVarDecl
815    HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
816                         D.getAttributes());
817
818    // Emit an error if an address space was applied to decl with local storage.
819    // This includes arrays of objects with address space qualifiers, but not
820    // automatic variables that point to other address spaces.
821    // ISO/IEC TR 18037 S5.1.2
822    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
823      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
824      InvalidDecl = true;
825    }
826    // Merge the decl with the existing one if appropriate. If the decl is
827    // in an outer scope, it isn't the same thing.
828    if (PrevDecl && S->isDeclScope(PrevDecl)) {
829      NewVD = MergeVarDecl(NewVD, PrevDecl);
830      if (NewVD == 0) return 0;
831    }
832    New = NewVD;
833  }
834
835  // If this has an identifier, add it to the scope stack.
836  if (II) {
837    New->setNext(II->getFETokenInfo<ScopedDecl>());
838    II->setFETokenInfo(New);
839    S->AddDecl(New);
840  }
841  // If any semantic error occurred, mark the decl as invalid.
842  if (D.getInvalidType() || InvalidDecl)
843    New->setInvalidDecl();
844
845  return New;
846}
847
848bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
849  SourceLocation loc;
850  // FIXME: Remove the isReference check and handle assignment to a reference.
851  if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
852    assert(loc.isValid() && "isConstantExpr didn't return a loc!");
853    Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
854    return true;
855  }
856  return false;
857}
858
859void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
860  Decl *RealDecl = static_cast<Decl *>(dcl);
861  Expr *Init = static_cast<Expr *>(init);
862  assert(Init && "missing initializer");
863
864  // If there is no declaration, there was an error parsing it.  Just ignore
865  // the initializer.
866  if (RealDecl == 0) {
867    delete Init;
868    return;
869  }
870
871  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
872  if (!VDecl) {
873    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
874         diag::err_illegal_initializer);
875    RealDecl->setInvalidDecl();
876    return;
877  }
878  // Get the decls type and save a reference for later, since
879  // CheckInitializerTypes may change it.
880  QualType DclT = VDecl->getType(), SavT = DclT;
881  if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
882    VarDecl::StorageClass SC = BVD->getStorageClass();
883    if (SC == VarDecl::Extern) { // C99 6.7.8p5
884      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
885      BVD->setInvalidDecl();
886    } else if (!BVD->isInvalidDecl()) {
887      if (CheckInitializerTypes(Init, DclT))
888        BVD->setInvalidDecl();
889      if (SC == VarDecl::Static) // C99 6.7.8p4.
890        CheckForConstantInitializer(Init, DclT);
891    }
892  } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
893    if (FVD->getStorageClass() == VarDecl::Extern)
894      Diag(VDecl->getLocation(), diag::warn_extern_init);
895    if (!FVD->isInvalidDecl())
896      if (CheckInitializerTypes(Init, DclT))
897        FVD->setInvalidDecl();
898
899    // C99 6.7.8p4. All file scoped initializers need to be constant.
900    CheckForConstantInitializer(Init, DclT);
901  }
902  // If the type changed, it means we had an incomplete type that was
903  // completed by the initializer. For example:
904  //   int ary[] = { 1, 3, 5 };
905  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
906  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
907    VDecl->setType(DclT);
908    Init->setType(DclT);
909  }
910
911  // Attach the initializer to the decl.
912  VDecl->setInit(Init);
913  return;
914}
915
916/// The declarators are chained together backwards, reverse the list.
917Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
918  // Often we have single declarators, handle them quickly.
919  Decl *GroupDecl = static_cast<Decl*>(group);
920  if (GroupDecl == 0)
921    return 0;
922
923  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
924  ScopedDecl *NewGroup = 0;
925  if (Group->getNextDeclarator() == 0)
926    NewGroup = Group;
927  else { // reverse the list.
928    while (Group) {
929      ScopedDecl *Next = Group->getNextDeclarator();
930      Group->setNextDeclarator(NewGroup);
931      NewGroup = Group;
932      Group = Next;
933    }
934  }
935  // Perform semantic analysis that depends on having fully processed both
936  // the declarator and initializer.
937  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
938    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
939    if (!IDecl)
940      continue;
941    FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
942    BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
943    QualType T = IDecl->getType();
944
945    // C99 6.7.5.2p2: If an identifier is declared to be an object with
946    // static storage duration, it shall not have a variable length array.
947    if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
948      if (T->getAsVariableArrayType()) {
949        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
950        IDecl->setInvalidDecl();
951      }
952    }
953    // Block scope. C99 6.7p7: If an identifier for an object is declared with
954    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
955    if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
956      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
957        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
958             T.getAsString());
959        IDecl->setInvalidDecl();
960      }
961    }
962    // File scope. C99 6.9.2p2: A declaration of an identifier for and
963    // object that has file scope without an initializer, and without a
964    // storage-class specifier or with the storage-class specifier "static",
965    // constitutes a tentative definition. Note: A tentative definition with
966    // external linkage is valid (C99 6.2.2p5).
967    if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
968                                   FVD->getStorageClass() == VarDecl::None)) {
969      if (T->isIncompleteArrayType()) {
970        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
971        // array to be completed. Don't issue a diagnostic.
972      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
973        // C99 6.9.2p3: If the declaration of an identifier for an object is
974        // a tentative definition and has internal linkage (C99 6.2.2p3), the
975        // declared type shall not be an incomplete type.
976        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
977             T.getAsString());
978        IDecl->setInvalidDecl();
979      }
980    }
981  }
982  return NewGroup;
983}
984
985// Called from Sema::ParseStartOfFunctionDef().
986ParmVarDecl *
987Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
988                           Scope *FnScope) {
989  IdentifierInfo *II = PI.Ident;
990  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
991  // Can this happen for params?  We already checked that they don't conflict
992  // among each other.  Here they can only shadow globals, which is ok.
993  if (/*Decl *PrevDecl = */LookupDecl(II, Decl::IDNS_Ordinary, FnScope)) {
994
995  }
996
997  // FIXME: Handle storage class (auto, register). No declarator?
998  // TODO: Chain to previous parameter with the prevdeclarator chain?
999
1000  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1001  // Doing the promotion here has a win and a loss. The win is the type for
1002  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1003  // code generator). The loss is the orginal type isn't preserved. For example:
1004  //
1005  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1006  //    int blockvardecl[5];
1007  //    sizeof(parmvardecl);  // size == 4
1008  //    sizeof(blockvardecl); // size == 20
1009  // }
1010  //
1011  // For expressions, all implicit conversions are captured using the
1012  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1013  //
1014  // FIXME: If a source translation tool needs to see the original type, then
1015  // we need to consider storing both types (in ParmVarDecl)...
1016  //
1017  QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
1018  if (parmDeclType->isArrayType()) {
1019    // int x[restrict 4] ->  int *restrict
1020    parmDeclType = Context.getArrayDecayedType(parmDeclType);
1021  } else if (parmDeclType->isFunctionType())
1022    parmDeclType = Context.getPointerType(parmDeclType);
1023
1024  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, PI.IdentLoc, II,
1025                                         parmDeclType,
1026                                         VarDecl::None, 0);
1027
1028  if (PI.InvalidType)
1029    New->setInvalidDecl();
1030
1031  // If this has an identifier, add it to the scope stack.
1032  if (II) {
1033    New->setNext(II->getFETokenInfo<ScopedDecl>());
1034    II->setFETokenInfo(New);
1035    FnScope->AddDecl(New);
1036  }
1037
1038  HandleDeclAttributes(New, PI.AttrList, 0);
1039  return New;
1040}
1041
1042Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1043  assert(CurFunctionDecl == 0 && "Function parsing confused");
1044  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1045         "Not a function declarator!");
1046  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1047
1048  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1049  // for a K&R function.
1050  if (!FTI.hasPrototype) {
1051    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1052      if (FTI.ArgInfo[i].TypeInfo == 0) {
1053        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1054             FTI.ArgInfo[i].Ident->getName());
1055        // Implicitly declare the argument as type 'int' for lack of a better
1056        // type.
1057        FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1058      }
1059    }
1060
1061    // Since this is a function definition, act as though we have information
1062    // about the arguments.
1063    if (FTI.NumArgs)
1064      FTI.hasPrototype = true;
1065  } else {
1066    // FIXME: Diagnose arguments without names in C.
1067
1068  }
1069
1070  Scope *GlobalScope = FnBodyScope->getParent();
1071
1072  // See if this is a redefinition.
1073  Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1074                             GlobalScope);
1075  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1076    if (FD->getBody()) {
1077      Diag(D.getIdentifierLoc(), diag::err_redefinition,
1078           D.getIdentifier()->getName());
1079      Diag(FD->getLocation(), diag::err_previous_definition);
1080    }
1081  }
1082  Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1083  FunctionDecl *FD = cast<FunctionDecl>(decl);
1084  CurFunctionDecl = FD;
1085  PushDeclContext(FD);
1086
1087  // Create Decl objects for each parameter, adding them to the FunctionDecl.
1088  llvm::SmallVector<ParmVarDecl*, 16> Params;
1089
1090  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1091  // no arguments, not a function that takes a single void argument.
1092  if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1093      !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
1094      QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
1095    // empty arg list, don't push any params.
1096  } else {
1097    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1098      ParmVarDecl *parmDecl;
1099
1100      parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1101                                      FnBodyScope);
1102      // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1103      // declarator that is part of a function definition of that function
1104      // shall not have incomplete type.
1105      if (parmDecl->getType()->isIncompleteType() &&
1106          !parmDecl->isInvalidDecl()) {
1107        Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1108             parmDecl->getType().getAsString());
1109        parmDecl->setInvalidDecl();
1110      }
1111      Params.push_back(parmDecl);
1112    }
1113  }
1114
1115  FD->setParams(&Params[0], Params.size());
1116
1117  return FD;
1118}
1119
1120Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1121  Decl *dcl = static_cast<Decl *>(D);
1122  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1123    FD->setBody((Stmt*)Body);
1124    assert(FD == CurFunctionDecl && "Function parsing confused");
1125    CurFunctionDecl = 0;
1126  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
1127    MD->setBody((Stmt*)Body);
1128    CurMethodDecl = 0;
1129  }
1130  PopDeclContext();
1131  // Verify and clean out per-function state.
1132
1133  // Check goto/label use.
1134  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1135       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1136    // Verify that we have no forward references left.  If so, there was a goto
1137    // or address of a label taken, but no definition of it.  Label fwd
1138    // definitions are indicated with a null substmt.
1139    if (I->second->getSubStmt() == 0) {
1140      LabelStmt *L = I->second;
1141      // Emit error.
1142      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1143
1144      // At this point, we have gotos that use the bogus label.  Stitch it into
1145      // the function body so that they aren't leaked and that the AST is well
1146      // formed.
1147      if (Body) {
1148        L->setSubStmt(new NullStmt(L->getIdentLoc()));
1149        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1150      } else {
1151        // The whole function wasn't parsed correctly, just delete this.
1152        delete L;
1153      }
1154    }
1155  }
1156  LabelMap.clear();
1157
1158  return D;
1159}
1160
1161/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1162/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1163ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1164                                           IdentifierInfo &II, Scope *S) {
1165  if (getLangOptions().C99)  // Extension in C99.
1166    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1167  else  // Legal in C90, but warn about it.
1168    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1169
1170  // FIXME: handle stuff like:
1171  // void foo() { extern float X(); }
1172  // void bar() { X(); }  <-- implicit decl for X in another scope.
1173
1174  // Set a Declarator for the implicit definition: int foo();
1175  const char *Dummy;
1176  DeclSpec DS;
1177  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1178  Error = Error; // Silence warning.
1179  assert(!Error && "Error setting up implicit decl!");
1180  Declarator D(DS, Declarator::BlockContext);
1181  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1182  D.SetIdentifier(&II, Loc);
1183
1184  // Find translation-unit scope to insert this function into.
1185  if (Scope *FnS = S->getFnParent())
1186    S = FnS->getParent();   // Skip all scopes in a function at once.
1187  while (S->getParent())
1188    S = S->getParent();
1189
1190  FunctionDecl *FD =
1191    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1192  FD->setImplicit();
1193  return FD;
1194}
1195
1196
1197TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1198                                    ScopedDecl *LastDeclarator) {
1199  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1200  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1201
1202  // Scope manipulation handled by caller.
1203  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1204                                           D.getIdentifierLoc(),
1205                                           D.getIdentifier(),
1206                                           T, LastDeclarator);
1207  if (D.getInvalidType())
1208    NewTD->setInvalidDecl();
1209  return NewTD;
1210}
1211
1212/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1213/// former case, Name will be non-null.  In the later case, Name will be null.
1214/// TagType indicates what kind of tag this is. TK indicates whether this is a
1215/// reference/declaration/definition of a tag.
1216Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1217                             SourceLocation KWLoc, IdentifierInfo *Name,
1218                             SourceLocation NameLoc, AttributeList *Attr) {
1219  // If this is a use of an existing tag, it must have a name.
1220  assert((Name != 0 || TK == TK_Definition) &&
1221         "Nameless record must be a definition!");
1222
1223  Decl::Kind Kind;
1224  switch (TagType) {
1225  default: assert(0 && "Unknown tag type!");
1226  case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1227  case DeclSpec::TST_union:  Kind = Decl::Union; break;
1228//case DeclSpec::TST_class:  Kind = Decl::Class; break;
1229  case DeclSpec::TST_enum:   Kind = Decl::Enum; break;
1230  }
1231
1232  // If this is a named struct, check to see if there was a previous forward
1233  // declaration or definition.
1234  if (TagDecl *PrevDecl =
1235          dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
1236
1237    // If this is a use of a previous tag, or if the tag is already declared in
1238    // the same scope (so that the definition/declaration completes or
1239    // rementions the tag), reuse the decl.
1240    if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1241      // Make sure that this wasn't declared as an enum and now used as a struct
1242      // or something similar.
1243      if (PrevDecl->getKind() != Kind) {
1244        Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1245        Diag(PrevDecl->getLocation(), diag::err_previous_use);
1246      }
1247
1248      // If this is a use or a forward declaration, we're good.
1249      if (TK != TK_Definition)
1250        return PrevDecl;
1251
1252      // Diagnose attempts to redefine a tag.
1253      if (PrevDecl->isDefinition()) {
1254        Diag(NameLoc, diag::err_redefinition, Name->getName());
1255        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1256        // If this is a redefinition, recover by making this struct be
1257        // anonymous, which will make any later references get the previous
1258        // definition.
1259        Name = 0;
1260      } else {
1261        // Okay, this is definition of a previously declared or referenced tag.
1262        // Move the location of the decl to be the definition site.
1263        PrevDecl->setLocation(NameLoc);
1264        return PrevDecl;
1265      }
1266    }
1267    // If we get here, this is a definition of a new struct type in a nested
1268    // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1269    // type.
1270  }
1271
1272  // If there is an identifier, use the location of the identifier as the
1273  // location of the decl, otherwise use the location of the struct/union
1274  // keyword.
1275  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1276
1277  // Otherwise, if this is the first time we've seen this tag, create the decl.
1278  TagDecl *New;
1279  switch (Kind) {
1280  default: assert(0 && "Unknown tag kind!");
1281  case Decl::Enum:
1282    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1283    // enum X { A, B, C } D;    D should chain to X.
1284    New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
1285    // If this is an undefined enum, warn.
1286    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1287    break;
1288  case Decl::Union:
1289  case Decl::Struct:
1290  case Decl::Class:
1291    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1292    // struct X { int A; } D;    D should chain to X.
1293    New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1294    break;
1295  }
1296
1297  // If this has an identifier, add it to the scope stack.
1298  if (Name) {
1299    // The scope passed in may not be a decl scope.  Zip up the scope tree until
1300    // we find one that is.
1301    while ((S->getFlags() & Scope::DeclScope) == 0)
1302      S = S->getParent();
1303
1304    // Add it to the decl chain.
1305    New->setNext(Name->getFETokenInfo<ScopedDecl>());
1306    Name->setFETokenInfo(New);
1307    S->AddDecl(New);
1308  }
1309
1310  HandleDeclAttributes(New, Attr, 0);
1311  return New;
1312}
1313
1314/// ActOnField - Each field of a struct/union/class is passed into this in order
1315/// to create a FieldDecl object for it.
1316Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
1317                               SourceLocation DeclStart,
1318                               Declarator &D, ExprTy *BitfieldWidth) {
1319  IdentifierInfo *II = D.getIdentifier();
1320  Expr *BitWidth = (Expr*)BitfieldWidth;
1321  Decl *TagDecl = static_cast<Decl *>(tagDecl);
1322  SourceLocation Loc = DeclStart;
1323  if (II) Loc = D.getIdentifierLoc();
1324
1325  // FIXME: Unnamed fields can be handled in various different ways, for
1326  // example, unnamed unions inject all members into the struct namespace!
1327
1328
1329  if (BitWidth) {
1330    // TODO: Validate.
1331    //printf("WARNING: BITFIELDS IGNORED!\n");
1332
1333    // 6.7.2.1p3
1334    // 6.7.2.1p4
1335
1336  } else {
1337    // Not a bitfield.
1338
1339    // validate II.
1340
1341  }
1342
1343  QualType T = GetTypeForDeclarator(D, S);
1344  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1345  bool InvalidDecl = false;
1346
1347  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1348  // than a variably modified type.
1349  if (T->isVariablyModifiedType()) {
1350    // FIXME: This diagnostic needs work
1351    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1352    InvalidDecl = true;
1353  }
1354  // FIXME: Chain fielddecls together.
1355  FieldDecl *NewFD;
1356
1357  if (isa<RecordDecl>(TagDecl))
1358    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
1359  else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1360           isa<ObjCImplementationDecl>(TagDecl) ||
1361           isa<ObjCCategoryDecl>(TagDecl) ||
1362           // FIXME: ivars are currently used to model properties, and
1363           // properties can appear within a protocol.
1364           // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1365           isa<ObjCProtocolDecl>(TagDecl))
1366    NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
1367  else
1368    assert(0 && "Sema::ActOnField(): Unknown TagDecl");
1369
1370  HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1371                       D.getAttributes());
1372
1373  if (D.getInvalidType() || InvalidDecl)
1374    NewFD->setInvalidDecl();
1375  return NewFD;
1376}
1377
1378/// TranslateIvarVisibility - Translate visibility from a token ID to an
1379///  AST enum value.
1380static ObjCIvarDecl::AccessControl
1381TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1382  switch (ivarVisibility) {
1383    case tok::objc_private: return ObjCIvarDecl::Private;
1384    case tok::objc_public: return ObjCIvarDecl::Public;
1385    case tok::objc_protected: return ObjCIvarDecl::Protected;
1386    case tok::objc_package: return ObjCIvarDecl::Package;
1387    default: assert(false && "Unknown visitibility kind");
1388  }
1389}
1390
1391void Sema::ActOnFields(Scope* S,
1392                       SourceLocation RecLoc, DeclTy *RecDecl,
1393                       DeclTy **Fields, unsigned NumFields,
1394                       SourceLocation LBrac, SourceLocation RBrac,
1395                       tok::ObjCKeywordKind *visibility) {
1396  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1397  assert(EnclosingDecl && "missing record or interface decl");
1398  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1399
1400  if (Record && Record->isDefinition()) {
1401    // Diagnose code like:
1402    //     struct S { struct S {} X; };
1403    // We discover this when we complete the outer S.  Reject and ignore the
1404    // outer S.
1405    Diag(Record->getLocation(), diag::err_nested_redefinition,
1406         Record->getKindName());
1407    Diag(RecLoc, diag::err_previous_definition);
1408    Record->setInvalidDecl();
1409    return;
1410  }
1411  // Verify that all the fields are okay.
1412  unsigned NumNamedMembers = 0;
1413  llvm::SmallVector<FieldDecl*, 32> RecFields;
1414  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1415
1416  for (unsigned i = 0; i != NumFields; ++i) {
1417
1418    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1419    assert(FD && "missing field decl");
1420
1421    // Remember all fields.
1422    RecFields.push_back(FD);
1423
1424    // Get the type for the field.
1425    Type *FDTy = FD->getType().getTypePtr();
1426
1427    // If we have visibility info, make sure the AST is set accordingly.
1428    if (visibility)
1429      cast<ObjCIvarDecl>(FD)->setAccessControl(
1430                                TranslateIvarVisibility(visibility[i]));
1431
1432    // C99 6.7.2.1p2 - A field may not be a function type.
1433    if (FDTy->isFunctionType()) {
1434      Diag(FD->getLocation(), diag::err_field_declared_as_function,
1435           FD->getName());
1436      FD->setInvalidDecl();
1437      EnclosingDecl->setInvalidDecl();
1438      continue;
1439    }
1440    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1441    if (FDTy->isIncompleteType()) {
1442      if (!Record) {  // Incomplete ivar type is always an error.
1443        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1444        FD->setInvalidDecl();
1445        EnclosingDecl->setInvalidDecl();
1446        continue;
1447      }
1448      if (i != NumFields-1 ||                   // ... that the last member ...
1449          Record->getKind() != Decl::Struct ||  // ... of a structure ...
1450          !FDTy->isArrayType()) {         //... may have incomplete array type.
1451        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1452        FD->setInvalidDecl();
1453        EnclosingDecl->setInvalidDecl();
1454        continue;
1455      }
1456      if (NumNamedMembers < 1) {  //... must have more than named member ...
1457        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1458             FD->getName());
1459        FD->setInvalidDecl();
1460        EnclosingDecl->setInvalidDecl();
1461        continue;
1462      }
1463      // Okay, we have a legal flexible array member at the end of the struct.
1464      if (Record)
1465        Record->setHasFlexibleArrayMember(true);
1466    }
1467    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1468    /// field of another structure or the element of an array.
1469    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
1470      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1471        // If this is a member of a union, then entire union becomes "flexible".
1472        if (Record && Record->getKind() == Decl::Union) {
1473          Record->setHasFlexibleArrayMember(true);
1474        } else {
1475          // If this is a struct/class and this is not the last element, reject
1476          // it.  Note that GCC supports variable sized arrays in the middle of
1477          // structures.
1478          if (i != NumFields-1) {
1479            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1480                 FD->getName());
1481            FD->setInvalidDecl();
1482            EnclosingDecl->setInvalidDecl();
1483            continue;
1484          }
1485          // We support flexible arrays at the end of structs in other structs
1486          // as an extension.
1487          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1488               FD->getName());
1489          if (Record)
1490            Record->setHasFlexibleArrayMember(true);
1491        }
1492      }
1493    }
1494    /// A field cannot be an Objective-c object
1495    if (FDTy->isObjCInterfaceType()) {
1496      Diag(FD->getLocation(), diag::err_statically_allocated_object,
1497           FD->getName());
1498      FD->setInvalidDecl();
1499      EnclosingDecl->setInvalidDecl();
1500      continue;
1501    }
1502    // Keep track of the number of named members.
1503    if (IdentifierInfo *II = FD->getIdentifier()) {
1504      // Detect duplicate member names.
1505      if (!FieldIDs.insert(II)) {
1506        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1507        // Find the previous decl.
1508        SourceLocation PrevLoc;
1509        for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1510          assert(i != e && "Didn't find previous def!");
1511          if (RecFields[i]->getIdentifier() == II) {
1512            PrevLoc = RecFields[i]->getLocation();
1513            break;
1514          }
1515        }
1516        Diag(PrevLoc, diag::err_previous_definition);
1517        FD->setInvalidDecl();
1518        EnclosingDecl->setInvalidDecl();
1519        continue;
1520      }
1521      ++NumNamedMembers;
1522    }
1523  }
1524
1525  // Okay, we successfully defined 'Record'.
1526  if (Record) {
1527    Record->defineBody(&RecFields[0], RecFields.size());
1528    Consumer.HandleTagDeclDefinition(Record);
1529  } else {
1530    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1531    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1532      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1533    else if (ObjCImplementationDecl *IMPDecl =
1534               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
1535      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1536      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1537      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
1538    }
1539  }
1540}
1541
1542Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
1543                                      DeclTy *lastEnumConst,
1544                                      SourceLocation IdLoc, IdentifierInfo *Id,
1545                                      SourceLocation EqualLoc, ExprTy *val) {
1546  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
1547  EnumConstantDecl *LastEnumConst =
1548    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1549  Expr *Val = static_cast<Expr*>(val);
1550
1551  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1552  // we find one that is.
1553  while ((S->getFlags() & Scope::DeclScope) == 0)
1554    S = S->getParent();
1555
1556  // Verify that there isn't already something declared with this name in this
1557  // scope.
1558  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
1559    if (S->isDeclScope(PrevDecl)) {
1560      if (isa<EnumConstantDecl>(PrevDecl))
1561        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1562      else
1563        Diag(IdLoc, diag::err_redefinition, Id->getName());
1564      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1565      delete Val;
1566      return 0;
1567    }
1568  }
1569
1570  llvm::APSInt EnumVal(32);
1571  QualType EltTy;
1572  if (Val) {
1573    // Make sure to promote the operand type to int.
1574    UsualUnaryConversions(Val);
1575
1576    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1577    SourceLocation ExpLoc;
1578    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1579      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1580           Id->getName());
1581      delete Val;
1582      Val = 0;  // Just forget about it.
1583    } else {
1584      EltTy = Val->getType();
1585    }
1586  }
1587
1588  if (!Val) {
1589    if (LastEnumConst) {
1590      // Assign the last value + 1.
1591      EnumVal = LastEnumConst->getInitVal();
1592      ++EnumVal;
1593
1594      // Check for overflow on increment.
1595      if (EnumVal < LastEnumConst->getInitVal())
1596        Diag(IdLoc, diag::warn_enum_value_overflow);
1597
1598      EltTy = LastEnumConst->getType();
1599    } else {
1600      // First value, set to zero.
1601      EltTy = Context.IntTy;
1602      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
1603    }
1604  }
1605
1606  EnumConstantDecl *New =
1607    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1608                             Val, EnumVal,
1609                             LastEnumConst);
1610
1611  // Register this decl in the current scope stack.
1612  New->setNext(Id->getFETokenInfo<ScopedDecl>());
1613  Id->setFETokenInfo(New);
1614  S->AddDecl(New);
1615  return New;
1616}
1617
1618void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1619                         DeclTy **Elements, unsigned NumElements) {
1620  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1621  assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1622
1623  // TODO: If the result value doesn't fit in an int, it must be a long or long
1624  // long value.  ISO C does not support this, but GCC does as an extension,
1625  // emit a warning.
1626  unsigned IntWidth = Context.Target.getIntWidth();
1627
1628  // Verify that all the values are okay, compute the size of the values, and
1629  // reverse the list.
1630  unsigned NumNegativeBits = 0;
1631  unsigned NumPositiveBits = 0;
1632
1633  // Keep track of whether all elements have type int.
1634  bool AllElementsInt = true;
1635
1636  EnumConstantDecl *EltList = 0;
1637  for (unsigned i = 0; i != NumElements; ++i) {
1638    EnumConstantDecl *ECD =
1639      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1640    if (!ECD) continue;  // Already issued a diagnostic.
1641
1642    // If the enum value doesn't fit in an int, emit an extension warning.
1643    const llvm::APSInt &InitVal = ECD->getInitVal();
1644    assert(InitVal.getBitWidth() >= IntWidth &&
1645           "Should have promoted value to int");
1646    if (InitVal.getBitWidth() > IntWidth) {
1647      llvm::APSInt V(InitVal);
1648      V.trunc(IntWidth);
1649      V.extend(InitVal.getBitWidth());
1650      if (V != InitVal)
1651        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1652             InitVal.toString());
1653    }
1654
1655    // Keep track of the size of positive and negative values.
1656    if (InitVal.isUnsigned() || InitVal.isNonNegative())
1657      NumPositiveBits = std::max(NumPositiveBits,
1658                                 (unsigned)InitVal.getActiveBits());
1659    else
1660      NumNegativeBits = std::max(NumNegativeBits,
1661                                 (unsigned)InitVal.getMinSignedBits());
1662
1663    // Keep track of whether every enum element has type int (very commmon).
1664    if (AllElementsInt)
1665      AllElementsInt = ECD->getType() == Context.IntTy;
1666
1667    ECD->setNextDeclarator(EltList);
1668    EltList = ECD;
1669  }
1670
1671  // Figure out the type that should be used for this enum.
1672  // FIXME: Support attribute(packed) on enums and -fshort-enums.
1673  QualType BestType;
1674  unsigned BestWidth;
1675
1676  if (NumNegativeBits) {
1677    // If there is a negative value, figure out the smallest integer type (of
1678    // int/long/longlong) that fits.
1679    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
1680      BestType = Context.IntTy;
1681      BestWidth = IntWidth;
1682    } else {
1683      BestWidth = Context.Target.getLongWidth();
1684
1685      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
1686        BestType = Context.LongTy;
1687      else {
1688        BestWidth = Context.Target.getLongLongWidth();
1689
1690        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
1691          Diag(Enum->getLocation(), diag::warn_enum_too_large);
1692        BestType = Context.LongLongTy;
1693      }
1694    }
1695  } else {
1696    // If there is no negative value, figure out which of uint, ulong, ulonglong
1697    // fits.
1698    if (NumPositiveBits <= IntWidth) {
1699      BestType = Context.UnsignedIntTy;
1700      BestWidth = IntWidth;
1701    } else if (NumPositiveBits <=
1702               (BestWidth = Context.Target.getLongWidth())) {
1703      BestType = Context.UnsignedLongTy;
1704    } else {
1705      BestWidth = Context.Target.getLongLongWidth();
1706      assert(NumPositiveBits <= BestWidth &&
1707             "How could an initializer get larger than ULL?");
1708      BestType = Context.UnsignedLongLongTy;
1709    }
1710  }
1711
1712  // Loop over all of the enumerator constants, changing their types to match
1713  // the type of the enum if needed.
1714  for (unsigned i = 0; i != NumElements; ++i) {
1715    EnumConstantDecl *ECD =
1716      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1717    if (!ECD) continue;  // Already issued a diagnostic.
1718
1719    // Standard C says the enumerators have int type, but we allow, as an
1720    // extension, the enumerators to be larger than int size.  If each
1721    // enumerator value fits in an int, type it as an int, otherwise type it the
1722    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
1723    // that X has type 'int', not 'unsigned'.
1724    if (ECD->getType() == Context.IntTy) {
1725      // Make sure the init value is signed.
1726      llvm::APSInt IV = ECD->getInitVal();
1727      IV.setIsSigned(true);
1728      ECD->setInitVal(IV);
1729      continue;  // Already int type.
1730    }
1731
1732    // Determine whether the value fits into an int.
1733    llvm::APSInt InitVal = ECD->getInitVal();
1734    bool FitsInInt;
1735    if (InitVal.isUnsigned() || !InitVal.isNegative())
1736      FitsInInt = InitVal.getActiveBits() < IntWidth;
1737    else
1738      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1739
1740    // If it fits into an integer type, force it.  Otherwise force it to match
1741    // the enum decl type.
1742    QualType NewTy;
1743    unsigned NewWidth;
1744    bool NewSign;
1745    if (FitsInInt) {
1746      NewTy = Context.IntTy;
1747      NewWidth = IntWidth;
1748      NewSign = true;
1749    } else if (ECD->getType() == BestType) {
1750      // Already the right type!
1751      continue;
1752    } else {
1753      NewTy = BestType;
1754      NewWidth = BestWidth;
1755      NewSign = BestType->isSignedIntegerType();
1756    }
1757
1758    // Adjust the APSInt value.
1759    InitVal.extOrTrunc(NewWidth);
1760    InitVal.setIsSigned(NewSign);
1761    ECD->setInitVal(InitVal);
1762
1763    // Adjust the Expr initializer and type.
1764    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1765    ECD->setType(NewTy);
1766  }
1767
1768  Enum->defineElements(EltList, BestType);
1769  Consumer.HandleTagDeclDefinition(Enum);
1770}
1771
1772Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1773                                          ExprTy *expr) {
1774  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1775
1776  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
1777}
1778
1779Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1780                                     SourceLocation LBrace,
1781                                     SourceLocation RBrace,
1782                                     const char *Lang,
1783                                     unsigned StrSize,
1784                                     DeclTy *D) {
1785  LinkageSpecDecl::LanguageIDs Language;
1786  Decl *dcl = static_cast<Decl *>(D);
1787  if (strncmp(Lang, "\"C\"", StrSize) == 0)
1788    Language = LinkageSpecDecl::lang_c;
1789  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1790    Language = LinkageSpecDecl::lang_cxx;
1791  else {
1792    Diag(Loc, diag::err_bad_language);
1793    return 0;
1794  }
1795
1796  // FIXME: Add all the various semantics of linkage specifications
1797  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
1798}
1799
1800void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
1801
1802  switch (Attr->getKind()) {
1803  case AttributeList::AT_vector_size:
1804    if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1805      QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
1806      if (!newType.isNull()) // install the new vector type into the decl
1807        vDecl->setType(newType);
1808    }
1809    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1810      QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1811                                                   Attr);
1812      if (!newType.isNull()) // install the new vector type into the decl
1813        tDecl->setUnderlyingType(newType);
1814    }
1815    break;
1816  case AttributeList::AT_ocu_vector_type:
1817    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1818      HandleOCUVectorTypeAttribute(tDecl, Attr);
1819    else
1820      Diag(Attr->getLoc(),
1821           diag::err_typecheck_ocu_vector_not_typedef);
1822    break;
1823  case AttributeList::AT_address_space:
1824    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1825      QualType newType = HandleAddressSpaceTypeAttribute(
1826                                                  tDecl->getUnderlyingType(),
1827                                                  Attr);
1828      tDecl->setUnderlyingType(newType);
1829    } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1830      QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1831                                                         Attr);
1832      // install the new addr spaced type into the decl
1833      vDecl->setType(newType);
1834    }
1835    break;
1836  case AttributeList::AT_deprecated:
1837    HandleDeprecatedAttribute(New, Attr);
1838    break;
1839  case AttributeList::AT_visibility:
1840    HandleVisibilityAttribute(New, Attr);
1841    break;
1842  case AttributeList::AT_weak:
1843    HandleWeakAttribute(New, Attr);
1844    break;
1845  case AttributeList::AT_dllimport:
1846    HandleDLLImportAttribute(New, Attr);
1847    break;
1848  case AttributeList::AT_dllexport:
1849    HandleDLLExportAttribute(New, Attr);
1850    break;
1851  case AttributeList::AT_nothrow:
1852    HandleNothrowAttribute(New, Attr);
1853    break;
1854  case AttributeList::AT_stdcall:
1855    HandleStdCallAttribute(New, Attr);
1856    break;
1857  case AttributeList::AT_fastcall:
1858    HandleFastCallAttribute(New, Attr);
1859    break;
1860  case AttributeList::AT_aligned:
1861    HandleAlignedAttribute(New, Attr);
1862    break;
1863  case AttributeList::AT_packed:
1864    HandlePackedAttribute(New, Attr);
1865    break;
1866  case AttributeList::AT_annotate:
1867    HandleAnnotateAttribute(New, Attr);
1868    break;
1869  case AttributeList::AT_noreturn:
1870    HandleNoReturnAttribute(New, Attr);
1871    break;
1872  case AttributeList::AT_format:
1873    HandleFormatAttribute(New, Attr);
1874    break;
1875  default:
1876#if 0
1877    // TODO: when we have the full set of attributes, warn about unknown ones.
1878    Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1879         Attr->getName()->getName());
1880#endif
1881    break;
1882  }
1883}
1884
1885void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1886                                AttributeList *declarator_postfix) {
1887  while (declspec_prefix) {
1888    HandleDeclAttribute(New, declspec_prefix);
1889    declspec_prefix = declspec_prefix->getNext();
1890  }
1891  while (declarator_postfix) {
1892    HandleDeclAttribute(New, declarator_postfix);
1893    declarator_postfix = declarator_postfix->getNext();
1894  }
1895}
1896
1897void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1898                                        AttributeList *rawAttr) {
1899  QualType curType = tDecl->getUnderlyingType();
1900  // check the attribute arguments.
1901  if (rawAttr->getNumArgs() != 1) {
1902    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1903         std::string("1"));
1904    return;
1905  }
1906  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1907  llvm::APSInt vecSize(32);
1908  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1909    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
1910         "ocu_vector_type", sizeExpr->getSourceRange());
1911    return;
1912  }
1913  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1914  // in conjunction with complex types (pointers, arrays, functions, etc.).
1915  Type *canonType = curType.getCanonicalType().getTypePtr();
1916  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1917    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
1918         curType.getCanonicalType().getAsString());
1919    return;
1920  }
1921  // unlike gcc's vector_size attribute, the size is specified as the
1922  // number of elements, not the number of bytes.
1923  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1924
1925  if (vectorSize == 0) {
1926    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
1927         sizeExpr->getSourceRange());
1928    return;
1929  }
1930  // Instantiate/Install the vector type, the number of elements is > 0.
1931  tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1932  // Remember this typedef decl, we will need it later for diagnostics.
1933  OCUVectorDecls.push_back(tDecl);
1934}
1935
1936QualType Sema::HandleVectorTypeAttribute(QualType curType,
1937                                         AttributeList *rawAttr) {
1938  // check the attribute arugments.
1939  if (rawAttr->getNumArgs() != 1) {
1940    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1941         std::string("1"));
1942    return QualType();
1943  }
1944  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1945  llvm::APSInt vecSize(32);
1946  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1947    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
1948         "vector_size", sizeExpr->getSourceRange());
1949    return QualType();
1950  }
1951  // navigate to the base type - we need to provide for vector pointers,
1952  // vector arrays, and functions returning vectors.
1953  Type *canonType = curType.getCanonicalType().getTypePtr();
1954
1955  if (canonType->isPointerType() || canonType->isArrayType() ||
1956      canonType->isFunctionType()) {
1957    assert(0 && "HandleVector(): Complex type construction unimplemented");
1958    /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1959        do {
1960          if (PointerType *PT = dyn_cast<PointerType>(canonType))
1961            canonType = PT->getPointeeType().getTypePtr();
1962          else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1963            canonType = AT->getElementType().getTypePtr();
1964          else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1965            canonType = FT->getResultType().getTypePtr();
1966        } while (canonType->isPointerType() || canonType->isArrayType() ||
1967                 canonType->isFunctionType());
1968    */
1969  }
1970  // the base type must be integer or float.
1971  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1972    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
1973         curType.getCanonicalType().getAsString());
1974    return QualType();
1975  }
1976  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
1977  // vecSize is specified in bytes - convert to bits.
1978  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1979
1980  // the vector size needs to be an integral multiple of the type size.
1981  if (vectorSize % typeSize) {
1982    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
1983         sizeExpr->getSourceRange());
1984    return QualType();
1985  }
1986  if (vectorSize == 0) {
1987    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
1988         sizeExpr->getSourceRange());
1989    return QualType();
1990  }
1991  // Instantiate the vector type, the number of elements is > 0, and not
1992  // required to be a power of 2, unlike GCC.
1993  return Context.getVectorType(curType, vectorSize/typeSize);
1994}
1995
1996void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
1997  // check the attribute arguments.
1998  if (rawAttr->getNumArgs() > 0) {
1999    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2000         std::string("0"));
2001    return;
2002  }
2003
2004  if (TagDecl *TD = dyn_cast<TagDecl>(d))
2005    TD->addAttr(new PackedAttr);
2006  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2007    // If the alignment is less than or equal to 8 bits, the packed attribute
2008    // has no effect.
2009    if (Context.getTypeAlign(FD->getType()) <= 8)
2010      Diag(rawAttr->getLoc(),
2011           diag::warn_attribute_ignored_for_field_of_type,
2012           rawAttr->getName()->getName(), FD->getType().getAsString());
2013    else
2014      FD->addAttr(new PackedAttr);
2015  } else
2016    Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2017         rawAttr->getName()->getName());
2018}
2019
2020void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2021  // check the attribute arguments.
2022  if (rawAttr->getNumArgs() != 0) {
2023    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2024         std::string("0"));
2025    return;
2026  }
2027
2028  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2029
2030  if (!Fn) {
2031    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2032         "noreturn", "function");
2033    return;
2034  }
2035
2036  d->addAttr(new NoReturnAttr());
2037}
2038
2039void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2040  // check the attribute arguments.
2041  if (rawAttr->getNumArgs() != 0) {
2042    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2043         std::string("0"));
2044    return;
2045  }
2046
2047  d->addAttr(new DeprecatedAttr());
2048}
2049
2050void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2051  // check the attribute arguments.
2052  if (rawAttr->getNumArgs() != 1) {
2053    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2054         std::string("1"));
2055    return;
2056  }
2057
2058  Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2059  Arg = Arg->IgnoreParenCasts();
2060  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2061
2062  if (Str == 0 || Str->isWide()) {
2063    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2064         "visibility", std::string("1"));
2065    return;
2066  }
2067
2068  const char *TypeStr = Str->getStrData();
2069  unsigned TypeLen = Str->getByteLength();
2070  llvm::GlobalValue::VisibilityTypes type;
2071
2072  if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
2073    type = llvm::GlobalValue::DefaultVisibility;
2074  else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
2075    type = llvm::GlobalValue::HiddenVisibility;
2076  else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
2077    type = llvm::GlobalValue::HiddenVisibility; // FIXME
2078  else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
2079    type = llvm::GlobalValue::ProtectedVisibility;
2080  else {
2081    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2082           "visibility", TypeStr);
2083    return;
2084  }
2085
2086  d->addAttr(new VisibilityAttr(type));
2087}
2088
2089void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2090  // check the attribute arguments.
2091  if (rawAttr->getNumArgs() != 0) {
2092    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2093         std::string("0"));
2094    return;
2095  }
2096
2097  d->addAttr(new WeakAttr());
2098}
2099
2100void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2101  // check the attribute arguments.
2102  if (rawAttr->getNumArgs() != 0) {
2103    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2104         std::string("0"));
2105    return;
2106  }
2107
2108  d->addAttr(new DLLImportAttr());
2109}
2110
2111void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2112  // check the attribute arguments.
2113  if (rawAttr->getNumArgs() != 0) {
2114    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2115         std::string("0"));
2116    return;
2117  }
2118
2119  d->addAttr(new DLLExportAttr());
2120}
2121
2122void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2123  // check the attribute arguments.
2124  if (rawAttr->getNumArgs() != 0) {
2125    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2126         std::string("0"));
2127    return;
2128  }
2129
2130  d->addAttr(new StdCallAttr());
2131}
2132
2133void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2134  // check the attribute arguments.
2135  if (rawAttr->getNumArgs() != 0) {
2136    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2137         std::string("0"));
2138    return;
2139  }
2140
2141  d->addAttr(new FastCallAttr());
2142}
2143
2144void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2145  // check the attribute arguments.
2146  if (rawAttr->getNumArgs() != 0) {
2147    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2148         std::string("0"));
2149    return;
2150  }
2151
2152  d->addAttr(new NoThrowAttr());
2153}
2154
2155static const FunctionTypeProto *getFunctionProto(Decl *d) {
2156  ValueDecl *decl = dyn_cast<ValueDecl>(d);
2157  if (!decl) return 0;
2158
2159  QualType Ty = decl->getType();
2160
2161  if (Ty->isFunctionPointerType()) {
2162    const PointerType *PtrTy = Ty->getAsPointerType();
2163    Ty = PtrTy->getPointeeType();
2164  }
2165
2166  if (const FunctionType *FnTy = Ty->getAsFunctionType())
2167    return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2168
2169  return 0;
2170}
2171
2172
2173/// Handle __attribute__((format(type,idx,firstarg))) attributes
2174/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2175void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2176
2177  if (!rawAttr->getParameterName()) {
2178    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2179           "format", std::string("1"));
2180    return;
2181  }
2182
2183  if (rawAttr->getNumArgs() != 2) {
2184    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2185         std::string("3"));
2186    return;
2187  }
2188
2189  // GCC ignores the format attribute on K&R style function
2190  // prototypes, so we ignore it as well
2191  const FunctionTypeProto *proto = getFunctionProto(d);
2192
2193  if (!proto) {
2194    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2195           "format", "function");
2196    return;
2197  }
2198
2199  // FIXME: in C++ the implicit 'this' function parameter also counts.
2200  // this is needed in order to be compatible with GCC
2201  // the index must start in 1 and the limit is numargs+1
2202  unsigned NumArgs  = proto->getNumArgs();
2203  unsigned FirstIdx = 1;
2204
2205  const char *Format = rawAttr->getParameterName()->getName();
2206  unsigned FormatLen = rawAttr->getParameterName()->getLength();
2207
2208  // Normalize the argument, __foo__ becomes foo.
2209  if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2210      Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2211    Format += 2;
2212    FormatLen -= 4;
2213  }
2214
2215  if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2216     || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2217     || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2218     || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2219    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2220           "format", rawAttr->getParameterName()->getName());
2221    return;
2222  }
2223
2224  // checks for the 2nd argument
2225  Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
2226  llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
2227  if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2228    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2229           "format", std::string("2"), IdxExpr->getSourceRange());
2230    return;
2231  }
2232
2233  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2234    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2235           "format", std::string("2"), IdxExpr->getSourceRange());
2236    return;
2237  }
2238
2239  // make sure the format string is really a string
2240  QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2241  if (!Ty->isPointerType() ||
2242      !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2243    Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2244         IdxExpr->getSourceRange());
2245    return;
2246  }
2247
2248
2249  // check the 3rd argument
2250  Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
2251  llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
2252  if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2253    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2254           "format", std::string("3"), FirstArgExpr->getSourceRange());
2255    return;
2256  }
2257
2258  // check if the function is variadic if the 3rd argument non-zero
2259  if (FirstArg != 0) {
2260    if (proto->isVariadic()) {
2261      ++NumArgs; // +1 for ...
2262    } else {
2263      Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2264      return;
2265    }
2266  }
2267
2268  // strftime requires FirstArg to be 0 because it doesn't read from any variable
2269  // the input is just the current time + the format string
2270  if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
2271    if (FirstArg != 0) {
2272      Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2273             FirstArgExpr->getSourceRange());
2274      return;
2275    }
2276  // if 0 it disables parameter checking (to use with e.g. va_list)
2277  } else if (FirstArg != 0 && FirstArg != NumArgs) {
2278    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2279           "format", std::string("3"), FirstArgExpr->getSourceRange());
2280    return;
2281  }
2282
2283  d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2284                            Idx.getZExtValue(), FirstArg.getZExtValue()));
2285}
2286
2287void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2288  // check the attribute arguments.
2289  if (rawAttr->getNumArgs() != 1) {
2290    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2291         std::string("1"));
2292    return;
2293  }
2294  Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2295  StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
2296
2297  // Make sure that there is a string literal as the annotation's single
2298  // argument.
2299  if (!SE) {
2300    Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2301    return;
2302  }
2303  d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2304                                          SE->getByteLength())));
2305}
2306
2307void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2308{
2309  // check the attribute arguments.
2310  if (rawAttr->getNumArgs() > 1) {
2311    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2312         std::string("1"));
2313    return;
2314  }
2315
2316  unsigned Align = 0;
2317
2318  if (rawAttr->getNumArgs() == 0) {
2319    // FIXME: This should be the target specific maximum alignment.
2320    // (For now we just use 128 bits which is the maximum on X86.
2321    Align = 128;
2322    return;
2323  } else {
2324    Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2325    llvm::APSInt alignment(32);
2326    if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
2327      Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2328           "aligned", alignmentExpr->getSourceRange());
2329      return;
2330    }
2331
2332    Align = alignment.getZExtValue() * 8;
2333  }
2334
2335  d->addAttr(new AlignedAttr(Align));
2336}
2337