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