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