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