SemaDecl.cpp revision f3a41af4d5c98a72a1d6720bbbfd658e57ef2541
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/APValue.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
30Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
31                               const CXXScopeSpec *SS) {
32  DeclContext *DC = 0;
33  if (SS) {
34    if (SS->isInvalid())
35      return 0;
36    DC = static_cast<DeclContext*>(SS->getScopeRep());
37  }
38  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
39
40  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41                 isa<ObjCInterfaceDecl>(IIDecl) ||
42                 isa<TagDecl>(IIDecl)))
43    return IIDecl;
44  return 0;
45}
46
47DeclContext *Sema::getContainingDC(DeclContext *DC) {
48  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
49    // A C++ out-of-line method will return to the file declaration context.
50    if (MD->isOutOfLineDefinition())
51      return MD->getLexicalDeclContext();
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 lexically declared in.
57    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
58    DC = MD->getParent();
59    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
60      DC = RD;
61
62    // Return the declaration context of the topmost class the inline method is
63    // declared in.
64    return DC;
65  }
66
67  if (isa<ObjCMethodDecl>(DC))
68    return Context.getTranslationUnitDecl();
69
70  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
71    return SD->getLexicalDeclContext();
72
73  return DC->getLexicalParent();
74}
75
76void Sema::PushDeclContext(DeclContext *DC) {
77  assert(getContainingDC(DC) == CurContext &&
78       "The next DeclContext should be lexically contained in the current one.");
79  CurContext = DC;
80}
81
82void Sema::PopDeclContext() {
83  assert(CurContext && "DeclContext imbalance!");
84  CurContext = getContainingDC(CurContext);
85}
86
87/// Add this decl to the scope shadowed decl chains.
88void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
89  S->AddDecl(D);
90
91  // C++ [basic.scope]p4:
92  //   -- exactly one declaration shall declare a class name or
93  //   enumeration name that is not a typedef name and the other
94  //   declarations shall all refer to the same object or
95  //   enumerator, or all refer to functions and function templates;
96  //   in this case the class name or enumeration name is hidden.
97  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
98    // We are pushing the name of a tag (enum or class).
99    IdentifierResolver::iterator
100        I = IdResolver.begin(TD->getIdentifier(),
101                             TD->getDeclContext(), false/*LookInParentCtx*/);
102    if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
103      // There is already a declaration with the same name in the same
104      // scope. It must be found before we find the new declaration,
105      // so swap the order on the shadowed declaration chain.
106
107      IdResolver.AddShadowedDecl(TD, *I);
108      return;
109    }
110  } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
111    FunctionDecl *FD = cast<FunctionDecl>(D);
112    // We are pushing the name of a function, which might be an
113    // overloaded name.
114    IdentifierResolver::iterator
115        I = IdResolver.begin(FD->getDeclName(),
116                             FD->getDeclContext(), false/*LookInParentCtx*/);
117    if (I != IdResolver.end() &&
118        IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
119        (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
120      // There is already a declaration with the same name in the same
121      // scope. It must be a function or an overloaded function.
122      OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
123      if (!Ovl) {
124        // We haven't yet overloaded this function. Take the existing
125        // FunctionDecl and put it into an OverloadedFunctionDecl.
126        Ovl = OverloadedFunctionDecl::Create(Context,
127                                             FD->getDeclContext(),
128                                             FD->getDeclName());
129        Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
130
131        // Remove the name binding to the existing FunctionDecl...
132        IdResolver.RemoveDecl(*I);
133
134        // ... and put the OverloadedFunctionDecl in its place.
135        IdResolver.AddDecl(Ovl);
136      }
137
138      // We have an OverloadedFunctionDecl. Add the new FunctionDecl
139      // to its list of overloads.
140      Ovl->addOverload(FD);
141
142      return;
143    }
144  }
145
146  IdResolver.AddDecl(D);
147}
148
149void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
150  if (S->decl_empty()) return;
151  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
152
153  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
154       I != E; ++I) {
155    Decl *TmpD = static_cast<Decl*>(*I);
156    assert(TmpD && "This decl didn't get pushed??");
157
158    if (isa<CXXFieldDecl>(TmpD)) continue;
159
160    assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
161    ScopedDecl *D = cast<ScopedDecl>(TmpD);
162
163    IdentifierInfo *II = D->getIdentifier();
164    if (!II) continue;
165
166    // We only want to remove the decls from the identifier decl chains for
167    // local scopes, when inside a function/method.
168    if (S->getFnParent() != 0)
169      IdResolver.RemoveDecl(D);
170
171    // Chain this decl to the containing DeclContext.
172    D->setNext(CurContext->getDeclChain());
173    CurContext->setDeclChain(D);
174  }
175}
176
177/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
178/// return 0 if one not found.
179ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
180  // The third "scope" argument is 0 since we aren't enabling lazy built-in
181  // creation from this context.
182  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
183
184  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
185}
186
187/// LookupDecl - Look up the inner-most declaration in the specified
188/// namespace.
189Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
190                       const DeclContext *LookupCtx,
191                       bool enableLazyBuiltinCreation) {
192  if (!Name) return 0;
193  unsigned NS = NSI;
194  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
195    NS |= Decl::IDNS_Tag;
196
197  IdentifierResolver::iterator
198    I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
199                  : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
200  // Scan up the scope chain looking for a decl that matches this identifier
201  // that is in the appropriate namespace.  This search should not take long, as
202  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
203  for (; I != IdResolver.end(); ++I)
204    if ((*I)->getIdentifierNamespace() & NS)
205      return *I;
206
207  // If we didn't find a use of this identifier, and if the identifier
208  // corresponds to a compiler builtin, create the decl object for the builtin
209  // now, injecting it into translation unit scope, and return it.
210  if (NS & Decl::IDNS_Ordinary) {
211    IdentifierInfo *II = Name.getAsIdentifierInfo();
212    if (enableLazyBuiltinCreation && II &&
213        (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
214      // If this is a builtin on this (or all) targets, create the decl.
215      if (unsigned BuiltinID = II->getBuiltinID())
216        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217    }
218    if (getLangOptions().ObjC1 && II) {
219      // @interface and @compatibility_alias introduce typedef-like names.
220      // Unlike typedef's, they can only be introduced at file-scope (and are
221      // therefore not scoped decls). They can, however, be shadowed by
222      // other names in IDNS_Ordinary.
223      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224      if (IDI != ObjCInterfaceDecls.end())
225        return IDI->second;
226      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227      if (I != ObjCAliasDecls.end())
228        return I->second->getClassInterface();
229    }
230  }
231  return 0;
232}
233
234void Sema::InitBuiltinVaListType() {
235  if (!Context.getBuiltinVaListType().isNull())
236    return;
237
238  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
239  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
240  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
241  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247                                      Scope *S) {
248  Builtin::ID BID = (Builtin::ID)bid;
249
250  if (Context.BuiltinInfo.hasVAListUse(BID))
251    InitBuiltinVaListType();
252
253  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
254  FunctionDecl *New = FunctionDecl::Create(Context,
255                                           Context.getTranslationUnitDecl(),
256                                           SourceLocation(), II, R,
257                                           FunctionDecl::Extern, false, 0);
258
259  // Create Decl objects for each parameter, adding them to the
260  // FunctionDecl.
261  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262    llvm::SmallVector<ParmVarDecl*, 16> Params;
263    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265                                           FT->getArgType(i), VarDecl::None, 0,
266                                           0));
267    New->setParams(&Params[0], Params.size());
268  }
269
270
271
272  // TUScope is the translation-unit scope to insert this function into.
273  PushOnScopeChains(New, TUScope);
274  return New;
275}
276
277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280  if (!StdNamespace) {
281    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
282    DeclContext *Global = Context.getTranslationUnitDecl();
283    Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
284                           0, Global, /*enableLazyBuiltinCreation=*/false);
285    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
286  }
287  return StdNamespace;
288}
289
290/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
291/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
292/// situation, merging decls or emitting diagnostics as appropriate.
293///
294TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
295  // Allow multiple definitions for ObjC built-in typedefs.
296  // FIXME: Verify the underlying types are equivalent!
297  if (getLangOptions().ObjC1) {
298    const IdentifierInfo *TypeID = New->getIdentifier();
299    switch (TypeID->getLength()) {
300    default: break;
301    case 2:
302      if (!TypeID->isStr("id"))
303        break;
304      Context.setObjCIdType(New);
305      return New;
306    case 5:
307      if (!TypeID->isStr("Class"))
308        break;
309      Context.setObjCClassType(New);
310      return New;
311    case 3:
312      if (!TypeID->isStr("SEL"))
313        break;
314      Context.setObjCSelType(New);
315      return New;
316    case 8:
317      if (!TypeID->isStr("Protocol"))
318        break;
319      Context.setObjCProtoType(New->getUnderlyingType());
320      return New;
321    }
322    // Fall through - the typedef name was not a builtin type.
323  }
324  // Verify the old decl was also a typedef.
325  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
326  if (!Old) {
327    Diag(New->getLocation(), diag::err_redefinition_different_kind)
328      << New->getName();
329    Diag(OldD->getLocation(), diag::err_previous_definition);
330    return New;
331  }
332
333  // If the typedef types are not identical, reject them in all languages and
334  // with any extensions enabled.
335  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
336      Context.getCanonicalType(Old->getUnderlyingType()) !=
337      Context.getCanonicalType(New->getUnderlyingType())) {
338    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
339      << New->getUnderlyingType().getAsString()
340      << Old->getUnderlyingType().getAsString();
341    Diag(Old->getLocation(), diag::err_previous_definition);
342    return Old;
343  }
344
345  if (getLangOptions().Microsoft) return New;
346
347  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
348  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
349  // *either* declaration is in a system header. The code below implements
350  // this adhoc compatibility rule. FIXME: The following code will not
351  // work properly when compiling ".i" files (containing preprocessed output).
352  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
353    SourceManager &SrcMgr = Context.getSourceManager();
354    if (SrcMgr.isInSystemHeader(Old->getLocation()))
355      return New;
356    if (SrcMgr.isInSystemHeader(New->getLocation()))
357      return New;
358  }
359
360  Diag(New->getLocation(), diag::err_redefinition) << New->getName();
361  Diag(Old->getLocation(), diag::err_previous_definition);
362  return New;
363}
364
365/// DeclhasAttr - returns true if decl Declaration already has the target
366/// attribute.
367static bool DeclHasAttr(const Decl *decl, const Attr *target) {
368  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
369    if (attr->getKind() == target->getKind())
370      return true;
371
372  return false;
373}
374
375/// MergeAttributes - append attributes from the Old decl to the New one.
376static void MergeAttributes(Decl *New, Decl *Old) {
377  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
378
379  while (attr) {
380     tmp = attr;
381     attr = attr->getNext();
382
383    if (!DeclHasAttr(New, tmp)) {
384       New->addAttr(tmp);
385    } else {
386       tmp->setNext(0);
387       delete(tmp);
388    }
389  }
390
391  Old->invalidateAttrs();
392}
393
394/// MergeFunctionDecl - We just parsed a function 'New' from
395/// declarator D which has the same name and scope as a previous
396/// declaration 'Old'.  Figure out how to resolve this situation,
397/// merging decls or emitting diagnostics as appropriate.
398/// Redeclaration will be set true if this New is a redeclaration OldD.
399///
400/// In C++, New and Old must be declarations that are not
401/// overloaded. Use IsOverload to determine whether New and Old are
402/// overloaded, and to select the Old declaration that New should be
403/// merged with.
404FunctionDecl *
405Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
406  assert(!isa<OverloadedFunctionDecl>(OldD) &&
407         "Cannot merge with an overloaded function declaration");
408
409  Redeclaration = false;
410  // Verify the old decl was also a function.
411  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
412  if (!Old) {
413    Diag(New->getLocation(), diag::err_redefinition_different_kind)
414      << New->getName();
415    Diag(OldD->getLocation(), diag::err_previous_definition);
416    return New;
417  }
418
419  // Determine whether the previous declaration was a definition,
420  // implicit declaration, or a declaration.
421  diag::kind PrevDiag;
422  if (Old->isThisDeclarationADefinition())
423    PrevDiag = diag::err_previous_definition;
424  else if (Old->isImplicit())
425    PrevDiag = diag::err_previous_implicit_declaration;
426  else
427    PrevDiag = diag::err_previous_declaration;
428
429  QualType OldQType = Context.getCanonicalType(Old->getType());
430  QualType NewQType = Context.getCanonicalType(New->getType());
431
432  if (getLangOptions().CPlusPlus) {
433    // (C++98 13.1p2):
434    //   Certain function declarations cannot be overloaded:
435    //     -- Function declarations that differ only in the return type
436    //        cannot be overloaded.
437    QualType OldReturnType
438      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
439    QualType NewReturnType
440      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
441    if (OldReturnType != NewReturnType) {
442      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
443      Diag(Old->getLocation(), PrevDiag);
444      return New;
445    }
446
447    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
448    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
449    if (OldMethod && NewMethod) {
450      //    -- Member function declarations with the same name and the
451      //       same parameter types cannot be overloaded if any of them
452      //       is a static member function declaration.
453      if (OldMethod->isStatic() || NewMethod->isStatic()) {
454        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
455        Diag(Old->getLocation(), PrevDiag);
456        return New;
457      }
458    }
459
460    // (C++98 8.3.5p3):
461    //   All declarations for a function shall agree exactly in both the
462    //   return type and the parameter-type-list.
463    if (OldQType == NewQType) {
464      // We have a redeclaration.
465      MergeAttributes(New, Old);
466      Redeclaration = true;
467      return MergeCXXFunctionDecl(New, Old);
468    }
469
470    // Fall through for conflicting redeclarations and redefinitions.
471  }
472
473  // C: Function types need to be compatible, not identical. This handles
474  // duplicate function decls like "void f(int); void f(enum X);" properly.
475  if (!getLangOptions().CPlusPlus &&
476      Context.typesAreCompatible(OldQType, NewQType)) {
477    MergeAttributes(New, Old);
478    Redeclaration = true;
479    return New;
480  }
481
482  // A function that has already been declared has been redeclared or defined
483  // with a different type- show appropriate diagnostic
484
485  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
486  // TODO: This is totally simplistic.  It should handle merging functions
487  // together etc, merging extern int X; int X; ...
488  Diag(New->getLocation(), diag::err_conflicting_types) << New->getName();
489  Diag(Old->getLocation(), PrevDiag);
490  return New;
491}
492
493/// Predicate for C "tentative" external object definitions (C99 6.9.2).
494static bool isTentativeDefinition(VarDecl *VD) {
495  if (VD->isFileVarDecl())
496    return (!VD->getInit() &&
497            (VD->getStorageClass() == VarDecl::None ||
498             VD->getStorageClass() == VarDecl::Static));
499  return false;
500}
501
502/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
503/// when dealing with C "tentative" external object definitions (C99 6.9.2).
504void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
505  bool VDIsTentative = isTentativeDefinition(VD);
506  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
507
508  for (IdentifierResolver::iterator
509       I = IdResolver.begin(VD->getIdentifier(),
510                            VD->getDeclContext(), false/*LookInParentCtx*/),
511       E = IdResolver.end(); I != E; ++I) {
512    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
513      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
514
515      // Handle the following case:
516      //   int a[10];
517      //   int a[];   - the code below makes sure we set the correct type.
518      //   int a[11]; - this is an error, size isn't 10.
519      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
520          OldDecl->getType()->isConstantArrayType())
521        VD->setType(OldDecl->getType());
522
523      // Check for "tentative" definitions. We can't accomplish this in
524      // MergeVarDecl since the initializer hasn't been attached.
525      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
526        continue;
527
528      // Handle __private_extern__ just like extern.
529      if (OldDecl->getStorageClass() != VarDecl::Extern &&
530          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
531          VD->getStorageClass() != VarDecl::Extern &&
532          VD->getStorageClass() != VarDecl::PrivateExtern) {
533        Diag(VD->getLocation(), diag::err_redefinition) << VD->getName();
534        Diag(OldDecl->getLocation(), diag::err_previous_definition);
535      }
536    }
537  }
538}
539
540/// MergeVarDecl - We just parsed a variable 'New' which has the same name
541/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
542/// situation, merging decls or emitting diagnostics as appropriate.
543///
544/// Tentative definition rules (C99 6.9.2p2) are checked by
545/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
546/// definitions here, since the initializer hasn't been attached.
547///
548VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
549  // Verify the old decl was also a variable.
550  VarDecl *Old = dyn_cast<VarDecl>(OldD);
551  if (!Old) {
552    Diag(New->getLocation(), diag::err_redefinition_different_kind)
553      << New->getName();
554    Diag(OldD->getLocation(), diag::err_previous_definition);
555    return New;
556  }
557
558  MergeAttributes(New, Old);
559
560  // Verify the types match.
561  QualType OldCType = Context.getCanonicalType(Old->getType());
562  QualType NewCType = Context.getCanonicalType(New->getType());
563  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
564    Diag(New->getLocation(), diag::err_redefinition) << New->getName();
565    Diag(Old->getLocation(), diag::err_previous_definition);
566    return New;
567  }
568  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
569  if (New->getStorageClass() == VarDecl::Static &&
570      (Old->getStorageClass() == VarDecl::None ||
571       Old->getStorageClass() == VarDecl::Extern)) {
572    Diag(New->getLocation(), diag::err_static_non_static) << New->getName();
573    Diag(Old->getLocation(), diag::err_previous_definition);
574    return New;
575  }
576  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
577  if (New->getStorageClass() != VarDecl::Static &&
578      Old->getStorageClass() == VarDecl::Static) {
579    Diag(New->getLocation(), diag::err_non_static_static) << New->getName();
580    Diag(Old->getLocation(), diag::err_previous_definition);
581    return New;
582  }
583  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
584  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
585    Diag(New->getLocation(), diag::err_redefinition) << New->getName();
586    Diag(Old->getLocation(), diag::err_previous_definition);
587  }
588  return New;
589}
590
591/// CheckParmsForFunctionDef - Check that the parameters of the given
592/// function are appropriate for the definition of a function. This
593/// takes care of any checks that cannot be performed on the
594/// declaration itself, e.g., that the types of each of the function
595/// parameters are complete.
596bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
597  bool HasInvalidParm = false;
598  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
599    ParmVarDecl *Param = FD->getParamDecl(p);
600
601    // C99 6.7.5.3p4: the parameters in a parameter type list in a
602    // function declarator that is part of a function definition of
603    // that function shall not have incomplete type.
604    if (Param->getType()->isIncompleteType() &&
605        !Param->isInvalidDecl()) {
606      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
607        << Param->getType().getAsString();
608      Param->setInvalidDecl();
609      HasInvalidParm = true;
610    }
611  }
612
613  return HasInvalidParm;
614}
615
616/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
617/// no declarator (e.g. "struct foo;") is parsed.
618Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
619  // TODO: emit error on 'int;' or 'const enum foo;'.
620  // TODO: emit error on 'typedef int;'
621  // if (!DS.isMissingDeclaratorOk()) Diag(...);
622
623  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
624}
625
626bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
627  // Get the type before calling CheckSingleAssignmentConstraints(), since
628  // it can promote the expression.
629  QualType InitType = Init->getType();
630
631  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
632  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
633                                  InitType, Init, "initializing");
634}
635
636bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
637  const ArrayType *AT = Context.getAsArrayType(DeclT);
638
639  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
640    // C99 6.7.8p14. We have an array of character type with unknown size
641    // being initialized to a string literal.
642    llvm::APSInt ConstVal(32);
643    ConstVal = strLiteral->getByteLength() + 1;
644    // Return a new array type (C99 6.7.8p22).
645    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
646                                         ArrayType::Normal, 0);
647  } else {
648    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
649    // C99 6.7.8p14. We have an array of character type with known size.
650    // FIXME: Avoid truncation for 64-bit length strings.
651    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
652      Diag(strLiteral->getSourceRange().getBegin(),
653           diag::warn_initializer_string_for_char_array_too_long)
654        << strLiteral->getSourceRange();
655  }
656  // Set type from "char *" to "constant array of char".
657  strLiteral->setType(DeclT);
658  // For now, we always return false (meaning success).
659  return false;
660}
661
662StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
663  const ArrayType *AT = Context.getAsArrayType(DeclType);
664  if (AT && AT->getElementType()->isCharType()) {
665    return dyn_cast<StringLiteral>(Init);
666  }
667  return 0;
668}
669
670bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
671                                 SourceLocation InitLoc,
672                                 std::string InitEntity) {
673  // C++ [dcl.init.ref]p1:
674  //   A variable declared to be a T&, that is “reference to type T”
675  //   (8.3.2), shall be initialized by an object, or function, of
676  //   type T or by an object that can be converted into a T.
677  if (DeclType->isReferenceType())
678    return CheckReferenceInit(Init, DeclType);
679
680  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
681  // of unknown size ("[]") or an object type that is not a variable array type.
682  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
683    return Diag(InitLoc,  diag::err_variable_object_no_init)
684      << VAT->getSizeExpr()->getSourceRange();
685
686  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
687  if (!InitList) {
688    // FIXME: Handle wide strings
689    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
690      return CheckStringLiteralInit(strLiteral, DeclType);
691
692    // C++ [dcl.init]p14:
693    //   -- If the destination type is a (possibly cv-qualified) class
694    //      type:
695    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
696      QualType DeclTypeC = Context.getCanonicalType(DeclType);
697      QualType InitTypeC = Context.getCanonicalType(Init->getType());
698
699      //   -- If the initialization is direct-initialization, or if it is
700      //      copy-initialization where the cv-unqualified version of the
701      //      source type is the same class as, or a derived class of, the
702      //      class of the destination, constructors are considered.
703      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
704          IsDerivedFrom(InitTypeC, DeclTypeC)) {
705        CXXConstructorDecl *Constructor
706          = PerformInitializationByConstructor(DeclType, &Init, 1,
707                                               InitLoc, Init->getSourceRange(),
708                                               InitEntity, IK_Copy);
709        return Constructor == 0;
710      }
711
712      //   -- Otherwise (i.e., for the remaining copy-initialization
713      //      cases), user-defined conversion sequences that can
714      //      convert from the source type to the destination type or
715      //      (when a conversion function is used) to a derived class
716      //      thereof are enumerated as described in 13.3.1.4, and the
717      //      best one is chosen through overload resolution
718      //      (13.3). If the conversion cannot be done or is
719      //      ambiguous, the initialization is ill-formed. The
720      //      function selected is called with the initializer
721      //      expression as its argument; if the function is a
722      //      constructor, the call initializes a temporary of the
723      //      destination type.
724      // FIXME: We're pretending to do copy elision here; return to
725      // this when we have ASTs for such things.
726      if (!PerformImplicitConversion(Init, DeclType))
727        return false;
728
729      return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
730        << DeclType.getAsString() << InitEntity << "initializing"
731        << Init->getSourceRange();
732    }
733
734    // C99 6.7.8p16.
735    if (DeclType->isArrayType())
736      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
737        << Init->getSourceRange();
738
739    return CheckSingleInitializer(Init, DeclType);
740  } else if (getLangOptions().CPlusPlus) {
741    // C++ [dcl.init]p14:
742    //   [...] If the class is an aggregate (8.5.1), and the initializer
743    //   is a brace-enclosed list, see 8.5.1.
744    //
745    // Note: 8.5.1 is handled below; here, we diagnose the case where
746    // we have an initializer list and a destination type that is not
747    // an aggregate.
748    // FIXME: In C++0x, this is yet another form of initialization.
749    if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
750      const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
751      if (!ClassDecl->isAggregate())
752        return Diag(InitLoc, diag::err_init_non_aggr_init_list)
753           << DeclType.getAsString() << Init->getSourceRange();
754    }
755  }
756
757  InitListChecker CheckInitList(this, InitList, DeclType);
758  return CheckInitList.HadError();
759}
760
761/// GetNameForDeclarator - Determine the full declaration name for the
762/// given Declarator.
763DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
764  switch (D.getKind()) {
765  case Declarator::DK_Abstract:
766    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
767    return DeclarationName();
768
769  case Declarator::DK_Normal:
770    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
771    return DeclarationName(D.getIdentifier());
772
773  case Declarator::DK_Constructor: {
774    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
775    Ty = Context.getCanonicalType(Ty);
776    return Context.DeclarationNames.getCXXConstructorName(Ty);
777  }
778
779  case Declarator::DK_Destructor: {
780    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
781    Ty = Context.getCanonicalType(Ty);
782    return Context.DeclarationNames.getCXXDestructorName(Ty);
783  }
784
785  case Declarator::DK_Conversion: {
786    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
787    Ty = Context.getCanonicalType(Ty);
788    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
789  }
790
791  case Declarator::DK_Operator:
792    assert(D.getIdentifier() == 0 && "operator names have no identifier");
793    return Context.DeclarationNames.getCXXOperatorName(
794                                                D.getOverloadedOperator());
795  }
796
797  assert(false && "Unknown name kind");
798  return DeclarationName();
799}
800
801Sema::DeclTy *
802Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
803  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
804  DeclarationName Name = GetNameForDeclarator(D);
805
806  // All of these full declarators require an identifier.  If it doesn't have
807  // one, the ParsedFreeStandingDeclSpec action should be used.
808  if (!Name) {
809    if (!D.getInvalidType())  // Reject this if we think it is valid.
810      Diag(D.getDeclSpec().getSourceRange().getBegin(),
811           diag::err_declarator_need_ident)
812        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
813    return 0;
814  }
815
816  // The scope passed in may not be a decl scope.  Zip up the scope tree until
817  // we find one that is.
818  while ((S->getFlags() & Scope::DeclScope) == 0)
819    S = S->getParent();
820
821  DeclContext *DC;
822  Decl *PrevDecl;
823  ScopedDecl *New;
824  bool InvalidDecl = false;
825
826  // See if this is a redefinition of a variable in the same scope.
827  if (!D.getCXXScopeSpec().isSet()) {
828    DC = CurContext;
829    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
830  } else { // Something like "int foo::x;"
831    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
832    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
833
834    // C++ 7.3.1.2p2:
835    // Members (including explicit specializations of templates) of a named
836    // namespace can also be defined outside that namespace by explicit
837    // qualification of the name being defined, provided that the entity being
838    // defined was already declared in the namespace and the definition appears
839    // after the point of declaration in a namespace that encloses the
840    // declarations namespace.
841    //
842    if (PrevDecl == 0) {
843      // No previous declaration in the qualifying scope.
844      Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
845        << Name.getAsString() << D.getCXXScopeSpec().getRange();
846    } else if (!CurContext->Encloses(DC)) {
847      // The qualifying scope doesn't enclose the original declaration.
848      // Emit diagnostic based on current scope.
849      SourceLocation L = D.getIdentifierLoc();
850      SourceRange R = D.getCXXScopeSpec().getRange();
851      if (isa<FunctionDecl>(CurContext)) {
852        Diag(L, diag::err_invalid_declarator_in_function)
853          << Name.getAsString() << R;
854      } else {
855      Diag(L, diag::err_invalid_declarator_scope)
856          << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R;
857      }
858    }
859  }
860
861  // In C++, the previous declaration we find might be a tag type
862  // (class or enum). In this case, the new declaration will hide the
863  // tag type.
864  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
865    PrevDecl = 0;
866
867  QualType R = GetTypeForDeclarator(D, S);
868  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
869
870  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
871    // Check that there are no default arguments (C++ only).
872    if (getLangOptions().CPlusPlus)
873      CheckExtraCXXDefaultArguments(D);
874
875    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
876    if (!NewTD) return 0;
877
878    // Handle attributes prior to checking for duplicates in MergeVarDecl
879    ProcessDeclAttributes(NewTD, D);
880    // Merge the decl with the existing one if appropriate. If the decl is
881    // in an outer scope, it isn't the same thing.
882    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
883      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
884      if (NewTD == 0) return 0;
885    }
886    New = NewTD;
887    if (S->getFnParent() == 0) {
888      // C99 6.7.7p2: If a typedef name specifies a variably modified type
889      // then it shall have block scope.
890      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
891        // FIXME: Diagnostic needs to be fixed.
892        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
893        InvalidDecl = true;
894      }
895    }
896  } else if (R.getTypePtr()->isFunctionType()) {
897    FunctionDecl::StorageClass SC = FunctionDecl::None;
898    switch (D.getDeclSpec().getStorageClassSpec()) {
899      default: assert(0 && "Unknown storage class!");
900      case DeclSpec::SCS_auto:
901      case DeclSpec::SCS_register:
902      case DeclSpec::SCS_mutable:
903        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func)
904          << R.getAsString();
905        InvalidDecl = true;
906        break;
907      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
908      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
909      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
910      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
911    }
912
913    bool isInline = D.getDeclSpec().isInlineSpecified();
914    // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
915    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
916
917    FunctionDecl *NewFD;
918    if (D.getKind() == Declarator::DK_Constructor) {
919      // This is a C++ constructor declaration.
920      assert(DC->isCXXRecord() &&
921             "Constructors can only be declared in a member context");
922
923      bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
924
925      // Create the new declaration
926      NewFD = CXXConstructorDecl::Create(Context,
927                                         cast<CXXRecordDecl>(DC),
928                                         D.getIdentifierLoc(), Name, R,
929                                         isExplicit, isInline,
930                                         /*isImplicitlyDeclared=*/false);
931
932      if (isInvalidDecl)
933        NewFD->setInvalidDecl();
934    } else if (D.getKind() == Declarator::DK_Destructor) {
935      // This is a C++ destructor declaration.
936      if (DC->isCXXRecord()) {
937        bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
938
939        NewFD = CXXDestructorDecl::Create(Context,
940                                          cast<CXXRecordDecl>(DC),
941                                          D.getIdentifierLoc(), Name, R,
942                                          isInline,
943                                          /*isImplicitlyDeclared=*/false);
944
945        if (isInvalidDecl)
946          NewFD->setInvalidDecl();
947      } else {
948        Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
949        // Create a FunctionDecl to satisfy the function definition parsing
950        // code path.
951        NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
952                                     Name, R, SC, isInline, LastDeclarator,
953                                     // FIXME: Move to DeclGroup...
954                                   D.getDeclSpec().getSourceRange().getBegin());
955        NewFD->setInvalidDecl();
956      }
957    } else if (D.getKind() == Declarator::DK_Conversion) {
958      if (!DC->isCXXRecord()) {
959        Diag(D.getIdentifierLoc(),
960             diag::err_conv_function_not_member);
961        return 0;
962      } else {
963        bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
964
965        NewFD = CXXConversionDecl::Create(Context,
966                                          cast<CXXRecordDecl>(DC),
967                                          D.getIdentifierLoc(), Name, R,
968                                          isInline, isExplicit);
969
970        if (isInvalidDecl)
971          NewFD->setInvalidDecl();
972      }
973    } else if (DC->isCXXRecord()) {
974      // This is a C++ method declaration.
975      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
976                                    D.getIdentifierLoc(), Name, R,
977                                    (SC == FunctionDecl::Static), isInline,
978                                    LastDeclarator);
979    } else {
980      NewFD = FunctionDecl::Create(Context, DC,
981                                   D.getIdentifierLoc(),
982                                   Name, R, SC, isInline, LastDeclarator,
983                                   // FIXME: Move to DeclGroup...
984                                   D.getDeclSpec().getSourceRange().getBegin());
985    }
986    // Handle attributes.
987    ProcessDeclAttributes(NewFD, D);
988
989    // Handle GNU asm-label extension (encoded as an attribute).
990    if (Expr *E = (Expr*) D.getAsmLabel()) {
991      // The parser guarantees this is a string.
992      StringLiteral *SE = cast<StringLiteral>(E);
993      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
994                                                  SE->getByteLength())));
995    }
996
997    // Copy the parameter declarations from the declarator D to
998    // the function declaration NewFD, if they are available.
999    if (D.getNumTypeObjects() > 0) {
1000      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1001
1002      // Create Decl objects for each parameter, adding them to the
1003      // FunctionDecl.
1004      llvm::SmallVector<ParmVarDecl*, 16> Params;
1005
1006      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1007      // function that takes no arguments, not a function that takes a
1008      // single void argument.
1009      // We let through "const void" here because Sema::GetTypeForDeclarator
1010      // already checks for that case.
1011      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1012          FTI.ArgInfo[0].Param &&
1013          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1014        // empty arg list, don't push any params.
1015        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1016
1017        // In C++, the empty parameter-type-list must be spelled "void"; a
1018        // typedef of void is not permitted.
1019        if (getLangOptions().CPlusPlus &&
1020            Param->getType().getUnqualifiedType() != Context.VoidTy) {
1021          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1022        }
1023      } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1024        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1025          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1026      }
1027
1028      NewFD->setParams(&Params[0], Params.size());
1029    } else if (R->getAsTypedefType()) {
1030      // When we're declaring a function with a typedef, as in the
1031      // following example, we'll need to synthesize (unnamed)
1032      // parameters for use in the declaration.
1033      //
1034      // @code
1035      // typedef void fn(int);
1036      // fn f;
1037      // @endcode
1038      const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1039      if (!FT) {
1040        // This is a typedef of a function with no prototype, so we
1041        // don't need to do anything.
1042      } else if ((FT->getNumArgs() == 0) ||
1043          (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1044           FT->getArgType(0)->isVoidType())) {
1045        // This is a zero-argument function. We don't need to do anything.
1046      } else {
1047        // Synthesize a parameter for each argument type.
1048        llvm::SmallVector<ParmVarDecl*, 16> Params;
1049        for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1050             ArgType != FT->arg_type_end(); ++ArgType) {
1051          Params.push_back(ParmVarDecl::Create(Context, DC,
1052                                               SourceLocation(), 0,
1053                                               *ArgType, VarDecl::None,
1054                                               0, 0));
1055        }
1056
1057        NewFD->setParams(&Params[0], Params.size());
1058      }
1059    }
1060
1061    // C++ constructors and destructors are handled by separate
1062    // routines, since they don't require any declaration merging (C++
1063    // [class.mfct]p2) and they aren't ever pushed into scope, because
1064    // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1065    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1066      return ActOnConstructorDeclarator(Constructor);
1067    else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1068      return ActOnDestructorDeclarator(Destructor);
1069
1070    // Extra checking for conversion functions, including recording
1071    // the conversion function in its class.
1072    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1073      ActOnConversionDeclarator(Conversion);
1074
1075    // Extra checking for C++ overloaded operators (C++ [over.oper]).
1076    if (NewFD->isOverloadedOperator() &&
1077        CheckOverloadedOperatorDeclaration(NewFD))
1078      NewFD->setInvalidDecl();
1079
1080    // Merge the decl with the existing one if appropriate. Since C functions
1081    // are in a flat namespace, make sure we consider decls in outer scopes.
1082    if (PrevDecl &&
1083        (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1084      bool Redeclaration = false;
1085
1086      // If C++, determine whether NewFD is an overload of PrevDecl or
1087      // a declaration that requires merging. If it's an overload,
1088      // there's no more work to do here; we'll just add the new
1089      // function to the scope.
1090      OverloadedFunctionDecl::function_iterator MatchedDecl;
1091      if (!getLangOptions().CPlusPlus ||
1092          !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1093        Decl *OldDecl = PrevDecl;
1094
1095        // If PrevDecl was an overloaded function, extract the
1096        // FunctionDecl that matched.
1097        if (isa<OverloadedFunctionDecl>(PrevDecl))
1098          OldDecl = *MatchedDecl;
1099
1100        // NewFD and PrevDecl represent declarations that need to be
1101        // merged.
1102        NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1103
1104        if (NewFD == 0) return 0;
1105        if (Redeclaration) {
1106          NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1107
1108          if (OldDecl == PrevDecl) {
1109            // Remove the name binding for the previous
1110            // declaration. We'll add the binding back later, but then
1111            // it will refer to the new declaration (which will
1112            // contain more information).
1113            IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1114          } else {
1115            // We need to update the OverloadedFunctionDecl with the
1116            // latest declaration of this function, so that name
1117            // lookup will always refer to the latest declaration of
1118            // this function.
1119            *MatchedDecl = NewFD;
1120
1121            // Add the redeclaration to the current scope, since we'll
1122            // be skipping PushOnScopeChains.
1123            S->AddDecl(NewFD);
1124
1125            return NewFD;
1126          }
1127        }
1128      }
1129    }
1130    New = NewFD;
1131
1132    // In C++, check default arguments now that we have merged decls.
1133    if (getLangOptions().CPlusPlus)
1134      CheckCXXDefaultArguments(NewFD);
1135  } else {
1136    // Check that there are no default arguments (C++ only).
1137    if (getLangOptions().CPlusPlus)
1138      CheckExtraCXXDefaultArguments(D);
1139
1140    if (R.getTypePtr()->isObjCInterfaceType()) {
1141      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1142        << D.getIdentifier();
1143      InvalidDecl = true;
1144    }
1145
1146    VarDecl *NewVD;
1147    VarDecl::StorageClass SC;
1148    switch (D.getDeclSpec().getStorageClassSpec()) {
1149    default: assert(0 && "Unknown storage class!");
1150    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1151    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1152    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1153    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1154    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1155    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1156    case DeclSpec::SCS_mutable:
1157      // mutable can only appear on non-static class members, so it's always
1158      // an error here
1159      Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1160      InvalidDecl = true;
1161      break;
1162    }
1163
1164    IdentifierInfo *II = Name.getAsIdentifierInfo();
1165    if (!II) {
1166      Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1167       << Name.getAsString();
1168      return 0;
1169    }
1170
1171    if (DC->isCXXRecord()) {
1172      assert(SC == VarDecl::Static && "Invalid storage class for member!");
1173      // This is a static data member for a C++ class.
1174      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1175                                      D.getIdentifierLoc(), II,
1176                                      R, LastDeclarator);
1177    } else {
1178      bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1179      if (S->getFnParent() == 0) {
1180        // C99 6.9p2: The storage-class specifiers auto and register shall not
1181        // appear in the declaration specifiers in an external declaration.
1182        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1183          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope)
1184            << R.getAsString();
1185          InvalidDecl = true;
1186        }
1187      }
1188      NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1189                              II, R, SC, LastDeclarator,
1190                              // FIXME: Move to DeclGroup...
1191                              D.getDeclSpec().getSourceRange().getBegin());
1192      NewVD->setThreadSpecified(ThreadSpecified);
1193    }
1194    // Handle attributes prior to checking for duplicates in MergeVarDecl
1195    ProcessDeclAttributes(NewVD, D);
1196
1197    // Handle GNU asm-label extension (encoded as an attribute).
1198    if (Expr *E = (Expr*) D.getAsmLabel()) {
1199      // The parser guarantees this is a string.
1200      StringLiteral *SE = cast<StringLiteral>(E);
1201      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1202                                                  SE->getByteLength())));
1203    }
1204
1205    // Emit an error if an address space was applied to decl with local storage.
1206    // This includes arrays of objects with address space qualifiers, but not
1207    // automatic variables that point to other address spaces.
1208    // ISO/IEC TR 18037 S5.1.2
1209    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1210      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1211      InvalidDecl = true;
1212    }
1213    // Merge the decl with the existing one if appropriate. If the decl is
1214    // in an outer scope, it isn't the same thing.
1215    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1216      NewVD = MergeVarDecl(NewVD, PrevDecl);
1217      if (NewVD == 0) return 0;
1218    }
1219    New = NewVD;
1220  }
1221
1222  // Set the lexical context. If the declarator has a C++ scope specifier, the
1223  // lexical context will be different from the semantic context.
1224  New->setLexicalDeclContext(CurContext);
1225
1226  // If this has an identifier, add it to the scope stack.
1227  if (Name)
1228    PushOnScopeChains(New, S);
1229  // If any semantic error occurred, mark the decl as invalid.
1230  if (D.getInvalidType() || InvalidDecl)
1231    New->setInvalidDecl();
1232
1233  return New;
1234}
1235
1236void Sema::InitializerElementNotConstant(const Expr *Init) {
1237  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1238    << Init->getSourceRange();
1239}
1240
1241bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1242  switch (Init->getStmtClass()) {
1243  default:
1244    InitializerElementNotConstant(Init);
1245    return true;
1246  case Expr::ParenExprClass: {
1247    const ParenExpr* PE = cast<ParenExpr>(Init);
1248    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1249  }
1250  case Expr::CompoundLiteralExprClass:
1251    return cast<CompoundLiteralExpr>(Init)->isFileScope();
1252  case Expr::DeclRefExprClass: {
1253    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1254    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1255      if (VD->hasGlobalStorage())
1256        return false;
1257      InitializerElementNotConstant(Init);
1258      return true;
1259    }
1260    if (isa<FunctionDecl>(D))
1261      return false;
1262    InitializerElementNotConstant(Init);
1263    return true;
1264  }
1265  case Expr::MemberExprClass: {
1266    const MemberExpr *M = cast<MemberExpr>(Init);
1267    if (M->isArrow())
1268      return CheckAddressConstantExpression(M->getBase());
1269    return CheckAddressConstantExpressionLValue(M->getBase());
1270  }
1271  case Expr::ArraySubscriptExprClass: {
1272    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1273    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1274    return CheckAddressConstantExpression(ASE->getBase()) ||
1275           CheckArithmeticConstantExpression(ASE->getIdx());
1276  }
1277  case Expr::StringLiteralClass:
1278  case Expr::PredefinedExprClass:
1279    return false;
1280  case Expr::UnaryOperatorClass: {
1281    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1282
1283    // C99 6.6p9
1284    if (Exp->getOpcode() == UnaryOperator::Deref)
1285      return CheckAddressConstantExpression(Exp->getSubExpr());
1286
1287    InitializerElementNotConstant(Init);
1288    return true;
1289  }
1290  }
1291}
1292
1293bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1294  switch (Init->getStmtClass()) {
1295  default:
1296    InitializerElementNotConstant(Init);
1297    return true;
1298  case Expr::ParenExprClass:
1299    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
1300  case Expr::StringLiteralClass:
1301  case Expr::ObjCStringLiteralClass:
1302    return false;
1303  case Expr::CallExprClass:
1304  case Expr::CXXOperatorCallExprClass:
1305    // __builtin___CFStringMakeConstantString is a valid constant l-value.
1306    if (cast<CallExpr>(Init)->isBuiltinCall() ==
1307           Builtin::BI__builtin___CFStringMakeConstantString)
1308      return false;
1309
1310    InitializerElementNotConstant(Init);
1311    return true;
1312
1313  case Expr::UnaryOperatorClass: {
1314    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1315
1316    // C99 6.6p9
1317    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1318      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1319
1320    if (Exp->getOpcode() == UnaryOperator::Extension)
1321      return CheckAddressConstantExpression(Exp->getSubExpr());
1322
1323    InitializerElementNotConstant(Init);
1324    return true;
1325  }
1326  case Expr::BinaryOperatorClass: {
1327    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1328    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1329
1330    Expr *PExp = Exp->getLHS();
1331    Expr *IExp = Exp->getRHS();
1332    if (IExp->getType()->isPointerType())
1333      std::swap(PExp, IExp);
1334
1335    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1336    return CheckAddressConstantExpression(PExp) ||
1337           CheckArithmeticConstantExpression(IExp);
1338  }
1339  case Expr::ImplicitCastExprClass:
1340  case Expr::CStyleCastExprClass: {
1341    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1342    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1343      // Check for implicit promotion
1344      if (SubExpr->getType()->isFunctionType() ||
1345          SubExpr->getType()->isArrayType())
1346        return CheckAddressConstantExpressionLValue(SubExpr);
1347    }
1348
1349    // Check for pointer->pointer cast
1350    if (SubExpr->getType()->isPointerType())
1351      return CheckAddressConstantExpression(SubExpr);
1352
1353    if (SubExpr->getType()->isIntegralType()) {
1354      // Check for the special-case of a pointer->int->pointer cast;
1355      // this isn't standard, but some code requires it. See
1356      // PR2720 for an example.
1357      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1358        if (SubCast->getSubExpr()->getType()->isPointerType()) {
1359          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1360          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1361          if (IntWidth >= PointerWidth) {
1362            return CheckAddressConstantExpression(SubCast->getSubExpr());
1363          }
1364        }
1365      }
1366    }
1367    if (SubExpr->getType()->isArithmeticType()) {
1368      return CheckArithmeticConstantExpression(SubExpr);
1369    }
1370
1371    InitializerElementNotConstant(Init);
1372    return true;
1373  }
1374  case Expr::ConditionalOperatorClass: {
1375    // FIXME: Should we pedwarn here?
1376    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1377    if (!Exp->getCond()->getType()->isArithmeticType()) {
1378      InitializerElementNotConstant(Init);
1379      return true;
1380    }
1381    if (CheckArithmeticConstantExpression(Exp->getCond()))
1382      return true;
1383    if (Exp->getLHS() &&
1384        CheckAddressConstantExpression(Exp->getLHS()))
1385      return true;
1386    return CheckAddressConstantExpression(Exp->getRHS());
1387  }
1388  case Expr::AddrLabelExprClass:
1389    return false;
1390  }
1391}
1392
1393static const Expr* FindExpressionBaseAddress(const Expr* E);
1394
1395static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1396  switch (E->getStmtClass()) {
1397  default:
1398    return E;
1399  case Expr::ParenExprClass: {
1400    const ParenExpr* PE = cast<ParenExpr>(E);
1401    return FindExpressionBaseAddressLValue(PE->getSubExpr());
1402  }
1403  case Expr::MemberExprClass: {
1404    const MemberExpr *M = cast<MemberExpr>(E);
1405    if (M->isArrow())
1406      return FindExpressionBaseAddress(M->getBase());
1407    return FindExpressionBaseAddressLValue(M->getBase());
1408  }
1409  case Expr::ArraySubscriptExprClass: {
1410    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1411    return FindExpressionBaseAddress(ASE->getBase());
1412  }
1413  case Expr::UnaryOperatorClass: {
1414    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1415
1416    if (Exp->getOpcode() == UnaryOperator::Deref)
1417      return FindExpressionBaseAddress(Exp->getSubExpr());
1418
1419    return E;
1420  }
1421  }
1422}
1423
1424static const Expr* FindExpressionBaseAddress(const Expr* E) {
1425  switch (E->getStmtClass()) {
1426  default:
1427    return E;
1428  case Expr::ParenExprClass: {
1429    const ParenExpr* PE = cast<ParenExpr>(E);
1430    return FindExpressionBaseAddress(PE->getSubExpr());
1431  }
1432  case Expr::UnaryOperatorClass: {
1433    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1434
1435    // C99 6.6p9
1436    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1437      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1438
1439    if (Exp->getOpcode() == UnaryOperator::Extension)
1440      return FindExpressionBaseAddress(Exp->getSubExpr());
1441
1442    return E;
1443  }
1444  case Expr::BinaryOperatorClass: {
1445    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1446
1447    Expr *PExp = Exp->getLHS();
1448    Expr *IExp = Exp->getRHS();
1449    if (IExp->getType()->isPointerType())
1450      std::swap(PExp, IExp);
1451
1452    return FindExpressionBaseAddress(PExp);
1453  }
1454  case Expr::ImplicitCastExprClass: {
1455    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1456
1457    // Check for implicit promotion
1458    if (SubExpr->getType()->isFunctionType() ||
1459        SubExpr->getType()->isArrayType())
1460      return FindExpressionBaseAddressLValue(SubExpr);
1461
1462    // Check for pointer->pointer cast
1463    if (SubExpr->getType()->isPointerType())
1464      return FindExpressionBaseAddress(SubExpr);
1465
1466    // We assume that we have an arithmetic expression here;
1467    // if we don't, we'll figure it out later
1468    return 0;
1469  }
1470  case Expr::CStyleCastExprClass: {
1471    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1472
1473    // Check for pointer->pointer cast
1474    if (SubExpr->getType()->isPointerType())
1475      return FindExpressionBaseAddress(SubExpr);
1476
1477    // We assume that we have an arithmetic expression here;
1478    // if we don't, we'll figure it out later
1479    return 0;
1480  }
1481  }
1482}
1483
1484bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1485  switch (Init->getStmtClass()) {
1486  default:
1487    InitializerElementNotConstant(Init);
1488    return true;
1489  case Expr::ParenExprClass: {
1490    const ParenExpr* PE = cast<ParenExpr>(Init);
1491    return CheckArithmeticConstantExpression(PE->getSubExpr());
1492  }
1493  case Expr::FloatingLiteralClass:
1494  case Expr::IntegerLiteralClass:
1495  case Expr::CharacterLiteralClass:
1496  case Expr::ImaginaryLiteralClass:
1497  case Expr::TypesCompatibleExprClass:
1498  case Expr::CXXBoolLiteralExprClass:
1499    return false;
1500  case Expr::CallExprClass:
1501  case Expr::CXXOperatorCallExprClass: {
1502    const CallExpr *CE = cast<CallExpr>(Init);
1503
1504    // Allow any constant foldable calls to builtins.
1505    if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
1506      return false;
1507
1508    InitializerElementNotConstant(Init);
1509    return true;
1510  }
1511  case Expr::DeclRefExprClass: {
1512    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1513    if (isa<EnumConstantDecl>(D))
1514      return false;
1515    InitializerElementNotConstant(Init);
1516    return true;
1517  }
1518  case Expr::CompoundLiteralExprClass:
1519    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1520    // but vectors are allowed to be magic.
1521    if (Init->getType()->isVectorType())
1522      return false;
1523    InitializerElementNotConstant(Init);
1524    return true;
1525  case Expr::UnaryOperatorClass: {
1526    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1527
1528    switch (Exp->getOpcode()) {
1529    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1530    // See C99 6.6p3.
1531    default:
1532      InitializerElementNotConstant(Init);
1533      return true;
1534    case UnaryOperator::OffsetOf:
1535      if (Exp->getSubExpr()->getType()->isConstantSizeType())
1536        return false;
1537      InitializerElementNotConstant(Init);
1538      return true;
1539    case UnaryOperator::Extension:
1540    case UnaryOperator::LNot:
1541    case UnaryOperator::Plus:
1542    case UnaryOperator::Minus:
1543    case UnaryOperator::Not:
1544      return CheckArithmeticConstantExpression(Exp->getSubExpr());
1545    }
1546  }
1547  case Expr::SizeOfAlignOfExprClass: {
1548    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
1549    // Special check for void types, which are allowed as an extension
1550    if (Exp->getTypeOfArgument()->isVoidType())
1551      return false;
1552    // alignof always evaluates to a constant.
1553    // FIXME: is sizeof(int[3.0]) a constant expression?
1554    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
1555      InitializerElementNotConstant(Init);
1556      return true;
1557    }
1558    return false;
1559  }
1560  case Expr::BinaryOperatorClass: {
1561    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1562
1563    if (Exp->getLHS()->getType()->isArithmeticType() &&
1564        Exp->getRHS()->getType()->isArithmeticType()) {
1565      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1566             CheckArithmeticConstantExpression(Exp->getRHS());
1567    }
1568
1569    if (Exp->getLHS()->getType()->isPointerType() &&
1570        Exp->getRHS()->getType()->isPointerType()) {
1571      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1572      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1573
1574      // Only allow a null (constant integer) base; we could
1575      // allow some additional cases if necessary, but this
1576      // is sufficient to cover offsetof-like constructs.
1577      if (!LHSBase && !RHSBase) {
1578        return CheckAddressConstantExpression(Exp->getLHS()) ||
1579               CheckAddressConstantExpression(Exp->getRHS());
1580      }
1581    }
1582
1583    InitializerElementNotConstant(Init);
1584    return true;
1585  }
1586  case Expr::ImplicitCastExprClass:
1587  case Expr::CStyleCastExprClass: {
1588    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
1589    if (SubExpr->getType()->isArithmeticType())
1590      return CheckArithmeticConstantExpression(SubExpr);
1591
1592    if (SubExpr->getType()->isPointerType()) {
1593      const Expr* Base = FindExpressionBaseAddress(SubExpr);
1594      // If the pointer has a null base, this is an offsetof-like construct
1595      if (!Base)
1596        return CheckAddressConstantExpression(SubExpr);
1597    }
1598
1599    InitializerElementNotConstant(Init);
1600    return true;
1601  }
1602  case Expr::ConditionalOperatorClass: {
1603    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1604
1605    // If GNU extensions are disabled, we require all operands to be arithmetic
1606    // constant expressions.
1607    if (getLangOptions().NoExtensions) {
1608      return CheckArithmeticConstantExpression(Exp->getCond()) ||
1609          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1610             CheckArithmeticConstantExpression(Exp->getRHS());
1611    }
1612
1613    // Otherwise, we have to emulate some of the behavior of fold here.
1614    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1615    // because it can constant fold things away.  To retain compatibility with
1616    // GCC code, we see if we can fold the condition to a constant (which we
1617    // should always be able to do in theory).  If so, we only require the
1618    // specified arm of the conditional to be a constant.  This is a horrible
1619    // hack, but is require by real world code that uses __builtin_constant_p.
1620    APValue Val;
1621    if (!Exp->getCond()->Evaluate(Val, Context)) {
1622      // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
1623      // won't be able to either.  Use it to emit the diagnostic though.
1624      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1625      assert(Res && "Evaluate couldn't evaluate this constant?");
1626      return Res;
1627    }
1628
1629    // Verify that the side following the condition is also a constant.
1630    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1631    if (Val.getInt() == 0)
1632      std::swap(TrueSide, FalseSide);
1633
1634    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
1635      return true;
1636
1637    // Okay, the evaluated side evaluates to a constant, so we accept this.
1638    // Check to see if the other side is obviously not a constant.  If so,
1639    // emit a warning that this is a GNU extension.
1640    if (FalseSide && !FalseSide->isEvaluatable(Context))
1641      Diag(Init->getExprLoc(),
1642           diag::ext_typecheck_expression_not_constant_but_accepted)
1643        << FalseSide->getSourceRange();
1644    return false;
1645  }
1646  }
1647}
1648
1649bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1650  Init = Init->IgnoreParens();
1651
1652  // Look through CXXDefaultArgExprs; they have no meaning in this context.
1653  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1654    return CheckForConstantInitializer(DAE->getExpr(), DclT);
1655
1656  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1657    return CheckForConstantInitializer(e->getInitializer(), DclT);
1658
1659  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1660    unsigned numInits = Exp->getNumInits();
1661    for (unsigned i = 0; i < numInits; i++) {
1662      // FIXME: Need to get the type of the declaration for C++,
1663      // because it could be a reference?
1664      if (CheckForConstantInitializer(Exp->getInit(i),
1665                                      Exp->getInit(i)->getType()))
1666        return true;
1667    }
1668    return false;
1669  }
1670
1671  if (Init->isNullPointerConstant(Context))
1672    return false;
1673  if (Init->getType()->isArithmeticType()) {
1674    QualType InitTy = Context.getCanonicalType(Init->getType())
1675                             .getUnqualifiedType();
1676    if (InitTy == Context.BoolTy) {
1677      // Special handling for pointers implicitly cast to bool;
1678      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1679      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1680        Expr* SubE = ICE->getSubExpr();
1681        if (SubE->getType()->isPointerType() ||
1682            SubE->getType()->isArrayType() ||
1683            SubE->getType()->isFunctionType()) {
1684          return CheckAddressConstantExpression(Init);
1685        }
1686      }
1687    } else if (InitTy->isIntegralType()) {
1688      Expr* SubE = 0;
1689      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1690        SubE = CE->getSubExpr();
1691      // Special check for pointer cast to int; we allow as an extension
1692      // an address constant cast to an integer if the integer
1693      // is of an appropriate width (this sort of code is apparently used
1694      // in some places).
1695      // FIXME: Add pedwarn?
1696      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
1697      if (SubE && (SubE->getType()->isPointerType() ||
1698                   SubE->getType()->isArrayType() ||
1699                   SubE->getType()->isFunctionType())) {
1700        unsigned IntWidth = Context.getTypeSize(Init->getType());
1701        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1702        if (IntWidth >= PointerWidth)
1703          return CheckAddressConstantExpression(Init);
1704      }
1705    }
1706
1707    return CheckArithmeticConstantExpression(Init);
1708  }
1709
1710  if (Init->getType()->isPointerType())
1711    return CheckAddressConstantExpression(Init);
1712
1713  // An array type at the top level that isn't an init-list must
1714  // be a string literal
1715  if (Init->getType()->isArrayType())
1716    return false;
1717
1718  if (Init->getType()->isFunctionType())
1719    return false;
1720
1721  // Allow block exprs at top level.
1722  if (Init->getType()->isBlockPointerType())
1723    return false;
1724
1725  InitializerElementNotConstant(Init);
1726  return true;
1727}
1728
1729void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
1730  Decl *RealDecl = static_cast<Decl *>(dcl);
1731  Expr *Init = static_cast<Expr *>(init);
1732  assert(Init && "missing initializer");
1733
1734  // If there is no declaration, there was an error parsing it.  Just ignore
1735  // the initializer.
1736  if (RealDecl == 0) {
1737    delete Init;
1738    return;
1739  }
1740
1741  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1742  if (!VDecl) {
1743    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1744         diag::err_illegal_initializer);
1745    RealDecl->setInvalidDecl();
1746    return;
1747  }
1748  // Get the decls type and save a reference for later, since
1749  // CheckInitializerTypes may change it.
1750  QualType DclT = VDecl->getType(), SavT = DclT;
1751  if (VDecl->isBlockVarDecl()) {
1752    VarDecl::StorageClass SC = VDecl->getStorageClass();
1753    if (SC == VarDecl::Extern) { // C99 6.7.8p5
1754      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
1755      VDecl->setInvalidDecl();
1756    } else if (!VDecl->isInvalidDecl()) {
1757      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1758                                VDecl->getName()))
1759        VDecl->setInvalidDecl();
1760
1761      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1762      if (!getLangOptions().CPlusPlus) {
1763        if (SC == VarDecl::Static) // C99 6.7.8p4.
1764          CheckForConstantInitializer(Init, DclT);
1765      }
1766    }
1767  } else if (VDecl->isFileVarDecl()) {
1768    if (VDecl->getStorageClass() == VarDecl::Extern)
1769      Diag(VDecl->getLocation(), diag::warn_extern_init);
1770    if (!VDecl->isInvalidDecl())
1771      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1772                                VDecl->getName()))
1773        VDecl->setInvalidDecl();
1774
1775    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1776    if (!getLangOptions().CPlusPlus) {
1777      // C99 6.7.8p4. All file scoped initializers need to be constant.
1778      CheckForConstantInitializer(Init, DclT);
1779    }
1780  }
1781  // If the type changed, it means we had an incomplete type that was
1782  // completed by the initializer. For example:
1783  //   int ary[] = { 1, 3, 5 };
1784  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
1785  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
1786    VDecl->setType(DclT);
1787    Init->setType(DclT);
1788  }
1789
1790  // Attach the initializer to the decl.
1791  VDecl->setInit(Init);
1792  return;
1793}
1794
1795void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1796  Decl *RealDecl = static_cast<Decl *>(dcl);
1797
1798  // If there is no declaration, there was an error parsing it. Just ignore it.
1799  if (RealDecl == 0)
1800    return;
1801
1802  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1803    QualType Type = Var->getType();
1804    // C++ [dcl.init.ref]p3:
1805    //   The initializer can be omitted for a reference only in a
1806    //   parameter declaration (8.3.5), in the declaration of a
1807    //   function return type, in the declaration of a class member
1808    //   within its class declaration (9.2), and where the extern
1809    //   specifier is explicitly used.
1810    if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
1811      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
1812       << Var->getName() << SourceRange(Var->getLocation(), Var->getLocation());
1813      Var->setInvalidDecl();
1814      return;
1815    }
1816
1817    // C++ [dcl.init]p9:
1818    //
1819    //   If no initializer is specified for an object, and the object
1820    //   is of (possibly cv-qualified) non-POD class type (or array
1821    //   thereof), the object shall be default-initialized; if the
1822    //   object is of const-qualified type, the underlying class type
1823    //   shall have a user-declared default constructor.
1824    if (getLangOptions().CPlusPlus) {
1825      QualType InitType = Type;
1826      if (const ArrayType *Array = Context.getAsArrayType(Type))
1827        InitType = Array->getElementType();
1828      if (InitType->isRecordType()) {
1829        const CXXConstructorDecl *Constructor
1830          = PerformInitializationByConstructor(InitType, 0, 0,
1831                                               Var->getLocation(),
1832                                               SourceRange(Var->getLocation(),
1833                                                           Var->getLocation()),
1834                                               Var->getName(),
1835                                               IK_Default);
1836        if (!Constructor)
1837          Var->setInvalidDecl();
1838      }
1839    }
1840
1841#if 0
1842    // FIXME: Temporarily disabled because we are not properly parsing
1843    // linkage specifications on declarations, e.g.,
1844    //
1845    //   extern "C" const CGPoint CGPointerZero;
1846    //
1847    // C++ [dcl.init]p9:
1848    //
1849    //     If no initializer is specified for an object, and the
1850    //     object is of (possibly cv-qualified) non-POD class type (or
1851    //     array thereof), the object shall be default-initialized; if
1852    //     the object is of const-qualified type, the underlying class
1853    //     type shall have a user-declared default
1854    //     constructor. Otherwise, if no initializer is specified for
1855    //     an object, the object and its subobjects, if any, have an
1856    //     indeterminate initial value; if the object or any of its
1857    //     subobjects are of const-qualified type, the program is
1858    //     ill-formed.
1859    //
1860    // This isn't technically an error in C, so we don't diagnose it.
1861    //
1862    // FIXME: Actually perform the POD/user-defined default
1863    // constructor check.
1864    if (getLangOptions().CPlusPlus &&
1865        Context.getCanonicalType(Type).isConstQualified() &&
1866        Var->getStorageClass() != VarDecl::Extern)
1867      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
1868        << Var->getName()
1869        << SourceRange(Var->getLocation(), Var->getLocation());
1870#endif
1871  }
1872}
1873
1874/// The declarators are chained together backwards, reverse the list.
1875Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1876  // Often we have single declarators, handle them quickly.
1877  Decl *GroupDecl = static_cast<Decl*>(group);
1878  if (GroupDecl == 0)
1879    return 0;
1880
1881  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1882  ScopedDecl *NewGroup = 0;
1883  if (Group->getNextDeclarator() == 0)
1884    NewGroup = Group;
1885  else { // reverse the list.
1886    while (Group) {
1887      ScopedDecl *Next = Group->getNextDeclarator();
1888      Group->setNextDeclarator(NewGroup);
1889      NewGroup = Group;
1890      Group = Next;
1891    }
1892  }
1893  // Perform semantic analysis that depends on having fully processed both
1894  // the declarator and initializer.
1895  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
1896    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1897    if (!IDecl)
1898      continue;
1899    QualType T = IDecl->getType();
1900
1901    // C99 6.7.5.2p2: If an identifier is declared to be an object with
1902    // static storage duration, it shall not have a variable length array.
1903    if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1904        IDecl->getStorageClass() == VarDecl::Static) {
1905      if (T->isVariableArrayType()) {
1906        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1907        IDecl->setInvalidDecl();
1908      }
1909    }
1910    // Block scope. C99 6.7p7: If an identifier for an object is declared with
1911    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1912    if (IDecl->isBlockVarDecl() &&
1913        IDecl->getStorageClass() != VarDecl::Extern) {
1914      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1915        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
1916          << T.getAsString();
1917        IDecl->setInvalidDecl();
1918      }
1919    }
1920    // File scope. C99 6.9.2p2: A declaration of an identifier for and
1921    // object that has file scope without an initializer, and without a
1922    // storage-class specifier or with the storage-class specifier "static",
1923    // constitutes a tentative definition. Note: A tentative definition with
1924    // external linkage is valid (C99 6.2.2p5).
1925    if (isTentativeDefinition(IDecl)) {
1926      if (T->isIncompleteArrayType()) {
1927        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1928        // array to be completed. Don't issue a diagnostic.
1929      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1930        // C99 6.9.2p3: If the declaration of an identifier for an object is
1931        // a tentative definition and has internal linkage (C99 6.2.2p3), the
1932        // declared type shall not be an incomplete type.
1933        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
1934          << T.getAsString();
1935        IDecl->setInvalidDecl();
1936      }
1937    }
1938    if (IDecl->isFileVarDecl())
1939      CheckForFileScopedRedefinitions(S, IDecl);
1940  }
1941  return NewGroup;
1942}
1943
1944/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1945/// to introduce parameters into function prototype scope.
1946Sema::DeclTy *
1947Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1948  // FIXME: disallow CXXScopeSpec for param declarators.
1949  const DeclSpec &DS = D.getDeclSpec();
1950
1951  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1952  VarDecl::StorageClass StorageClass = VarDecl::None;
1953  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1954    StorageClass = VarDecl::Register;
1955  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1956    Diag(DS.getStorageClassSpecLoc(),
1957         diag::err_invalid_storage_class_in_func_decl);
1958    D.getMutableDeclSpec().ClearStorageClassSpecs();
1959  }
1960  if (DS.isThreadSpecified()) {
1961    Diag(DS.getThreadSpecLoc(),
1962         diag::err_invalid_storage_class_in_func_decl);
1963    D.getMutableDeclSpec().ClearStorageClassSpecs();
1964  }
1965
1966  // Check that there are no default arguments inside the type of this
1967  // parameter (C++ only).
1968  if (getLangOptions().CPlusPlus)
1969    CheckExtraCXXDefaultArguments(D);
1970
1971  // In this context, we *do not* check D.getInvalidType(). If the declarator
1972  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1973  // though it will not reflect the user specified type.
1974  QualType parmDeclType = GetTypeForDeclarator(D, S);
1975
1976  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1977
1978  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1979  // Can this happen for params?  We already checked that they don't conflict
1980  // among each other.  Here they can only shadow globals, which is ok.
1981  IdentifierInfo *II = D.getIdentifier();
1982  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1983    if (S->isDeclScope(PrevDecl)) {
1984      Diag(D.getIdentifierLoc(), diag::err_param_redefinition)
1985        << cast<NamedDecl>(PrevDecl)->getName();
1986
1987      // Recover by removing the name
1988      II = 0;
1989      D.SetIdentifier(0, D.getIdentifierLoc());
1990    }
1991  }
1992
1993  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1994  // Doing the promotion here has a win and a loss. The win is the type for
1995  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1996  // code generator). The loss is the orginal type isn't preserved. For example:
1997  //
1998  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1999  //    int blockvardecl[5];
2000  //    sizeof(parmvardecl);  // size == 4
2001  //    sizeof(blockvardecl); // size == 20
2002  // }
2003  //
2004  // For expressions, all implicit conversions are captured using the
2005  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2006  //
2007  // FIXME: If a source translation tool needs to see the original type, then
2008  // we need to consider storing both types (in ParmVarDecl)...
2009  //
2010  if (parmDeclType->isArrayType()) {
2011    // int x[restrict 4] ->  int *restrict
2012    parmDeclType = Context.getArrayDecayedType(parmDeclType);
2013  } else if (parmDeclType->isFunctionType())
2014    parmDeclType = Context.getPointerType(parmDeclType);
2015
2016  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2017                                         D.getIdentifierLoc(), II,
2018                                         parmDeclType, StorageClass,
2019                                         0, 0);
2020
2021  if (D.getInvalidType())
2022    New->setInvalidDecl();
2023
2024  if (II)
2025    PushOnScopeChains(New, S);
2026
2027  ProcessDeclAttributes(New, D);
2028  return New;
2029
2030}
2031
2032Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2033  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2034  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2035         "Not a function declarator!");
2036  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2037
2038  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2039  // for a K&R function.
2040  if (!FTI.hasPrototype) {
2041    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2042      if (FTI.ArgInfo[i].Param == 0) {
2043        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2044          << FTI.ArgInfo[i].Ident;
2045        // Implicitly declare the argument as type 'int' for lack of a better
2046        // type.
2047        DeclSpec DS;
2048        const char* PrevSpec; // unused
2049        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2050                           PrevSpec);
2051        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2052        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2053        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
2054      }
2055    }
2056  } else {
2057    // FIXME: Diagnose arguments without names in C.
2058  }
2059
2060  Scope *GlobalScope = FnBodyScope->getParent();
2061
2062  return ActOnStartOfFunctionDef(FnBodyScope,
2063                                 ActOnDeclarator(GlobalScope, D, 0));
2064}
2065
2066Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2067  Decl *decl = static_cast<Decl*>(D);
2068  FunctionDecl *FD = cast<FunctionDecl>(decl);
2069
2070  // See if this is a redefinition.
2071  const FunctionDecl *Definition;
2072  if (FD->getBody(Definition)) {
2073    Diag(FD->getLocation(), diag::err_redefinition) << FD->getName();
2074    Diag(Definition->getLocation(), diag::err_previous_definition);
2075  }
2076
2077  PushDeclContext(FD);
2078
2079  // Check the validity of our function parameters
2080  CheckParmsForFunctionDef(FD);
2081
2082  // Introduce our parameters into the function scope
2083  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2084    ParmVarDecl *Param = FD->getParamDecl(p);
2085    // If this has an identifier, add it to the scope stack.
2086    if (Param->getIdentifier())
2087      PushOnScopeChains(Param, FnBodyScope);
2088  }
2089
2090  return FD;
2091}
2092
2093Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2094  Decl *dcl = static_cast<Decl *>(D);
2095  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
2096    FD->setBody((Stmt*)Body);
2097    assert(FD == getCurFunctionDecl() && "Function parsing confused");
2098  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
2099    MD->setBody((Stmt*)Body);
2100  } else
2101    return 0;
2102  PopDeclContext();
2103  // Verify and clean out per-function state.
2104
2105  // Check goto/label use.
2106  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2107       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2108    // Verify that we have no forward references left.  If so, there was a goto
2109    // or address of a label taken, but no definition of it.  Label fwd
2110    // definitions are indicated with a null substmt.
2111    if (I->second->getSubStmt() == 0) {
2112      LabelStmt *L = I->second;
2113      // Emit error.
2114      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
2115
2116      // At this point, we have gotos that use the bogus label.  Stitch it into
2117      // the function body so that they aren't leaked and that the AST is well
2118      // formed.
2119      if (Body) {
2120        L->setSubStmt(new NullStmt(L->getIdentLoc()));
2121        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2122      } else {
2123        // The whole function wasn't parsed correctly, just delete this.
2124        delete L;
2125      }
2126    }
2127  }
2128  LabelMap.clear();
2129
2130  return D;
2131}
2132
2133/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2134/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
2135ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2136                                           IdentifierInfo &II, Scope *S) {
2137  // Extension in C99.  Legal in C90, but warn about it.
2138  if (getLangOptions().C99)
2139    Diag(Loc, diag::ext_implicit_function_decl) << &II;
2140  else
2141    Diag(Loc, diag::warn_implicit_function_decl) << &II;
2142
2143  // FIXME: handle stuff like:
2144  // void foo() { extern float X(); }
2145  // void bar() { X(); }  <-- implicit decl for X in another scope.
2146
2147  // Set a Declarator for the implicit definition: int foo();
2148  const char *Dummy;
2149  DeclSpec DS;
2150  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2151  Error = Error; // Silence warning.
2152  assert(!Error && "Error setting up implicit decl!");
2153  Declarator D(DS, Declarator::BlockContext);
2154  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
2155  D.SetIdentifier(&II, Loc);
2156
2157  // Insert this function into translation-unit scope.
2158
2159  DeclContext *PrevDC = CurContext;
2160  CurContext = Context.getTranslationUnitDecl();
2161
2162  FunctionDecl *FD =
2163    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
2164  FD->setImplicit();
2165
2166  CurContext = PrevDC;
2167
2168  return FD;
2169}
2170
2171
2172TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2173                                    ScopedDecl *LastDeclarator) {
2174  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
2175  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2176
2177  // Scope manipulation handled by caller.
2178  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2179                                           D.getIdentifierLoc(),
2180                                           D.getIdentifier(),
2181                                           T, LastDeclarator);
2182  if (D.getInvalidType())
2183    NewTD->setInvalidDecl();
2184  return NewTD;
2185}
2186
2187/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
2188/// former case, Name will be non-null.  In the later case, Name will be null.
2189/// TagType indicates what kind of tag this is. TK indicates whether this is a
2190/// reference/declaration/definition of a tag.
2191Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
2192                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2193                             IdentifierInfo *Name, SourceLocation NameLoc,
2194                             AttributeList *Attr) {
2195  // If this is a use of an existing tag, it must have a name.
2196  assert((Name != 0 || TK == TK_Definition) &&
2197         "Nameless record must be a definition!");
2198
2199  TagDecl::TagKind Kind;
2200  switch (TagType) {
2201  default: assert(0 && "Unknown tag type!");
2202  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2203  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2204  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2205  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
2206  }
2207
2208  // Two code paths: a new one for structs/unions/classes where we create
2209  //   separate decls for forward declarations, and an old (eventually to
2210  //   be removed) code path for enums.
2211  if (Kind != TagDecl::TK_enum)
2212    return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
2213
2214  DeclContext *DC = CurContext;
2215  ScopedDecl *PrevDecl = 0;
2216
2217  if (Name && SS.isNotEmpty()) {
2218    // We have a nested-name tag ('struct foo::bar').
2219
2220    // Check for invalid 'foo::'.
2221    if (SS.isInvalid()) {
2222      Name = 0;
2223      goto CreateNewDecl;
2224    }
2225
2226    DC = static_cast<DeclContext*>(SS.getScopeRep());
2227    // Look-up name inside 'foo::'.
2228    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2229
2230    // A tag 'foo::bar' must already exist.
2231    if (PrevDecl == 0) {
2232      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
2233      Name = 0;
2234      goto CreateNewDecl;
2235    }
2236  } else {
2237    // If this is a named struct, check to see if there was a previous forward
2238    // declaration or definition.
2239    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2240    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2241  }
2242
2243  if (PrevDecl) {
2244    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2245            "unexpected Decl type");
2246    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2247      // If this is a use of a previous tag, or if the tag is already declared
2248      // in the same scope (so that the definition/declaration completes or
2249      // rementions the tag), reuse the decl.
2250      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2251        // Make sure that this wasn't declared as an enum and now used as a
2252        // struct or something similar.
2253        if (PrevTagDecl->getTagKind() != Kind) {
2254          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
2255          Diag(PrevDecl->getLocation(), diag::err_previous_use);
2256          // Recover by making this an anonymous redefinition.
2257          Name = 0;
2258          PrevDecl = 0;
2259        } else {
2260          // If this is a use or a forward declaration, we're good.
2261          if (TK != TK_Definition)
2262            return PrevDecl;
2263
2264          // Diagnose attempts to redefine a tag.
2265          if (PrevTagDecl->isDefinition()) {
2266            Diag(NameLoc, diag::err_redefinition) << Name;
2267            Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2268            // If this is a redefinition, recover by making this struct be
2269            // anonymous, which will make any later references get the previous
2270            // definition.
2271            Name = 0;
2272          } else {
2273            // Okay, this is definition of a previously declared or referenced
2274            // tag. Move the location of the decl to be the definition site.
2275            PrevDecl->setLocation(NameLoc);
2276            return PrevDecl;
2277          }
2278        }
2279      }
2280      // If we get here, this is a definition of a new struct type in a nested
2281      // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2282      // type.
2283    } else {
2284      // PrevDecl is a namespace.
2285      if (isDeclInScope(PrevDecl, DC, S)) {
2286        // The tag name clashes with a namespace name, issue an error and
2287        // recover by making this tag be anonymous.
2288        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2289        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2290        Name = 0;
2291      }
2292    }
2293  }
2294
2295  CreateNewDecl:
2296
2297  // If there is an identifier, use the location of the identifier as the
2298  // location of the decl, otherwise use the location of the struct/union
2299  // keyword.
2300  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2301
2302  // Otherwise, if this is the first time we've seen this tag, create the decl.
2303  TagDecl *New;
2304  if (Kind == TagDecl::TK_enum) {
2305    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2306    // enum X { A, B, C } D;    D should chain to X.
2307    New = EnumDecl::Create(Context, DC, Loc, Name, 0);
2308    // If this is an undefined enum, warn.
2309    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
2310  } else {
2311    // struct/union/class
2312
2313    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2314    // struct X { int A; } D;    D should chain to X.
2315    if (getLangOptions().CPlusPlus)
2316      // FIXME: Look for a way to use RecordDecl for simple structs.
2317      New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
2318    else
2319      New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
2320  }
2321
2322  // If this has an identifier, add it to the scope stack.
2323  if (Name) {
2324    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2325    // we find one that is.
2326    while ((S->getFlags() & Scope::DeclScope) == 0)
2327      S = S->getParent();
2328
2329    // Add it to the decl chain.
2330    PushOnScopeChains(New, S);
2331  }
2332
2333  if (Attr)
2334    ProcessDeclAttributeList(New, Attr);
2335
2336  // Set the lexical context. If the tag has a C++ scope specifier, the
2337  // lexical context will be different from the semantic context.
2338  New->setLexicalDeclContext(CurContext);
2339
2340  return New;
2341}
2342
2343/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes.  Unlike
2344///  the logic for enums, we create separate decls for forward declarations.
2345///  This is called by ActOnTag, but eventually will replace its logic.
2346Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2347                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2348                             IdentifierInfo *Name, SourceLocation NameLoc,
2349                             AttributeList *Attr) {
2350  DeclContext *DC = CurContext;
2351  ScopedDecl *PrevDecl = 0;
2352
2353  if (Name && SS.isNotEmpty()) {
2354    // We have a nested-name tag ('struct foo::bar').
2355
2356    // Check for invalid 'foo::'.
2357    if (SS.isInvalid()) {
2358      Name = 0;
2359      goto CreateNewDecl;
2360    }
2361
2362    DC = static_cast<DeclContext*>(SS.getScopeRep());
2363    // Look-up name inside 'foo::'.
2364    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2365
2366    // A tag 'foo::bar' must already exist.
2367    if (PrevDecl == 0) {
2368      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
2369      Name = 0;
2370      goto CreateNewDecl;
2371    }
2372  } else {
2373    // If this is a named struct, check to see if there was a previous forward
2374    // declaration or definition.
2375    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2376    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2377  }
2378
2379  if (PrevDecl) {
2380    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2381           "unexpected Decl type");
2382
2383    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2384      // If this is a use of a previous tag, or if the tag is already declared
2385      // in the same scope (so that the definition/declaration completes or
2386      // rementions the tag), reuse the decl.
2387      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2388        // Make sure that this wasn't declared as an enum and now used as a
2389        // struct or something similar.
2390        if (PrevTagDecl->getTagKind() != Kind) {
2391          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
2392          Diag(PrevDecl->getLocation(), diag::err_previous_use);
2393          // Recover by making this an anonymous redefinition.
2394          Name = 0;
2395          PrevDecl = 0;
2396        } else {
2397          // If this is a use, return the original decl.
2398
2399          // FIXME: In the future, return a variant or some other clue
2400          //  for the consumer of this Decl to know it doesn't own it.
2401          //  For our current ASTs this shouldn't be a problem, but will
2402          //  need to be changed with DeclGroups.
2403          if (TK == TK_Reference)
2404            return PrevDecl;
2405
2406          // The new decl is a definition?
2407          if (TK == TK_Definition) {
2408            // Diagnose attempts to redefine a tag.
2409            if (RecordDecl* DefRecord =
2410                cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2411              Diag(NameLoc, diag::err_redefinition) << Name;
2412              Diag(DefRecord->getLocation(), diag::err_previous_definition);
2413              // If this is a redefinition, recover by making this struct be
2414              // anonymous, which will make any later references get the previous
2415              // definition.
2416              Name = 0;
2417              PrevDecl = 0;
2418            }
2419            // Okay, this is definition of a previously declared or referenced
2420            // tag.  We're going to create a new Decl.
2421          }
2422        }
2423        // If we get here we have (another) forward declaration.  Just create
2424        // a new decl.
2425      }
2426      else {
2427        // If we get here, this is a definition of a new struct type in a nested
2428        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2429        // new decl/type.  We set PrevDecl to NULL so that the Records
2430        // have distinct types.
2431        PrevDecl = 0;
2432      }
2433    } else {
2434      // PrevDecl is a namespace.
2435      if (isDeclInScope(PrevDecl, DC, S)) {
2436        // The tag name clashes with a namespace name, issue an error and
2437        // recover by making this tag be anonymous.
2438        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2439        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2440        Name = 0;
2441      }
2442    }
2443  }
2444
2445  CreateNewDecl:
2446
2447  // If there is an identifier, use the location of the identifier as the
2448  // location of the decl, otherwise use the location of the struct/union
2449  // keyword.
2450  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2451
2452  // Otherwise, if this is the first time we've seen this tag, create the decl.
2453  TagDecl *New;
2454
2455  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2456  // struct X { int A; } D;    D should chain to X.
2457  if (getLangOptions().CPlusPlus)
2458    // FIXME: Look for a way to use RecordDecl for simple structs.
2459    New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2460                                dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2461  else
2462    New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2463                             dyn_cast_or_null<RecordDecl>(PrevDecl));
2464
2465  // If this has an identifier, add it to the scope stack.
2466  if ((TK == TK_Definition || !PrevDecl) && Name) {
2467    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2468    // we find one that is.
2469    while ((S->getFlags() & Scope::DeclScope) == 0)
2470      S = S->getParent();
2471
2472    // Add it to the decl chain.
2473    PushOnScopeChains(New, S);
2474  }
2475
2476  // Handle #pragma pack: if the #pragma pack stack has non-default
2477  // alignment, make up a packed attribute for this decl. These
2478  // attributes are checked when the ASTContext lays out the
2479  // structure.
2480  //
2481  // It is important for implementing the correct semantics that this
2482  // happen here (in act on tag decl). The #pragma pack stack is
2483  // maintained as a result of parser callbacks which can occur at
2484  // many points during the parsing of a struct declaration (because
2485  // the #pragma tokens are effectively skipped over during the
2486  // parsing of the struct).
2487  if (unsigned Alignment = PackContext.getAlignment())
2488    New->addAttr(new PackedAttr(Alignment * 8));
2489
2490  if (Attr)
2491    ProcessDeclAttributeList(New, Attr);
2492
2493  // Set the lexical context. If the tag has a C++ scope specifier, the
2494  // lexical context will be different from the semantic context.
2495  New->setLexicalDeclContext(CurContext);
2496
2497  return New;
2498}
2499
2500
2501/// Collect the instance variables declared in an Objective-C object.  Used in
2502/// the creation of structures from objects using the @defs directive.
2503static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
2504                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
2505  if (Class->getSuperClass())
2506    CollectIvars(Class->getSuperClass(), Ctx, ivars);
2507
2508  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2509  for (ObjCInterfaceDecl::ivar_iterator
2510        I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2511
2512    ObjCIvarDecl* ID = *I;
2513    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2514                                                ID->getIdentifier(),
2515                                                ID->getType(),
2516                                                ID->getBitWidth()));
2517  }
2518}
2519
2520/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2521/// instance variables of ClassName into Decls.
2522void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2523                     IdentifierInfo *ClassName,
2524                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
2525  // Check that ClassName is a valid class
2526  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2527  if (!Class) {
2528    Diag(DeclStart, diag::err_undef_interface) << ClassName;
2529    return;
2530  }
2531  // Collect the instance variables
2532  CollectIvars(Class, Context, Decls);
2533}
2534
2535/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2536/// types into constant array types in certain situations which would otherwise
2537/// be errors (for GCC compatibility).
2538static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2539                                                    ASTContext &Context) {
2540  // This method tries to turn a variable array into a constant
2541  // array even when the size isn't an ICE.  This is necessary
2542  // for compatibility with code that depends on gcc's buggy
2543  // constant expression folding, like struct {char x[(int)(char*)2];}
2544  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2545  if (!VLATy) return QualType();
2546
2547  APValue Result;
2548  if (!VLATy->getSizeExpr() ||
2549      !VLATy->getSizeExpr()->Evaluate(Result, Context))
2550    return QualType();
2551
2552  assert(Result.isInt() && "Size expressions must be integers!");
2553  llvm::APSInt &Res = Result.getInt();
2554  if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2555    return Context.getConstantArrayType(VLATy->getElementType(),
2556                                        Res, ArrayType::Normal, 0);
2557  return QualType();
2558}
2559
2560/// ActOnField - Each field of a struct/union/class is passed into this in order
2561/// to create a FieldDecl object for it.
2562Sema::DeclTy *Sema::ActOnField(Scope *S,
2563                               SourceLocation DeclStart,
2564                               Declarator &D, ExprTy *BitfieldWidth) {
2565  IdentifierInfo *II = D.getIdentifier();
2566  Expr *BitWidth = (Expr*)BitfieldWidth;
2567  SourceLocation Loc = DeclStart;
2568  if (II) Loc = D.getIdentifierLoc();
2569
2570  // FIXME: Unnamed fields can be handled in various different ways, for
2571  // example, unnamed unions inject all members into the struct namespace!
2572
2573  if (BitWidth) {
2574    // TODO: Validate.
2575    //printf("WARNING: BITFIELDS IGNORED!\n");
2576
2577    // 6.7.2.1p3
2578    // 6.7.2.1p4
2579
2580  } else {
2581    // Not a bitfield.
2582
2583    // validate II.
2584
2585  }
2586
2587  QualType T = GetTypeForDeclarator(D, S);
2588  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2589  bool InvalidDecl = false;
2590
2591  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2592  // than a variably modified type.
2593  if (T->isVariablyModifiedType()) {
2594    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
2595    if (!FixedTy.isNull()) {
2596      Diag(Loc, diag::warn_illegal_constant_array_size);
2597      T = FixedTy;
2598    } else {
2599      Diag(Loc, diag::err_typecheck_field_variable_size);
2600      T = Context.IntTy;
2601      InvalidDecl = true;
2602    }
2603  }
2604  // FIXME: Chain fielddecls together.
2605  FieldDecl *NewFD;
2606
2607  if (getLangOptions().CPlusPlus) {
2608    // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2609    NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2610                                 Loc, II, T,
2611                                 D.getDeclSpec().getStorageClassSpec() ==
2612                                   DeclSpec::SCS_mutable, BitWidth);
2613    if (II)
2614      PushOnScopeChains(NewFD, S);
2615  }
2616  else
2617    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
2618
2619  ProcessDeclAttributes(NewFD, D);
2620
2621  if (D.getInvalidType() || InvalidDecl)
2622    NewFD->setInvalidDecl();
2623  return NewFD;
2624}
2625
2626/// TranslateIvarVisibility - Translate visibility from a token ID to an
2627///  AST enum value.
2628static ObjCIvarDecl::AccessControl
2629TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
2630  switch (ivarVisibility) {
2631  default: assert(0 && "Unknown visitibility kind");
2632  case tok::objc_private: return ObjCIvarDecl::Private;
2633  case tok::objc_public: return ObjCIvarDecl::Public;
2634  case tok::objc_protected: return ObjCIvarDecl::Protected;
2635  case tok::objc_package: return ObjCIvarDecl::Package;
2636  }
2637}
2638
2639/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2640/// in order to create an IvarDecl object for it.
2641Sema::DeclTy *Sema::ActOnIvar(Scope *S,
2642                              SourceLocation DeclStart,
2643                              Declarator &D, ExprTy *BitfieldWidth,
2644                              tok::ObjCKeywordKind Visibility) {
2645  IdentifierInfo *II = D.getIdentifier();
2646  Expr *BitWidth = (Expr*)BitfieldWidth;
2647  SourceLocation Loc = DeclStart;
2648  if (II) Loc = D.getIdentifierLoc();
2649
2650  // FIXME: Unnamed fields can be handled in various different ways, for
2651  // example, unnamed unions inject all members into the struct namespace!
2652
2653
2654  if (BitWidth) {
2655    // TODO: Validate.
2656    //printf("WARNING: BITFIELDS IGNORED!\n");
2657
2658    // 6.7.2.1p3
2659    // 6.7.2.1p4
2660
2661  } else {
2662    // Not a bitfield.
2663
2664    // validate II.
2665
2666  }
2667
2668  QualType T = GetTypeForDeclarator(D, S);
2669  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2670  bool InvalidDecl = false;
2671
2672  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2673  // than a variably modified type.
2674  if (T->isVariablyModifiedType()) {
2675    // FIXME: This diagnostic needs work
2676    Diag(Loc, diag::err_typecheck_illegal_vla) << SourceRange(Loc);
2677    InvalidDecl = true;
2678  }
2679
2680  // Get the visibility (access control) for this ivar.
2681  ObjCIvarDecl::AccessControl ac =
2682    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2683                                        : ObjCIvarDecl::None;
2684
2685  // Construct the decl.
2686  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
2687                                             (Expr *)BitfieldWidth);
2688
2689  // Process attributes attached to the ivar.
2690  ProcessDeclAttributes(NewID, D);
2691
2692  if (D.getInvalidType() || InvalidDecl)
2693    NewID->setInvalidDecl();
2694
2695  return NewID;
2696}
2697
2698void Sema::ActOnFields(Scope* S,
2699                       SourceLocation RecLoc, DeclTy *RecDecl,
2700                       DeclTy **Fields, unsigned NumFields,
2701                       SourceLocation LBrac, SourceLocation RBrac,
2702                       AttributeList *Attr) {
2703  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2704  assert(EnclosingDecl && "missing record or interface decl");
2705  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2706
2707  if (Record)
2708    if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2709      // Diagnose code like:
2710      //     struct S { struct S {} X; };
2711      // We discover this when we complete the outer S.  Reject and ignore the
2712      // outer S.
2713      Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
2714        << DefRecord->getKindName();
2715      Diag(RecLoc, diag::err_previous_definition);
2716      Record->setInvalidDecl();
2717      return;
2718    }
2719
2720  // Verify that all the fields are okay.
2721  unsigned NumNamedMembers = 0;
2722  llvm::SmallVector<FieldDecl*, 32> RecFields;
2723  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
2724
2725  for (unsigned i = 0; i != NumFields; ++i) {
2726
2727    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2728    assert(FD && "missing field decl");
2729
2730    // Remember all fields.
2731    RecFields.push_back(FD);
2732
2733    // Get the type for the field.
2734    Type *FDTy = FD->getType().getTypePtr();
2735
2736    // C99 6.7.2.1p2 - A field may not be a function type.
2737    if (FDTy->isFunctionType()) {
2738      Diag(FD->getLocation(), diag::err_field_declared_as_function)
2739        << FD->getName();
2740      FD->setInvalidDecl();
2741      EnclosingDecl->setInvalidDecl();
2742      continue;
2743    }
2744    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2745    if (FDTy->isIncompleteType()) {
2746      if (!Record) {  // Incomplete ivar type is always an error.
2747        Diag(FD->getLocation(), diag::err_field_incomplete) << FD->getName();
2748        FD->setInvalidDecl();
2749        EnclosingDecl->setInvalidDecl();
2750        continue;
2751      }
2752      if (i != NumFields-1 ||                   // ... that the last member ...
2753          !Record->isStruct() ||  // ... of a structure ...
2754          !FDTy->isArrayType()) {         //... may have incomplete array type.
2755        Diag(FD->getLocation(), diag::err_field_incomplete) << FD->getName();
2756        FD->setInvalidDecl();
2757        EnclosingDecl->setInvalidDecl();
2758        continue;
2759      }
2760      if (NumNamedMembers < 1) {  //... must have more than named member ...
2761        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
2762          << FD->getName();
2763        FD->setInvalidDecl();
2764        EnclosingDecl->setInvalidDecl();
2765        continue;
2766      }
2767      // Okay, we have a legal flexible array member at the end of the struct.
2768      if (Record)
2769        Record->setHasFlexibleArrayMember(true);
2770    }
2771    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2772    /// field of another structure or the element of an array.
2773    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
2774      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2775        // If this is a member of a union, then entire union becomes "flexible".
2776        if (Record && Record->isUnion()) {
2777          Record->setHasFlexibleArrayMember(true);
2778        } else {
2779          // If this is a struct/class and this is not the last element, reject
2780          // it.  Note that GCC supports variable sized arrays in the middle of
2781          // structures.
2782          if (i != NumFields-1) {
2783            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
2784              << FD->getName();
2785            FD->setInvalidDecl();
2786            EnclosingDecl->setInvalidDecl();
2787            continue;
2788          }
2789          // We support flexible arrays at the end of structs in other structs
2790          // as an extension.
2791          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
2792            << FD->getName();
2793          if (Record)
2794            Record->setHasFlexibleArrayMember(true);
2795        }
2796      }
2797    }
2798    /// A field cannot be an Objective-c object
2799    if (FDTy->isObjCInterfaceType()) {
2800      Diag(FD->getLocation(), diag::err_statically_allocated_object)
2801        << FD->getName();
2802      FD->setInvalidDecl();
2803      EnclosingDecl->setInvalidDecl();
2804      continue;
2805    }
2806    // Keep track of the number of named members.
2807    if (IdentifierInfo *II = FD->getIdentifier()) {
2808      // Detect duplicate member names.
2809      if (!FieldIDs.insert(II)) {
2810        Diag(FD->getLocation(), diag::err_duplicate_member) << II;
2811        // Find the previous decl.
2812        SourceLocation PrevLoc;
2813        for (unsigned i = 0; ; ++i) {
2814          assert(i != RecFields.size() && "Didn't find previous def!");
2815          if (RecFields[i]->getIdentifier() == II) {
2816            PrevLoc = RecFields[i]->getLocation();
2817            break;
2818          }
2819        }
2820        Diag(PrevLoc, diag::err_previous_definition);
2821        FD->setInvalidDecl();
2822        EnclosingDecl->setInvalidDecl();
2823        continue;
2824      }
2825      ++NumNamedMembers;
2826    }
2827  }
2828
2829  // Okay, we successfully defined 'Record'.
2830  if (Record) {
2831    Record->defineBody(Context, &RecFields[0], RecFields.size());
2832    // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2833    // Sema::ActOnFinishCXXClassDef.
2834    if (!isa<CXXRecordDecl>(Record))
2835      Consumer.HandleTagDeclDefinition(Record);
2836  } else {
2837    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2838    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2839      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2840    else if (ObjCImplementationDecl *IMPDecl =
2841               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
2842      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2843      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
2844      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
2845    }
2846  }
2847
2848  if (Attr)
2849    ProcessDeclAttributeList(Record, Attr);
2850}
2851
2852Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
2853                                      DeclTy *lastEnumConst,
2854                                      SourceLocation IdLoc, IdentifierInfo *Id,
2855                                      SourceLocation EqualLoc, ExprTy *val) {
2856  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
2857  EnumConstantDecl *LastEnumConst =
2858    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2859  Expr *Val = static_cast<Expr*>(val);
2860
2861  // The scope passed in may not be a decl scope.  Zip up the scope tree until
2862  // we find one that is.
2863  while ((S->getFlags() & Scope::DeclScope) == 0)
2864    S = S->getParent();
2865
2866  // Verify that there isn't already something declared with this name in this
2867  // scope.
2868  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
2869    // When in C++, we may get a TagDecl with the same name; in this case the
2870    // enum constant will 'hide' the tag.
2871    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2872           "Received TagDecl when not in C++!");
2873    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
2874      if (isa<EnumConstantDecl>(PrevDecl))
2875        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
2876      else
2877        Diag(IdLoc, diag::err_redefinition) << Id;
2878      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2879      delete Val;
2880      return 0;
2881    }
2882  }
2883
2884  llvm::APSInt EnumVal(32);
2885  QualType EltTy;
2886  if (Val) {
2887    // Make sure to promote the operand type to int.
2888    UsualUnaryConversions(Val);
2889
2890    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2891    SourceLocation ExpLoc;
2892    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2893      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr) << Id;
2894      delete Val;
2895      Val = 0;  // Just forget about it.
2896    } else {
2897      EltTy = Val->getType();
2898    }
2899  }
2900
2901  if (!Val) {
2902    if (LastEnumConst) {
2903      // Assign the last value + 1.
2904      EnumVal = LastEnumConst->getInitVal();
2905      ++EnumVal;
2906
2907      // Check for overflow on increment.
2908      if (EnumVal < LastEnumConst->getInitVal())
2909        Diag(IdLoc, diag::warn_enum_value_overflow);
2910
2911      EltTy = LastEnumConst->getType();
2912    } else {
2913      // First value, set to zero.
2914      EltTy = Context.IntTy;
2915      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
2916    }
2917  }
2918
2919  EnumConstantDecl *New =
2920    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2921                             Val, EnumVal,
2922                             LastEnumConst);
2923
2924  // Register this decl in the current scope stack.
2925  PushOnScopeChains(New, S);
2926  return New;
2927}
2928
2929// FIXME: For consistency with ActOnFields(), we should have the parser
2930// pass in the source location for the left/right braces.
2931void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
2932                         DeclTy **Elements, unsigned NumElements) {
2933  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2934
2935  if (Enum && Enum->isDefinition()) {
2936    // Diagnose code like:
2937    //   enum e0 {
2938    //     E0 = sizeof(enum e0 { E1 })
2939    //   };
2940    Diag(Enum->getLocation(), diag::err_nested_redefinition) << Enum->getName();
2941    Diag(EnumLoc, diag::err_previous_definition);
2942    Enum->setInvalidDecl();
2943    return;
2944  }
2945  // TODO: If the result value doesn't fit in an int, it must be a long or long
2946  // long value.  ISO C does not support this, but GCC does as an extension,
2947  // emit a warning.
2948  unsigned IntWidth = Context.Target.getIntWidth();
2949
2950  // Verify that all the values are okay, compute the size of the values, and
2951  // reverse the list.
2952  unsigned NumNegativeBits = 0;
2953  unsigned NumPositiveBits = 0;
2954
2955  // Keep track of whether all elements have type int.
2956  bool AllElementsInt = true;
2957
2958  EnumConstantDecl *EltList = 0;
2959  for (unsigned i = 0; i != NumElements; ++i) {
2960    EnumConstantDecl *ECD =
2961      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2962    if (!ECD) continue;  // Already issued a diagnostic.
2963
2964    // If the enum value doesn't fit in an int, emit an extension warning.
2965    const llvm::APSInt &InitVal = ECD->getInitVal();
2966    assert(InitVal.getBitWidth() >= IntWidth &&
2967           "Should have promoted value to int");
2968    if (InitVal.getBitWidth() > IntWidth) {
2969      llvm::APSInt V(InitVal);
2970      V.trunc(IntWidth);
2971      V.extend(InitVal.getBitWidth());
2972      if (V != InitVal)
2973        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
2974          << InitVal.toString(10);
2975    }
2976
2977    // Keep track of the size of positive and negative values.
2978    if (InitVal.isUnsigned() || InitVal.isNonNegative())
2979      NumPositiveBits = std::max(NumPositiveBits,
2980                                 (unsigned)InitVal.getActiveBits());
2981    else
2982      NumNegativeBits = std::max(NumNegativeBits,
2983                                 (unsigned)InitVal.getMinSignedBits());
2984
2985    // Keep track of whether every enum element has type int (very commmon).
2986    if (AllElementsInt)
2987      AllElementsInt = ECD->getType() == Context.IntTy;
2988
2989    ECD->setNextDeclarator(EltList);
2990    EltList = ECD;
2991  }
2992
2993  // Figure out the type that should be used for this enum.
2994  // FIXME: Support attribute(packed) on enums and -fshort-enums.
2995  QualType BestType;
2996  unsigned BestWidth;
2997
2998  if (NumNegativeBits) {
2999    // If there is a negative value, figure out the smallest integer type (of
3000    // int/long/longlong) that fits.
3001    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
3002      BestType = Context.IntTy;
3003      BestWidth = IntWidth;
3004    } else {
3005      BestWidth = Context.Target.getLongWidth();
3006
3007      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
3008        BestType = Context.LongTy;
3009      else {
3010        BestWidth = Context.Target.getLongLongWidth();
3011
3012        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
3013          Diag(Enum->getLocation(), diag::warn_enum_too_large);
3014        BestType = Context.LongLongTy;
3015      }
3016    }
3017  } else {
3018    // If there is no negative value, figure out which of uint, ulong, ulonglong
3019    // fits.
3020    if (NumPositiveBits <= IntWidth) {
3021      BestType = Context.UnsignedIntTy;
3022      BestWidth = IntWidth;
3023    } else if (NumPositiveBits <=
3024               (BestWidth = Context.Target.getLongWidth())) {
3025      BestType = Context.UnsignedLongTy;
3026    } else {
3027      BestWidth = Context.Target.getLongLongWidth();
3028      assert(NumPositiveBits <= BestWidth &&
3029             "How could an initializer get larger than ULL?");
3030      BestType = Context.UnsignedLongLongTy;
3031    }
3032  }
3033
3034  // Loop over all of the enumerator constants, changing their types to match
3035  // the type of the enum if needed.
3036  for (unsigned i = 0; i != NumElements; ++i) {
3037    EnumConstantDecl *ECD =
3038      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3039    if (!ECD) continue;  // Already issued a diagnostic.
3040
3041    // Standard C says the enumerators have int type, but we allow, as an
3042    // extension, the enumerators to be larger than int size.  If each
3043    // enumerator value fits in an int, type it as an int, otherwise type it the
3044    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
3045    // that X has type 'int', not 'unsigned'.
3046    if (ECD->getType() == Context.IntTy) {
3047      // Make sure the init value is signed.
3048      llvm::APSInt IV = ECD->getInitVal();
3049      IV.setIsSigned(true);
3050      ECD->setInitVal(IV);
3051      continue;  // Already int type.
3052    }
3053
3054    // Determine whether the value fits into an int.
3055    llvm::APSInt InitVal = ECD->getInitVal();
3056    bool FitsInInt;
3057    if (InitVal.isUnsigned() || !InitVal.isNegative())
3058      FitsInInt = InitVal.getActiveBits() < IntWidth;
3059    else
3060      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3061
3062    // If it fits into an integer type, force it.  Otherwise force it to match
3063    // the enum decl type.
3064    QualType NewTy;
3065    unsigned NewWidth;
3066    bool NewSign;
3067    if (FitsInInt) {
3068      NewTy = Context.IntTy;
3069      NewWidth = IntWidth;
3070      NewSign = true;
3071    } else if (ECD->getType() == BestType) {
3072      // Already the right type!
3073      continue;
3074    } else {
3075      NewTy = BestType;
3076      NewWidth = BestWidth;
3077      NewSign = BestType->isSignedIntegerType();
3078    }
3079
3080    // Adjust the APSInt value.
3081    InitVal.extOrTrunc(NewWidth);
3082    InitVal.setIsSigned(NewSign);
3083    ECD->setInitVal(InitVal);
3084
3085    // Adjust the Expr initializer and type.
3086    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3087                                          /*isLvalue=*/false));
3088    ECD->setType(NewTy);
3089  }
3090
3091  Enum->defineElements(EltList, BestType);
3092  Consumer.HandleTagDeclDefinition(Enum);
3093}
3094
3095Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3096                                          ExprTy *expr) {
3097  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3098
3099  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
3100}
3101
3102Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
3103                                     SourceLocation LBrace,
3104                                     SourceLocation RBrace,
3105                                     const char *Lang,
3106                                     unsigned StrSize,
3107                                     DeclTy *D) {
3108  LinkageSpecDecl::LanguageIDs Language;
3109  Decl *dcl = static_cast<Decl *>(D);
3110  if (strncmp(Lang, "\"C\"", StrSize) == 0)
3111    Language = LinkageSpecDecl::lang_c;
3112  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3113    Language = LinkageSpecDecl::lang_cxx;
3114  else {
3115    Diag(Loc, diag::err_bad_language);
3116    return 0;
3117  }
3118
3119  // FIXME: Add all the various semantics of linkage specifications
3120  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
3121}
3122
3123void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3124                           ExprTy *alignment, SourceLocation PragmaLoc,
3125                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
3126  Expr *Alignment = static_cast<Expr *>(alignment);
3127
3128  // If specified then alignment must be a "small" power of two.
3129  unsigned AlignmentVal = 0;
3130  if (Alignment) {
3131    llvm::APSInt Val;
3132    if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3133        !Val.isPowerOf2() ||
3134        Val.getZExtValue() > 16) {
3135      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3136      delete Alignment;
3137      return; // Ignore
3138    }
3139
3140    AlignmentVal = (unsigned) Val.getZExtValue();
3141  }
3142
3143  switch (Kind) {
3144  case Action::PPK_Default: // pack([n])
3145    PackContext.setAlignment(AlignmentVal);
3146    break;
3147
3148  case Action::PPK_Show: // pack(show)
3149    // Show the current alignment, making sure to show the right value
3150    // for the default.
3151    AlignmentVal = PackContext.getAlignment();
3152    // FIXME: This should come from the target.
3153    if (AlignmentVal == 0)
3154      AlignmentVal = 8;
3155    Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
3156    break;
3157
3158  case Action::PPK_Push: // pack(push [, id] [, [n])
3159    PackContext.push(Name);
3160    // Set the new alignment if specified.
3161    if (Alignment)
3162      PackContext.setAlignment(AlignmentVal);
3163    break;
3164
3165  case Action::PPK_Pop: // pack(pop [, id] [,  n])
3166    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3167    // "#pragma pack(pop, identifier, n) is undefined"
3168    if (Alignment && Name)
3169      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3170
3171    // Do the pop.
3172    if (!PackContext.pop(Name)) {
3173      // If a name was specified then failure indicates the name
3174      // wasn't found. Otherwise failure indicates the stack was
3175      // empty.
3176      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3177        << (Name ? "no record matching name" : "stack empty");
3178
3179      // FIXME: Warn about popping named records as MSVC does.
3180    } else {
3181      // Pop succeeded, set the new alignment if specified.
3182      if (Alignment)
3183        PackContext.setAlignment(AlignmentVal);
3184    }
3185    break;
3186
3187  default:
3188    assert(0 && "Invalid #pragma pack kind.");
3189  }
3190}
3191
3192bool PragmaPackStack::pop(IdentifierInfo *Name) {
3193  if (Stack.empty())
3194    return false;
3195
3196  // If name is empty just pop top.
3197  if (!Name) {
3198    Alignment = Stack.back().first;
3199    Stack.pop_back();
3200    return true;
3201  }
3202
3203  // Otherwise, find the named record.
3204  for (unsigned i = Stack.size(); i != 0; ) {
3205    --i;
3206    if (Stack[i].second == Name) {
3207      // Found it, pop up to and including this record.
3208      Alignment = Stack[i].first;
3209      Stack.erase(Stack.begin() + i, Stack.end());
3210      return true;
3211    }
3212  }
3213
3214  return false;
3215}
3216