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