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