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