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