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