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