SemaDecl.cpp revision a24dc2e38c7fb0f7f138b3d14b5f0f241fd0eccf
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/Analysis/CFG.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/ParseDiagnostic.h"
27#include "clang/Parse/Template.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "llvm/ADT/BitVector.h"
35#include "llvm/ADT/STLExtras.h"
36#include <algorithm>
37#include <cstring>
38#include <functional>
39#include <queue>
40using namespace clang;
41
42/// getDeclName - Return a pretty name for the specified decl if possible, or
43/// an empty string if not.  This is used for pretty crash reporting.
44std::string Sema::getDeclName(DeclPtrTy d) {
45  Decl *D = d.getAs<Decl>();
46  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
47    return DN->getQualifiedNameAsString();
48  return "";
49}
50
51Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
52  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
53}
54
55/// \brief If the identifier refers to a type name within this scope,
56/// return the declaration of that type.
57///
58/// This routine performs ordinary name lookup of the identifier II
59/// within the given scope, with optional C++ scope specifier SS, to
60/// determine whether the name refers to a type. If so, returns an
61/// opaque pointer (actually a QualType) corresponding to that
62/// type. Otherwise, returns NULL.
63///
64/// If name lookup results in an ambiguity, this routine will complain
65/// and then return NULL.
66Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
67                                Scope *S, const CXXScopeSpec *SS,
68                                bool isClassName) {
69  // C++ [temp.res]p3:
70  //   A qualified-id that refers to a type and in which the
71  //   nested-name-specifier depends on a template-parameter (14.6.2)
72  //   shall be prefixed by the keyword typename to indicate that the
73  //   qualified-id denotes a type, forming an
74  //   elaborated-type-specifier (7.1.5.3).
75  //
76  // We therefore do not perform any name lookup if the result would
77  // refer to a member of an unknown specialization.
78  if (SS && isUnknownSpecialization(*SS)) {
79    if (!isClassName)
80      return 0;
81
82    // We know from the grammar that this name refers to a type, so build a
83    // TypenameType node to describe the type.
84    // FIXME: Record somewhere that this TypenameType node has no "typename"
85    // keyword associated with it.
86    return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
87                             II, SS->getRange()).getAsOpaquePtr();
88  }
89
90  LookupResult Result(*this, &II, NameLoc, LookupOrdinaryName);
91  LookupParsedName(Result, S, SS, false);
92
93  NamedDecl *IIDecl = 0;
94  switch (Result.getResultKind()) {
95  case LookupResult::NotFound:
96  case LookupResult::FoundOverloaded:
97    return 0;
98
99  case LookupResult::Ambiguous:
100    // Recover from type-hiding ambiguities by hiding the type.  We'll
101    // do the lookup again when looking for an object, and we can
102    // diagnose the error then.  If we don't do this, then the error
103    // about hiding the type will be immediately followed by an error
104    // that only makes sense if the identifier was treated like a type.
105    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
106      Result.suppressDiagnostics();
107      return 0;
108    }
109
110    // Look to see if we have a type anywhere in the list of results.
111    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
112         Res != ResEnd; ++Res) {
113      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
114        if (!IIDecl ||
115            (*Res)->getLocation().getRawEncoding() <
116              IIDecl->getLocation().getRawEncoding())
117          IIDecl = *Res;
118      }
119    }
120
121    if (!IIDecl) {
122      // None of the entities we found is a type, so there is no way
123      // to even assume that the result is a type. In this case, don't
124      // complain about the ambiguity. The parser will either try to
125      // perform this lookup again (e.g., as an object name), which
126      // will produce the ambiguity, or will complain that it expected
127      // a type name.
128      Result.suppressDiagnostics();
129      return 0;
130    }
131
132    // We found a type within the ambiguous lookup; diagnose the
133    // ambiguity and then return that type. This might be the right
134    // answer, or it might not be, but it suppresses any attempt to
135    // perform the name lookup again.
136    break;
137
138  case LookupResult::Found:
139    IIDecl = Result.getFoundDecl();
140    break;
141  }
142
143  assert(IIDecl && "Didn't find decl");
144
145  QualType T;
146  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
147    DiagnoseUseOfDecl(IIDecl, NameLoc);
148
149    // C++ [temp.local]p2:
150    //   Within the scope of a class template specialization or
151    //   partial specialization, when the injected-class-name is
152    //   not followed by a <, it is equivalent to the
153    //   injected-class-name followed by the template-argument s
154    //   of the class template specialization or partial
155    //   specialization enclosed in <>.
156    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
157      if (RD->isInjectedClassName())
158        if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
159          T = Template->getInjectedClassNameType(Context);
160
161    if (T.isNull())
162      T = Context.getTypeDeclType(TD);
163
164    if (SS)
165      T = getQualifiedNameType(*SS, T);
166
167  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
168    T = Context.getObjCInterfaceType(IDecl);
169  } else {
170    // If it's not plausibly a type, suppress diagnostics.
171    Result.suppressDiagnostics();
172    return 0;
173  }
174
175  return T.getAsOpaquePtr();
176}
177
178/// isTagName() - This method is called *for error recovery purposes only*
179/// to determine if the specified name is a valid tag name ("struct foo").  If
180/// so, this returns the TST for the tag corresponding to it (TST_enum,
181/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
182/// where the user forgot to specify the tag.
183DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
184  // Do a tag name lookup in this scope.
185  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
186  LookupName(R, S, false);
187  R.suppressDiagnostics();
188  if (R.getResultKind() == LookupResult::Found)
189    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsSingleDecl(Context))) {
190      switch (TD->getTagKind()) {
191      case TagDecl::TK_struct: return DeclSpec::TST_struct;
192      case TagDecl::TK_union:  return DeclSpec::TST_union;
193      case TagDecl::TK_class:  return DeclSpec::TST_class;
194      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
195      }
196    }
197
198  return DeclSpec::TST_unspecified;
199}
200
201bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
202                                   SourceLocation IILoc,
203                                   Scope *S,
204                                   const CXXScopeSpec *SS,
205                                   TypeTy *&SuggestedType) {
206  // We don't have anything to suggest (yet).
207  SuggestedType = 0;
208
209  // FIXME: Should we move the logic that tries to recover from a missing tag
210  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
211
212  if (!SS)
213    Diag(IILoc, diag::err_unknown_typename) << &II;
214  else if (DeclContext *DC = computeDeclContext(*SS, false))
215    Diag(IILoc, diag::err_typename_nested_not_found)
216      << &II << DC << SS->getRange();
217  else if (isDependentScopeSpecifier(*SS)) {
218    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
219      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
220      << SourceRange(SS->getRange().getBegin(), IILoc)
221      << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
222                                               "typename ");
223    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
224  } else {
225    assert(SS && SS->isInvalid() &&
226           "Invalid scope specifier has already been diagnosed");
227  }
228
229  return true;
230}
231
232// Determines the context to return to after temporarily entering a
233// context.  This depends in an unnecessarily complicated way on the
234// exact ordering of callbacks from the parser.
235DeclContext *Sema::getContainingDC(DeclContext *DC) {
236
237  // Functions defined inline within classes aren't parsed until we've
238  // finished parsing the top-level class, so the top-level class is
239  // the context we'll need to return to.
240  if (isa<FunctionDecl>(DC)) {
241    DC = DC->getLexicalParent();
242
243    // A function not defined within a class will always return to its
244    // lexical context.
245    if (!isa<CXXRecordDecl>(DC))
246      return DC;
247
248    // A C++ inline method/friend is parsed *after* the topmost class
249    // it was declared in is fully parsed ("complete");  the topmost
250    // class is the context we need to return to.
251    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
252      DC = RD;
253
254    // Return the declaration context of the topmost class the inline method is
255    // declared in.
256    return DC;
257  }
258
259  if (isa<ObjCMethodDecl>(DC))
260    return Context.getTranslationUnitDecl();
261
262  return DC->getLexicalParent();
263}
264
265void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
266  assert(getContainingDC(DC) == CurContext &&
267      "The next DeclContext should be lexically contained in the current one.");
268  CurContext = DC;
269  S->setEntity(DC);
270}
271
272void Sema::PopDeclContext() {
273  assert(CurContext && "DeclContext imbalance!");
274
275  CurContext = getContainingDC(CurContext);
276}
277
278/// EnterDeclaratorContext - Used when we must lookup names in the context
279/// of a declarator's nested name specifier.
280void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
281  assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
282  PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
283  CurContext = DC;
284  assert(CurContext && "No context?");
285  S->setEntity(CurContext);
286}
287
288void Sema::ExitDeclaratorContext(Scope *S) {
289  S->setEntity(PreDeclaratorDC);
290  PreDeclaratorDC = 0;
291
292  // Reset CurContext to the nearest enclosing context.
293  while (!S->getEntity() && S->getParent())
294    S = S->getParent();
295  CurContext = static_cast<DeclContext*>(S->getEntity());
296  assert(CurContext && "No context?");
297}
298
299/// \brief Determine whether we allow overloading of the function
300/// PrevDecl with another declaration.
301///
302/// This routine determines whether overloading is possible, not
303/// whether some new function is actually an overload. It will return
304/// true in C++ (where we can always provide overloads) or, as an
305/// extension, in C when the previous function is already an
306/// overloaded function declaration or has the "overloadable"
307/// attribute.
308static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
309  if (Context.getLangOptions().CPlusPlus)
310    return true;
311
312  if (isa<OverloadedFunctionDecl>(PrevDecl))
313    return true;
314
315  return PrevDecl->getAttr<OverloadableAttr>() != 0;
316}
317
318/// Add this decl to the scope shadowed decl chains.
319void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
320  // Move up the scope chain until we find the nearest enclosing
321  // non-transparent context. The declaration will be introduced into this
322  // scope.
323  while (S->getEntity() &&
324         ((DeclContext *)S->getEntity())->isTransparentContext())
325    S = S->getParent();
326
327  // Add scoped declarations into their context, so that they can be
328  // found later. Declarations without a context won't be inserted
329  // into any context.
330  if (AddToContext)
331    CurContext->addDecl(D);
332
333  // Out-of-line function and variable definitions should not be pushed into
334  // scope.
335  if ((isa<FunctionTemplateDecl>(D) &&
336       cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
337      (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isOutOfLine()) ||
338      (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
339    return;
340
341  // If this replaces anything in the current scope,
342  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
343                               IEnd = IdResolver.end();
344  for (; I != IEnd; ++I) {
345    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
346      S->RemoveDecl(DeclPtrTy::make(*I));
347      IdResolver.RemoveDecl(*I);
348
349      // Should only need to replace one decl.
350      break;
351    }
352  }
353
354  S->AddDecl(DeclPtrTy::make(D));
355  IdResolver.AddDecl(D);
356}
357
358bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
359  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
360    // Look inside the overload set to determine if any of the declarations
361    // are in scope. (Possibly) build a new overload set containing only
362    // those declarations that are in scope.
363    OverloadedFunctionDecl *NewOvl = 0;
364    bool FoundInScope = false;
365    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
366         FEnd = Ovl->function_end();
367         F != FEnd; ++F) {
368      NamedDecl *FD = F->get();
369      if (!isDeclInScope(FD, Ctx, S)) {
370        if (!NewOvl && F != Ovl->function_begin()) {
371          NewOvl = OverloadedFunctionDecl::Create(Context,
372                                                  F->get()->getDeclContext(),
373                                                  F->get()->getDeclName());
374          D = NewOvl;
375          for (OverloadedFunctionDecl::function_iterator
376               First = Ovl->function_begin();
377               First != F; ++First)
378            NewOvl->addOverload(*First);
379        }
380      } else {
381        FoundInScope = true;
382        if (NewOvl)
383          NewOvl->addOverload(*F);
384      }
385    }
386
387    return FoundInScope;
388  }
389
390  return IdResolver.isDeclInScope(D, Ctx, Context, S);
391}
392
393static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
394  if (D->isUsed() || D->hasAttr<UnusedAttr>())
395    return false;
396
397  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
398    if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
399      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
400        if (!RD->hasTrivialConstructor())
401          return false;
402        if (!RD->hasTrivialDestructor())
403          return false;
404      }
405    }
406  }
407
408  return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
409          !isa<ImplicitParamDecl>(D) &&
410          D->getDeclContext()->isFunctionOrMethod());
411}
412
413void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
414  if (S->decl_empty()) return;
415  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
416         "Scope shouldn't contain decls!");
417
418  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
419       I != E; ++I) {
420    Decl *TmpD = (*I).getAs<Decl>();
421    assert(TmpD && "This decl didn't get pushed??");
422
423    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
424    NamedDecl *D = cast<NamedDecl>(TmpD);
425
426    if (!D->getDeclName()) continue;
427
428    // Diagnose unused variables in this scope.
429    if (ShouldDiagnoseUnusedDecl(D))
430      Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
431
432    // Remove this name from our lexical scope.
433    IdResolver.RemoveDecl(D);
434  }
435}
436
437/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
438/// return 0 if one not found.
439ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
440  // The third "scope" argument is 0 since we aren't enabling lazy built-in
441  // creation from this context.
442  NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
443
444  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
445}
446
447/// getNonFieldDeclScope - Retrieves the innermost scope, starting
448/// from S, where a non-field would be declared. This routine copes
449/// with the difference between C and C++ scoping rules in structs and
450/// unions. For example, the following code is well-formed in C but
451/// ill-formed in C++:
452/// @code
453/// struct S6 {
454///   enum { BAR } e;
455/// };
456///
457/// void test_S6() {
458///   struct S6 a;
459///   a.e = BAR;
460/// }
461/// @endcode
462/// For the declaration of BAR, this routine will return a different
463/// scope. The scope S will be the scope of the unnamed enumeration
464/// within S6. In C++, this routine will return the scope associated
465/// with S6, because the enumeration's scope is a transparent
466/// context but structures can contain non-field names. In C, this
467/// routine will return the translation unit scope, since the
468/// enumeration's scope is a transparent context and structures cannot
469/// contain non-field names.
470Scope *Sema::getNonFieldDeclScope(Scope *S) {
471  while (((S->getFlags() & Scope::DeclScope) == 0) ||
472         (S->getEntity() &&
473          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
474         (S->isClassScope() && !getLangOptions().CPlusPlus))
475    S = S->getParent();
476  return S;
477}
478
479void Sema::InitBuiltinVaListType() {
480  if (!Context.getBuiltinVaListType().isNull())
481    return;
482
483  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
484  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
485  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
486  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
487}
488
489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
490/// file scope.  lazily create a decl for it. ForRedeclaration is true
491/// if we're creating this built-in in anticipation of redeclaring the
492/// built-in.
493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
494                                     Scope *S, bool ForRedeclaration,
495                                     SourceLocation Loc) {
496  Builtin::ID BID = (Builtin::ID)bid;
497
498  if (Context.BuiltinInfo.hasVAListUse(BID))
499    InitBuiltinVaListType();
500
501  ASTContext::GetBuiltinTypeError Error;
502  QualType R = Context.GetBuiltinType(BID, Error);
503  switch (Error) {
504  case ASTContext::GE_None:
505    // Okay
506    break;
507
508  case ASTContext::GE_Missing_stdio:
509    if (ForRedeclaration)
510      Diag(Loc, diag::err_implicit_decl_requires_stdio)
511        << Context.BuiltinInfo.GetName(BID);
512    return 0;
513
514  case ASTContext::GE_Missing_setjmp:
515    if (ForRedeclaration)
516      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
517        << Context.BuiltinInfo.GetName(BID);
518    return 0;
519  }
520
521  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
522    Diag(Loc, diag::ext_implicit_lib_function_decl)
523      << Context.BuiltinInfo.GetName(BID)
524      << R;
525    if (Context.BuiltinInfo.getHeaderName(BID) &&
526        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
527          != Diagnostic::Ignored)
528      Diag(Loc, diag::note_please_include_header)
529        << Context.BuiltinInfo.getHeaderName(BID)
530        << Context.BuiltinInfo.GetName(BID);
531  }
532
533  FunctionDecl *New = FunctionDecl::Create(Context,
534                                           Context.getTranslationUnitDecl(),
535                                           Loc, II, R, /*DInfo=*/0,
536                                           FunctionDecl::Extern, false,
537                                           /*hasPrototype=*/true);
538  New->setImplicit();
539
540  // Create Decl objects for each parameter, adding them to the
541  // FunctionDecl.
542  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
543    llvm::SmallVector<ParmVarDecl*, 16> Params;
544    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
545      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
546                                           FT->getArgType(i), /*DInfo=*/0,
547                                           VarDecl::None, 0));
548    New->setParams(Context, Params.data(), Params.size());
549  }
550
551  AddKnownFunctionAttributes(New);
552
553  // TUScope is the translation-unit scope to insert this function into.
554  // FIXME: This is hideous. We need to teach PushOnScopeChains to
555  // relate Scopes to DeclContexts, and probably eliminate CurContext
556  // entirely, but we're not there yet.
557  DeclContext *SavedContext = CurContext;
558  CurContext = Context.getTranslationUnitDecl();
559  PushOnScopeChains(New, TUScope);
560  CurContext = SavedContext;
561  return New;
562}
563
564/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
565/// same name and scope as a previous declaration 'Old'.  Figure out
566/// how to resolve this situation, merging decls or emitting
567/// diagnostics as appropriate. If there was an error, set New to be invalid.
568///
569void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
570  // If either decl is known invalid already, set the new one to be invalid and
571  // don't bother doing any merging checks.
572  if (New->isInvalidDecl() || OldD->isInvalidDecl())
573    return New->setInvalidDecl();
574
575  // Allow multiple definitions for ObjC built-in typedefs.
576  // FIXME: Verify the underlying types are equivalent!
577  if (getLangOptions().ObjC1) {
578    const IdentifierInfo *TypeID = New->getIdentifier();
579    switch (TypeID->getLength()) {
580    default: break;
581    case 2:
582      if (!TypeID->isStr("id"))
583        break;
584      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
585      // Install the built-in type for 'id', ignoring the current definition.
586      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
587      return;
588    case 5:
589      if (!TypeID->isStr("Class"))
590        break;
591      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
592      // Install the built-in type for 'Class', ignoring the current definition.
593      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
594      return;
595    case 3:
596      if (!TypeID->isStr("SEL"))
597        break;
598      Context.setObjCSelType(Context.getTypeDeclType(New));
599      return;
600    case 8:
601      if (!TypeID->isStr("Protocol"))
602        break;
603      Context.setObjCProtoType(New->getUnderlyingType());
604      return;
605    }
606    // Fall through - the typedef name was not a builtin type.
607  }
608  // Verify the old decl was also a type.
609  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
610  if (!Old) {
611    Diag(New->getLocation(), diag::err_redefinition_different_kind)
612      << New->getDeclName();
613    if (OldD->getLocation().isValid())
614      Diag(OldD->getLocation(), diag::note_previous_definition);
615    return New->setInvalidDecl();
616  }
617
618  // Determine the "old" type we'll use for checking and diagnostics.
619  QualType OldType;
620  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
621    OldType = OldTypedef->getUnderlyingType();
622  else
623    OldType = Context.getTypeDeclType(Old);
624
625  // If the typedef types are not identical, reject them in all languages and
626  // with any extensions enabled.
627
628  if (OldType != New->getUnderlyingType() &&
629      Context.getCanonicalType(OldType) !=
630      Context.getCanonicalType(New->getUnderlyingType())) {
631    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
632      << New->getUnderlyingType() << OldType;
633    if (Old->getLocation().isValid())
634      Diag(Old->getLocation(), diag::note_previous_definition);
635    return New->setInvalidDecl();
636  }
637
638  if (getLangOptions().Microsoft)
639    return;
640
641  // C++ [dcl.typedef]p2:
642  //   In a given non-class scope, a typedef specifier can be used to
643  //   redefine the name of any type declared in that scope to refer
644  //   to the type to which it already refers.
645  if (getLangOptions().CPlusPlus) {
646    if (!isa<CXXRecordDecl>(CurContext))
647      return;
648    Diag(New->getLocation(), diag::err_redefinition)
649      << New->getDeclName();
650    Diag(Old->getLocation(), diag::note_previous_definition);
651    return New->setInvalidDecl();
652  }
653
654  // If we have a redefinition of a typedef in C, emit a warning.  This warning
655  // is normally mapped to an error, but can be controlled with
656  // -Wtypedef-redefinition.  If either the original or the redefinition is
657  // in a system header, don't emit this for compatibility with GCC.
658  if (PP.getDiagnostics().getSuppressSystemWarnings() &&
659      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
660       Context.getSourceManager().isInSystemHeader(New->getLocation())))
661    return;
662
663  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
664    << New->getDeclName();
665  Diag(Old->getLocation(), diag::note_previous_definition);
666  return;
667}
668
669/// DeclhasAttr - returns true if decl Declaration already has the target
670/// attribute.
671static bool
672DeclHasAttr(const Decl *decl, const Attr *target) {
673  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
674    if (attr->getKind() == target->getKind())
675      return true;
676
677  return false;
678}
679
680/// MergeAttributes - append attributes from the Old decl to the New one.
681static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
682  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
683    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
684      Attr *NewAttr = attr->clone(C);
685      NewAttr->setInherited(true);
686      New->addAttr(NewAttr);
687    }
688  }
689}
690
691/// Used in MergeFunctionDecl to keep track of function parameters in
692/// C.
693struct GNUCompatibleParamWarning {
694  ParmVarDecl *OldParm;
695  ParmVarDecl *NewParm;
696  QualType PromotedType;
697};
698
699/// MergeFunctionDecl - We just parsed a function 'New' from
700/// declarator D which has the same name and scope as a previous
701/// declaration 'Old'.  Figure out how to resolve this situation,
702/// merging decls or emitting diagnostics as appropriate.
703///
704/// In C++, New and Old must be declarations that are not
705/// overloaded. Use IsOverload to determine whether New and Old are
706/// overloaded, and to select the Old declaration that New should be
707/// merged with.
708///
709/// Returns true if there was an error, false otherwise.
710bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
711  assert(!isa<OverloadedFunctionDecl>(OldD) &&
712         "Cannot merge with an overloaded function declaration");
713
714  // Verify the old decl was also a function.
715  FunctionDecl *Old = 0;
716  if (FunctionTemplateDecl *OldFunctionTemplate
717        = dyn_cast<FunctionTemplateDecl>(OldD))
718    Old = OldFunctionTemplate->getTemplatedDecl();
719  else
720    Old = dyn_cast<FunctionDecl>(OldD);
721  if (!Old) {
722    Diag(New->getLocation(), diag::err_redefinition_different_kind)
723      << New->getDeclName();
724    Diag(OldD->getLocation(), diag::note_previous_definition);
725    return true;
726  }
727
728  // Determine whether the previous declaration was a definition,
729  // implicit declaration, or a declaration.
730  diag::kind PrevDiag;
731  if (Old->isThisDeclarationADefinition())
732    PrevDiag = diag::note_previous_definition;
733  else if (Old->isImplicit())
734    PrevDiag = diag::note_previous_implicit_declaration;
735  else
736    PrevDiag = diag::note_previous_declaration;
737
738  QualType OldQType = Context.getCanonicalType(Old->getType());
739  QualType NewQType = Context.getCanonicalType(New->getType());
740
741  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
742      New->getStorageClass() == FunctionDecl::Static &&
743      Old->getStorageClass() != FunctionDecl::Static) {
744    Diag(New->getLocation(), diag::err_static_non_static)
745      << New;
746    Diag(Old->getLocation(), PrevDiag);
747    return true;
748  }
749
750  if (getLangOptions().CPlusPlus) {
751    // (C++98 13.1p2):
752    //   Certain function declarations cannot be overloaded:
753    //     -- Function declarations that differ only in the return type
754    //        cannot be overloaded.
755    QualType OldReturnType
756      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
757    QualType NewReturnType
758      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
759    if (OldReturnType != NewReturnType) {
760      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
761      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
762      return true;
763    }
764
765    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
766    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
767    if (OldMethod && NewMethod && !NewMethod->getFriendObjectKind() &&
768        NewMethod->getLexicalDeclContext()->isRecord()) {
769      //    -- Member function declarations with the same name and the
770      //       same parameter types cannot be overloaded if any of them
771      //       is a static member function declaration.
772      if (OldMethod->isStatic() || NewMethod->isStatic()) {
773        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
774        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
775        return true;
776      }
777
778      // C++ [class.mem]p1:
779      //   [...] A member shall not be declared twice in the
780      //   member-specification, except that a nested class or member
781      //   class template can be declared and then later defined.
782      unsigned NewDiag;
783      if (isa<CXXConstructorDecl>(OldMethod))
784        NewDiag = diag::err_constructor_redeclared;
785      else if (isa<CXXDestructorDecl>(NewMethod))
786        NewDiag = diag::err_destructor_redeclared;
787      else if (isa<CXXConversionDecl>(NewMethod))
788        NewDiag = diag::err_conv_function_redeclared;
789      else
790        NewDiag = diag::err_member_redeclared;
791
792      Diag(New->getLocation(), NewDiag);
793      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
794    }
795
796    // (C++98 8.3.5p3):
797    //   All declarations for a function shall agree exactly in both the
798    //   return type and the parameter-type-list.
799    if (OldQType == NewQType)
800      return MergeCompatibleFunctionDecls(New, Old);
801
802    // Fall through for conflicting redeclarations and redefinitions.
803  }
804
805  // C: Function types need to be compatible, not identical. This handles
806  // duplicate function decls like "void f(int); void f(enum X);" properly.
807  if (!getLangOptions().CPlusPlus &&
808      Context.typesAreCompatible(OldQType, NewQType)) {
809    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
810    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
811    const FunctionProtoType *OldProto = 0;
812    if (isa<FunctionNoProtoType>(NewFuncType) &&
813        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
814      // The old declaration provided a function prototype, but the
815      // new declaration does not. Merge in the prototype.
816      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
817      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
818                                                 OldProto->arg_type_end());
819      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
820                                         ParamTypes.data(), ParamTypes.size(),
821                                         OldProto->isVariadic(),
822                                         OldProto->getTypeQuals());
823      New->setType(NewQType);
824      New->setHasInheritedPrototype();
825
826      // Synthesize a parameter for each argument type.
827      llvm::SmallVector<ParmVarDecl*, 16> Params;
828      for (FunctionProtoType::arg_type_iterator
829             ParamType = OldProto->arg_type_begin(),
830             ParamEnd = OldProto->arg_type_end();
831           ParamType != ParamEnd; ++ParamType) {
832        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
833                                                 SourceLocation(), 0,
834                                                 *ParamType, /*DInfo=*/0,
835                                                 VarDecl::None, 0);
836        Param->setImplicit();
837        Params.push_back(Param);
838      }
839
840      New->setParams(Context, Params.data(), Params.size());
841    }
842
843    return MergeCompatibleFunctionDecls(New, Old);
844  }
845
846  // GNU C permits a K&R definition to follow a prototype declaration
847  // if the declared types of the parameters in the K&R definition
848  // match the types in the prototype declaration, even when the
849  // promoted types of the parameters from the K&R definition differ
850  // from the types in the prototype. GCC then keeps the types from
851  // the prototype.
852  //
853  // If a variadic prototype is followed by a non-variadic K&R definition,
854  // the K&R definition becomes variadic.  This is sort of an edge case, but
855  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
856  // C99 6.9.1p8.
857  if (!getLangOptions().CPlusPlus &&
858      Old->hasPrototype() && !New->hasPrototype() &&
859      New->getType()->getAs<FunctionProtoType>() &&
860      Old->getNumParams() == New->getNumParams()) {
861    llvm::SmallVector<QualType, 16> ArgTypes;
862    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
863    const FunctionProtoType *OldProto
864      = Old->getType()->getAs<FunctionProtoType>();
865    const FunctionProtoType *NewProto
866      = New->getType()->getAs<FunctionProtoType>();
867
868    // Determine whether this is the GNU C extension.
869    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
870                                               NewProto->getResultType());
871    bool LooseCompatible = !MergedReturn.isNull();
872    for (unsigned Idx = 0, End = Old->getNumParams();
873         LooseCompatible && Idx != End; ++Idx) {
874      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
875      ParmVarDecl *NewParm = New->getParamDecl(Idx);
876      if (Context.typesAreCompatible(OldParm->getType(),
877                                     NewProto->getArgType(Idx))) {
878        ArgTypes.push_back(NewParm->getType());
879      } else if (Context.typesAreCompatible(OldParm->getType(),
880                                            NewParm->getType())) {
881        GNUCompatibleParamWarning Warn
882          = { OldParm, NewParm, NewProto->getArgType(Idx) };
883        Warnings.push_back(Warn);
884        ArgTypes.push_back(NewParm->getType());
885      } else
886        LooseCompatible = false;
887    }
888
889    if (LooseCompatible) {
890      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
891        Diag(Warnings[Warn].NewParm->getLocation(),
892             diag::ext_param_promoted_not_compatible_with_prototype)
893          << Warnings[Warn].PromotedType
894          << Warnings[Warn].OldParm->getType();
895        Diag(Warnings[Warn].OldParm->getLocation(),
896             diag::note_previous_declaration);
897      }
898
899      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
900                                           ArgTypes.size(),
901                                           OldProto->isVariadic(), 0));
902      return MergeCompatibleFunctionDecls(New, Old);
903    }
904
905    // Fall through to diagnose conflicting types.
906  }
907
908  // A function that has already been declared has been redeclared or defined
909  // with a different type- show appropriate diagnostic
910  if (unsigned BuiltinID = Old->getBuiltinID()) {
911    // The user has declared a builtin function with an incompatible
912    // signature.
913    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
914      // The function the user is redeclaring is a library-defined
915      // function like 'malloc' or 'printf'. Warn about the
916      // redeclaration, then pretend that we don't know about this
917      // library built-in.
918      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
919      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
920        << Old << Old->getType();
921      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
922      Old->setInvalidDecl();
923      return false;
924    }
925
926    PrevDiag = diag::note_previous_builtin_declaration;
927  }
928
929  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
930  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
931  return true;
932}
933
934/// \brief Completes the merge of two function declarations that are
935/// known to be compatible.
936///
937/// This routine handles the merging of attributes and other
938/// properties of function declarations form the old declaration to
939/// the new declaration, once we know that New is in fact a
940/// redeclaration of Old.
941///
942/// \returns false
943bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
944  // Merge the attributes
945  MergeAttributes(New, Old, Context);
946
947  // Merge the storage class.
948  if (Old->getStorageClass() != FunctionDecl::Extern &&
949      Old->getStorageClass() != FunctionDecl::None)
950    New->setStorageClass(Old->getStorageClass());
951
952  // Merge "pure" flag.
953  if (Old->isPure())
954    New->setPure();
955
956  // Merge the "deleted" flag.
957  if (Old->isDeleted())
958    New->setDeleted();
959
960  if (getLangOptions().CPlusPlus)
961    return MergeCXXFunctionDecl(New, Old);
962
963  return false;
964}
965
966/// MergeVarDecl - We just parsed a variable 'New' which has the same name
967/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
968/// situation, merging decls or emitting diagnostics as appropriate.
969///
970/// Tentative definition rules (C99 6.9.2p2) are checked by
971/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
972/// definitions here, since the initializer hasn't been attached.
973///
974void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
975  // If either decl is invalid, make sure the new one is marked invalid and
976  // don't do any other checking.
977  if (New->isInvalidDecl() || OldD->isInvalidDecl())
978    return New->setInvalidDecl();
979
980  // Verify the old decl was also a variable.
981  VarDecl *Old = dyn_cast<VarDecl>(OldD);
982  if (!Old) {
983    Diag(New->getLocation(), diag::err_redefinition_different_kind)
984      << New->getDeclName();
985    Diag(OldD->getLocation(), diag::note_previous_definition);
986    return New->setInvalidDecl();
987  }
988
989  MergeAttributes(New, Old, Context);
990
991  // Merge the types
992  QualType MergedT;
993  if (getLangOptions().CPlusPlus) {
994    if (Context.hasSameType(New->getType(), Old->getType()))
995      MergedT = New->getType();
996    // C++ [basic.types]p7:
997    //   [...] The declared type of an array object might be an array of
998    //   unknown size and therefore be incomplete at one point in a
999    //   translation unit and complete later on; [...]
1000    else if (Old->getType()->isIncompleteArrayType() &&
1001             New->getType()->isArrayType()) {
1002      CanQual<ArrayType> OldArray
1003        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1004      CanQual<ArrayType> NewArray
1005        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1006      if (OldArray->getElementType() == NewArray->getElementType())
1007        MergedT = New->getType();
1008    }
1009  } else {
1010    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1011  }
1012  if (MergedT.isNull()) {
1013    Diag(New->getLocation(), diag::err_redefinition_different_type)
1014      << New->getDeclName();
1015    Diag(Old->getLocation(), diag::note_previous_definition);
1016    return New->setInvalidDecl();
1017  }
1018  New->setType(MergedT);
1019
1020  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1021  if (New->getStorageClass() == VarDecl::Static &&
1022      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1023    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1024    Diag(Old->getLocation(), diag::note_previous_definition);
1025    return New->setInvalidDecl();
1026  }
1027  // C99 6.2.2p4:
1028  //   For an identifier declared with the storage-class specifier
1029  //   extern in a scope in which a prior declaration of that
1030  //   identifier is visible,23) if the prior declaration specifies
1031  //   internal or external linkage, the linkage of the identifier at
1032  //   the later declaration is the same as the linkage specified at
1033  //   the prior declaration. If no prior declaration is visible, or
1034  //   if the prior declaration specifies no linkage, then the
1035  //   identifier has external linkage.
1036  if (New->hasExternalStorage() && Old->hasLinkage())
1037    /* Okay */;
1038  else if (New->getStorageClass() != VarDecl::Static &&
1039           Old->getStorageClass() == VarDecl::Static) {
1040    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1041    Diag(Old->getLocation(), diag::note_previous_definition);
1042    return New->setInvalidDecl();
1043  }
1044
1045  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1046
1047  // FIXME: The test for external storage here seems wrong? We still
1048  // need to check for mismatches.
1049  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1050      // Don't complain about out-of-line definitions of static members.
1051      !(Old->getLexicalDeclContext()->isRecord() &&
1052        !New->getLexicalDeclContext()->isRecord())) {
1053    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1054    Diag(Old->getLocation(), diag::note_previous_definition);
1055    return New->setInvalidDecl();
1056  }
1057
1058  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1059    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1060    Diag(Old->getLocation(), diag::note_previous_definition);
1061  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1062    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1063    Diag(Old->getLocation(), diag::note_previous_definition);
1064  }
1065
1066  // Keep a chain of previous declarations.
1067  New->setPreviousDeclaration(Old);
1068}
1069
1070/// CheckFallThrough - Check that we don't fall off the end of a
1071/// Statement that should return a value.
1072///
1073/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1074/// MaybeFallThrough iff we might or might not fall off the end,
1075/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1076/// return.  We assume NeverFallThrough iff we never fall off the end of the
1077/// statement but we may return.  We assume that functions not marked noreturn
1078/// will return.
1079Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1080  // FIXME: Eventually share this CFG object when we have other warnings based
1081  // of the CFG.  This can be done using AnalysisContext.
1082  llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1083
1084  // FIXME: They should never return 0, fix that, delete this code.
1085  if (cfg == 0)
1086    // FIXME: This should be NeverFallThrough
1087    return NeverFallThroughOrReturn;
1088  // The CFG leaves in dead things, and we don't want to dead code paths to
1089  // confuse us, so we mark all live things first.
1090  std::queue<CFGBlock*> workq;
1091  llvm::BitVector live(cfg->getNumBlockIDs());
1092  // Prep work queue
1093  workq.push(&cfg->getEntry());
1094  // Solve
1095  while (!workq.empty()) {
1096    CFGBlock *item = workq.front();
1097    workq.pop();
1098    live.set(item->getBlockID());
1099    for (CFGBlock::succ_iterator I=item->succ_begin(),
1100           E=item->succ_end();
1101         I != E;
1102         ++I) {
1103      if ((*I) && !live[(*I)->getBlockID()]) {
1104        live.set((*I)->getBlockID());
1105        workq.push(*I);
1106      }
1107    }
1108  }
1109
1110  // Now we know what is live, we check the live precessors of the exit block
1111  // and look for fall through paths, being careful to ignore normal returns,
1112  // and exceptional paths.
1113  bool HasLiveReturn = false;
1114  bool HasFakeEdge = false;
1115  bool HasPlainEdge = false;
1116  for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
1117         E = cfg->getExit().pred_end();
1118       I != E;
1119       ++I) {
1120    CFGBlock& B = **I;
1121    if (!live[B.getBlockID()])
1122      continue;
1123    if (B.size() == 0) {
1124      // A labeled empty statement, or the entry block...
1125      HasPlainEdge = true;
1126      continue;
1127    }
1128    Stmt *S = B[B.size()-1];
1129    if (isa<ReturnStmt>(S)) {
1130      HasLiveReturn = true;
1131      continue;
1132    }
1133    if (isa<ObjCAtThrowStmt>(S)) {
1134      HasFakeEdge = true;
1135      continue;
1136    }
1137    if (isa<CXXThrowExpr>(S)) {
1138      HasFakeEdge = true;
1139      continue;
1140    }
1141    bool NoReturnEdge = false;
1142    if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1143      Expr *CEE = C->getCallee()->IgnoreParenCasts();
1144      if (CEE->getType().getNoReturnAttr()) {
1145        NoReturnEdge = true;
1146        HasFakeEdge = true;
1147      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1148        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1149          if (FD->hasAttr<NoReturnAttr>()) {
1150            NoReturnEdge = true;
1151            HasFakeEdge = true;
1152          }
1153        }
1154      }
1155    }
1156    // FIXME: Add noreturn message sends.
1157    if (NoReturnEdge == false)
1158      HasPlainEdge = true;
1159  }
1160  if (!HasPlainEdge) {
1161    if (HasLiveReturn)
1162      return NeverFallThrough;
1163    return NeverFallThroughOrReturn;
1164  }
1165  if (HasFakeEdge || HasLiveReturn)
1166    return MaybeFallThrough;
1167  // This says AlwaysFallThrough for calls to functions that are not marked
1168  // noreturn, that don't return.  If people would like this warning to be more
1169  // accurate, such functions should be marked as noreturn.
1170  return AlwaysFallThrough;
1171}
1172
1173/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1174/// function that should return a value.  Check that we don't fall off the end
1175/// of a noreturn function.  We assume that functions and blocks not marked
1176/// noreturn will return.
1177void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1178  // FIXME: Would be nice if we had a better way to control cascading errors,
1179  // but for now, avoid them.  The problem is that when Parse sees:
1180  //   int foo() { return a; }
1181  // The return is eaten and the Sema code sees just:
1182  //   int foo() { }
1183  // which this code would then warn about.
1184  if (getDiagnostics().hasErrorOccurred())
1185    return;
1186
1187  bool ReturnsVoid = false;
1188  bool HasNoReturn = false;
1189  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1190    // If the result type of the function is a dependent type, we don't know
1191    // whether it will be void or not, so don't
1192    if (FD->getResultType()->isDependentType())
1193      return;
1194    if (FD->getResultType()->isVoidType())
1195      ReturnsVoid = true;
1196    if (FD->hasAttr<NoReturnAttr>())
1197      HasNoReturn = true;
1198  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1199    if (MD->getResultType()->isVoidType())
1200      ReturnsVoid = true;
1201    if (MD->hasAttr<NoReturnAttr>())
1202      HasNoReturn = true;
1203  }
1204
1205  // Short circuit for compilation speed.
1206  if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1207       == Diagnostic::Ignored || ReturnsVoid)
1208      && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1209          == Diagnostic::Ignored || !HasNoReturn)
1210      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1211          == Diagnostic::Ignored || !ReturnsVoid))
1212    return;
1213  // FIXME: Function try block
1214  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1215    switch (CheckFallThrough(Body)) {
1216    case MaybeFallThrough:
1217      if (HasNoReturn)
1218        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1219      else if (!ReturnsVoid)
1220        Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1221      break;
1222    case AlwaysFallThrough:
1223      if (HasNoReturn)
1224        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1225      else if (!ReturnsVoid)
1226        Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1227      break;
1228    case NeverFallThroughOrReturn:
1229      if (ReturnsVoid && !HasNoReturn)
1230        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1231      break;
1232    case NeverFallThrough:
1233      break;
1234    }
1235  }
1236}
1237
1238/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1239/// that should return a value.  Check that we don't fall off the end of a
1240/// noreturn block.  We assume that functions and blocks not marked noreturn
1241/// will return.
1242void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1243  // FIXME: Would be nice if we had a better way to control cascading errors,
1244  // but for now, avoid them.  The problem is that when Parse sees:
1245  //   int foo() { return a; }
1246  // The return is eaten and the Sema code sees just:
1247  //   int foo() { }
1248  // which this code would then warn about.
1249  if (getDiagnostics().hasErrorOccurred())
1250    return;
1251  bool ReturnsVoid = false;
1252  bool HasNoReturn = false;
1253  if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
1254    if (FT->getResultType()->isVoidType())
1255      ReturnsVoid = true;
1256    if (FT->getNoReturnAttr())
1257      HasNoReturn = true;
1258  }
1259
1260  // Short circuit for compilation speed.
1261  if (ReturnsVoid
1262      && !HasNoReturn
1263      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1264          == Diagnostic::Ignored || !ReturnsVoid))
1265    return;
1266  // FIXME: Funtion try block
1267  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1268    switch (CheckFallThrough(Body)) {
1269    case MaybeFallThrough:
1270      if (HasNoReturn)
1271        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1272      else if (!ReturnsVoid)
1273        Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1274      break;
1275    case AlwaysFallThrough:
1276      if (HasNoReturn)
1277        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1278      else if (!ReturnsVoid)
1279        Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1280      break;
1281    case NeverFallThroughOrReturn:
1282      if (ReturnsVoid)
1283        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1284      break;
1285    case NeverFallThrough:
1286      break;
1287    }
1288  }
1289}
1290
1291/// CheckParmsForFunctionDef - Check that the parameters of the given
1292/// function are appropriate for the definition of a function. This
1293/// takes care of any checks that cannot be performed on the
1294/// declaration itself, e.g., that the types of each of the function
1295/// parameters are complete.
1296bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1297  bool HasInvalidParm = false;
1298  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1299    ParmVarDecl *Param = FD->getParamDecl(p);
1300
1301    // C99 6.7.5.3p4: the parameters in a parameter type list in a
1302    // function declarator that is part of a function definition of
1303    // that function shall not have incomplete type.
1304    //
1305    // This is also C++ [dcl.fct]p6.
1306    if (!Param->isInvalidDecl() &&
1307        RequireCompleteType(Param->getLocation(), Param->getType(),
1308                               diag::err_typecheck_decl_incomplete_type)) {
1309      Param->setInvalidDecl();
1310      HasInvalidParm = true;
1311    }
1312
1313    // C99 6.9.1p5: If the declarator includes a parameter type list, the
1314    // declaration of each parameter shall include an identifier.
1315    if (Param->getIdentifier() == 0 &&
1316        !Param->isImplicit() &&
1317        !getLangOptions().CPlusPlus)
1318      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1319  }
1320
1321  return HasInvalidParm;
1322}
1323
1324/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1325/// no declarator (e.g. "struct foo;") is parsed.
1326Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1327  // FIXME: Error on auto/register at file scope
1328  // FIXME: Error on inline/virtual/explicit
1329  // FIXME: Error on invalid restrict
1330  // FIXME: Warn on useless __thread
1331  // FIXME: Warn on useless const/volatile
1332  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1333  // FIXME: Warn on useless attributes
1334  Decl *TagD = 0;
1335  TagDecl *Tag = 0;
1336  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1337      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1338      DS.getTypeSpecType() == DeclSpec::TST_union ||
1339      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1340    TagD = static_cast<Decl *>(DS.getTypeRep());
1341
1342    if (!TagD) // We probably had an error
1343      return DeclPtrTy();
1344
1345    // Note that the above type specs guarantee that the
1346    // type rep is a Decl, whereas in many of the others
1347    // it's a Type.
1348    Tag = dyn_cast<TagDecl>(TagD);
1349  }
1350
1351  if (DS.isFriendSpecified()) {
1352    // If we're dealing with a class template decl, assume that the
1353    // template routines are handling it.
1354    if (TagD && isa<ClassTemplateDecl>(TagD))
1355      return DeclPtrTy();
1356    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1357  }
1358
1359  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1360    // If there are attributes in the DeclSpec, apply them to the record.
1361    if (const AttributeList *AL = DS.getAttributes())
1362      ProcessDeclAttributeList(S, Record, AL);
1363
1364    if (!Record->getDeclName() && Record->isDefinition() &&
1365        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1366      if (getLangOptions().CPlusPlus ||
1367          Record->getDeclContext()->isRecord())
1368        return BuildAnonymousStructOrUnion(S, DS, Record);
1369
1370      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1371        << DS.getSourceRange();
1372    }
1373
1374    // Microsoft allows unnamed struct/union fields. Don't complain
1375    // about them.
1376    // FIXME: Should we support Microsoft's extensions in this area?
1377    if (Record->getDeclName() && getLangOptions().Microsoft)
1378      return DeclPtrTy::make(Tag);
1379  }
1380
1381  if (!DS.isMissingDeclaratorOk() &&
1382      DS.getTypeSpecType() != DeclSpec::TST_error) {
1383    // Warn about typedefs of enums without names, since this is an
1384    // extension in both Microsoft an GNU.
1385    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1386        Tag && isa<EnumDecl>(Tag)) {
1387      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1388        << DS.getSourceRange();
1389      return DeclPtrTy::make(Tag);
1390    }
1391
1392    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1393      << DS.getSourceRange();
1394    return DeclPtrTy();
1395  }
1396
1397  return DeclPtrTy::make(Tag);
1398}
1399
1400/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1401/// anonymous struct or union AnonRecord into the owning context Owner
1402/// and scope S. This routine will be invoked just after we realize
1403/// that an unnamed union or struct is actually an anonymous union or
1404/// struct, e.g.,
1405///
1406/// @code
1407/// union {
1408///   int i;
1409///   float f;
1410/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1411///    // f into the surrounding scope.x
1412/// @endcode
1413///
1414/// This routine is recursive, injecting the names of nested anonymous
1415/// structs/unions into the owning context and scope as well.
1416bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1417                                               RecordDecl *AnonRecord) {
1418  bool Invalid = false;
1419  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1420                               FEnd = AnonRecord->field_end();
1421       F != FEnd; ++F) {
1422    if ((*F)->getDeclName()) {
1423      LookupResult R(*this, (*F)->getDeclName(), SourceLocation(),
1424                     LookupOrdinaryName, LookupResult::ForRedeclaration);
1425      LookupQualifiedName(R, Owner);
1426      NamedDecl *PrevDecl = R.getAsSingleDecl(Context);
1427      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
1428        // C++ [class.union]p2:
1429        //   The names of the members of an anonymous union shall be
1430        //   distinct from the names of any other entity in the
1431        //   scope in which the anonymous union is declared.
1432        unsigned diagKind
1433          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1434                                 : diag::err_anonymous_struct_member_redecl;
1435        Diag((*F)->getLocation(), diagKind)
1436          << (*F)->getDeclName();
1437        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1438        Invalid = true;
1439      } else {
1440        // C++ [class.union]p2:
1441        //   For the purpose of name lookup, after the anonymous union
1442        //   definition, the members of the anonymous union are
1443        //   considered to have been defined in the scope in which the
1444        //   anonymous union is declared.
1445        Owner->makeDeclVisibleInContext(*F);
1446        S->AddDecl(DeclPtrTy::make(*F));
1447        IdResolver.AddDecl(*F);
1448      }
1449    } else if (const RecordType *InnerRecordType
1450                 = (*F)->getType()->getAs<RecordType>()) {
1451      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1452      if (InnerRecord->isAnonymousStructOrUnion())
1453        Invalid = Invalid ||
1454          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1455    }
1456  }
1457
1458  return Invalid;
1459}
1460
1461/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1462/// anonymous structure or union. Anonymous unions are a C++ feature
1463/// (C++ [class.union]) and a GNU C extension; anonymous structures
1464/// are a GNU C and GNU C++ extension.
1465Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1466                                                  RecordDecl *Record) {
1467  DeclContext *Owner = Record->getDeclContext();
1468
1469  // Diagnose whether this anonymous struct/union is an extension.
1470  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1471    Diag(Record->getLocation(), diag::ext_anonymous_union);
1472  else if (!Record->isUnion())
1473    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1474
1475  // C and C++ require different kinds of checks for anonymous
1476  // structs/unions.
1477  bool Invalid = false;
1478  if (getLangOptions().CPlusPlus) {
1479    const char* PrevSpec = 0;
1480    unsigned DiagID;
1481    // C++ [class.union]p3:
1482    //   Anonymous unions declared in a named namespace or in the
1483    //   global namespace shall be declared static.
1484    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1485        (isa<TranslationUnitDecl>(Owner) ||
1486         (isa<NamespaceDecl>(Owner) &&
1487          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1488      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1489      Invalid = true;
1490
1491      // Recover by adding 'static'.
1492      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1493                             PrevSpec, DiagID);
1494    }
1495    // C++ [class.union]p3:
1496    //   A storage class is not allowed in a declaration of an
1497    //   anonymous union in a class scope.
1498    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1499             isa<RecordDecl>(Owner)) {
1500      Diag(DS.getStorageClassSpecLoc(),
1501           diag::err_anonymous_union_with_storage_spec);
1502      Invalid = true;
1503
1504      // Recover by removing the storage specifier.
1505      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1506                             PrevSpec, DiagID);
1507    }
1508
1509    // C++ [class.union]p2:
1510    //   The member-specification of an anonymous union shall only
1511    //   define non-static data members. [Note: nested types and
1512    //   functions cannot be declared within an anonymous union. ]
1513    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1514                                 MemEnd = Record->decls_end();
1515         Mem != MemEnd; ++Mem) {
1516      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1517        // C++ [class.union]p3:
1518        //   An anonymous union shall not have private or protected
1519        //   members (clause 11).
1520        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1521          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1522            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1523          Invalid = true;
1524        }
1525      } else if ((*Mem)->isImplicit()) {
1526        // Any implicit members are fine.
1527      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1528        // This is a type that showed up in an
1529        // elaborated-type-specifier inside the anonymous struct or
1530        // union, but which actually declares a type outside of the
1531        // anonymous struct or union. It's okay.
1532      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1533        if (!MemRecord->isAnonymousStructOrUnion() &&
1534            MemRecord->getDeclName()) {
1535          // This is a nested type declaration.
1536          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1537            << (int)Record->isUnion();
1538          Invalid = true;
1539        }
1540      } else {
1541        // We have something that isn't a non-static data
1542        // member. Complain about it.
1543        unsigned DK = diag::err_anonymous_record_bad_member;
1544        if (isa<TypeDecl>(*Mem))
1545          DK = diag::err_anonymous_record_with_type;
1546        else if (isa<FunctionDecl>(*Mem))
1547          DK = diag::err_anonymous_record_with_function;
1548        else if (isa<VarDecl>(*Mem))
1549          DK = diag::err_anonymous_record_with_static;
1550        Diag((*Mem)->getLocation(), DK)
1551            << (int)Record->isUnion();
1552          Invalid = true;
1553      }
1554    }
1555  }
1556
1557  if (!Record->isUnion() && !Owner->isRecord()) {
1558    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1559      << (int)getLangOptions().CPlusPlus;
1560    Invalid = true;
1561  }
1562
1563  // Mock up a declarator.
1564  Declarator Dc(DS, Declarator::TypeNameContext);
1565  DeclaratorInfo *DInfo = 0;
1566  GetTypeForDeclarator(Dc, S, &DInfo);
1567  assert(DInfo && "couldn't build declarator info for anonymous struct/union");
1568
1569  // Create a declaration for this anonymous struct/union.
1570  NamedDecl *Anon = 0;
1571  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1572    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1573                             /*IdentifierInfo=*/0,
1574                             Context.getTypeDeclType(Record),
1575                             DInfo,
1576                             /*BitWidth=*/0, /*Mutable=*/false);
1577    Anon->setAccess(AS_public);
1578    if (getLangOptions().CPlusPlus)
1579      FieldCollector->Add(cast<FieldDecl>(Anon));
1580  } else {
1581    VarDecl::StorageClass SC;
1582    switch (DS.getStorageClassSpec()) {
1583    default: assert(0 && "Unknown storage class!");
1584    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1585    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1586    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1587    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1588    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1589    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1590    case DeclSpec::SCS_mutable:
1591      // mutable can only appear on non-static class members, so it's always
1592      // an error here
1593      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1594      Invalid = true;
1595      SC = VarDecl::None;
1596      break;
1597    }
1598
1599    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1600                           /*IdentifierInfo=*/0,
1601                           Context.getTypeDeclType(Record),
1602                           DInfo,
1603                           SC);
1604  }
1605  Anon->setImplicit();
1606
1607  // Add the anonymous struct/union object to the current
1608  // context. We'll be referencing this object when we refer to one of
1609  // its members.
1610  Owner->addDecl(Anon);
1611
1612  // Inject the members of the anonymous struct/union into the owning
1613  // context and into the identifier resolver chain for name lookup
1614  // purposes.
1615  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1616    Invalid = true;
1617
1618  // Mark this as an anonymous struct/union type. Note that we do not
1619  // do this until after we have already checked and injected the
1620  // members of this anonymous struct/union type, because otherwise
1621  // the members could be injected twice: once by DeclContext when it
1622  // builds its lookup table, and once by
1623  // InjectAnonymousStructOrUnionMembers.
1624  Record->setAnonymousStructOrUnion(true);
1625
1626  if (Invalid)
1627    Anon->setInvalidDecl();
1628
1629  return DeclPtrTy::make(Anon);
1630}
1631
1632
1633/// GetNameForDeclarator - Determine the full declaration name for the
1634/// given Declarator.
1635DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1636  return GetNameFromUnqualifiedId(D.getName());
1637}
1638
1639/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1640DeclarationName Sema::GetNameFromUnqualifiedId(UnqualifiedId &Name) {
1641  switch (Name.getKind()) {
1642    case UnqualifiedId::IK_Identifier:
1643      return DeclarationName(Name.Identifier);
1644
1645    case UnqualifiedId::IK_OperatorFunctionId:
1646      return Context.DeclarationNames.getCXXOperatorName(
1647                                                         Name.OperatorFunctionId.Operator);
1648
1649    case UnqualifiedId::IK_ConversionFunctionId: {
1650      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1651      if (Ty.isNull())
1652        return DeclarationName();
1653
1654      return Context.DeclarationNames.getCXXConversionFunctionName(
1655                                                                   Context.getCanonicalType(Ty));
1656    }
1657
1658    case UnqualifiedId::IK_ConstructorName: {
1659      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1660      if (Ty.isNull())
1661        return DeclarationName();
1662
1663      return Context.DeclarationNames.getCXXConstructorName(
1664                                                            Context.getCanonicalType(Ty));
1665    }
1666
1667    case UnqualifiedId::IK_DestructorName: {
1668      QualType Ty = GetTypeFromParser(Name.DestructorName);
1669      if (Ty.isNull())
1670        return DeclarationName();
1671
1672      return Context.DeclarationNames.getCXXDestructorName(
1673                                                           Context.getCanonicalType(Ty));
1674    }
1675
1676    case UnqualifiedId::IK_TemplateId: {
1677      TemplateName TName
1678        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1679      if (TemplateDecl *Template = TName.getAsTemplateDecl())
1680        return Template->getDeclName();
1681      if (OverloadedFunctionDecl *Ovl = TName.getAsOverloadedFunctionDecl())
1682        return Ovl->getDeclName();
1683
1684      return DeclarationName();
1685    }
1686  }
1687
1688  assert(false && "Unknown name kind");
1689  return DeclarationName();
1690}
1691
1692/// isNearlyMatchingFunction - Determine whether the C++ functions
1693/// Declaration and Definition are "nearly" matching. This heuristic
1694/// is used to improve diagnostics in the case where an out-of-line
1695/// function definition doesn't match any declaration within
1696/// the class or namespace.
1697static bool isNearlyMatchingFunction(ASTContext &Context,
1698                                     FunctionDecl *Declaration,
1699                                     FunctionDecl *Definition) {
1700  if (Declaration->param_size() != Definition->param_size())
1701    return false;
1702  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1703    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1704    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1705
1706    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1707                                        DefParamTy.getNonReferenceType()))
1708      return false;
1709  }
1710
1711  return true;
1712}
1713
1714Sema::DeclPtrTy
1715Sema::HandleDeclarator(Scope *S, Declarator &D,
1716                       MultiTemplateParamsArg TemplateParamLists,
1717                       bool IsFunctionDefinition) {
1718  DeclarationName Name = GetNameForDeclarator(D);
1719
1720  // All of these full declarators require an identifier.  If it doesn't have
1721  // one, the ParsedFreeStandingDeclSpec action should be used.
1722  if (!Name) {
1723    if (!D.isInvalidType())  // Reject this if we think it is valid.
1724      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1725           diag::err_declarator_need_ident)
1726        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1727    return DeclPtrTy();
1728  }
1729
1730  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1731  // we find one that is.
1732  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1733         (S->getFlags() & Scope::TemplateParamScope) != 0)
1734    S = S->getParent();
1735
1736  // If this is an out-of-line definition of a member of a class template
1737  // or class template partial specialization, we may need to rebuild the
1738  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1739  // for more information.
1740  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1741  // handle expressions properly.
1742  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1743  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1744      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1745      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1746       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1747       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1748       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1749    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1750      // FIXME: Preserve type source info.
1751      QualType T = GetTypeFromParser(DS.getTypeRep());
1752      EnterDeclaratorContext(S, DC);
1753      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1754      ExitDeclaratorContext(S);
1755      if (T.isNull())
1756        return DeclPtrTy();
1757      DS.UpdateTypeRep(T.getAsOpaquePtr());
1758    }
1759  }
1760
1761  DeclContext *DC;
1762  NamedDecl *PrevDecl;
1763  NamedDecl *New;
1764
1765  DeclaratorInfo *DInfo = 0;
1766  QualType R = GetTypeForDeclarator(D, S, &DInfo);
1767
1768  // See if this is a redefinition of a variable in the same scope.
1769  if (D.getCXXScopeSpec().isInvalid()) {
1770    DC = CurContext;
1771    PrevDecl = 0;
1772    D.setInvalidType();
1773  } else if (!D.getCXXScopeSpec().isSet()) {
1774    LookupNameKind NameKind = LookupOrdinaryName;
1775
1776    // If the declaration we're planning to build will be a function
1777    // or object with linkage, then look for another declaration with
1778    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1779    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1780      /* Do nothing*/;
1781    else if (R->isFunctionType()) {
1782      if (CurContext->isFunctionOrMethod() ||
1783          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1784        NameKind = LookupRedeclarationWithLinkage;
1785    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1786      NameKind = LookupRedeclarationWithLinkage;
1787    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1788             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1789      NameKind = LookupRedeclarationWithLinkage;
1790
1791    DC = CurContext;
1792    LookupResult R(*this, Name, D.getIdentifierLoc(), NameKind,
1793                   LookupResult::ForRedeclaration);
1794
1795    LookupName(R, S, NameKind == LookupRedeclarationWithLinkage);
1796    PrevDecl = R.getAsSingleDecl(Context);
1797  } else { // Something like "int foo::x;"
1798    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1799
1800    if (!DC) {
1801      // If we could not compute the declaration context, it's because the
1802      // declaration context is dependent but does not refer to a class,
1803      // class template, or class template partial specialization. Complain
1804      // and return early, to avoid the coming semantic disaster.
1805      Diag(D.getIdentifierLoc(),
1806           diag::err_template_qualified_declarator_no_match)
1807        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1808        << D.getCXXScopeSpec().getRange();
1809      return DeclPtrTy();
1810    }
1811
1812    if (!DC->isDependentContext() &&
1813        RequireCompleteDeclContext(D.getCXXScopeSpec()))
1814      return DeclPtrTy();
1815
1816    LookupResult Res(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1817                     LookupResult::ForRedeclaration);
1818    LookupQualifiedName(Res, DC);
1819    PrevDecl = Res.getAsSingleDecl(Context);
1820
1821    // C++ 7.3.1.2p2:
1822    // Members (including explicit specializations of templates) of a named
1823    // namespace can also be defined outside that namespace by explicit
1824    // qualification of the name being defined, provided that the entity being
1825    // defined was already declared in the namespace and the definition appears
1826    // after the point of declaration in a namespace that encloses the
1827    // declarations namespace.
1828    //
1829    // Note that we only check the context at this point. We don't yet
1830    // have enough information to make sure that PrevDecl is actually
1831    // the declaration we want to match. For example, given:
1832    //
1833    //   class X {
1834    //     void f();
1835    //     void f(float);
1836    //   };
1837    //
1838    //   void X::f(int) { } // ill-formed
1839    //
1840    // In this case, PrevDecl will point to the overload set
1841    // containing the two f's declared in X, but neither of them
1842    // matches.
1843
1844    // First check whether we named the global scope.
1845    if (isa<TranslationUnitDecl>(DC)) {
1846      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1847        << Name << D.getCXXScopeSpec().getRange();
1848    } else {
1849      DeclContext *Cur = CurContext;
1850      while (isa<LinkageSpecDecl>(Cur))
1851        Cur = Cur->getParent();
1852      if (!Cur->Encloses(DC)) {
1853        // The qualifying scope doesn't enclose the original declaration.
1854        // Emit diagnostic based on current scope.
1855        SourceLocation L = D.getIdentifierLoc();
1856        SourceRange R = D.getCXXScopeSpec().getRange();
1857        if (isa<FunctionDecl>(Cur))
1858          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1859        else
1860          Diag(L, diag::err_invalid_declarator_scope)
1861            << Name << cast<NamedDecl>(DC) << R;
1862        D.setInvalidType();
1863      }
1864    }
1865  }
1866
1867  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1868    // Maybe we will complain about the shadowed template parameter.
1869    if (!D.isInvalidType())
1870      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl))
1871        D.setInvalidType();
1872
1873    // Just pretend that we didn't see the previous declaration.
1874    PrevDecl = 0;
1875  }
1876
1877  // In C++, the previous declaration we find might be a tag type
1878  // (class or enum). In this case, the new declaration will hide the
1879  // tag type. Note that this does does not apply if we're declaring a
1880  // typedef (C++ [dcl.typedef]p4).
1881  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1882      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1883    PrevDecl = 0;
1884
1885  bool Redeclaration = false;
1886  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1887    if (TemplateParamLists.size()) {
1888      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
1889      return DeclPtrTy();
1890    }
1891
1892    New = ActOnTypedefDeclarator(S, D, DC, R, DInfo, PrevDecl, Redeclaration);
1893  } else if (R->isFunctionType()) {
1894    New = ActOnFunctionDeclarator(S, D, DC, R, DInfo, PrevDecl,
1895                                  move(TemplateParamLists),
1896                                  IsFunctionDefinition, Redeclaration);
1897  } else {
1898    New = ActOnVariableDeclarator(S, D, DC, R, DInfo, PrevDecl,
1899                                  move(TemplateParamLists),
1900                                  Redeclaration);
1901  }
1902
1903  if (New == 0)
1904    return DeclPtrTy();
1905
1906  // If this has an identifier and is not an invalid redeclaration or
1907  // function template specialization, add it to the scope stack.
1908  if (Name && !(Redeclaration && New->isInvalidDecl()) &&
1909      !(isa<FunctionDecl>(New) &&
1910        cast<FunctionDecl>(New)->isFunctionTemplateSpecialization()))
1911    PushOnScopeChains(New, S);
1912
1913  return DeclPtrTy::make(New);
1914}
1915
1916/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1917/// types into constant array types in certain situations which would otherwise
1918/// be errors (for GCC compatibility).
1919static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1920                                                    ASTContext &Context,
1921                                                    bool &SizeIsNegative) {
1922  // This method tries to turn a variable array into a constant
1923  // array even when the size isn't an ICE.  This is necessary
1924  // for compatibility with code that depends on gcc's buggy
1925  // constant expression folding, like struct {char x[(int)(char*)2];}
1926  SizeIsNegative = false;
1927
1928  QualifierCollector Qs;
1929  const Type *Ty = Qs.strip(T);
1930
1931  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
1932    QualType Pointee = PTy->getPointeeType();
1933    QualType FixedType =
1934        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1935    if (FixedType.isNull()) return FixedType;
1936    FixedType = Context.getPointerType(FixedType);
1937    return Qs.apply(FixedType);
1938  }
1939
1940  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1941  if (!VLATy)
1942    return QualType();
1943  // FIXME: We should probably handle this case
1944  if (VLATy->getElementType()->isVariablyModifiedType())
1945    return QualType();
1946
1947  Expr::EvalResult EvalResult;
1948  if (!VLATy->getSizeExpr() ||
1949      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1950      !EvalResult.Val.isInt())
1951    return QualType();
1952
1953  llvm::APSInt &Res = EvalResult.Val.getInt();
1954  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
1955    // TODO: preserve the size expression in declarator info
1956    return Context.getConstantArrayType(VLATy->getElementType(),
1957                                        Res, ArrayType::Normal, 0);
1958  }
1959
1960  SizeIsNegative = true;
1961  return QualType();
1962}
1963
1964/// \brief Register the given locally-scoped external C declaration so
1965/// that it can be found later for redeclarations
1966void
1967Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1968                                       Scope *S) {
1969  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1970         "Decl is not a locally-scoped decl!");
1971  // Note that we have a locally-scoped external with this name.
1972  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1973
1974  if (!PrevDecl)
1975    return;
1976
1977  // If there was a previous declaration of this variable, it may be
1978  // in our identifier chain. Update the identifier chain with the new
1979  // declaration.
1980  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
1981    // The previous declaration was found on the identifer resolver
1982    // chain, so remove it from its scope.
1983    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
1984      S = S->getParent();
1985
1986    if (S)
1987      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
1988  }
1989}
1990
1991/// \brief Diagnose function specifiers on a declaration of an identifier that
1992/// does not identify a function.
1993void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
1994  // FIXME: We should probably indicate the identifier in question to avoid
1995  // confusion for constructs like "inline int a(), b;"
1996  if (D.getDeclSpec().isInlineSpecified())
1997    Diag(D.getDeclSpec().getInlineSpecLoc(),
1998         diag::err_inline_non_function);
1999
2000  if (D.getDeclSpec().isVirtualSpecified())
2001    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2002         diag::err_virtual_non_function);
2003
2004  if (D.getDeclSpec().isExplicitSpecified())
2005    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2006         diag::err_explicit_non_function);
2007}
2008
2009NamedDecl*
2010Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2011                             QualType R,  DeclaratorInfo *DInfo,
2012                             NamedDecl* PrevDecl, bool &Redeclaration) {
2013  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2014  if (D.getCXXScopeSpec().isSet()) {
2015    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2016      << D.getCXXScopeSpec().getRange();
2017    D.setInvalidType();
2018    // Pretend we didn't see the scope specifier.
2019    DC = 0;
2020  }
2021
2022  if (getLangOptions().CPlusPlus) {
2023    // Check that there are no default arguments (C++ only).
2024    CheckExtraCXXDefaultArguments(D);
2025  }
2026
2027  DiagnoseFunctionSpecifiers(D);
2028
2029  if (D.getDeclSpec().isThreadSpecified())
2030    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2031
2032  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, DInfo);
2033  if (!NewTD) return 0;
2034
2035  // Handle attributes prior to checking for duplicates in MergeVarDecl
2036  ProcessDeclAttributes(S, NewTD, D);
2037  // Merge the decl with the existing one if appropriate. If the decl is
2038  // in an outer scope, it isn't the same thing.
2039  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
2040    Redeclaration = true;
2041    MergeTypeDefDecl(NewTD, PrevDecl);
2042  }
2043
2044  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2045  // then it shall have block scope.
2046  QualType T = NewTD->getUnderlyingType();
2047  if (T->isVariablyModifiedType()) {
2048    CurFunctionNeedsScopeChecking = true;
2049
2050    if (S->getFnParent() == 0) {
2051      bool SizeIsNegative;
2052      QualType FixedTy =
2053          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2054      if (!FixedTy.isNull()) {
2055        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2056        NewTD->setTypeDeclaratorInfo(Context.getTrivialDeclaratorInfo(FixedTy));
2057      } else {
2058        if (SizeIsNegative)
2059          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2060        else if (T->isVariableArrayType())
2061          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2062        else
2063          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2064        NewTD->setInvalidDecl();
2065      }
2066    }
2067  }
2068
2069  // If this is the C FILE type, notify the AST context.
2070  if (IdentifierInfo *II = NewTD->getIdentifier())
2071    if (!NewTD->isInvalidDecl() &&
2072        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2073      if (II->isStr("FILE"))
2074        Context.setFILEDecl(NewTD);
2075      else if (II->isStr("jmp_buf"))
2076        Context.setjmp_bufDecl(NewTD);
2077      else if (II->isStr("sigjmp_buf"))
2078        Context.setsigjmp_bufDecl(NewTD);
2079    }
2080
2081  return NewTD;
2082}
2083
2084/// \brief Determines whether the given declaration is an out-of-scope
2085/// previous declaration.
2086///
2087/// This routine should be invoked when name lookup has found a
2088/// previous declaration (PrevDecl) that is not in the scope where a
2089/// new declaration by the same name is being introduced. If the new
2090/// declaration occurs in a local scope, previous declarations with
2091/// linkage may still be considered previous declarations (C99
2092/// 6.2.2p4-5, C++ [basic.link]p6).
2093///
2094/// \param PrevDecl the previous declaration found by name
2095/// lookup
2096///
2097/// \param DC the context in which the new declaration is being
2098/// declared.
2099///
2100/// \returns true if PrevDecl is an out-of-scope previous declaration
2101/// for a new delcaration with the same name.
2102static bool
2103isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2104                                ASTContext &Context) {
2105  if (!PrevDecl)
2106    return 0;
2107
2108  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
2109  // case we need to check each of the overloaded functions.
2110  if (!PrevDecl->hasLinkage())
2111    return false;
2112
2113  if (Context.getLangOptions().CPlusPlus) {
2114    // C++ [basic.link]p6:
2115    //   If there is a visible declaration of an entity with linkage
2116    //   having the same name and type, ignoring entities declared
2117    //   outside the innermost enclosing namespace scope, the block
2118    //   scope declaration declares that same entity and receives the
2119    //   linkage of the previous declaration.
2120    DeclContext *OuterContext = DC->getLookupContext();
2121    if (!OuterContext->isFunctionOrMethod())
2122      // This rule only applies to block-scope declarations.
2123      return false;
2124    else {
2125      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2126      if (PrevOuterContext->isRecord())
2127        // We found a member function: ignore it.
2128        return false;
2129      else {
2130        // Find the innermost enclosing namespace for the new and
2131        // previous declarations.
2132        while (!OuterContext->isFileContext())
2133          OuterContext = OuterContext->getParent();
2134        while (!PrevOuterContext->isFileContext())
2135          PrevOuterContext = PrevOuterContext->getParent();
2136
2137        // The previous declaration is in a different namespace, so it
2138        // isn't the same function.
2139        if (OuterContext->getPrimaryContext() !=
2140            PrevOuterContext->getPrimaryContext())
2141          return false;
2142      }
2143    }
2144  }
2145
2146  return true;
2147}
2148
2149NamedDecl*
2150Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2151                              QualType R, DeclaratorInfo *DInfo,
2152                              NamedDecl* PrevDecl,
2153                              MultiTemplateParamsArg TemplateParamLists,
2154                              bool &Redeclaration) {
2155  DeclarationName Name = GetNameForDeclarator(D);
2156
2157  // Check that there are no default arguments (C++ only).
2158  if (getLangOptions().CPlusPlus)
2159    CheckExtraCXXDefaultArguments(D);
2160
2161  VarDecl *NewVD;
2162  VarDecl::StorageClass SC;
2163  switch (D.getDeclSpec().getStorageClassSpec()) {
2164  default: assert(0 && "Unknown storage class!");
2165  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
2166  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
2167  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
2168  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
2169  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
2170  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2171  case DeclSpec::SCS_mutable:
2172    // mutable can only appear on non-static class members, so it's always
2173    // an error here
2174    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2175    D.setInvalidType();
2176    SC = VarDecl::None;
2177    break;
2178  }
2179
2180  IdentifierInfo *II = Name.getAsIdentifierInfo();
2181  if (!II) {
2182    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2183      << Name.getAsString();
2184    return 0;
2185  }
2186
2187  DiagnoseFunctionSpecifiers(D);
2188
2189  if (!DC->isRecord() && S->getFnParent() == 0) {
2190    // C99 6.9p2: The storage-class specifiers auto and register shall not
2191    // appear in the declaration specifiers in an external declaration.
2192    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2193
2194      // If this is a register variable with an asm label specified, then this
2195      // is a GNU extension.
2196      if (SC == VarDecl::Register && D.getAsmLabel())
2197        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2198      else
2199        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2200      D.setInvalidType();
2201    }
2202  }
2203  if (DC->isRecord() && !CurContext->isRecord()) {
2204    // This is an out-of-line definition of a static data member.
2205    if (SC == VarDecl::Static) {
2206      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2207           diag::err_static_out_of_line)
2208        << CodeModificationHint::CreateRemoval(
2209                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2210    } else if (SC == VarDecl::None)
2211      SC = VarDecl::Static;
2212  }
2213  if (SC == VarDecl::Static) {
2214    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2215      if (RD->isLocalClass())
2216        Diag(D.getIdentifierLoc(),
2217             diag::err_static_data_member_not_allowed_in_local_class)
2218          << Name << RD->getDeclName();
2219    }
2220  }
2221
2222  // Match up the template parameter lists with the scope specifier, then
2223  // determine whether we have a template or a template specialization.
2224  bool isExplicitSpecialization = false;
2225  if (TemplateParameterList *TemplateParams
2226        = MatchTemplateParametersToScopeSpecifier(
2227                                  D.getDeclSpec().getSourceRange().getBegin(),
2228                                                  D.getCXXScopeSpec(),
2229                        (TemplateParameterList**)TemplateParamLists.get(),
2230                                                   TemplateParamLists.size(),
2231                                                  isExplicitSpecialization)) {
2232    if (TemplateParams->size() > 0) {
2233      // There is no such thing as a variable template.
2234      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2235        << II
2236        << SourceRange(TemplateParams->getTemplateLoc(),
2237                       TemplateParams->getRAngleLoc());
2238      return 0;
2239    } else {
2240      // There is an extraneous 'template<>' for this variable. Complain
2241      // about it, but allow the declaration of the variable.
2242      Diag(TemplateParams->getTemplateLoc(),
2243           diag::err_template_variable_noparams)
2244        << II
2245        << SourceRange(TemplateParams->getTemplateLoc(),
2246                       TemplateParams->getRAngleLoc());
2247
2248      isExplicitSpecialization = true;
2249    }
2250  }
2251
2252  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2253                          II, R, DInfo, SC);
2254
2255  if (D.isInvalidType())
2256    NewVD->setInvalidDecl();
2257
2258  if (D.getDeclSpec().isThreadSpecified()) {
2259    if (NewVD->hasLocalStorage())
2260      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2261    else if (!Context.Target.isTLSSupported())
2262      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2263    else
2264      NewVD->setThreadSpecified(true);
2265  }
2266
2267  // Set the lexical context. If the declarator has a C++ scope specifier, the
2268  // lexical context will be different from the semantic context.
2269  NewVD->setLexicalDeclContext(CurContext);
2270
2271  // Handle attributes prior to checking for duplicates in MergeVarDecl
2272  ProcessDeclAttributes(S, NewVD, D);
2273
2274  // Handle GNU asm-label extension (encoded as an attribute).
2275  if (Expr *E = (Expr*) D.getAsmLabel()) {
2276    // The parser guarantees this is a string.
2277    StringLiteral *SE = cast<StringLiteral>(E);
2278    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2279                                                        SE->getByteLength())));
2280  }
2281
2282  // If name lookup finds a previous declaration that is not in the
2283  // same scope as the new declaration, this may still be an
2284  // acceptable redeclaration.
2285  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2286      !(NewVD->hasLinkage() &&
2287        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2288    PrevDecl = 0;
2289
2290  // Merge the decl with the existing one if appropriate.
2291  if (PrevDecl) {
2292    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
2293      // The user tried to define a non-static data member
2294      // out-of-line (C++ [dcl.meaning]p1).
2295      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2296        << D.getCXXScopeSpec().getRange();
2297      PrevDecl = 0;
2298      NewVD->setInvalidDecl();
2299    }
2300  } else if (D.getCXXScopeSpec().isSet()) {
2301    // No previous declaration in the qualifying scope.
2302    Diag(D.getIdentifierLoc(), diag::err_no_member)
2303      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2304      << D.getCXXScopeSpec().getRange();
2305    NewVD->setInvalidDecl();
2306  }
2307
2308  CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration);
2309
2310  // This is an explicit specialization of a static data member. Check it.
2311  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2312      CheckMemberSpecialization(NewVD, PrevDecl))
2313    NewVD->setInvalidDecl();
2314
2315  // attributes declared post-definition are currently ignored
2316  if (PrevDecl) {
2317    const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl);
2318    if (PrevVD->getDefinition(Def) && D.hasAttributes()) {
2319      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2320      Diag(Def->getLocation(), diag::note_previous_definition);
2321    }
2322  }
2323
2324  // If this is a locally-scoped extern C variable, update the map of
2325  // such variables.
2326  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2327      !NewVD->isInvalidDecl())
2328    RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
2329
2330  return NewVD;
2331}
2332
2333/// \brief Perform semantic checking on a newly-created variable
2334/// declaration.
2335///
2336/// This routine performs all of the type-checking required for a
2337/// variable declaration once it has been built. It is used both to
2338/// check variables after they have been parsed and their declarators
2339/// have been translated into a declaration, and to check variables
2340/// that have been instantiated from a template.
2341///
2342/// Sets NewVD->isInvalidDecl() if an error was encountered.
2343void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
2344                                    bool &Redeclaration) {
2345  // If the decl is already known invalid, don't check it.
2346  if (NewVD->isInvalidDecl())
2347    return;
2348
2349  QualType T = NewVD->getType();
2350
2351  if (T->isObjCInterfaceType()) {
2352    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2353    return NewVD->setInvalidDecl();
2354  }
2355
2356  // The variable can not have an abstract class type.
2357  if (RequireNonAbstractType(NewVD->getLocation(), T,
2358                             diag::err_abstract_type_in_decl,
2359                             AbstractVariableType))
2360    return NewVD->setInvalidDecl();
2361
2362  // Emit an error if an address space was applied to decl with local storage.
2363  // This includes arrays of objects with address space qualifiers, but not
2364  // automatic variables that point to other address spaces.
2365  // ISO/IEC TR 18037 S5.1.2
2366  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2367    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2368    return NewVD->setInvalidDecl();
2369  }
2370
2371  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2372      && !NewVD->hasAttr<BlocksAttr>())
2373    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2374
2375  bool isVM = T->isVariablyModifiedType();
2376  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2377      NewVD->hasAttr<BlocksAttr>())
2378    CurFunctionNeedsScopeChecking = true;
2379
2380  if ((isVM && NewVD->hasLinkage()) ||
2381      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2382    bool SizeIsNegative;
2383    QualType FixedTy =
2384        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2385
2386    if (FixedTy.isNull() && T->isVariableArrayType()) {
2387      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2388      // FIXME: This won't give the correct result for
2389      // int a[10][n];
2390      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2391
2392      if (NewVD->isFileVarDecl())
2393        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2394        << SizeRange;
2395      else if (NewVD->getStorageClass() == VarDecl::Static)
2396        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2397        << SizeRange;
2398      else
2399        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2400        << SizeRange;
2401      return NewVD->setInvalidDecl();
2402    }
2403
2404    if (FixedTy.isNull()) {
2405      if (NewVD->isFileVarDecl())
2406        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2407      else
2408        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2409      return NewVD->setInvalidDecl();
2410    }
2411
2412    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2413    NewVD->setType(FixedTy);
2414  }
2415
2416  if (!PrevDecl && NewVD->isExternC()) {
2417    // Since we did not find anything by this name and we're declaring
2418    // an extern "C" variable, look for a non-visible extern "C"
2419    // declaration with the same name.
2420    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2421      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2422    if (Pos != LocallyScopedExternalDecls.end())
2423      PrevDecl = Pos->second;
2424  }
2425
2426  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2427    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2428      << T;
2429    return NewVD->setInvalidDecl();
2430  }
2431
2432  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2433    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2434    return NewVD->setInvalidDecl();
2435  }
2436
2437  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2438    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2439    return NewVD->setInvalidDecl();
2440  }
2441
2442  if (PrevDecl) {
2443    Redeclaration = true;
2444    MergeVarDecl(NewVD, PrevDecl);
2445  }
2446}
2447
2448static bool isUsingDecl(Decl *D) {
2449  return isa<UsingDecl>(D) || isa<UnresolvedUsingDecl>(D);
2450}
2451
2452/// \brief Data used with FindOverriddenMethod
2453struct FindOverriddenMethodData {
2454  Sema *S;
2455  CXXMethodDecl *Method;
2456};
2457
2458/// \brief Member lookup function that determines whether a given C++
2459/// method overrides a method in a base class, to be used with
2460/// CXXRecordDecl::lookupInBases().
2461static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2462                                 CXXBasePath &Path,
2463                                 void *UserData) {
2464  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2465
2466  FindOverriddenMethodData *Data
2467    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2468  for (Path.Decls = BaseRecord->lookup(Data->Method->getDeclName());
2469       Path.Decls.first != Path.Decls.second;
2470       ++Path.Decls.first) {
2471    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2472      OverloadedFunctionDecl::function_iterator MatchedDecl;
2473      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, MatchedDecl))
2474        return true;
2475    }
2476  }
2477
2478  return false;
2479}
2480
2481NamedDecl*
2482Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2483                              QualType R, DeclaratorInfo *DInfo,
2484                              NamedDecl* PrevDecl,
2485                              MultiTemplateParamsArg TemplateParamLists,
2486                              bool IsFunctionDefinition, bool &Redeclaration) {
2487  assert(R.getTypePtr()->isFunctionType());
2488
2489  DeclarationName Name = GetNameForDeclarator(D);
2490  FunctionDecl::StorageClass SC = FunctionDecl::None;
2491  switch (D.getDeclSpec().getStorageClassSpec()) {
2492  default: assert(0 && "Unknown storage class!");
2493  case DeclSpec::SCS_auto:
2494  case DeclSpec::SCS_register:
2495  case DeclSpec::SCS_mutable:
2496    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2497         diag::err_typecheck_sclass_func);
2498    D.setInvalidType();
2499    break;
2500  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2501  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2502  case DeclSpec::SCS_static: {
2503    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2504      // C99 6.7.1p5:
2505      //   The declaration of an identifier for a function that has
2506      //   block scope shall have no explicit storage-class specifier
2507      //   other than extern
2508      // See also (C++ [dcl.stc]p4).
2509      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2510           diag::err_static_block_func);
2511      SC = FunctionDecl::None;
2512    } else
2513      SC = FunctionDecl::Static;
2514    break;
2515  }
2516  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2517  }
2518
2519  if (D.getDeclSpec().isThreadSpecified())
2520    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2521
2522  bool isFriend = D.getDeclSpec().isFriendSpecified();
2523  bool isInline = D.getDeclSpec().isInlineSpecified();
2524  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2525  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2526
2527  // Check that the return type is not an abstract class type.
2528  // For record types, this is done by the AbstractClassUsageDiagnoser once
2529  // the class has been completely parsed.
2530  if (!DC->isRecord() &&
2531      RequireNonAbstractType(D.getIdentifierLoc(),
2532                             R->getAs<FunctionType>()->getResultType(),
2533                             diag::err_abstract_type_in_decl,
2534                             AbstractReturnType))
2535    D.setInvalidType();
2536
2537  // Do not allow returning a objc interface by-value.
2538  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2539    Diag(D.getIdentifierLoc(),
2540         diag::err_object_cannot_be_passed_returned_by_value) << 0
2541      << R->getAs<FunctionType>()->getResultType();
2542    D.setInvalidType();
2543  }
2544
2545  bool isVirtualOkay = false;
2546  FunctionDecl *NewFD;
2547
2548  if (isFriend) {
2549    // DC is the namespace in which the function is being declared.
2550    assert((DC->isFileContext() || PrevDecl) && "previously-undeclared "
2551           "friend function being created in a non-namespace context");
2552
2553    // C++ [class.friend]p5
2554    //   A function can be defined in a friend declaration of a
2555    //   class . . . . Such a function is implicitly inline.
2556    isInline |= IsFunctionDefinition;
2557  }
2558
2559  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2560    // This is a C++ constructor declaration.
2561    assert(DC->isRecord() &&
2562           "Constructors can only be declared in a member context");
2563
2564    R = CheckConstructorDeclarator(D, R, SC);
2565
2566    // Create the new declaration
2567    NewFD = CXXConstructorDecl::Create(Context,
2568                                       cast<CXXRecordDecl>(DC),
2569                                       D.getIdentifierLoc(), Name, R, DInfo,
2570                                       isExplicit, isInline,
2571                                       /*isImplicitlyDeclared=*/false);
2572  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2573    // This is a C++ destructor declaration.
2574    if (DC->isRecord()) {
2575      R = CheckDestructorDeclarator(D, SC);
2576
2577      NewFD = CXXDestructorDecl::Create(Context,
2578                                        cast<CXXRecordDecl>(DC),
2579                                        D.getIdentifierLoc(), Name, R,
2580                                        isInline,
2581                                        /*isImplicitlyDeclared=*/false);
2582
2583      isVirtualOkay = true;
2584    } else {
2585      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2586
2587      // Create a FunctionDecl to satisfy the function definition parsing
2588      // code path.
2589      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2590                                   Name, R, DInfo, SC, isInline,
2591                                   /*hasPrototype=*/true);
2592      D.setInvalidType();
2593    }
2594  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2595    if (!DC->isRecord()) {
2596      Diag(D.getIdentifierLoc(),
2597           diag::err_conv_function_not_member);
2598      return 0;
2599    }
2600
2601    CheckConversionDeclarator(D, R, SC);
2602    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2603                                      D.getIdentifierLoc(), Name, R, DInfo,
2604                                      isInline, isExplicit);
2605
2606    isVirtualOkay = true;
2607  } else if (DC->isRecord()) {
2608    // If the of the function is the same as the name of the record, then this
2609    // must be an invalid constructor that has a return type.
2610    // (The parser checks for a return type and makes the declarator a
2611    // constructor if it has no return type).
2612    // must have an invalid constructor that has a return type
2613    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2614      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2615        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2616        << SourceRange(D.getIdentifierLoc());
2617      return 0;
2618    }
2619
2620    bool isStatic = SC == FunctionDecl::Static;
2621
2622    // [class.free]p1:
2623    // Any allocation function for a class T is a static member
2624    // (even if not explicitly declared static).
2625    if (Name.getCXXOverloadedOperator() == OO_New ||
2626        Name.getCXXOverloadedOperator() == OO_Array_New)
2627      isStatic = true;
2628
2629    // [class.free]p6 Any deallocation function for a class X is a static member
2630    // (even if not explicitly declared static).
2631    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2632        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2633      isStatic = true;
2634
2635    // This is a C++ method declaration.
2636    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2637                                  D.getIdentifierLoc(), Name, R, DInfo,
2638                                  isStatic, isInline);
2639
2640    isVirtualOkay = !isStatic;
2641  } else {
2642    // Determine whether the function was written with a
2643    // prototype. This true when:
2644    //   - we're in C++ (where every function has a prototype),
2645    //   - there is a prototype in the declarator, or
2646    //   - the type R of the function is some kind of typedef or other reference
2647    //     to a type name (which eventually refers to a function type).
2648    bool HasPrototype =
2649       getLangOptions().CPlusPlus ||
2650       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2651       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2652
2653    NewFD = FunctionDecl::Create(Context, DC,
2654                                 D.getIdentifierLoc(),
2655                                 Name, R, DInfo, SC, isInline, HasPrototype);
2656  }
2657
2658  if (D.isInvalidType())
2659    NewFD->setInvalidDecl();
2660
2661  // Set the lexical context. If the declarator has a C++
2662  // scope specifier, or is the object of a friend declaration, the
2663  // lexical context will be different from the semantic context.
2664  NewFD->setLexicalDeclContext(CurContext);
2665
2666  // Match up the template parameter lists with the scope specifier, then
2667  // determine whether we have a template or a template specialization.
2668  FunctionTemplateDecl *FunctionTemplate = 0;
2669  bool isExplicitSpecialization = false;
2670  bool isFunctionTemplateSpecialization = false;
2671  if (TemplateParameterList *TemplateParams
2672        = MatchTemplateParametersToScopeSpecifier(
2673                                  D.getDeclSpec().getSourceRange().getBegin(),
2674                                  D.getCXXScopeSpec(),
2675                           (TemplateParameterList**)TemplateParamLists.get(),
2676                                                  TemplateParamLists.size(),
2677                                                  isExplicitSpecialization)) {
2678    if (TemplateParams->size() > 0) {
2679      // This is a function template
2680
2681      // Check that we can declare a template here.
2682      if (CheckTemplateDeclScope(S, TemplateParams))
2683        return 0;
2684
2685      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2686                                                      NewFD->getLocation(),
2687                                                      Name, TemplateParams,
2688                                                      NewFD);
2689      FunctionTemplate->setLexicalDeclContext(CurContext);
2690      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2691    } else {
2692      // This is a function template specialization.
2693      isFunctionTemplateSpecialization = true;
2694    }
2695
2696    // FIXME: Free this memory properly.
2697    TemplateParamLists.release();
2698  }
2699
2700  // C++ [dcl.fct.spec]p5:
2701  //   The virtual specifier shall only be used in declarations of
2702  //   nonstatic class member functions that appear within a
2703  //   member-specification of a class declaration; see 10.3.
2704  //
2705  if (isVirtual && !NewFD->isInvalidDecl()) {
2706    if (!isVirtualOkay) {
2707       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2708           diag::err_virtual_non_function);
2709    } else if (!CurContext->isRecord()) {
2710      // 'virtual' was specified outside of the class.
2711      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2712        << CodeModificationHint::CreateRemoval(
2713                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2714    } else {
2715      // Okay: Add virtual to the method.
2716      cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true);
2717      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2718      CurClass->setAggregate(false);
2719      CurClass->setPOD(false);
2720      CurClass->setEmpty(false);
2721      CurClass->setPolymorphic(true);
2722      CurClass->setHasTrivialConstructor(false);
2723      CurClass->setHasTrivialCopyConstructor(false);
2724      CurClass->setHasTrivialCopyAssignment(false);
2725    }
2726  }
2727
2728  if (isFriend) {
2729    if (FunctionTemplate) {
2730      FunctionTemplate->setObjectOfFriendDecl(
2731                                   /* PreviouslyDeclared= */ PrevDecl != NULL);
2732      FunctionTemplate->setAccess(AS_public);
2733    }
2734    else
2735      NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ PrevDecl != NULL);
2736
2737    NewFD->setAccess(AS_public);
2738  }
2739
2740
2741  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) {
2742    // Look for virtual methods in base classes that this method might override.
2743    CXXBasePaths Paths;
2744    FindOverriddenMethodData Data;
2745    Data.Method = NewMD;
2746    Data.S = this;
2747    if (cast<CXXRecordDecl>(DC)->lookupInBases(&FindOverriddenMethod, &Data,
2748                                                Paths)) {
2749      for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2750           E = Paths.found_decls_end(); I != E; ++I) {
2751        if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2752          if (!CheckOverridingFunctionReturnType(NewMD, OldMD) &&
2753              !CheckOverridingFunctionExceptionSpec(NewMD, OldMD))
2754            NewMD->addOverriddenMethod(OldMD);
2755        }
2756      }
2757    }
2758  }
2759
2760  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2761      !CurContext->isRecord()) {
2762    // C++ [class.static]p1:
2763    //   A data or function member of a class may be declared static
2764    //   in a class definition, in which case it is a static member of
2765    //   the class.
2766
2767    // Complain about the 'static' specifier if it's on an out-of-line
2768    // member function definition.
2769    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2770         diag::err_static_out_of_line)
2771      << CodeModificationHint::CreateRemoval(
2772                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2773  }
2774
2775  // Handle GNU asm-label extension (encoded as an attribute).
2776  if (Expr *E = (Expr*) D.getAsmLabel()) {
2777    // The parser guarantees this is a string.
2778    StringLiteral *SE = cast<StringLiteral>(E);
2779    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2780                                                        SE->getByteLength())));
2781  }
2782
2783  // Copy the parameter declarations from the declarator D to the function
2784  // declaration NewFD, if they are available.  First scavenge them into Params.
2785  llvm::SmallVector<ParmVarDecl*, 16> Params;
2786  if (D.getNumTypeObjects() > 0) {
2787    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2788
2789    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2790    // function that takes no arguments, not a function that takes a
2791    // single void argument.
2792    // We let through "const void" here because Sema::GetTypeForDeclarator
2793    // already checks for that case.
2794    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2795        FTI.ArgInfo[0].Param &&
2796        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2797      // Empty arg list, don't push any params.
2798      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2799
2800      // In C++, the empty parameter-type-list must be spelled "void"; a
2801      // typedef of void is not permitted.
2802      if (getLangOptions().CPlusPlus &&
2803          Param->getType().getUnqualifiedType() != Context.VoidTy)
2804        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2805      // FIXME: Leaks decl?
2806    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2807      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2808        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2809        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2810        Param->setDeclContext(NewFD);
2811        Params.push_back(Param);
2812      }
2813    }
2814
2815  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2816    // When we're declaring a function with a typedef, typeof, etc as in the
2817    // following example, we'll need to synthesize (unnamed)
2818    // parameters for use in the declaration.
2819    //
2820    // @code
2821    // typedef void fn(int);
2822    // fn f;
2823    // @endcode
2824
2825    // Synthesize a parameter for each argument type.
2826    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2827         AE = FT->arg_type_end(); AI != AE; ++AI) {
2828      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2829                                               SourceLocation(), 0,
2830                                               *AI, /*DInfo=*/0,
2831                                               VarDecl::None, 0);
2832      Param->setImplicit();
2833      Params.push_back(Param);
2834    }
2835  } else {
2836    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2837           "Should not need args for typedef of non-prototype fn");
2838  }
2839  // Finally, we know we have the right number of parameters, install them.
2840  NewFD->setParams(Context, Params.data(), Params.size());
2841
2842  // If name lookup finds a previous declaration that is not in the
2843  // same scope as the new declaration, this may still be an
2844  // acceptable redeclaration.
2845  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2846      !(NewFD->hasLinkage() &&
2847        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2848    PrevDecl = 0;
2849
2850  // If the declarator is a template-id, translate the parser's template
2851  // argument list into our AST format.
2852  bool HasExplicitTemplateArgs = false;
2853  llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2854  SourceLocation LAngleLoc, RAngleLoc;
2855  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2856    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2857    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2858                                       TemplateId->getTemplateArgs(),
2859                                       TemplateId->NumArgs);
2860    translateTemplateArguments(TemplateArgsPtr,
2861                               TemplateArgs);
2862    TemplateArgsPtr.release();
2863
2864    HasExplicitTemplateArgs = true;
2865    LAngleLoc = TemplateId->LAngleLoc;
2866    RAngleLoc = TemplateId->RAngleLoc;
2867
2868    if (FunctionTemplate) {
2869      // FIXME: Diagnose function template with explicit template
2870      // arguments.
2871      HasExplicitTemplateArgs = false;
2872    } else if (!isFunctionTemplateSpecialization &&
2873               !D.getDeclSpec().isFriendSpecified()) {
2874      // We have encountered something that the user meant to be a
2875      // specialization (because it has explicitly-specified template
2876      // arguments) but that was not introduced with a "template<>" (or had
2877      // too few of them).
2878      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
2879        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
2880        << CodeModificationHint::CreateInsertion(
2881                                   D.getDeclSpec().getSourceRange().getBegin(),
2882                                                 "template<> ");
2883      isFunctionTemplateSpecialization = true;
2884    }
2885  }
2886
2887  if (isFunctionTemplateSpecialization) {
2888      if (CheckFunctionTemplateSpecialization(NewFD, HasExplicitTemplateArgs,
2889                                              LAngleLoc, TemplateArgs.data(),
2890                                              TemplateArgs.size(), RAngleLoc,
2891                                              PrevDecl))
2892        NewFD->setInvalidDecl();
2893  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
2894             CheckMemberSpecialization(NewFD, PrevDecl))
2895    NewFD->setInvalidDecl();
2896
2897  // Perform semantic checking on the function declaration.
2898  bool OverloadableAttrRequired = false; // FIXME: HACK!
2899  CheckFunctionDeclaration(NewFD, PrevDecl, isExplicitSpecialization,
2900                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
2901
2902  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
2903    // An out-of-line member function declaration must also be a
2904    // definition (C++ [dcl.meaning]p1).
2905    // Note that this is not the case for explicit specializations of
2906    // function templates or member functions of class templates, per
2907    // C++ [temp.expl.spec]p2.
2908    if (!IsFunctionDefinition && !isFriend &&
2909        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
2910      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2911        << D.getCXXScopeSpec().getRange();
2912      NewFD->setInvalidDecl();
2913    } else if (!Redeclaration && (!PrevDecl || !isUsingDecl(PrevDecl))) {
2914      // The user tried to provide an out-of-line definition for a
2915      // function that is a member of a class or namespace, but there
2916      // was no such member function declared (C++ [class.mfct]p2,
2917      // C++ [namespace.memdef]p2). For example:
2918      //
2919      // class X {
2920      //   void f() const;
2921      // };
2922      //
2923      // void X::f() { } // ill-formed
2924      //
2925      // Complain about this problem, and attempt to suggest close
2926      // matches (e.g., those that differ only in cv-qualifiers and
2927      // whether the parameter types are references).
2928      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
2929        << Name << DC << D.getCXXScopeSpec().getRange();
2930      NewFD->setInvalidDecl();
2931
2932      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
2933                        LookupResult::ForRedeclaration);
2934      LookupQualifiedName(Prev, DC);
2935      assert(!Prev.isAmbiguous() &&
2936             "Cannot have an ambiguity in previous-declaration lookup");
2937      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2938           Func != FuncEnd; ++Func) {
2939        if (isa<FunctionDecl>(*Func) &&
2940            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2941          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
2942      }
2943
2944      PrevDecl = 0;
2945    }
2946  }
2947
2948  // Handle attributes. We need to have merged decls when handling attributes
2949  // (for example to check for conflicts, etc).
2950  // FIXME: This needs to happen before we merge declarations. Then,
2951  // let attribute merging cope with attribute conflicts.
2952  ProcessDeclAttributes(S, NewFD, D);
2953
2954  // attributes declared post-definition are currently ignored
2955  if (Redeclaration && PrevDecl) {
2956    const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl);
2957    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
2958      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
2959      Diag(Def->getLocation(), diag::note_previous_definition);
2960    }
2961  }
2962
2963  AddKnownFunctionAttributes(NewFD);
2964
2965  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2966    // If a function name is overloadable in C, then every function
2967    // with that name must be marked "overloadable".
2968    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2969      << Redeclaration << NewFD;
2970    if (PrevDecl)
2971      Diag(PrevDecl->getLocation(),
2972           diag::note_attribute_overloadable_prev_overload);
2973    NewFD->addAttr(::new (Context) OverloadableAttr());
2974  }
2975
2976  // If this is a locally-scoped extern C function, update the
2977  // map of such names.
2978  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
2979      && !NewFD->isInvalidDecl())
2980    RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2981
2982  // Set this FunctionDecl's range up to the right paren.
2983  NewFD->setLocEnd(D.getSourceRange().getEnd());
2984
2985  if (FunctionTemplate && NewFD->isInvalidDecl())
2986    FunctionTemplate->setInvalidDecl();
2987
2988  if (FunctionTemplate)
2989    return FunctionTemplate;
2990
2991  return NewFD;
2992}
2993
2994/// \brief Perform semantic checking of a new function declaration.
2995///
2996/// Performs semantic analysis of the new function declaration
2997/// NewFD. This routine performs all semantic checking that does not
2998/// require the actual declarator involved in the declaration, and is
2999/// used both for the declaration of functions as they are parsed
3000/// (called via ActOnDeclarator) and for the declaration of functions
3001/// that have been instantiated via C++ template instantiation (called
3002/// via InstantiateDecl).
3003///
3004/// \param IsExplicitSpecialiation whether this new function declaration is
3005/// an explicit specialization of the previous declaration.
3006///
3007/// This sets NewFD->isInvalidDecl() to true if there was an error.
3008void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
3009                                    bool IsExplicitSpecialization,
3010                                    bool &Redeclaration,
3011                                    bool &OverloadableAttrRequired) {
3012  // If NewFD is already known erroneous, don't do any of this checking.
3013  if (NewFD->isInvalidDecl())
3014    return;
3015
3016  if (NewFD->getResultType()->isVariablyModifiedType()) {
3017    // Functions returning a variably modified type violate C99 6.7.5.2p2
3018    // because all functions have linkage.
3019    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3020    return NewFD->setInvalidDecl();
3021  }
3022
3023  if (NewFD->isMain())
3024    CheckMain(NewFD);
3025
3026  // Check for a previous declaration of this name.
3027  if (!PrevDecl && NewFD->isExternC()) {
3028    // Since we did not find anything by this name and we're declaring
3029    // an extern "C" function, look for a non-visible extern "C"
3030    // declaration with the same name.
3031    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3032      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3033    if (Pos != LocallyScopedExternalDecls.end())
3034      PrevDecl = Pos->second;
3035  }
3036
3037  // Merge or overload the declaration with an existing declaration of
3038  // the same name, if appropriate.
3039  if (PrevDecl) {
3040    // Determine whether NewFD is an overload of PrevDecl or
3041    // a declaration that requires merging. If it's an overload,
3042    // there's no more work to do here; we'll just add the new
3043    // function to the scope.
3044    OverloadedFunctionDecl::function_iterator MatchedDecl;
3045
3046    if (!getLangOptions().CPlusPlus &&
3047        AllowOverloadingOfFunction(PrevDecl, Context)) {
3048      OverloadableAttrRequired = true;
3049
3050      // Functions marked "overloadable" must have a prototype (that
3051      // we can't get through declaration merging).
3052      if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3053        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
3054          << NewFD;
3055        Redeclaration = true;
3056
3057        // Turn this into a variadic function with no parameters.
3058        QualType R = Context.getFunctionType(
3059                       NewFD->getType()->getAs<FunctionType>()->getResultType(),
3060                       0, 0, true, 0);
3061        NewFD->setType(R);
3062        return NewFD->setInvalidDecl();
3063      }
3064    }
3065
3066    if (PrevDecl &&
3067        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
3068         !IsOverload(NewFD, PrevDecl, MatchedDecl)) && !isUsingDecl(PrevDecl)) {
3069      Redeclaration = true;
3070      Decl *OldDecl = PrevDecl;
3071
3072      // If PrevDecl was an overloaded function, extract the
3073      // FunctionDecl that matched.
3074      if (isa<OverloadedFunctionDecl>(PrevDecl))
3075        OldDecl = *MatchedDecl;
3076
3077      // NewFD and OldDecl represent declarations that need to be
3078      // merged.
3079      if (MergeFunctionDecl(NewFD, OldDecl))
3080        return NewFD->setInvalidDecl();
3081
3082      if (FunctionTemplateDecl *OldTemplateDecl
3083                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3084        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3085        FunctionTemplateDecl *NewTemplateDecl
3086          = NewFD->getDescribedFunctionTemplate();
3087        assert(NewTemplateDecl && "Template/non-template mismatch");
3088        if (CXXMethodDecl *Method
3089              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3090          Method->setAccess(OldTemplateDecl->getAccess());
3091          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3092        }
3093
3094        // If this is an explicit specialization of a member that is a function
3095        // template, mark it as a member specialization.
3096        if (IsExplicitSpecialization &&
3097            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3098          NewTemplateDecl->setMemberSpecialization();
3099          assert(OldTemplateDecl->isMemberSpecialization());
3100        }
3101      } else {
3102        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3103          NewFD->setAccess(OldDecl->getAccess());
3104        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3105      }
3106    }
3107  }
3108
3109  // Semantic checking for this function declaration (in isolation).
3110  if (getLangOptions().CPlusPlus) {
3111    // C++-specific checks.
3112    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3113      CheckConstructor(Constructor);
3114    } else if (CXXDestructorDecl *Destructor =
3115                dyn_cast<CXXDestructorDecl>(NewFD)) {
3116      CXXRecordDecl *Record = Destructor->getParent();
3117      QualType ClassType = Context.getTypeDeclType(Record);
3118
3119      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3120      // type is dependent? Both gcc and edg can handle that.
3121      if (!ClassType->isDependentType()) {
3122        DeclarationName Name
3123          = Context.DeclarationNames.getCXXDestructorName(
3124                                        Context.getCanonicalType(ClassType));
3125        if (NewFD->getDeclName() != Name) {
3126          Diag(NewFD->getLocation(), diag::err_destructor_name);
3127          return NewFD->setInvalidDecl();
3128        }
3129
3130        CheckDestructor(Destructor);
3131      }
3132
3133      Record->setUserDeclaredDestructor(true);
3134      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3135      // user-defined destructor.
3136      Record->setPOD(false);
3137
3138      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3139      // declared destructor.
3140      // FIXME: C++0x: don't do this for "= default" destructors
3141      Record->setHasTrivialDestructor(false);
3142    } else if (CXXConversionDecl *Conversion
3143               = dyn_cast<CXXConversionDecl>(NewFD))
3144      ActOnConversionDeclarator(Conversion);
3145
3146    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3147    if (NewFD->isOverloadedOperator() &&
3148        CheckOverloadedOperatorDeclaration(NewFD))
3149      return NewFD->setInvalidDecl();
3150
3151    // In C++, check default arguments now that we have merged decls. Unless
3152    // the lexical context is the class, because in this case this is done
3153    // during delayed parsing anyway.
3154    if (!CurContext->isRecord())
3155      CheckCXXDefaultArguments(NewFD);
3156  }
3157}
3158
3159void Sema::CheckMain(FunctionDecl* FD) {
3160  // C++ [basic.start.main]p3:  A program that declares main to be inline
3161  //   or static is ill-formed.
3162  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3163  //   shall not appear in a declaration of main.
3164  // static main is not an error under C99, but we should warn about it.
3165  bool isInline = FD->isInlineSpecified();
3166  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3167  if (isInline || isStatic) {
3168    unsigned diagID = diag::warn_unusual_main_decl;
3169    if (isInline || getLangOptions().CPlusPlus)
3170      diagID = diag::err_unusual_main_decl;
3171
3172    int which = isStatic + (isInline << 1) - 1;
3173    Diag(FD->getLocation(), diagID) << which;
3174  }
3175
3176  QualType T = FD->getType();
3177  assert(T->isFunctionType() && "function decl is not of function type");
3178  const FunctionType* FT = T->getAs<FunctionType>();
3179
3180  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3181    // TODO: add a replacement fixit to turn the return type into 'int'.
3182    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3183    FD->setInvalidDecl(true);
3184  }
3185
3186  // Treat protoless main() as nullary.
3187  if (isa<FunctionNoProtoType>(FT)) return;
3188
3189  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3190  unsigned nparams = FTP->getNumArgs();
3191  assert(FD->getNumParams() == nparams);
3192
3193  if (nparams > 3) {
3194    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3195    FD->setInvalidDecl(true);
3196    nparams = 3;
3197  }
3198
3199  // FIXME: a lot of the following diagnostics would be improved
3200  // if we had some location information about types.
3201
3202  QualType CharPP =
3203    Context.getPointerType(Context.getPointerType(Context.CharTy));
3204  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
3205
3206  for (unsigned i = 0; i < nparams; ++i) {
3207    QualType AT = FTP->getArgType(i);
3208
3209    bool mismatch = true;
3210
3211    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3212      mismatch = false;
3213    else if (Expected[i] == CharPP) {
3214      // As an extension, the following forms are okay:
3215      //   char const **
3216      //   char const * const *
3217      //   char * const *
3218
3219      QualifierCollector qs;
3220      const PointerType* PT;
3221      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3222          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3223          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3224        qs.removeConst();
3225        mismatch = !qs.empty();
3226      }
3227    }
3228
3229    if (mismatch) {
3230      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3231      // TODO: suggest replacing given type with expected type
3232      FD->setInvalidDecl(true);
3233    }
3234  }
3235
3236  if (nparams == 1 && !FD->isInvalidDecl()) {
3237    Diag(FD->getLocation(), diag::warn_main_one_arg);
3238  }
3239}
3240
3241bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3242  // FIXME: Need strict checking.  In C89, we need to check for
3243  // any assignment, increment, decrement, function-calls, or
3244  // commas outside of a sizeof.  In C99, it's the same list,
3245  // except that the aforementioned are allowed in unevaluated
3246  // expressions.  Everything else falls under the
3247  // "may accept other forms of constant expressions" exception.
3248  // (We never end up here for C++, so the constant expression
3249  // rules there don't matter.)
3250  if (Init->isConstantInitializer(Context))
3251    return false;
3252  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3253    << Init->getSourceRange();
3254  return true;
3255}
3256
3257void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3258  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3259}
3260
3261/// AddInitializerToDecl - Adds the initializer Init to the
3262/// declaration dcl. If DirectInit is true, this is C++ direct
3263/// initialization rather than copy initialization.
3264void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3265  Decl *RealDecl = dcl.getAs<Decl>();
3266  // If there is no declaration, there was an error parsing it.  Just ignore
3267  // the initializer.
3268  if (RealDecl == 0)
3269    return;
3270
3271  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3272    // With declarators parsed the way they are, the parser cannot
3273    // distinguish between a normal initializer and a pure-specifier.
3274    // Thus this grotesque test.
3275    IntegerLiteral *IL;
3276    Expr *Init = static_cast<Expr *>(init.get());
3277    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3278        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
3279      if (Method->isVirtualAsWritten()) {
3280        Method->setPure();
3281
3282        // A class is abstract if at least one function is pure virtual.
3283        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
3284      } else if (!Method->isInvalidDecl()) {
3285        Diag(Method->getLocation(), diag::err_non_virtual_pure)
3286          << Method->getDeclName() << Init->getSourceRange();
3287        Method->setInvalidDecl();
3288      }
3289    } else {
3290      Diag(Method->getLocation(), diag::err_member_function_initialization)
3291        << Method->getDeclName() << Init->getSourceRange();
3292      Method->setInvalidDecl();
3293    }
3294    return;
3295  }
3296
3297  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3298  if (!VDecl) {
3299    if (getLangOptions().CPlusPlus &&
3300        RealDecl->getLexicalDeclContext()->isRecord() &&
3301        isa<NamedDecl>(RealDecl))
3302      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3303        << cast<NamedDecl>(RealDecl)->getDeclName();
3304    else
3305      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3306    RealDecl->setInvalidDecl();
3307    return;
3308  }
3309
3310  // A definition must end up with a complete type, which means it must be
3311  // complete with the restriction that an array type might be completed by the
3312  // initializer; note that later code assumes this restriction.
3313  QualType BaseDeclType = VDecl->getType();
3314  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3315    BaseDeclType = Array->getElementType();
3316  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3317                          diag::err_typecheck_decl_incomplete_type)) {
3318    RealDecl->setInvalidDecl();
3319    return;
3320  }
3321
3322  const VarDecl *Def = 0;
3323  if (VDecl->getDefinition(Def)) {
3324    Diag(VDecl->getLocation(), diag::err_redefinition)
3325      << VDecl->getDeclName();
3326    Diag(Def->getLocation(), diag::note_previous_definition);
3327    VDecl->setInvalidDecl();
3328    return;
3329  }
3330
3331  // Take ownership of the expression, now that we're sure we have somewhere
3332  // to put it.
3333  Expr *Init = init.takeAs<Expr>();
3334  assert(Init && "missing initializer");
3335
3336  // Get the decls type and save a reference for later, since
3337  // CheckInitializerTypes may change it.
3338  QualType DclT = VDecl->getType(), SavT = DclT;
3339  if (VDecl->isBlockVarDecl()) {
3340    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3341      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3342      VDecl->setInvalidDecl();
3343    } else if (!VDecl->isInvalidDecl()) {
3344      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3345                                VDecl->getDeclName(), DirectInit))
3346        VDecl->setInvalidDecl();
3347
3348      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3349      // Don't check invalid declarations to avoid emitting useless diagnostics.
3350      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3351        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3352          CheckForConstantInitializer(Init, DclT);
3353      }
3354    }
3355  } else if (VDecl->isStaticDataMember() &&
3356             VDecl->getLexicalDeclContext()->isRecord()) {
3357    // This is an in-class initialization for a static data member, e.g.,
3358    //
3359    // struct S {
3360    //   static const int value = 17;
3361    // };
3362
3363    // Attach the initializer
3364    VDecl->setInit(Context, Init);
3365
3366    // C++ [class.mem]p4:
3367    //   A member-declarator can contain a constant-initializer only
3368    //   if it declares a static member (9.4) of const integral or
3369    //   const enumeration type, see 9.4.2.
3370    QualType T = VDecl->getType();
3371    if (!T->isDependentType() &&
3372        (!Context.getCanonicalType(T).isConstQualified() ||
3373         !T->isIntegralType())) {
3374      Diag(VDecl->getLocation(), diag::err_member_initialization)
3375        << VDecl->getDeclName() << Init->getSourceRange();
3376      VDecl->setInvalidDecl();
3377    } else {
3378      // C++ [class.static.data]p4:
3379      //   If a static data member is of const integral or const
3380      //   enumeration type, its declaration in the class definition
3381      //   can specify a constant-initializer which shall be an
3382      //   integral constant expression (5.19).
3383      if (!Init->isTypeDependent() &&
3384          !Init->getType()->isIntegralType()) {
3385        // We have a non-dependent, non-integral or enumeration type.
3386        Diag(Init->getSourceRange().getBegin(),
3387             diag::err_in_class_initializer_non_integral_type)
3388          << Init->getType() << Init->getSourceRange();
3389        VDecl->setInvalidDecl();
3390      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3391        // Check whether the expression is a constant expression.
3392        llvm::APSInt Value;
3393        SourceLocation Loc;
3394        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3395          Diag(Loc, diag::err_in_class_initializer_non_constant)
3396            << Init->getSourceRange();
3397          VDecl->setInvalidDecl();
3398        } else if (!VDecl->getType()->isDependentType())
3399          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3400      }
3401    }
3402  } else if (VDecl->isFileVarDecl()) {
3403    if (VDecl->getStorageClass() == VarDecl::Extern)
3404      Diag(VDecl->getLocation(), diag::warn_extern_init);
3405    if (!VDecl->isInvalidDecl())
3406      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
3407                                VDecl->getDeclName(), DirectInit))
3408        VDecl->setInvalidDecl();
3409
3410    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3411    // Don't check invalid declarations to avoid emitting useless diagnostics.
3412    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3413      // C99 6.7.8p4. All file scoped initializers need to be constant.
3414      CheckForConstantInitializer(Init, DclT);
3415    }
3416  }
3417  // If the type changed, it means we had an incomplete type that was
3418  // completed by the initializer. For example:
3419  //   int ary[] = { 1, 3, 5 };
3420  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3421  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3422    VDecl->setType(DclT);
3423    Init->setType(DclT);
3424  }
3425
3426  Init = MaybeCreateCXXExprWithTemporaries(Init,
3427                                           /*ShouldDestroyTemporaries=*/true);
3428  // Attach the initializer to the decl.
3429  VDecl->setInit(Context, Init);
3430
3431  // If the previous declaration of VDecl was a tentative definition,
3432  // remove it from the set of tentative definitions.
3433  if (VDecl->getPreviousDeclaration() &&
3434      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3435    bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3436    assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
3437  }
3438
3439  return;
3440}
3441
3442void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3443                                  bool TypeContainsUndeducedAuto) {
3444  Decl *RealDecl = dcl.getAs<Decl>();
3445
3446  // If there is no declaration, there was an error parsing it. Just ignore it.
3447  if (RealDecl == 0)
3448    return;
3449
3450  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3451    QualType Type = Var->getType();
3452
3453    // Record tentative definitions.
3454    if (Var->isTentativeDefinition(Context)) {
3455      std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
3456        InsertPair =
3457           TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
3458
3459      // Keep the latest definition in the map.  If we see 'int i; int i;' we
3460      // want the second one in the map.
3461      InsertPair.first->second = Var;
3462
3463      // However, for the list, we don't care about the order, just make sure
3464      // that there are no dupes for a given declaration name.
3465      if (InsertPair.second)
3466        TentativeDefinitionList.push_back(Var->getDeclName());
3467    }
3468
3469    // C++ [dcl.init.ref]p3:
3470    //   The initializer can be omitted for a reference only in a
3471    //   parameter declaration (8.3.5), in the declaration of a
3472    //   function return type, in the declaration of a class member
3473    //   within its class declaration (9.2), and where the extern
3474    //   specifier is explicitly used.
3475    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3476      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3477        << Var->getDeclName()
3478        << SourceRange(Var->getLocation(), Var->getLocation());
3479      Var->setInvalidDecl();
3480      return;
3481    }
3482
3483    // C++0x [dcl.spec.auto]p3
3484    if (TypeContainsUndeducedAuto) {
3485      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3486        << Var->getDeclName() << Type;
3487      Var->setInvalidDecl();
3488      return;
3489    }
3490
3491    // An array without size is an incomplete type, and there are no special
3492    // rules in C++ to make such a definition acceptable.
3493    if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3494        !Var->hasExternalStorage()) {
3495      Diag(Var->getLocation(),
3496           diag::err_typecheck_incomplete_array_needs_initializer);
3497      Var->setInvalidDecl();
3498      return;
3499    }
3500
3501    // C++ [temp.expl.spec]p15:
3502    //   An explicit specialization of a static data member of a template is a
3503    //   definition if the declaration includes an initializer; otherwise, it
3504    //   is a declaration.
3505    if (Var->isStaticDataMember() &&
3506        Var->getInstantiatedFromStaticDataMember() &&
3507        Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3508      return;
3509
3510    // C++ [dcl.init]p9:
3511    //   If no initializer is specified for an object, and the object
3512    //   is of (possibly cv-qualified) non-POD class type (or array
3513    //   thereof), the object shall be default-initialized; if the
3514    //   object is of const-qualified type, the underlying class type
3515    //   shall have a user-declared default constructor.
3516    //
3517    // FIXME: Diagnose the "user-declared default constructor" bit.
3518    if (getLangOptions().CPlusPlus) {
3519      QualType InitType = Type;
3520      if (const ArrayType *Array = Context.getAsArrayType(Type))
3521        InitType = Context.getBaseElementType(Array);
3522      if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
3523          InitType->isRecordType() && !InitType->isDependentType()) {
3524        if (!RequireCompleteType(Var->getLocation(), InitType,
3525                                 diag::err_invalid_incomplete_type_use)) {
3526          ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3527
3528          CXXConstructorDecl *Constructor
3529            = PerformInitializationByConstructor(InitType,
3530                                                 MultiExprArg(*this, 0, 0),
3531                                                 Var->getLocation(),
3532                                               SourceRange(Var->getLocation(),
3533                                                           Var->getLocation()),
3534                                                 Var->getDeclName(),
3535                                                 IK_Default,
3536                                                 ConstructorArgs);
3537
3538          // FIXME: Location info for the variable initialization?
3539          if (!Constructor)
3540            Var->setInvalidDecl();
3541          else {
3542            // FIXME: Cope with initialization of arrays
3543            if (!Constructor->isTrivial() &&
3544                InitializeVarWithConstructor(Var, Constructor,
3545                                             move_arg(ConstructorArgs)))
3546              Var->setInvalidDecl();
3547
3548            FinalizeVarWithDestructor(Var, InitType);
3549          }
3550        } else {
3551          Var->setInvalidDecl();
3552        }
3553      }
3554    }
3555
3556#if 0
3557    // FIXME: Temporarily disabled because we are not properly parsing
3558    // linkage specifications on declarations, e.g.,
3559    //
3560    //   extern "C" const CGPoint CGPointerZero;
3561    //
3562    // C++ [dcl.init]p9:
3563    //
3564    //     If no initializer is specified for an object, and the
3565    //     object is of (possibly cv-qualified) non-POD class type (or
3566    //     array thereof), the object shall be default-initialized; if
3567    //     the object is of const-qualified type, the underlying class
3568    //     type shall have a user-declared default
3569    //     constructor. Otherwise, if no initializer is specified for
3570    //     an object, the object and its subobjects, if any, have an
3571    //     indeterminate initial value; if the object or any of its
3572    //     subobjects are of const-qualified type, the program is
3573    //     ill-formed.
3574    //
3575    // This isn't technically an error in C, so we don't diagnose it.
3576    //
3577    // FIXME: Actually perform the POD/user-defined default
3578    // constructor check.
3579    if (getLangOptions().CPlusPlus &&
3580        Context.getCanonicalType(Type).isConstQualified() &&
3581        !Var->hasExternalStorage())
3582      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3583        << Var->getName()
3584        << SourceRange(Var->getLocation(), Var->getLocation());
3585#endif
3586  }
3587}
3588
3589Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3590                                                   DeclPtrTy *Group,
3591                                                   unsigned NumDecls) {
3592  llvm::SmallVector<Decl*, 8> Decls;
3593
3594  if (DS.isTypeSpecOwned())
3595    Decls.push_back((Decl*)DS.getTypeRep());
3596
3597  for (unsigned i = 0; i != NumDecls; ++i)
3598    if (Decl *D = Group[i].getAs<Decl>())
3599      Decls.push_back(D);
3600
3601  // Perform semantic analysis that depends on having fully processed both
3602  // the declarator and initializer.
3603  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3604    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3605    if (!IDecl)
3606      continue;
3607    QualType T = IDecl->getType();
3608
3609    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3610    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3611    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3612      if (T->isDependentType()) {
3613        // If T is dependent, we should not require a complete type.
3614        // (RequireCompleteType shouldn't be called with dependent types.)
3615        // But we still can at least check if we've got an array of unspecified
3616        // size without an initializer.
3617        if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3618            !IDecl->getInit()) {
3619          Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3620            << T;
3621          IDecl->setInvalidDecl();
3622        }
3623      } else if (!IDecl->isInvalidDecl()) {
3624        // If T is an incomplete array type with an initializer list that is
3625        // dependent on something, its size has not been fixed. We could attempt
3626        // to fix the size for such arrays, but we would still have to check
3627        // here for initializers containing a C++0x vararg expansion, e.g.
3628        // template <typename... Args> void f(Args... args) {
3629        //   int vals[] = { args };
3630        // }
3631        const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
3632        Expr *Init = IDecl->getInit();
3633        if (IAT && Init &&
3634            (Init->isTypeDependent() || Init->isValueDependent())) {
3635          // Check that the member type of the array is complete, at least.
3636          if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3637                                  diag::err_typecheck_decl_incomplete_type))
3638            IDecl->setInvalidDecl();
3639        } else if (RequireCompleteType(IDecl->getLocation(), T,
3640                                      diag::err_typecheck_decl_incomplete_type))
3641          IDecl->setInvalidDecl();
3642      }
3643    }
3644    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3645    // object that has file scope without an initializer, and without a
3646    // storage-class specifier or with the storage-class specifier "static",
3647    // constitutes a tentative definition. Note: A tentative definition with
3648    // external linkage is valid (C99 6.2.2p5).
3649    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3650      if (const IncompleteArrayType *ArrayT
3651          = Context.getAsIncompleteArrayType(T)) {
3652        if (RequireCompleteType(IDecl->getLocation(),
3653                                ArrayT->getElementType(),
3654                                diag::err_illegal_decl_array_incomplete_type))
3655          IDecl->setInvalidDecl();
3656      } else if (IDecl->getStorageClass() == VarDecl::Static) {
3657        // C99 6.9.2p3: If the declaration of an identifier for an object is
3658        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3659        // declared type shall not be an incomplete type.
3660        // NOTE: code such as the following
3661        //     static struct s;
3662        //     struct s { int a; };
3663        // is accepted by gcc. Hence here we issue a warning instead of
3664        // an error and we do not invalidate the static declaration.
3665        // NOTE: to avoid multiple warnings, only check the first declaration.
3666        if (IDecl->getPreviousDeclaration() == 0)
3667          RequireCompleteType(IDecl->getLocation(), T,
3668                              diag::ext_typecheck_decl_incomplete_type);
3669      }
3670    }
3671  }
3672  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3673                                                   Decls.data(), Decls.size()));
3674}
3675
3676
3677/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3678/// to introduce parameters into function prototype scope.
3679Sema::DeclPtrTy
3680Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3681  const DeclSpec &DS = D.getDeclSpec();
3682
3683  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3684  VarDecl::StorageClass StorageClass = VarDecl::None;
3685  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3686    StorageClass = VarDecl::Register;
3687  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3688    Diag(DS.getStorageClassSpecLoc(),
3689         diag::err_invalid_storage_class_in_func_decl);
3690    D.getMutableDeclSpec().ClearStorageClassSpecs();
3691  }
3692
3693  if (D.getDeclSpec().isThreadSpecified())
3694    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3695
3696  DiagnoseFunctionSpecifiers(D);
3697
3698  // Check that there are no default arguments inside the type of this
3699  // parameter (C++ only).
3700  if (getLangOptions().CPlusPlus)
3701    CheckExtraCXXDefaultArguments(D);
3702
3703  DeclaratorInfo *DInfo = 0;
3704  TagDecl *OwnedDecl = 0;
3705  QualType parmDeclType = GetTypeForDeclarator(D, S, &DInfo, &OwnedDecl);
3706
3707  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3708    // C++ [dcl.fct]p6:
3709    //   Types shall not be defined in return or parameter types.
3710    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3711      << Context.getTypeDeclType(OwnedDecl);
3712  }
3713
3714  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3715  // Can this happen for params?  We already checked that they don't conflict
3716  // among each other.  Here they can only shadow globals, which is ok.
3717  IdentifierInfo *II = D.getIdentifier();
3718  if (II) {
3719    if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3720      if (PrevDecl->isTemplateParameter()) {
3721        // Maybe we will complain about the shadowed template parameter.
3722        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3723        // Just pretend that we didn't see the previous declaration.
3724        PrevDecl = 0;
3725      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3726        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3727
3728        // Recover by removing the name
3729        II = 0;
3730        D.SetIdentifier(0, D.getIdentifierLoc());
3731      }
3732    }
3733  }
3734
3735  // Parameters can not be abstract class types.
3736  // For record types, this is done by the AbstractClassUsageDiagnoser once
3737  // the class has been completely parsed.
3738  if (!CurContext->isRecord() &&
3739      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3740                             diag::err_abstract_type_in_decl,
3741                             AbstractParamType))
3742    D.setInvalidType(true);
3743
3744  QualType T = adjustParameterType(parmDeclType);
3745
3746  ParmVarDecl *New
3747    = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
3748                          T, DInfo, StorageClass, 0);
3749
3750  if (D.isInvalidType())
3751    New->setInvalidDecl();
3752
3753  // Parameter declarators cannot be interface types. All ObjC objects are
3754  // passed by reference.
3755  if (T->isObjCInterfaceType()) {
3756    Diag(D.getIdentifierLoc(),
3757         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3758    New->setInvalidDecl();
3759  }
3760
3761  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3762  if (D.getCXXScopeSpec().isSet()) {
3763    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3764      << D.getCXXScopeSpec().getRange();
3765    New->setInvalidDecl();
3766  }
3767
3768  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3769  // duration shall not be qualified by an address-space qualifier."
3770  // Since all parameters have automatic store duration, they can not have
3771  // an address space.
3772  if (T.getAddressSpace() != 0) {
3773    Diag(D.getIdentifierLoc(),
3774         diag::err_arg_with_address_space);
3775    New->setInvalidDecl();
3776  }
3777
3778
3779  // Add the parameter declaration into this scope.
3780  S->AddDecl(DeclPtrTy::make(New));
3781  if (II)
3782    IdResolver.AddDecl(New);
3783
3784  ProcessDeclAttributes(S, New, D);
3785
3786  if (New->hasAttr<BlocksAttr>()) {
3787    Diag(New->getLocation(), diag::err_block_on_nonlocal);
3788  }
3789  return DeclPtrTy::make(New);
3790}
3791
3792void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3793                                           SourceLocation LocAfterDecls) {
3794  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3795         "Not a function declarator!");
3796  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3797
3798  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3799  // for a K&R function.
3800  if (!FTI.hasPrototype) {
3801    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3802      --i;
3803      if (FTI.ArgInfo[i].Param == 0) {
3804        llvm::SmallString<256> Code;
3805        llvm::raw_svector_ostream(Code) << "  int "
3806                                        << FTI.ArgInfo[i].Ident->getName()
3807                                        << ";\n";
3808        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3809          << FTI.ArgInfo[i].Ident
3810          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
3811
3812        // Implicitly declare the argument as type 'int' for lack of a better
3813        // type.
3814        DeclSpec DS;
3815        const char* PrevSpec; // unused
3816        unsigned DiagID; // unused
3817        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3818                           PrevSpec, DiagID);
3819        Declarator ParamD(DS, Declarator::KNRTypeListContext);
3820        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3821        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3822      }
3823    }
3824  }
3825}
3826
3827Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3828                                              Declarator &D) {
3829  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3830  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3831         "Not a function declarator!");
3832  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3833
3834  if (FTI.hasPrototype) {
3835    // FIXME: Diagnose arguments without names in C.
3836  }
3837
3838  Scope *ParentScope = FnBodyScope->getParent();
3839
3840  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3841                                  MultiTemplateParamsArg(*this),
3842                                  /*IsFunctionDefinition=*/true);
3843  return ActOnStartOfFunctionDef(FnBodyScope, DP);
3844}
3845
3846Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
3847  // Clear the last template instantiation error context.
3848  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
3849
3850  if (!D)
3851    return D;
3852  FunctionDecl *FD = 0;
3853
3854  if (FunctionTemplateDecl *FunTmpl
3855        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
3856    FD = FunTmpl->getTemplatedDecl();
3857  else
3858    FD = cast<FunctionDecl>(D.getAs<Decl>());
3859
3860  CurFunctionNeedsScopeChecking = false;
3861
3862  // See if this is a redefinition.
3863  const FunctionDecl *Definition;
3864  if (FD->getBody(Definition)) {
3865    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
3866    Diag(Definition->getLocation(), diag::note_previous_definition);
3867  }
3868
3869  // Builtin functions cannot be defined.
3870  if (unsigned BuiltinID = FD->getBuiltinID()) {
3871    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3872      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
3873      FD->setInvalidDecl();
3874    }
3875  }
3876
3877  // The return type of a function definition must be complete
3878  // (C99 6.9.1p3, C++ [dcl.fct]p6).
3879  QualType ResultType = FD->getResultType();
3880  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
3881      !FD->isInvalidDecl() &&
3882      RequireCompleteType(FD->getLocation(), ResultType,
3883                          diag::err_func_def_incomplete_result))
3884    FD->setInvalidDecl();
3885
3886  // GNU warning -Wmissing-prototypes:
3887  //   Warn if a global function is defined without a previous
3888  //   prototype declaration. This warning is issued even if the
3889  //   definition itself provides a prototype. The aim is to detect
3890  //   global functions that fail to be declared in header files.
3891  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
3892      !FD->isMain()) {
3893    bool MissingPrototype = true;
3894    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
3895         Prev; Prev = Prev->getPreviousDeclaration()) {
3896      // Ignore any declarations that occur in function or method
3897      // scope, because they aren't visible from the header.
3898      if (Prev->getDeclContext()->isFunctionOrMethod())
3899        continue;
3900
3901      MissingPrototype = !Prev->getType()->isFunctionProtoType();
3902      break;
3903    }
3904
3905    if (MissingPrototype)
3906      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
3907  }
3908
3909  if (FnBodyScope)
3910    PushDeclContext(FnBodyScope, FD);
3911
3912  // Check the validity of our function parameters
3913  CheckParmsForFunctionDef(FD);
3914
3915  // Introduce our parameters into the function scope
3916  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
3917    ParmVarDecl *Param = FD->getParamDecl(p);
3918    Param->setOwningFunction(FD);
3919
3920    // If this has an identifier, add it to the scope stack.
3921    if (Param->getIdentifier() && FnBodyScope)
3922      PushOnScopeChains(Param, FnBodyScope);
3923  }
3924
3925  // Checking attributes of current function definition
3926  // dllimport attribute.
3927  if (FD->getAttr<DLLImportAttr>() &&
3928      (!FD->getAttr<DLLExportAttr>())) {
3929    // dllimport attribute cannot be applied to definition.
3930    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
3931      Diag(FD->getLocation(),
3932           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
3933        << "dllimport";
3934      FD->setInvalidDecl();
3935      return DeclPtrTy::make(FD);
3936    } else {
3937      // If a symbol previously declared dllimport is later defined, the
3938      // attribute is ignored in subsequent references, and a warning is
3939      // emitted.
3940      Diag(FD->getLocation(),
3941           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3942        << FD->getNameAsCString() << "dllimport";
3943    }
3944  }
3945  return DeclPtrTy::make(FD);
3946}
3947
3948Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
3949  return ActOnFinishFunctionBody(D, move(BodyArg), false);
3950}
3951
3952Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
3953                                              bool IsInstantiation) {
3954  Decl *dcl = D.getAs<Decl>();
3955  Stmt *Body = BodyArg.takeAs<Stmt>();
3956
3957  FunctionDecl *FD = 0;
3958  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
3959  if (FunTmpl)
3960    FD = FunTmpl->getTemplatedDecl();
3961  else
3962    FD = dyn_cast_or_null<FunctionDecl>(dcl);
3963
3964  if (FD) {
3965    FD->setBody(Body);
3966    if (FD->isMain())
3967      // C and C++ allow for main to automagically return 0.
3968      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
3969      FD->setHasImplicitReturnZero(true);
3970    else
3971      CheckFallThroughForFunctionDef(FD, Body);
3972
3973    if (!FD->isInvalidDecl())
3974      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
3975
3976    // C++ [basic.def.odr]p2:
3977    //   [...] A virtual member function is used if it is not pure. [...]
3978    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
3979      if (Method->isVirtual() && !Method->isPure())
3980        MarkDeclarationReferenced(Method->getLocation(), Method);
3981
3982    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3983  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3984    assert(MD == getCurMethodDecl() && "Method parsing confused");
3985    MD->setBody(Body);
3986    CheckFallThroughForFunctionDef(MD, Body);
3987    MD->setEndLoc(Body->getLocEnd());
3988
3989    if (!MD->isInvalidDecl())
3990      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
3991  } else {
3992    Body->Destroy(Context);
3993    return DeclPtrTy();
3994  }
3995  if (!IsInstantiation)
3996    PopDeclContext();
3997
3998  // Verify and clean out per-function state.
3999
4000  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4001
4002  // Check goto/label use.
4003  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4004       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4005    LabelStmt *L = I->second;
4006
4007    // Verify that we have no forward references left.  If so, there was a goto
4008    // or address of a label taken, but no definition of it.  Label fwd
4009    // definitions are indicated with a null substmt.
4010    if (L->getSubStmt() != 0)
4011      continue;
4012
4013    // Emit error.
4014    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4015
4016    // At this point, we have gotos that use the bogus label.  Stitch it into
4017    // the function body so that they aren't leaked and that the AST is well
4018    // formed.
4019    if (Body == 0) {
4020      // The whole function wasn't parsed correctly, just delete this.
4021      L->Destroy(Context);
4022      continue;
4023    }
4024
4025    // Otherwise, the body is valid: we want to stitch the label decl into the
4026    // function somewhere so that it is properly owned and so that the goto
4027    // has a valid target.  Do this by creating a new compound stmt with the
4028    // label in it.
4029
4030    // Give the label a sub-statement.
4031    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4032
4033    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4034                               cast<CXXTryStmt>(Body)->getTryBlock() :
4035                               cast<CompoundStmt>(Body);
4036    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4037    Elements.push_back(L);
4038    Compound->setStmts(Context, &Elements[0], Elements.size());
4039  }
4040  FunctionLabelMap.clear();
4041
4042  if (!Body) return D;
4043
4044  // Verify that that gotos and switch cases don't jump into scopes illegally.
4045  if (CurFunctionNeedsScopeChecking)
4046    DiagnoseInvalidJumps(Body);
4047
4048  // C++ constructors that have function-try-blocks can't have return
4049  // statements in the handlers of that block. (C++ [except.handle]p14)
4050  // Verify this.
4051  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4052    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4053
4054  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4055    computeBaseOrMembersToDestroy(Destructor);
4056
4057  // If any errors have occurred, clear out any temporaries that may have
4058  // been leftover. This ensures that these temporaries won't be picked up for
4059  // deletion in some later function.
4060  if (PP.getDiagnostics().hasErrorOccurred())
4061    ExprTemporaries.clear();
4062
4063  assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4064  return D;
4065}
4066
4067/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4068/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4069NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4070                                          IdentifierInfo &II, Scope *S) {
4071  // Before we produce a declaration for an implicitly defined
4072  // function, see whether there was a locally-scoped declaration of
4073  // this name as a function or variable. If so, use that
4074  // (non-visible) declaration, and complain about it.
4075  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4076    = LocallyScopedExternalDecls.find(&II);
4077  if (Pos != LocallyScopedExternalDecls.end()) {
4078    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4079    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4080    return Pos->second;
4081  }
4082
4083  // Extension in C99.  Legal in C90, but warn about it.
4084  if (II.getName().startswith("__builtin_"))
4085    Diag(Loc, diag::warn_builtin_unknown) << &II;
4086  else if (getLangOptions().C99)
4087    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4088  else
4089    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4090
4091  // Set a Declarator for the implicit definition: int foo();
4092  const char *Dummy;
4093  DeclSpec DS;
4094  unsigned DiagID;
4095  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4096  Error = Error; // Silence warning.
4097  assert(!Error && "Error setting up implicit decl!");
4098  Declarator D(DS, Declarator::BlockContext);
4099  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4100                                             0, 0, false, SourceLocation(),
4101                                             false, 0,0,0, Loc, Loc, D),
4102                SourceLocation());
4103  D.SetIdentifier(&II, Loc);
4104
4105  // Insert this function into translation-unit scope.
4106
4107  DeclContext *PrevDC = CurContext;
4108  CurContext = Context.getTranslationUnitDecl();
4109
4110  FunctionDecl *FD =
4111 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4112  FD->setImplicit();
4113
4114  CurContext = PrevDC;
4115
4116  AddKnownFunctionAttributes(FD);
4117
4118  return FD;
4119}
4120
4121/// \brief Adds any function attributes that we know a priori based on
4122/// the declaration of this function.
4123///
4124/// These attributes can apply both to implicitly-declared builtins
4125/// (like __builtin___printf_chk) or to library-declared functions
4126/// like NSLog or printf.
4127void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4128  if (FD->isInvalidDecl())
4129    return;
4130
4131  // If this is a built-in function, map its builtin attributes to
4132  // actual attributes.
4133  if (unsigned BuiltinID = FD->getBuiltinID()) {
4134    // Handle printf-formatting attributes.
4135    unsigned FormatIdx;
4136    bool HasVAListArg;
4137    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4138      if (!FD->getAttr<FormatAttr>())
4139        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4140                                             HasVAListArg ? 0 : FormatIdx + 2));
4141    }
4142
4143    // Mark const if we don't care about errno and that is the only
4144    // thing preventing the function from being const. This allows
4145    // IRgen to use LLVM intrinsics for such functions.
4146    if (!getLangOptions().MathErrno &&
4147        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4148      if (!FD->getAttr<ConstAttr>())
4149        FD->addAttr(::new (Context) ConstAttr());
4150    }
4151
4152    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4153      FD->addAttr(::new (Context) NoReturnAttr());
4154  }
4155
4156  IdentifierInfo *Name = FD->getIdentifier();
4157  if (!Name)
4158    return;
4159  if ((!getLangOptions().CPlusPlus &&
4160       FD->getDeclContext()->isTranslationUnit()) ||
4161      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4162       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4163       LinkageSpecDecl::lang_c)) {
4164    // Okay: this could be a libc/libm/Objective-C function we know
4165    // about.
4166  } else
4167    return;
4168
4169  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4170    // FIXME: NSLog and NSLogv should be target specific
4171    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4172      // FIXME: We known better than our headers.
4173      const_cast<FormatAttr *>(Format)->setType("printf");
4174    } else
4175      FD->addAttr(::new (Context) FormatAttr("printf", 1,
4176                                             Name->isStr("NSLogv") ? 0 : 2));
4177  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4178    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4179    // target-specific builtins, perhaps?
4180    if (!FD->getAttr<FormatAttr>())
4181      FD->addAttr(::new (Context) FormatAttr("printf", 2,
4182                                             Name->isStr("vasprintf") ? 0 : 3));
4183  }
4184}
4185
4186TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4187                                    DeclaratorInfo *DInfo) {
4188  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4189  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4190
4191  if (!DInfo) {
4192    assert(D.isInvalidType() && "no declarator info for valid type");
4193    DInfo = Context.getTrivialDeclaratorInfo(T);
4194  }
4195
4196  // Scope manipulation handled by caller.
4197  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4198                                           D.getIdentifierLoc(),
4199                                           D.getIdentifier(),
4200                                           DInfo);
4201
4202  if (const TagType *TT = T->getAs<TagType>()) {
4203    TagDecl *TD = TT->getDecl();
4204
4205    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4206    // keep track of the TypedefDecl.
4207    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4208      TD->setTypedefForAnonDecl(NewTD);
4209  }
4210
4211  if (D.isInvalidType())
4212    NewTD->setInvalidDecl();
4213  return NewTD;
4214}
4215
4216
4217/// \brief Determine whether a tag with a given kind is acceptable
4218/// as a redeclaration of the given tag declaration.
4219///
4220/// \returns true if the new tag kind is acceptable, false otherwise.
4221bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4222                                        TagDecl::TagKind NewTag,
4223                                        SourceLocation NewTagLoc,
4224                                        const IdentifierInfo &Name) {
4225  // C++ [dcl.type.elab]p3:
4226  //   The class-key or enum keyword present in the
4227  //   elaborated-type-specifier shall agree in kind with the
4228  //   declaration to which the name in theelaborated-type-specifier
4229  //   refers. This rule also applies to the form of
4230  //   elaborated-type-specifier that declares a class-name or
4231  //   friend class since it can be construed as referring to the
4232  //   definition of the class. Thus, in any
4233  //   elaborated-type-specifier, the enum keyword shall be used to
4234  //   refer to an enumeration (7.2), the union class-keyshall be
4235  //   used to refer to a union (clause 9), and either the class or
4236  //   struct class-key shall be used to refer to a class (clause 9)
4237  //   declared using the class or struct class-key.
4238  TagDecl::TagKind OldTag = Previous->getTagKind();
4239  if (OldTag == NewTag)
4240    return true;
4241
4242  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4243      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4244    // Warn about the struct/class tag mismatch.
4245    bool isTemplate = false;
4246    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4247      isTemplate = Record->getDescribedClassTemplate();
4248
4249    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4250      << (NewTag == TagDecl::TK_class)
4251      << isTemplate << &Name
4252      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4253                              OldTag == TagDecl::TK_class? "class" : "struct");
4254    Diag(Previous->getLocation(), diag::note_previous_use);
4255    return true;
4256  }
4257  return false;
4258}
4259
4260/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4261/// former case, Name will be non-null.  In the later case, Name will be null.
4262/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4263/// reference/declaration/definition of a tag.
4264Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4265                               SourceLocation KWLoc, const CXXScopeSpec &SS,
4266                               IdentifierInfo *Name, SourceLocation NameLoc,
4267                               AttributeList *Attr, AccessSpecifier AS,
4268                               MultiTemplateParamsArg TemplateParameterLists,
4269                               bool &OwnedDecl, bool &IsDependent) {
4270  // If this is not a definition, it must have a name.
4271  assert((Name != 0 || TUK == TUK_Definition) &&
4272         "Nameless record must be a definition!");
4273
4274  OwnedDecl = false;
4275  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4276
4277  // FIXME: Check explicit specializations more carefully.
4278  bool isExplicitSpecialization = false;
4279  if (TUK != TUK_Reference) {
4280    if (TemplateParameterList *TemplateParams
4281          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4282                        (TemplateParameterList**)TemplateParameterLists.get(),
4283                                              TemplateParameterLists.size(),
4284                                                    isExplicitSpecialization)) {
4285      if (TemplateParams->size() > 0) {
4286        // This is a declaration or definition of a class template (which may
4287        // be a member of another template).
4288        OwnedDecl = false;
4289        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4290                                               SS, Name, NameLoc, Attr,
4291                                               TemplateParams,
4292                                               AS);
4293        TemplateParameterLists.release();
4294        return Result.get();
4295      } else {
4296        // The "template<>" header is extraneous.
4297        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4298          << ElaboratedType::getNameForTagKind(Kind) << Name;
4299        isExplicitSpecialization = true;
4300      }
4301    }
4302
4303    TemplateParameterLists.release();
4304  }
4305
4306  DeclContext *SearchDC = CurContext;
4307  DeclContext *DC = CurContext;
4308  NamedDecl *PrevDecl = 0;
4309  bool isStdBadAlloc = false;
4310  bool Invalid = false;
4311
4312  LookupResult::RedeclarationKind Redecl =
4313    (LookupResult::RedeclarationKind) (TUK != TUK_Reference);
4314
4315  if (Name && SS.isNotEmpty()) {
4316    // We have a nested-name tag ('struct foo::bar').
4317
4318    // Check for invalid 'foo::'.
4319    if (SS.isInvalid()) {
4320      Name = 0;
4321      goto CreateNewDecl;
4322    }
4323
4324    // If this is a friend or a reference to a class in a dependent
4325    // context, don't try to make a decl for it.
4326    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4327      DC = computeDeclContext(SS, false);
4328      if (!DC) {
4329        IsDependent = true;
4330        return DeclPtrTy();
4331      }
4332    }
4333
4334    if (RequireCompleteDeclContext(SS))
4335      return DeclPtrTy::make((Decl *)0);
4336
4337    DC = computeDeclContext(SS, true);
4338    SearchDC = DC;
4339    // Look-up name inside 'foo::'.
4340    LookupResult R(*this, Name, NameLoc, LookupTagName, Redecl);
4341    LookupQualifiedName(R, DC);
4342
4343    if (R.isAmbiguous())
4344      return DeclPtrTy();
4345
4346    if (R.getResultKind() == LookupResult::Found)
4347      PrevDecl = dyn_cast<TagDecl>(R.getFoundDecl());
4348
4349    // A tag 'foo::bar' must already exist.
4350    if (!PrevDecl) {
4351      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4352      Name = 0;
4353      Invalid = true;
4354      goto CreateNewDecl;
4355    }
4356  } else if (Name) {
4357    // If this is a named struct, check to see if there was a previous forward
4358    // declaration or definition.
4359    // FIXME: We're looking into outer scopes here, even when we
4360    // shouldn't be. Doing so can result in ambiguities that we
4361    // shouldn't be diagnosing.
4362    LookupResult R(*this, Name, NameLoc, LookupTagName, Redecl);
4363    LookupName(R, S);
4364    if (R.isAmbiguous()) {
4365      // FIXME: This is not best way to recover from case like:
4366      //
4367      // struct S s;
4368      //
4369      // causes needless "incomplete type" error later.
4370      Name = 0;
4371      PrevDecl = 0;
4372      Invalid = true;
4373    } else
4374      PrevDecl = R.getAsSingleDecl(Context);
4375
4376    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4377      // FIXME: This makes sure that we ignore the contexts associated
4378      // with C structs, unions, and enums when looking for a matching
4379      // tag declaration or definition. See the similar lookup tweak
4380      // in Sema::LookupName; is there a better way to deal with this?
4381      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4382        SearchDC = SearchDC->getParent();
4383    }
4384  }
4385
4386  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4387    // Maybe we will complain about the shadowed template parameter.
4388    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
4389    // Just pretend that we didn't see the previous declaration.
4390    PrevDecl = 0;
4391  }
4392
4393  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4394      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4395    // This is a declaration of or a reference to "std::bad_alloc".
4396    isStdBadAlloc = true;
4397
4398    if (!PrevDecl && StdBadAlloc) {
4399      // std::bad_alloc has been implicitly declared (but made invisible to
4400      // name lookup). Fill in this implicit declaration as the previous
4401      // declaration, so that the declarations get chained appropriately.
4402      PrevDecl = StdBadAlloc;
4403    }
4404  }
4405
4406  if (PrevDecl) {
4407    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4408      // If this is a use of a previous tag, or if the tag is already declared
4409      // in the same scope (so that the definition/declaration completes or
4410      // rementions the tag), reuse the decl.
4411      if (TUK == TUK_Reference || TUK == TUK_Friend ||
4412          isDeclInScope(PrevDecl, SearchDC, S)) {
4413        // Make sure that this wasn't declared as an enum and now used as a
4414        // struct or something similar.
4415        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4416          bool SafeToContinue
4417            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4418               Kind != TagDecl::TK_enum);
4419          if (SafeToContinue)
4420            Diag(KWLoc, diag::err_use_with_wrong_tag)
4421              << Name
4422              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4423                                                  PrevTagDecl->getKindName());
4424          else
4425            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4426          Diag(PrevDecl->getLocation(), diag::note_previous_use);
4427
4428          if (SafeToContinue)
4429            Kind = PrevTagDecl->getTagKind();
4430          else {
4431            // Recover by making this an anonymous redefinition.
4432            Name = 0;
4433            PrevDecl = 0;
4434            Invalid = true;
4435          }
4436        }
4437
4438        if (!Invalid) {
4439          // If this is a use, just return the declaration we found.
4440
4441          // FIXME: In the future, return a variant or some other clue
4442          // for the consumer of this Decl to know it doesn't own it.
4443          // For our current ASTs this shouldn't be a problem, but will
4444          // need to be changed with DeclGroups.
4445          if (TUK == TUK_Reference || TUK == TUK_Friend)
4446            return DeclPtrTy::make(PrevDecl);
4447
4448          // Diagnose attempts to redefine a tag.
4449          if (TUK == TUK_Definition) {
4450            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4451              // If we're defining a specialization and the previous definition
4452              // is from an implicit instantiation, don't emit an error
4453              // here; we'll catch this in the general case below.
4454              if (!isExplicitSpecialization ||
4455                  !isa<CXXRecordDecl>(Def) ||
4456                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4457                                               == TSK_ExplicitSpecialization) {
4458                Diag(NameLoc, diag::err_redefinition) << Name;
4459                Diag(Def->getLocation(), diag::note_previous_definition);
4460                // If this is a redefinition, recover by making this
4461                // struct be anonymous, which will make any later
4462                // references get the previous definition.
4463                Name = 0;
4464                PrevDecl = 0;
4465                Invalid = true;
4466              }
4467            } else {
4468              // If the type is currently being defined, complain
4469              // about a nested redefinition.
4470              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4471              if (Tag->isBeingDefined()) {
4472                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4473                Diag(PrevTagDecl->getLocation(),
4474                     diag::note_previous_definition);
4475                Name = 0;
4476                PrevDecl = 0;
4477                Invalid = true;
4478              }
4479            }
4480
4481            // Okay, this is definition of a previously declared or referenced
4482            // tag PrevDecl. We're going to create a new Decl for it.
4483          }
4484        }
4485        // If we get here we have (another) forward declaration or we
4486        // have a definition.  Just create a new decl.
4487
4488      } else {
4489        // If we get here, this is a definition of a new tag type in a nested
4490        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4491        // new decl/type.  We set PrevDecl to NULL so that the entities
4492        // have distinct types.
4493        PrevDecl = 0;
4494      }
4495      // If we get here, we're going to create a new Decl. If PrevDecl
4496      // is non-NULL, it's a definition of the tag declared by
4497      // PrevDecl. If it's NULL, we have a new definition.
4498    } else {
4499      // PrevDecl is a namespace, template, or anything else
4500      // that lives in the IDNS_Tag identifier namespace.
4501      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4502        // The tag name clashes with a namespace name, issue an error and
4503        // recover by making this tag be anonymous.
4504        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4505        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4506        Name = 0;
4507        PrevDecl = 0;
4508        Invalid = true;
4509      } else {
4510        // The existing declaration isn't relevant to us; we're in a
4511        // new scope, so clear out the previous declaration.
4512        PrevDecl = 0;
4513      }
4514    }
4515  } else if (TUK == TUK_Reference && SS.isEmpty() && Name &&
4516             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
4517    // C++ [basic.scope.pdecl]p5:
4518    //   -- for an elaborated-type-specifier of the form
4519    //
4520    //          class-key identifier
4521    //
4522    //      if the elaborated-type-specifier is used in the
4523    //      decl-specifier-seq or parameter-declaration-clause of a
4524    //      function defined in namespace scope, the identifier is
4525    //      declared as a class-name in the namespace that contains
4526    //      the declaration; otherwise, except as a friend
4527    //      declaration, the identifier is declared in the smallest
4528    //      non-class, non-function-prototype scope that contains the
4529    //      declaration.
4530    //
4531    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4532    // C structs and unions.
4533    //
4534    // GNU C also supports this behavior as part of its incomplete
4535    // enum types extension, while GNU C++ does not.
4536    //
4537    // Find the context where we'll be declaring the tag.
4538    // FIXME: We would like to maintain the current DeclContext as the
4539    // lexical context,
4540    while (SearchDC->isRecord())
4541      SearchDC = SearchDC->getParent();
4542
4543    // Find the scope where we'll be declaring the tag.
4544    while (S->isClassScope() ||
4545           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4546           ((S->getFlags() & Scope::DeclScope) == 0) ||
4547           (S->getEntity() &&
4548            ((DeclContext *)S->getEntity())->isTransparentContext()))
4549      S = S->getParent();
4550
4551  } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4552    // C++ [namespace.memdef]p3:
4553    //   If a friend declaration in a non-local class first declares a
4554    //   class or function, the friend class or function is a member of
4555    //   the innermost enclosing namespace.
4556    while (!SearchDC->isFileContext())
4557      SearchDC = SearchDC->getParent();
4558
4559    // The entity of a decl scope is a DeclContext; see PushDeclContext.
4560    while (S->getEntity() != SearchDC)
4561      S = S->getParent();
4562  }
4563
4564CreateNewDecl:
4565
4566  // If there is an identifier, use the location of the identifier as the
4567  // location of the decl, otherwise use the location of the struct/union
4568  // keyword.
4569  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4570
4571  // Otherwise, create a new declaration. If there is a previous
4572  // declaration of the same entity, the two will be linked via
4573  // PrevDecl.
4574  TagDecl *New;
4575
4576  if (Kind == TagDecl::TK_enum) {
4577    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4578    // enum X { A, B, C } D;    D should chain to X.
4579    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4580                           cast_or_null<EnumDecl>(PrevDecl));
4581    // If this is an undefined enum, warn.
4582    if (TUK != TUK_Definition && !Invalid)  {
4583      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4584                                              : diag::ext_forward_ref_enum;
4585      Diag(Loc, DK);
4586    }
4587  } else {
4588    // struct/union/class
4589
4590    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4591    // struct X { int A; } D;    D should chain to X.
4592    if (getLangOptions().CPlusPlus) {
4593      // FIXME: Look for a way to use RecordDecl for simple structs.
4594      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4595                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4596
4597      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4598        StdBadAlloc = cast<CXXRecordDecl>(New);
4599    } else
4600      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4601                               cast_or_null<RecordDecl>(PrevDecl));
4602  }
4603
4604  if (Kind != TagDecl::TK_enum) {
4605    // Handle #pragma pack: if the #pragma pack stack has non-default
4606    // alignment, make up a packed attribute for this decl. These
4607    // attributes are checked when the ASTContext lays out the
4608    // structure.
4609    //
4610    // It is important for implementing the correct semantics that this
4611    // happen here (in act on tag decl). The #pragma pack stack is
4612    // maintained as a result of parser callbacks which can occur at
4613    // many points during the parsing of a struct declaration (because
4614    // the #pragma tokens are effectively skipped over during the
4615    // parsing of the struct).
4616    if (unsigned Alignment = getPragmaPackAlignment())
4617      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4618  }
4619
4620  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4621    // C++ [dcl.typedef]p3:
4622    //   [...] Similarly, in a given scope, a class or enumeration
4623    //   shall not be declared with the same name as a typedef-name
4624    //   that is declared in that scope and refers to a type other
4625    //   than the class or enumeration itself.
4626    LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4627                        LookupResult::ForRedeclaration);
4628    LookupName(Lookup, S);
4629    TypedefDecl *PrevTypedef = 0;
4630    if (NamedDecl *Prev = Lookup.getAsSingleDecl(Context))
4631      PrevTypedef = dyn_cast<TypedefDecl>(Prev);
4632
4633    NamedDecl *PrevTypedefNamed = PrevTypedef;
4634    if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4635        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4636          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4637      Diag(Loc, diag::err_tag_definition_of_typedef)
4638        << Context.getTypeDeclType(New)
4639        << PrevTypedef->getUnderlyingType();
4640      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4641      Invalid = true;
4642    }
4643  }
4644
4645  // If this is a specialization of a member class (of a class template),
4646  // check the specialization.
4647  if (isExplicitSpecialization && CheckMemberSpecialization(New, PrevDecl))
4648    Invalid = true;
4649
4650  if (Invalid)
4651    New->setInvalidDecl();
4652
4653  if (Attr)
4654    ProcessDeclAttributeList(S, New, Attr);
4655
4656  // If we're declaring or defining a tag in function prototype scope
4657  // in C, note that this type can only be used within the function.
4658  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4659    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4660
4661  // Set the lexical context. If the tag has a C++ scope specifier, the
4662  // lexical context will be different from the semantic context.
4663  New->setLexicalDeclContext(CurContext);
4664
4665  // Mark this as a friend decl if applicable.
4666  if (TUK == TUK_Friend)
4667    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ PrevDecl != NULL);
4668
4669  // Set the access specifier.
4670  if (!Invalid && TUK != TUK_Friend)
4671    SetMemberAccessSpecifier(New, PrevDecl, AS);
4672
4673  if (TUK == TUK_Definition)
4674    New->startDefinition();
4675
4676  // If this has an identifier, add it to the scope stack.
4677  if (TUK == TUK_Friend) {
4678    // We might be replacing an existing declaration in the lookup tables;
4679    // if so, borrow its access specifier.
4680    if (PrevDecl)
4681      New->setAccess(PrevDecl->getAccess());
4682
4683    // Friend tag decls are visible in fairly strange ways.
4684    if (!CurContext->isDependentContext()) {
4685      DeclContext *DC = New->getDeclContext()->getLookupContext();
4686      DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4687      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4688        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4689    }
4690  } else if (Name) {
4691    S = getNonFieldDeclScope(S);
4692    PushOnScopeChains(New, S);
4693  } else {
4694    CurContext->addDecl(New);
4695  }
4696
4697  // If this is the C FILE type, notify the AST context.
4698  if (IdentifierInfo *II = New->getIdentifier())
4699    if (!New->isInvalidDecl() &&
4700        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4701        II->isStr("FILE"))
4702      Context.setFILEDecl(New);
4703
4704  OwnedDecl = true;
4705  return DeclPtrTy::make(New);
4706}
4707
4708void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4709  AdjustDeclIfTemplate(TagD);
4710  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4711
4712  // Enter the tag context.
4713  PushDeclContext(S, Tag);
4714
4715  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4716    FieldCollector->StartClass();
4717
4718    if (Record->getIdentifier()) {
4719      // C++ [class]p2:
4720      //   [...] The class-name is also inserted into the scope of the
4721      //   class itself; this is known as the injected-class-name. For
4722      //   purposes of access checking, the injected-class-name is treated
4723      //   as if it were a public member name.
4724      CXXRecordDecl *InjectedClassName
4725        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4726                                CurContext, Record->getLocation(),
4727                                Record->getIdentifier(),
4728                                Record->getTagKeywordLoc(),
4729                                Record);
4730      InjectedClassName->setImplicit();
4731      InjectedClassName->setAccess(AS_public);
4732      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4733        InjectedClassName->setDescribedClassTemplate(Template);
4734      PushOnScopeChains(InjectedClassName, S);
4735      assert(InjectedClassName->isInjectedClassName() &&
4736             "Broken injected-class-name");
4737    }
4738  }
4739}
4740
4741void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4742                                    SourceLocation RBraceLoc) {
4743  AdjustDeclIfTemplate(TagD);
4744  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4745  Tag->setRBraceLoc(RBraceLoc);
4746
4747  if (isa<CXXRecordDecl>(Tag))
4748    FieldCollector->FinishClass();
4749
4750  // Exit this scope of this tag's definition.
4751  PopDeclContext();
4752
4753  // Notify the consumer that we've defined a tag.
4754  Consumer.HandleTagDeclDefinition(Tag);
4755}
4756
4757// Note that FieldName may be null for anonymous bitfields.
4758bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4759                          QualType FieldTy, const Expr *BitWidth,
4760                          bool *ZeroWidth) {
4761  // Default to true; that shouldn't confuse checks for emptiness
4762  if (ZeroWidth)
4763    *ZeroWidth = true;
4764
4765  // C99 6.7.2.1p4 - verify the field type.
4766  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4767  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4768    // Handle incomplete types with specific error.
4769    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
4770      return true;
4771    if (FieldName)
4772      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
4773        << FieldName << FieldTy << BitWidth->getSourceRange();
4774    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
4775      << FieldTy << BitWidth->getSourceRange();
4776  }
4777
4778  // If the bit-width is type- or value-dependent, don't try to check
4779  // it now.
4780  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
4781    return false;
4782
4783  llvm::APSInt Value;
4784  if (VerifyIntegerConstantExpression(BitWidth, &Value))
4785    return true;
4786
4787  if (Value != 0 && ZeroWidth)
4788    *ZeroWidth = false;
4789
4790  // Zero-width bitfield is ok for anonymous field.
4791  if (Value == 0 && FieldName)
4792    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
4793
4794  if (Value.isSigned() && Value.isNegative()) {
4795    if (FieldName)
4796      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
4797               << FieldName << Value.toString(10);
4798    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
4799      << Value.toString(10);
4800  }
4801
4802  if (!FieldTy->isDependentType()) {
4803    uint64_t TypeSize = Context.getTypeSize(FieldTy);
4804    if (Value.getZExtValue() > TypeSize) {
4805      if (FieldName)
4806        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
4807          << FieldName << (unsigned)TypeSize;
4808      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
4809        << (unsigned)TypeSize;
4810    }
4811  }
4812
4813  return false;
4814}
4815
4816/// ActOnField - Each field of a struct/union/class is passed into this in order
4817/// to create a FieldDecl object for it.
4818Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
4819                                 SourceLocation DeclStart,
4820                                 Declarator &D, ExprTy *BitfieldWidth) {
4821  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
4822                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
4823                               AS_public);
4824  return DeclPtrTy::make(Res);
4825}
4826
4827/// HandleField - Analyze a field of a C struct or a C++ data member.
4828///
4829FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
4830                             SourceLocation DeclStart,
4831                             Declarator &D, Expr *BitWidth,
4832                             AccessSpecifier AS) {
4833  IdentifierInfo *II = D.getIdentifier();
4834  SourceLocation Loc = DeclStart;
4835  if (II) Loc = D.getIdentifierLoc();
4836
4837  DeclaratorInfo *DInfo = 0;
4838  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4839  if (getLangOptions().CPlusPlus)
4840    CheckExtraCXXDefaultArguments(D);
4841
4842  DiagnoseFunctionSpecifiers(D);
4843
4844  if (D.getDeclSpec().isThreadSpecified())
4845    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4846
4847  NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
4848                                         LookupResult::ForRedeclaration);
4849
4850  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4851    // Maybe we will complain about the shadowed template parameter.
4852    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4853    // Just pretend that we didn't see the previous declaration.
4854    PrevDecl = 0;
4855  }
4856
4857  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
4858    PrevDecl = 0;
4859
4860  bool Mutable
4861    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
4862  SourceLocation TSSL = D.getSourceRange().getBegin();
4863  FieldDecl *NewFD
4864    = CheckFieldDecl(II, T, DInfo, Record, Loc, Mutable, BitWidth, TSSL,
4865                     AS, PrevDecl, &D);
4866  if (NewFD->isInvalidDecl() && PrevDecl) {
4867    // Don't introduce NewFD into scope; there's already something
4868    // with the same name in the same scope.
4869  } else if (II) {
4870    PushOnScopeChains(NewFD, S);
4871  } else
4872    Record->addDecl(NewFD);
4873
4874  return NewFD;
4875}
4876
4877/// \brief Build a new FieldDecl and check its well-formedness.
4878///
4879/// This routine builds a new FieldDecl given the fields name, type,
4880/// record, etc. \p PrevDecl should refer to any previous declaration
4881/// with the same name and in the same scope as the field to be
4882/// created.
4883///
4884/// \returns a new FieldDecl.
4885///
4886/// \todo The Declarator argument is a hack. It will be removed once
4887FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
4888                                DeclaratorInfo *DInfo,
4889                                RecordDecl *Record, SourceLocation Loc,
4890                                bool Mutable, Expr *BitWidth,
4891                                SourceLocation TSSL,
4892                                AccessSpecifier AS, NamedDecl *PrevDecl,
4893                                Declarator *D) {
4894  IdentifierInfo *II = Name.getAsIdentifierInfo();
4895  bool InvalidDecl = false;
4896  if (D) InvalidDecl = D->isInvalidType();
4897
4898  // If we receive a broken type, recover by assuming 'int' and
4899  // marking this declaration as invalid.
4900  if (T.isNull()) {
4901    InvalidDecl = true;
4902    T = Context.IntTy;
4903  }
4904
4905  // C99 6.7.2.1p8: A member of a structure or union may have any type other
4906  // than a variably modified type.
4907  if (T->isVariablyModifiedType()) {
4908    bool SizeIsNegative;
4909    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
4910                                                           SizeIsNegative);
4911    if (!FixedTy.isNull()) {
4912      Diag(Loc, diag::warn_illegal_constant_array_size);
4913      T = FixedTy;
4914    } else {
4915      if (SizeIsNegative)
4916        Diag(Loc, diag::err_typecheck_negative_array_size);
4917      else
4918        Diag(Loc, diag::err_typecheck_field_variable_size);
4919      InvalidDecl = true;
4920    }
4921  }
4922
4923  // Fields can not have abstract class types
4924  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
4925                             AbstractFieldType))
4926    InvalidDecl = true;
4927
4928  bool ZeroWidth = false;
4929  // If this is declared as a bit-field, check the bit-field.
4930  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
4931    InvalidDecl = true;
4932    DeleteExpr(BitWidth);
4933    BitWidth = 0;
4934    ZeroWidth = false;
4935  }
4936
4937  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, DInfo,
4938                                       BitWidth, Mutable);
4939  if (InvalidDecl)
4940    NewFD->setInvalidDecl();
4941
4942  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
4943    Diag(Loc, diag::err_duplicate_member) << II;
4944    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4945    NewFD->setInvalidDecl();
4946  }
4947
4948  if (getLangOptions().CPlusPlus) {
4949    QualType EltTy = Context.getBaseElementType(T);
4950
4951    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
4952
4953    if (!T->isPODType())
4954      CXXRecord->setPOD(false);
4955    if (!ZeroWidth)
4956      CXXRecord->setEmpty(false);
4957
4958    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
4959      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
4960
4961      if (!RDecl->hasTrivialConstructor())
4962        CXXRecord->setHasTrivialConstructor(false);
4963      if (!RDecl->hasTrivialCopyConstructor())
4964        CXXRecord->setHasTrivialCopyConstructor(false);
4965      if (!RDecl->hasTrivialCopyAssignment())
4966        CXXRecord->setHasTrivialCopyAssignment(false);
4967      if (!RDecl->hasTrivialDestructor())
4968        CXXRecord->setHasTrivialDestructor(false);
4969
4970      // C++ 9.5p1: An object of a class with a non-trivial
4971      // constructor, a non-trivial copy constructor, a non-trivial
4972      // destructor, or a non-trivial copy assignment operator
4973      // cannot be a member of a union, nor can an array of such
4974      // objects.
4975      // TODO: C++0x alters this restriction significantly.
4976      if (Record->isUnion()) {
4977        // We check for copy constructors before constructors
4978        // because otherwise we'll never get complaints about
4979        // copy constructors.
4980
4981        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
4982
4983        CXXSpecialMember member;
4984        if (!RDecl->hasTrivialCopyConstructor())
4985          member = CXXCopyConstructor;
4986        else if (!RDecl->hasTrivialConstructor())
4987          member = CXXDefaultConstructor;
4988        else if (!RDecl->hasTrivialCopyAssignment())
4989          member = CXXCopyAssignment;
4990        else if (!RDecl->hasTrivialDestructor())
4991          member = CXXDestructor;
4992        else
4993          member = invalid;
4994
4995        if (member != invalid) {
4996          Diag(Loc, diag::err_illegal_union_member) << Name << member;
4997          DiagnoseNontrivial(RT, member);
4998          NewFD->setInvalidDecl();
4999        }
5000      }
5001    }
5002  }
5003
5004  // FIXME: We need to pass in the attributes given an AST
5005  // representation, not a parser representation.
5006  if (D)
5007    // FIXME: What to pass instead of TUScope?
5008    ProcessDeclAttributes(TUScope, NewFD, *D);
5009
5010  if (T.isObjCGCWeak())
5011    Diag(Loc, diag::warn_attribute_weak_on_field);
5012
5013  NewFD->setAccess(AS);
5014
5015  // C++ [dcl.init.aggr]p1:
5016  //   An aggregate is an array or a class (clause 9) with [...] no
5017  //   private or protected non-static data members (clause 11).
5018  // A POD must be an aggregate.
5019  if (getLangOptions().CPlusPlus &&
5020      (AS == AS_private || AS == AS_protected)) {
5021    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5022    CXXRecord->setAggregate(false);
5023    CXXRecord->setPOD(false);
5024  }
5025
5026  return NewFD;
5027}
5028
5029/// DiagnoseNontrivial - Given that a class has a non-trivial
5030/// special member, figure out why.
5031void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5032  QualType QT(T, 0U);
5033  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5034
5035  // Check whether the member was user-declared.
5036  switch (member) {
5037  case CXXDefaultConstructor:
5038    if (RD->hasUserDeclaredConstructor()) {
5039      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5040      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5041        const FunctionDecl *body = 0;
5042        ci->getBody(body);
5043        if (!body ||
5044            !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5045          SourceLocation CtorLoc = ci->getLocation();
5046          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5047          return;
5048        }
5049      }
5050
5051      assert(0 && "found no user-declared constructors");
5052      return;
5053    }
5054    break;
5055
5056  case CXXCopyConstructor:
5057    if (RD->hasUserDeclaredCopyConstructor()) {
5058      SourceLocation CtorLoc =
5059        RD->getCopyConstructor(Context, 0)->getLocation();
5060      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5061      return;
5062    }
5063    break;
5064
5065  case CXXCopyAssignment:
5066    if (RD->hasUserDeclaredCopyAssignment()) {
5067      // FIXME: this should use the location of the copy
5068      // assignment, not the type.
5069      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5070      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5071      return;
5072    }
5073    break;
5074
5075  case CXXDestructor:
5076    if (RD->hasUserDeclaredDestructor()) {
5077      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5078      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5079      return;
5080    }
5081    break;
5082  }
5083
5084  typedef CXXRecordDecl::base_class_iterator base_iter;
5085
5086  // Virtual bases and members inhibit trivial copying/construction,
5087  // but not trivial destruction.
5088  if (member != CXXDestructor) {
5089    // Check for virtual bases.  vbases includes indirect virtual bases,
5090    // so we just iterate through the direct bases.
5091    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5092      if (bi->isVirtual()) {
5093        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5094        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5095        return;
5096      }
5097
5098    // Check for virtual methods.
5099    typedef CXXRecordDecl::method_iterator meth_iter;
5100    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5101         ++mi) {
5102      if (mi->isVirtual()) {
5103        SourceLocation MLoc = mi->getSourceRange().getBegin();
5104        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5105        return;
5106      }
5107    }
5108  }
5109
5110  bool (CXXRecordDecl::*hasTrivial)() const;
5111  switch (member) {
5112  case CXXDefaultConstructor:
5113    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5114  case CXXCopyConstructor:
5115    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5116  case CXXCopyAssignment:
5117    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5118  case CXXDestructor:
5119    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5120  default:
5121    assert(0 && "unexpected special member"); return;
5122  }
5123
5124  // Check for nontrivial bases (and recurse).
5125  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5126    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5127    assert(BaseRT && "Don't know how to handle dependent bases");
5128    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5129    if (!(BaseRecTy->*hasTrivial)()) {
5130      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5131      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5132      DiagnoseNontrivial(BaseRT, member);
5133      return;
5134    }
5135  }
5136
5137  // Check for nontrivial members (and recurse).
5138  typedef RecordDecl::field_iterator field_iter;
5139  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5140       ++fi) {
5141    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5142    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5143      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5144
5145      if (!(EltRD->*hasTrivial)()) {
5146        SourceLocation FLoc = (*fi)->getLocation();
5147        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5148        DiagnoseNontrivial(EltRT, member);
5149        return;
5150      }
5151    }
5152  }
5153
5154  assert(0 && "found no explanation for non-trivial member");
5155}
5156
5157/// TranslateIvarVisibility - Translate visibility from a token ID to an
5158///  AST enum value.
5159static ObjCIvarDecl::AccessControl
5160TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5161  switch (ivarVisibility) {
5162  default: assert(0 && "Unknown visitibility kind");
5163  case tok::objc_private: return ObjCIvarDecl::Private;
5164  case tok::objc_public: return ObjCIvarDecl::Public;
5165  case tok::objc_protected: return ObjCIvarDecl::Protected;
5166  case tok::objc_package: return ObjCIvarDecl::Package;
5167  }
5168}
5169
5170/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5171/// in order to create an IvarDecl object for it.
5172Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5173                                SourceLocation DeclStart,
5174                                DeclPtrTy IntfDecl,
5175                                Declarator &D, ExprTy *BitfieldWidth,
5176                                tok::ObjCKeywordKind Visibility) {
5177
5178  IdentifierInfo *II = D.getIdentifier();
5179  Expr *BitWidth = (Expr*)BitfieldWidth;
5180  SourceLocation Loc = DeclStart;
5181  if (II) Loc = D.getIdentifierLoc();
5182
5183  // FIXME: Unnamed fields can be handled in various different ways, for
5184  // example, unnamed unions inject all members into the struct namespace!
5185
5186  DeclaratorInfo *DInfo = 0;
5187  QualType T = GetTypeForDeclarator(D, S, &DInfo);
5188
5189  if (BitWidth) {
5190    // 6.7.2.1p3, 6.7.2.1p4
5191    if (VerifyBitField(Loc, II, T, BitWidth)) {
5192      D.setInvalidType();
5193      DeleteExpr(BitWidth);
5194      BitWidth = 0;
5195    }
5196  } else {
5197    // Not a bitfield.
5198
5199    // validate II.
5200
5201  }
5202
5203  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5204  // than a variably modified type.
5205  if (T->isVariablyModifiedType()) {
5206    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5207    D.setInvalidType();
5208  }
5209
5210  // Get the visibility (access control) for this ivar.
5211  ObjCIvarDecl::AccessControl ac =
5212    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5213                                        : ObjCIvarDecl::None;
5214  // Must set ivar's DeclContext to its enclosing interface.
5215  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5216  DeclContext *EnclosingContext;
5217  if (ObjCImplementationDecl *IMPDecl =
5218      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5219    // Case of ivar declared in an implementation. Context is that of its class.
5220    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5221    assert(IDecl && "No class- ActOnIvar");
5222    EnclosingContext = cast_or_null<DeclContext>(IDecl);
5223  } else
5224    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5225  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5226
5227  // Construct the decl.
5228  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5229                                             EnclosingContext, Loc, II, T,
5230                                             DInfo, ac, (Expr *)BitfieldWidth);
5231
5232  if (II) {
5233    NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5234                                           LookupResult::ForRedeclaration);
5235    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5236        && !isa<TagDecl>(PrevDecl)) {
5237      Diag(Loc, diag::err_duplicate_member) << II;
5238      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5239      NewID->setInvalidDecl();
5240    }
5241  }
5242
5243  // Process attributes attached to the ivar.
5244  ProcessDeclAttributes(S, NewID, D);
5245
5246  if (D.isInvalidType())
5247    NewID->setInvalidDecl();
5248
5249  if (II) {
5250    // FIXME: When interfaces are DeclContexts, we'll need to add
5251    // these to the interface.
5252    S->AddDecl(DeclPtrTy::make(NewID));
5253    IdResolver.AddDecl(NewID);
5254  }
5255
5256  return DeclPtrTy::make(NewID);
5257}
5258
5259void Sema::ActOnFields(Scope* S,
5260                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5261                       DeclPtrTy *Fields, unsigned NumFields,
5262                       SourceLocation LBrac, SourceLocation RBrac,
5263                       AttributeList *Attr) {
5264  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5265  assert(EnclosingDecl && "missing record or interface decl");
5266
5267  // If the decl this is being inserted into is invalid, then it may be a
5268  // redeclaration or some other bogus case.  Don't try to add fields to it.
5269  if (EnclosingDecl->isInvalidDecl()) {
5270    // FIXME: Deallocate fields?
5271    return;
5272  }
5273
5274
5275  // Verify that all the fields are okay.
5276  unsigned NumNamedMembers = 0;
5277  llvm::SmallVector<FieldDecl*, 32> RecFields;
5278
5279  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5280  for (unsigned i = 0; i != NumFields; ++i) {
5281    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5282
5283    // Get the type for the field.
5284    Type *FDTy = FD->getType().getTypePtr();
5285
5286    if (!FD->isAnonymousStructOrUnion()) {
5287      // Remember all fields written by the user.
5288      RecFields.push_back(FD);
5289    }
5290
5291    // If the field is already invalid for some reason, don't emit more
5292    // diagnostics about it.
5293    if (FD->isInvalidDecl())
5294      continue;
5295
5296    // C99 6.7.2.1p2:
5297    //   A structure or union shall not contain a member with
5298    //   incomplete or function type (hence, a structure shall not
5299    //   contain an instance of itself, but may contain a pointer to
5300    //   an instance of itself), except that the last member of a
5301    //   structure with more than one named member may have incomplete
5302    //   array type; such a structure (and any union containing,
5303    //   possibly recursively, a member that is such a structure)
5304    //   shall not be a member of a structure or an element of an
5305    //   array.
5306    if (FDTy->isFunctionType()) {
5307      // Field declared as a function.
5308      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5309        << FD->getDeclName();
5310      FD->setInvalidDecl();
5311      EnclosingDecl->setInvalidDecl();
5312      continue;
5313    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5314               Record && Record->isStruct()) {
5315      // Flexible array member.
5316      if (NumNamedMembers < 1) {
5317        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5318          << FD->getDeclName();
5319        FD->setInvalidDecl();
5320        EnclosingDecl->setInvalidDecl();
5321        continue;
5322      }
5323      // Okay, we have a legal flexible array member at the end of the struct.
5324      if (Record)
5325        Record->setHasFlexibleArrayMember(true);
5326    } else if (!FDTy->isDependentType() &&
5327               RequireCompleteType(FD->getLocation(), FD->getType(),
5328                                   diag::err_field_incomplete)) {
5329      // Incomplete type
5330      FD->setInvalidDecl();
5331      EnclosingDecl->setInvalidDecl();
5332      continue;
5333    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5334      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5335        // If this is a member of a union, then entire union becomes "flexible".
5336        if (Record && Record->isUnion()) {
5337          Record->setHasFlexibleArrayMember(true);
5338        } else {
5339          // If this is a struct/class and this is not the last element, reject
5340          // it.  Note that GCC supports variable sized arrays in the middle of
5341          // structures.
5342          if (i != NumFields-1)
5343            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5344              << FD->getDeclName() << FD->getType();
5345          else {
5346            // We support flexible arrays at the end of structs in
5347            // other structs as an extension.
5348            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5349              << FD->getDeclName();
5350            if (Record)
5351              Record->setHasFlexibleArrayMember(true);
5352          }
5353        }
5354      }
5355      if (Record && FDTTy->getDecl()->hasObjectMember())
5356        Record->setHasObjectMember(true);
5357    } else if (FDTy->isObjCInterfaceType()) {
5358      /// A field cannot be an Objective-c object
5359      Diag(FD->getLocation(), diag::err_statically_allocated_object);
5360      FD->setInvalidDecl();
5361      EnclosingDecl->setInvalidDecl();
5362      continue;
5363    } else if (getLangOptions().ObjC1 &&
5364               getLangOptions().getGCMode() != LangOptions::NonGC &&
5365               Record &&
5366               (FD->getType()->isObjCObjectPointerType() ||
5367                FD->getType().isObjCGCStrong()))
5368      Record->setHasObjectMember(true);
5369    // Keep track of the number of named members.
5370    if (FD->getIdentifier())
5371      ++NumNamedMembers;
5372  }
5373
5374  // Okay, we successfully defined 'Record'.
5375  if (Record) {
5376    Record->completeDefinition(Context);
5377  } else {
5378    ObjCIvarDecl **ClsFields =
5379      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5380    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5381      ID->setIVarList(ClsFields, RecFields.size(), Context);
5382      ID->setLocEnd(RBrac);
5383      // Add ivar's to class's DeclContext.
5384      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5385        ClsFields[i]->setLexicalDeclContext(ID);
5386        ID->addDecl(ClsFields[i]);
5387      }
5388      // Must enforce the rule that ivars in the base classes may not be
5389      // duplicates.
5390      if (ID->getSuperClass()) {
5391        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5392             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5393          ObjCIvarDecl* Ivar = (*IVI);
5394
5395          if (IdentifierInfo *II = Ivar->getIdentifier()) {
5396            ObjCIvarDecl* prevIvar =
5397              ID->getSuperClass()->lookupInstanceVariable(II);
5398            if (prevIvar) {
5399              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5400              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5401            }
5402          }
5403        }
5404      }
5405    } else if (ObjCImplementationDecl *IMPDecl =
5406                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5407      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5408      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5409        // Ivar declared in @implementation never belongs to the implementation.
5410        // Only it is in implementation's lexical context.
5411        ClsFields[I]->setLexicalDeclContext(IMPDecl);
5412      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5413    }
5414  }
5415
5416  if (Attr)
5417    ProcessDeclAttributeList(S, Record, Attr);
5418}
5419
5420EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5421                                          EnumConstantDecl *LastEnumConst,
5422                                          SourceLocation IdLoc,
5423                                          IdentifierInfo *Id,
5424                                          ExprArg val) {
5425  Expr *Val = (Expr *)val.get();
5426
5427  llvm::APSInt EnumVal(32);
5428  QualType EltTy;
5429  if (Val) {
5430    if (Val->isTypeDependent())
5431      EltTy = Context.DependentTy;
5432    else {
5433      // Make sure to promote the operand type to int.
5434      UsualUnaryConversions(Val);
5435      if (Val != val.get()) {
5436        val.release();
5437        val = Val;
5438      }
5439
5440      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5441      SourceLocation ExpLoc;
5442      if (!Val->isValueDependent() &&
5443          VerifyIntegerConstantExpression(Val, &EnumVal)) {
5444        Val = 0;
5445      } else {
5446        EltTy = Val->getType();
5447      }
5448    }
5449  }
5450
5451  if (!Val) {
5452    if (LastEnumConst) {
5453      // Assign the last value + 1.
5454      EnumVal = LastEnumConst->getInitVal();
5455      ++EnumVal;
5456
5457      // Check for overflow on increment.
5458      if (EnumVal < LastEnumConst->getInitVal())
5459        Diag(IdLoc, diag::warn_enum_value_overflow);
5460
5461      EltTy = LastEnumConst->getType();
5462    } else {
5463      // First value, set to zero.
5464      EltTy = Context.IntTy;
5465      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5466    }
5467  }
5468
5469  assert(!EltTy.isNull() && "Enum constant with NULL type");
5470
5471  val.release();
5472  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5473                                  Val, EnumVal);
5474}
5475
5476
5477Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5478                                        DeclPtrTy lastEnumConst,
5479                                        SourceLocation IdLoc,
5480                                        IdentifierInfo *Id,
5481                                        SourceLocation EqualLoc, ExprTy *val) {
5482  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5483  EnumConstantDecl *LastEnumConst =
5484    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5485  Expr *Val = static_cast<Expr*>(val);
5486
5487  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5488  // we find one that is.
5489  S = getNonFieldDeclScope(S);
5490
5491  // Verify that there isn't already something declared with this name in this
5492  // scope.
5493  NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
5494  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5495    // Maybe we will complain about the shadowed template parameter.
5496    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5497    // Just pretend that we didn't see the previous declaration.
5498    PrevDecl = 0;
5499  }
5500
5501  if (PrevDecl) {
5502    // When in C++, we may get a TagDecl with the same name; in this case the
5503    // enum constant will 'hide' the tag.
5504    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5505           "Received TagDecl when not in C++!");
5506    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5507      if (isa<EnumConstantDecl>(PrevDecl))
5508        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5509      else
5510        Diag(IdLoc, diag::err_redefinition) << Id;
5511      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5512      if (Val) Val->Destroy(Context);
5513      return DeclPtrTy();
5514    }
5515  }
5516
5517  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5518                                            IdLoc, Id, Owned(Val));
5519
5520  // Register this decl in the current scope stack.
5521  if (New)
5522    PushOnScopeChains(New, S);
5523
5524  return DeclPtrTy::make(New);
5525}
5526
5527void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5528                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5529                         DeclPtrTy *Elements, unsigned NumElements,
5530                         Scope *S, AttributeList *Attr) {
5531  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5532  QualType EnumType = Context.getTypeDeclType(Enum);
5533
5534  if (Attr)
5535    ProcessDeclAttributeList(S, Enum, Attr);
5536
5537  // TODO: If the result value doesn't fit in an int, it must be a long or long
5538  // long value.  ISO C does not support this, but GCC does as an extension,
5539  // emit a warning.
5540  unsigned IntWidth = Context.Target.getIntWidth();
5541  unsigned CharWidth = Context.Target.getCharWidth();
5542  unsigned ShortWidth = Context.Target.getShortWidth();
5543
5544  // Verify that all the values are okay, compute the size of the values, and
5545  // reverse the list.
5546  unsigned NumNegativeBits = 0;
5547  unsigned NumPositiveBits = 0;
5548
5549  // Keep track of whether all elements have type int.
5550  bool AllElementsInt = true;
5551
5552  for (unsigned i = 0; i != NumElements; ++i) {
5553    EnumConstantDecl *ECD =
5554      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5555    if (!ECD) continue;  // Already issued a diagnostic.
5556
5557    // If the enum value doesn't fit in an int, emit an extension warning.
5558    const llvm::APSInt &InitVal = ECD->getInitVal();
5559    assert(InitVal.getBitWidth() >= IntWidth &&
5560           "Should have promoted value to int");
5561    if (InitVal.getBitWidth() > IntWidth) {
5562      llvm::APSInt V(InitVal);
5563      V.trunc(IntWidth);
5564      V.extend(InitVal.getBitWidth());
5565      if (V != InitVal)
5566        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5567          << InitVal.toString(10);
5568    }
5569
5570    // Keep track of the size of positive and negative values.
5571    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5572      NumPositiveBits = std::max(NumPositiveBits,
5573                                 (unsigned)InitVal.getActiveBits());
5574    else
5575      NumNegativeBits = std::max(NumNegativeBits,
5576                                 (unsigned)InitVal.getMinSignedBits());
5577
5578    // Keep track of whether every enum element has type int (very commmon).
5579    if (AllElementsInt)
5580      AllElementsInt = ECD->getType() == Context.IntTy;
5581  }
5582
5583  // Figure out the type that should be used for this enum.
5584  // FIXME: Support -fshort-enums.
5585  QualType BestType;
5586  unsigned BestWidth;
5587
5588  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5589
5590  if (NumNegativeBits) {
5591    // If there is a negative value, figure out the smallest integer type (of
5592    // int/long/longlong) that fits.
5593    // If it's packed, check also if it fits a char or a short.
5594    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5595        BestType = Context.SignedCharTy;
5596        BestWidth = CharWidth;
5597    } else if (Packed && NumNegativeBits <= ShortWidth &&
5598               NumPositiveBits < ShortWidth) {
5599        BestType = Context.ShortTy;
5600        BestWidth = ShortWidth;
5601    }
5602    else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5603      BestType = Context.IntTy;
5604      BestWidth = IntWidth;
5605    } else {
5606      BestWidth = Context.Target.getLongWidth();
5607
5608      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
5609        BestType = Context.LongTy;
5610      else {
5611        BestWidth = Context.Target.getLongLongWidth();
5612
5613        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5614          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5615        BestType = Context.LongLongTy;
5616      }
5617    }
5618  } else {
5619    // If there is no negative value, figure out which of uint, ulong, ulonglong
5620    // fits.
5621    // If it's packed, check also if it fits a char or a short.
5622    if (Packed && NumPositiveBits <= CharWidth) {
5623        BestType = Context.UnsignedCharTy;
5624        BestWidth = CharWidth;
5625    } else if (Packed && NumPositiveBits <= ShortWidth) {
5626        BestType = Context.UnsignedShortTy;
5627        BestWidth = ShortWidth;
5628    }
5629    else if (NumPositiveBits <= IntWidth) {
5630      BestType = Context.UnsignedIntTy;
5631      BestWidth = IntWidth;
5632    } else if (NumPositiveBits <=
5633               (BestWidth = Context.Target.getLongWidth())) {
5634      BestType = Context.UnsignedLongTy;
5635    } else {
5636      BestWidth = Context.Target.getLongLongWidth();
5637      assert(NumPositiveBits <= BestWidth &&
5638             "How could an initializer get larger than ULL?");
5639      BestType = Context.UnsignedLongLongTy;
5640    }
5641  }
5642
5643  // Loop over all of the enumerator constants, changing their types to match
5644  // the type of the enum if needed.
5645  for (unsigned i = 0; i != NumElements; ++i) {
5646    EnumConstantDecl *ECD =
5647      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5648    if (!ECD) continue;  // Already issued a diagnostic.
5649
5650    // Standard C says the enumerators have int type, but we allow, as an
5651    // extension, the enumerators to be larger than int size.  If each
5652    // enumerator value fits in an int, type it as an int, otherwise type it the
5653    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5654    // that X has type 'int', not 'unsigned'.
5655    if (ECD->getType() == Context.IntTy) {
5656      // Make sure the init value is signed.
5657      llvm::APSInt IV = ECD->getInitVal();
5658      IV.setIsSigned(true);
5659      ECD->setInitVal(IV);
5660
5661      if (getLangOptions().CPlusPlus)
5662        // C++ [dcl.enum]p4: Following the closing brace of an
5663        // enum-specifier, each enumerator has the type of its
5664        // enumeration.
5665        ECD->setType(EnumType);
5666      continue;  // Already int type.
5667    }
5668
5669    // Determine whether the value fits into an int.
5670    llvm::APSInt InitVal = ECD->getInitVal();
5671    bool FitsInInt;
5672    if (InitVal.isUnsigned() || !InitVal.isNegative())
5673      FitsInInt = InitVal.getActiveBits() < IntWidth;
5674    else
5675      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5676
5677    // If it fits into an integer type, force it.  Otherwise force it to match
5678    // the enum decl type.
5679    QualType NewTy;
5680    unsigned NewWidth;
5681    bool NewSign;
5682    if (FitsInInt) {
5683      NewTy = Context.IntTy;
5684      NewWidth = IntWidth;
5685      NewSign = true;
5686    } else if (ECD->getType() == BestType) {
5687      // Already the right type!
5688      if (getLangOptions().CPlusPlus)
5689        // C++ [dcl.enum]p4: Following the closing brace of an
5690        // enum-specifier, each enumerator has the type of its
5691        // enumeration.
5692        ECD->setType(EnumType);
5693      continue;
5694    } else {
5695      NewTy = BestType;
5696      NewWidth = BestWidth;
5697      NewSign = BestType->isSignedIntegerType();
5698    }
5699
5700    // Adjust the APSInt value.
5701    InitVal.extOrTrunc(NewWidth);
5702    InitVal.setIsSigned(NewSign);
5703    ECD->setInitVal(InitVal);
5704
5705    // Adjust the Expr initializer and type.
5706    if (ECD->getInitExpr())
5707      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5708                                                      CastExpr::CK_IntegralCast,
5709                                                      ECD->getInitExpr(),
5710                                                      /*isLvalue=*/false));
5711    if (getLangOptions().CPlusPlus)
5712      // C++ [dcl.enum]p4: Following the closing brace of an
5713      // enum-specifier, each enumerator has the type of its
5714      // enumeration.
5715      ECD->setType(EnumType);
5716    else
5717      ECD->setType(NewTy);
5718  }
5719
5720  Enum->completeDefinition(Context, BestType);
5721}
5722
5723Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
5724                                            ExprArg expr) {
5725  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
5726
5727  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
5728                                                   Loc, AsmString);
5729  CurContext->addDecl(New);
5730  return DeclPtrTy::make(New);
5731}
5732
5733void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
5734                             SourceLocation PragmaLoc,
5735                             SourceLocation NameLoc) {
5736  Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
5737
5738  if (PrevDecl) {
5739    PrevDecl->addAttr(::new (Context) WeakAttr());
5740  } else {
5741    (void)WeakUndeclaredIdentifiers.insert(
5742      std::pair<IdentifierInfo*,WeakInfo>
5743        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
5744  }
5745}
5746
5747void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
5748                                IdentifierInfo* AliasName,
5749                                SourceLocation PragmaLoc,
5750                                SourceLocation NameLoc,
5751                                SourceLocation AliasNameLoc) {
5752  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
5753  WeakInfo W = WeakInfo(Name, NameLoc);
5754
5755  if (PrevDecl) {
5756    if (!PrevDecl->hasAttr<AliasAttr>())
5757      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
5758        DeclApplyPragmaWeak(TUScope, ND, W);
5759  } else {
5760    (void)WeakUndeclaredIdentifiers.insert(
5761      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
5762  }
5763}
5764