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