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