]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Copy stable/9 to releng/9.1 as part of the 9.1-RELEASE release process.
[FreeBSD/releng/9.1.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
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 "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/CXXFieldCollector.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "TypeLocBuilder.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/HeaderSearch.h"
41 #include "clang/Lex/ModuleLoader.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <functional>
47 using namespace clang;
48 using namespace sema;
49
50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51   if (OwnedType) {
52     Decl *Group[2] = { OwnedType, Ptr };
53     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54   }
55
56   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57 }
58
59 namespace {
60
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62  public:
63   TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
64     WantExpressionKeywords = false;
65     WantCXXNamedCasts = false;
66     WantRemainingKeywords = false;
67   }
68
69   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
70     if (NamedDecl *ND = candidate.getCorrectionDecl())
71       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
72           (AllowInvalidDecl || !ND->isInvalidDecl());
73     else
74       return candidate.isKeyword();
75   }
76
77  private:
78   bool AllowInvalidDecl;
79 };
80
81 }
82
83 /// \brief If the identifier refers to a type name within this scope,
84 /// return the declaration of that type.
85 ///
86 /// This routine performs ordinary name lookup of the identifier II
87 /// within the given scope, with optional C++ scope specifier SS, to
88 /// determine whether the name refers to a type. If so, returns an
89 /// opaque pointer (actually a QualType) corresponding to that
90 /// type. Otherwise, returns NULL.
91 ///
92 /// If name lookup results in an ambiguity, this routine will complain
93 /// and then return NULL.
94 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95                              Scope *S, CXXScopeSpec *SS,
96                              bool isClassName, bool HasTrailingDot,
97                              ParsedType ObjectTypePtr,
98                              bool IsCtorOrDtorName,
99                              bool WantNontrivialTypeSourceInfo,
100                              IdentifierInfo **CorrectedII) {
101   // Determine where we will perform name lookup.
102   DeclContext *LookupCtx = 0;
103   if (ObjectTypePtr) {
104     QualType ObjectType = ObjectTypePtr.get();
105     if (ObjectType->isRecordType())
106       LookupCtx = computeDeclContext(ObjectType);
107   } else if (SS && SS->isNotEmpty()) {
108     LookupCtx = computeDeclContext(*SS, false);
109
110     if (!LookupCtx) {
111       if (isDependentScopeSpecifier(*SS)) {
112         // C++ [temp.res]p3:
113         //   A qualified-id that refers to a type and in which the
114         //   nested-name-specifier depends on a template-parameter (14.6.2)
115         //   shall be prefixed by the keyword typename to indicate that the
116         //   qualified-id denotes a type, forming an
117         //   elaborated-type-specifier (7.1.5.3).
118         //
119         // We therefore do not perform any name lookup if the result would
120         // refer to a member of an unknown specialization.
121         if (!isClassName && !IsCtorOrDtorName)
122           return ParsedType();
123         
124         // We know from the grammar that this name refers to a type,
125         // so build a dependent node to describe the type.
126         if (WantNontrivialTypeSourceInfo)
127           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
128         
129         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
130         QualType T =
131           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
132                             II, NameLoc);
133         
134           return ParsedType::make(T);
135       }
136       
137       return ParsedType();
138     }
139     
140     if (!LookupCtx->isDependentContext() &&
141         RequireCompleteDeclContext(*SS, LookupCtx))
142       return ParsedType();
143   }
144
145   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
146   // lookup for class-names.
147   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
148                                       LookupOrdinaryName;
149   LookupResult Result(*this, &II, NameLoc, Kind);
150   if (LookupCtx) {
151     // Perform "qualified" name lookup into the declaration context we
152     // computed, which is either the type of the base of a member access
153     // expression or the declaration context associated with a prior
154     // nested-name-specifier.
155     LookupQualifiedName(Result, LookupCtx);
156
157     if (ObjectTypePtr && Result.empty()) {
158       // C++ [basic.lookup.classref]p3:
159       //   If the unqualified-id is ~type-name, the type-name is looked up
160       //   in the context of the entire postfix-expression. If the type T of 
161       //   the object expression is of a class type C, the type-name is also
162       //   looked up in the scope of class C. At least one of the lookups shall
163       //   find a name that refers to (possibly cv-qualified) T.
164       LookupName(Result, S);
165     }
166   } else {
167     // Perform unqualified name lookup.
168     LookupName(Result, S);
169   }
170   
171   NamedDecl *IIDecl = 0;
172   switch (Result.getResultKind()) {
173   case LookupResult::NotFound:
174   case LookupResult::NotFoundInCurrentInstantiation:
175     if (CorrectedII) {
176       TypeNameValidatorCCC Validator(true);
177       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
178                                               Kind, S, SS, Validator);
179       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
180       TemplateTy Template;
181       bool MemberOfUnknownSpecialization;
182       UnqualifiedId TemplateName;
183       TemplateName.setIdentifier(NewII, NameLoc);
184       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
185       CXXScopeSpec NewSS, *NewSSPtr = SS;
186       if (SS && NNS) {
187         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
188         NewSSPtr = &NewSS;
189       }
190       if (Correction && (NNS || NewII != &II) &&
191           // Ignore a correction to a template type as the to-be-corrected
192           // identifier is not a template (typo correction for template names
193           // is handled elsewhere).
194           !(getLangOpts().CPlusPlus && NewSSPtr &&
195             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
196                            false, Template, MemberOfUnknownSpecialization))) {
197         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
198                                     isClassName, HasTrailingDot, ObjectTypePtr,
199                                     IsCtorOrDtorName,
200                                     WantNontrivialTypeSourceInfo);
201         if (Ty) {
202           std::string CorrectedStr(Correction.getAsString(getLangOpts()));
203           std::string CorrectedQuotedStr(
204               Correction.getQuoted(getLangOpts()));
205           Diag(NameLoc, diag::err_unknown_typename_suggest)
206               << Result.getLookupName() << CorrectedQuotedStr
207               << FixItHint::CreateReplacement(SourceRange(NameLoc),
208                                               CorrectedStr);
209           if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
210             Diag(FirstDecl->getLocation(), diag::note_previous_decl)
211               << CorrectedQuotedStr;
212
213           if (SS && NNS)
214             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
215           *CorrectedII = NewII;
216           return Ty;
217         }
218       }
219     }
220     // If typo correction failed or was not performed, fall through
221   case LookupResult::FoundOverloaded:
222   case LookupResult::FoundUnresolvedValue:
223     Result.suppressDiagnostics();
224     return ParsedType();
225
226   case LookupResult::Ambiguous:
227     // Recover from type-hiding ambiguities by hiding the type.  We'll
228     // do the lookup again when looking for an object, and we can
229     // diagnose the error then.  If we don't do this, then the error
230     // about hiding the type will be immediately followed by an error
231     // that only makes sense if the identifier was treated like a type.
232     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233       Result.suppressDiagnostics();
234       return ParsedType();
235     }
236
237     // Look to see if we have a type anywhere in the list of results.
238     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
239          Res != ResEnd; ++Res) {
240       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
241         if (!IIDecl ||
242             (*Res)->getLocation().getRawEncoding() <
243               IIDecl->getLocation().getRawEncoding())
244           IIDecl = *Res;
245       }
246     }
247
248     if (!IIDecl) {
249       // None of the entities we found is a type, so there is no way
250       // to even assume that the result is a type. In this case, don't
251       // complain about the ambiguity. The parser will either try to
252       // perform this lookup again (e.g., as an object name), which
253       // will produce the ambiguity, or will complain that it expected
254       // a type name.
255       Result.suppressDiagnostics();
256       return ParsedType();
257     }
258
259     // We found a type within the ambiguous lookup; diagnose the
260     // ambiguity and then return that type. This might be the right
261     // answer, or it might not be, but it suppresses any attempt to
262     // perform the name lookup again.
263     break;
264
265   case LookupResult::Found:
266     IIDecl = Result.getFoundDecl();
267     break;
268   }
269
270   assert(IIDecl && "Didn't find decl");
271
272   QualType T;
273   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
274     DiagnoseUseOfDecl(IIDecl, NameLoc);
275
276     if (T.isNull())
277       T = Context.getTypeDeclType(TD);
278
279     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
280     // constructor or destructor name (in such a case, the scope specifier
281     // will be attached to the enclosing Expr or Decl node).
282     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
283       if (WantNontrivialTypeSourceInfo) {
284         // Construct a type with type-source information.
285         TypeLocBuilder Builder;
286         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
287         
288         T = getElaboratedType(ETK_None, *SS, T);
289         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
290         ElabTL.setElaboratedKeywordLoc(SourceLocation());
291         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
292         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
293       } else {
294         T = getElaboratedType(ETK_None, *SS, T);
295       }
296     }
297   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
298     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
299     if (!HasTrailingDot)
300       T = Context.getObjCInterfaceType(IDecl);
301   }
302
303   if (T.isNull()) {
304     // If it's not plausibly a type, suppress diagnostics.
305     Result.suppressDiagnostics();
306     return ParsedType();
307   }
308   return ParsedType::make(T);
309 }
310
311 /// isTagName() - This method is called *for error recovery purposes only*
312 /// to determine if the specified name is a valid tag name ("struct foo").  If
313 /// so, this returns the TST for the tag corresponding to it (TST_enum,
314 /// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
315 /// where the user forgot to specify the tag.
316 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
317   // Do a tag name lookup in this scope.
318   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
319   LookupName(R, S, false);
320   R.suppressDiagnostics();
321   if (R.getResultKind() == LookupResult::Found)
322     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
323       switch (TD->getTagKind()) {
324       case TTK_Struct: return DeclSpec::TST_struct;
325       case TTK_Union:  return DeclSpec::TST_union;
326       case TTK_Class:  return DeclSpec::TST_class;
327       case TTK_Enum:   return DeclSpec::TST_enum;
328       }
329     }
330
331   return DeclSpec::TST_unspecified;
332 }
333
334 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
335 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
336 /// then downgrade the missing typename error to a warning.
337 /// This is needed for MSVC compatibility; Example:
338 /// @code
339 /// template<class T> class A {
340 /// public:
341 ///   typedef int TYPE;
342 /// };
343 /// template<class T> class B : public A<T> {
344 /// public:
345 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
346 /// };
347 /// @endcode
348 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
349   if (CurContext->isRecord()) {
350     const Type *Ty = SS->getScopeRep()->getAsType();
351
352     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
353     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
354           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
355       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
356         return true;
357     return S->isFunctionPrototypeScope();
358   } 
359   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
360 }
361
362 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 
363                                    SourceLocation IILoc,
364                                    Scope *S,
365                                    CXXScopeSpec *SS,
366                                    ParsedType &SuggestedType) {
367   // We don't have anything to suggest (yet).
368   SuggestedType = ParsedType();
369   
370   // There may have been a typo in the name of the type. Look up typo
371   // results, in case we have something that we can suggest.
372   TypeNameValidatorCCC Validator(false);
373   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
374                                              LookupOrdinaryName, S, SS,
375                                              Validator)) {
376     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
378
379     if (Corrected.isKeyword()) {
380       // We corrected to a keyword.
381       // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
382       Diag(IILoc, diag::err_unknown_typename_suggest)
383         << &II << CorrectedQuotedStr;
384     } else {
385       NamedDecl *Result = Corrected.getCorrectionDecl();
386       // We found a similarly-named type or interface; suggest that.
387       if (!SS || !SS->isSet())
388         Diag(IILoc, diag::err_unknown_typename_suggest)
389           << &II << CorrectedQuotedStr
390           << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
391       else if (DeclContext *DC = computeDeclContext(*SS, false))
392         Diag(IILoc, diag::err_unknown_nested_typename_suggest)
393           << &II << DC << CorrectedQuotedStr << SS->getRange()
394           << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
395       else
396         llvm_unreachable("could not have corrected a typo here");
397
398       Diag(Result->getLocation(), diag::note_previous_decl)
399         << CorrectedQuotedStr;
400
401       SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
402                                   false, false, ParsedType(),
403                                   /*IsCtorOrDtorName=*/false,
404                                   /*NonTrivialTypeSourceInfo=*/true);
405     }
406     return true;
407   }
408
409   if (getLangOpts().CPlusPlus) {
410     // See if II is a class template that the user forgot to pass arguments to.
411     UnqualifiedId Name;
412     Name.setIdentifier(&II, IILoc);
413     CXXScopeSpec EmptySS;
414     TemplateTy TemplateResult;
415     bool MemberOfUnknownSpecialization;
416     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
417                        Name, ParsedType(), true, TemplateResult,
418                        MemberOfUnknownSpecialization) == TNK_Type_template) {
419       TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
420       Diag(IILoc, diag::err_template_missing_args) << TplName;
421       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
422         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
423           << TplDecl->getTemplateParameters()->getSourceRange();
424       }
425       return true;
426     }
427   }
428
429   // FIXME: Should we move the logic that tries to recover from a missing tag
430   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
431   
432   if (!SS || (!SS->isSet() && !SS->isInvalid()))
433     Diag(IILoc, diag::err_unknown_typename) << &II;
434   else if (DeclContext *DC = computeDeclContext(*SS, false))
435     Diag(IILoc, diag::err_typename_nested_not_found) 
436       << &II << DC << SS->getRange();
437   else if (isDependentScopeSpecifier(*SS)) {
438     unsigned DiagID = diag::err_typename_missing;
439     if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
440       DiagID = diag::warn_typename_missing;
441
442     Diag(SS->getRange().getBegin(), DiagID)
443       << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
444       << SourceRange(SS->getRange().getBegin(), IILoc)
445       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
446     SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
447                                                                          .get();
448   } else {
449     assert(SS && SS->isInvalid() && 
450            "Invalid scope specifier has already been diagnosed");
451   }
452   
453   return true;
454 }
455
456 /// \brief Determine whether the given result set contains either a type name
457 /// or 
458 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
459   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
460                        NextToken.is(tok::less);
461   
462   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
463     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
464       return true;
465     
466     if (CheckTemplate && isa<TemplateDecl>(*I))
467       return true;
468   }
469   
470   return false;
471 }
472
473 Sema::NameClassification Sema::ClassifyName(Scope *S,
474                                             CXXScopeSpec &SS,
475                                             IdentifierInfo *&Name,
476                                             SourceLocation NameLoc,
477                                             const Token &NextToken) {
478   DeclarationNameInfo NameInfo(Name, NameLoc);
479   ObjCMethodDecl *CurMethod = getCurMethodDecl();
480   
481   if (NextToken.is(tok::coloncolon)) {
482     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
483                                 QualType(), false, SS, 0, false);
484     
485   }
486       
487   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
488   LookupParsedName(Result, S, &SS, !CurMethod);
489   
490   // Perform lookup for Objective-C instance variables (including automatically 
491   // synthesized instance variables), if we're in an Objective-C method.
492   // FIXME: This lookup really, really needs to be folded in to the normal
493   // unqualified lookup mechanism.
494   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
495     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
496     if (E.get() || E.isInvalid())
497       return E;
498   }
499   
500   bool SecondTry = false;
501   bool IsFilteredTemplateName = false;
502   
503 Corrected:
504   switch (Result.getResultKind()) {
505   case LookupResult::NotFound:
506     // If an unqualified-id is followed by a '(', then we have a function
507     // call.
508     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
509       // In C++, this is an ADL-only call.
510       // FIXME: Reference?
511       if (getLangOpts().CPlusPlus)
512         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
513       
514       // C90 6.3.2.2:
515       //   If the expression that precedes the parenthesized argument list in a 
516       //   function call consists solely of an identifier, and if no 
517       //   declaration is visible for this identifier, the identifier is 
518       //   implicitly declared exactly as if, in the innermost block containing
519       //   the function call, the declaration
520       //
521       //     extern int identifier (); 
522       //
523       //   appeared. 
524       // 
525       // We also allow this in C99 as an extension.
526       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
527         Result.addDecl(D);
528         Result.resolveKind();
529         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
530       }
531     }
532     
533     // In C, we first see whether there is a tag type by the same name, in 
534     // which case it's likely that the user just forget to write "enum", 
535     // "struct", or "union".
536     if (!getLangOpts().CPlusPlus && !SecondTry) {
537       Result.clear(LookupTagName);
538       LookupParsedName(Result, S, &SS);
539       if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
540         const char *TagName = 0;
541         const char *FixItTagName = 0;
542         switch (Tag->getTagKind()) {
543           case TTK_Class:
544             TagName = "class";
545             FixItTagName = "class ";
546             break;
547
548           case TTK_Enum:
549             TagName = "enum";
550             FixItTagName = "enum ";
551             break;
552             
553           case TTK_Struct:
554             TagName = "struct";
555             FixItTagName = "struct ";
556             break;
557             
558           case TTK_Union:
559             TagName = "union";
560             FixItTagName = "union ";
561             break;
562         }
563
564         Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
565           << Name << TagName << getLangOpts().CPlusPlus
566           << FixItHint::CreateInsertion(NameLoc, FixItTagName);
567         break;
568       }
569       
570       Result.clear(LookupOrdinaryName);
571     }
572
573     // Perform typo correction to determine if there is another name that is
574     // close to this name.
575     if (!SecondTry) {
576       SecondTry = true;
577       CorrectionCandidateCallback DefaultValidator;
578       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
579                                                  Result.getLookupKind(), S, 
580                                                  &SS, DefaultValidator)) {
581         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
582         unsigned QualifiedDiag = diag::err_no_member_suggest;
583         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584         std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
585         
586         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
587         NamedDecl *UnderlyingFirstDecl
588           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
589         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
590             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
591           UnqualifiedDiag = diag::err_no_template_suggest;
592           QualifiedDiag = diag::err_no_member_template_suggest;
593         } else if (UnderlyingFirstDecl && 
594                    (isa<TypeDecl>(UnderlyingFirstDecl) || 
595                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
596                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
597            UnqualifiedDiag = diag::err_unknown_typename_suggest;
598            QualifiedDiag = diag::err_unknown_nested_typename_suggest;
599          }
600
601         if (SS.isEmpty())
602           Diag(NameLoc, UnqualifiedDiag)
603             << Name << CorrectedQuotedStr
604             << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
605         else
606           Diag(NameLoc, QualifiedDiag)
607             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
608             << SS.getRange()
609             << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
610
611         // Update the name, so that the caller has the new name.
612         Name = Corrected.getCorrectionAsIdentifierInfo();
613         
614         // Typo correction corrected to a keyword.
615         if (Corrected.isKeyword())
616           return Corrected.getCorrectionAsIdentifierInfo();
617
618         // Also update the LookupResult...
619         // FIXME: This should probably go away at some point
620         Result.clear();
621         Result.setLookupName(Corrected.getCorrection());
622         if (FirstDecl) {
623           Result.addDecl(FirstDecl);
624           Diag(FirstDecl->getLocation(), diag::note_previous_decl)
625             << CorrectedQuotedStr;
626         }
627
628         // If we found an Objective-C instance variable, let
629         // LookupInObjCMethod build the appropriate expression to
630         // reference the ivar.
631         // FIXME: This is a gross hack.
632         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
633           Result.clear();
634           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
635           return move(E);
636         }
637         
638         goto Corrected;
639       }
640     }
641       
642     // We failed to correct; just fall through and let the parser deal with it.
643     Result.suppressDiagnostics();
644     return NameClassification::Unknown();
645       
646   case LookupResult::NotFoundInCurrentInstantiation: {
647     // We performed name lookup into the current instantiation, and there were 
648     // dependent bases, so we treat this result the same way as any other
649     // dependent nested-name-specifier.
650       
651     // C++ [temp.res]p2:
652     //   A name used in a template declaration or definition and that is 
653     //   dependent on a template-parameter is assumed not to name a type 
654     //   unless the applicable name lookup finds a type name or the name is 
655     //   qualified by the keyword typename.
656     //
657     // FIXME: If the next token is '<', we might want to ask the parser to
658     // perform some heroics to see if we actually have a 
659     // template-argument-list, which would indicate a missing 'template'
660     // keyword here.
661     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
662                                      NameInfo, /*TemplateArgs=*/0);
663   }
664
665   case LookupResult::Found:
666   case LookupResult::FoundOverloaded:
667   case LookupResult::FoundUnresolvedValue:
668     break;
669       
670   case LookupResult::Ambiguous:
671     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672         hasAnyAcceptableTemplateNames(Result)) {
673       // C++ [temp.local]p3:
674       //   A lookup that finds an injected-class-name (10.2) can result in an
675       //   ambiguity in certain cases (for example, if it is found in more than
676       //   one base class). If all of the injected-class-names that are found
677       //   refer to specializations of the same class template, and if the name
678       //   is followed by a template-argument-list, the reference refers to the
679       //   class template itself and not a specialization thereof, and is not
680       //   ambiguous.
681       //
682       // This filtering can make an ambiguous result into an unambiguous one,
683       // so try again after filtering out template names.
684       FilterAcceptableTemplateNames(Result);
685       if (!Result.isAmbiguous()) {
686         IsFilteredTemplateName = true;
687         break;
688       }
689     }
690       
691     // Diagnose the ambiguity and return an error.
692     return NameClassification::Error();
693   }
694   
695   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
696       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
697     // C++ [temp.names]p3:
698     //   After name lookup (3.4) finds that a name is a template-name or that
699     //   an operator-function-id or a literal- operator-id refers to a set of
700     //   overloaded functions any member of which is a function template if 
701     //   this is followed by a <, the < is always taken as the delimiter of a
702     //   template-argument-list and never as the less-than operator.
703     if (!IsFilteredTemplateName)
704       FilterAcceptableTemplateNames(Result);
705     
706     if (!Result.empty()) {
707       bool IsFunctionTemplate;
708       TemplateName Template;
709       if (Result.end() - Result.begin() > 1) {
710         IsFunctionTemplate = true;
711         Template = Context.getOverloadedTemplateName(Result.begin(), 
712                                                      Result.end());
713       } else {
714         TemplateDecl *TD
715           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
716         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
717         
718         if (SS.isSet() && !SS.isInvalid())
719           Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 
720                                                     /*TemplateKeyword=*/false,
721                                                       TD);
722         else
723           Template = TemplateName(TD);
724       }
725       
726       if (IsFunctionTemplate) {
727         // Function templates always go through overload resolution, at which
728         // point we'll perform the various checks (e.g., accessibility) we need
729         // to based on which function we selected.
730         Result.suppressDiagnostics();
731         
732         return NameClassification::FunctionTemplate(Template);
733       }
734       
735       return NameClassification::TypeTemplate(Template);
736     }
737   }
738   
739   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
740   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
741     DiagnoseUseOfDecl(Type, NameLoc);
742     QualType T = Context.getTypeDeclType(Type);
743     return ParsedType::make(T);    
744   }
745   
746   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
747   if (!Class) {
748     // FIXME: It's unfortunate that we don't have a Type node for handling this.
749     if (ObjCCompatibleAliasDecl *Alias 
750                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
751       Class = Alias->getClassInterface();
752   }
753   
754   if (Class) {
755     DiagnoseUseOfDecl(Class, NameLoc);
756     
757     if (NextToken.is(tok::period)) {
758       // Interface. <something> is parsed as a property reference expression.
759       // Just return "unknown" as a fall-through for now.
760       Result.suppressDiagnostics();
761       return NameClassification::Unknown();
762     }
763     
764     QualType T = Context.getObjCInterfaceType(Class);
765     return ParsedType::make(T);
766   }
767   
768   if (!Result.empty() && (*Result.begin())->isCXXClassMember())
769     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
770
771   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
772   return BuildDeclarationNameExpr(SS, Result, ADL);
773 }
774
775 // Determines the context to return to after temporarily entering a
776 // context.  This depends in an unnecessarily complicated way on the
777 // exact ordering of callbacks from the parser.
778 DeclContext *Sema::getContainingDC(DeclContext *DC) {
779
780   // Functions defined inline within classes aren't parsed until we've
781   // finished parsing the top-level class, so the top-level class is
782   // the context we'll need to return to.
783   if (isa<FunctionDecl>(DC)) {
784     DC = DC->getLexicalParent();
785
786     // A function not defined within a class will always return to its
787     // lexical context.
788     if (!isa<CXXRecordDecl>(DC))
789       return DC;
790
791     // A C++ inline method/friend is parsed *after* the topmost class
792     // it was declared in is fully parsed ("complete");  the topmost
793     // class is the context we need to return to.
794     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
795       DC = RD;
796
797     // Return the declaration context of the topmost class the inline method is
798     // declared in.
799     return DC;
800   }
801
802   return DC->getLexicalParent();
803 }
804
805 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
806   assert(getContainingDC(DC) == CurContext &&
807       "The next DeclContext should be lexically contained in the current one.");
808   CurContext = DC;
809   S->setEntity(DC);
810 }
811
812 void Sema::PopDeclContext() {
813   assert(CurContext && "DeclContext imbalance!");
814
815   CurContext = getContainingDC(CurContext);
816   assert(CurContext && "Popped translation unit!");
817 }
818
819 /// EnterDeclaratorContext - Used when we must lookup names in the context
820 /// of a declarator's nested name specifier.
821 ///
822 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
823   // C++0x [basic.lookup.unqual]p13:
824   //   A name used in the definition of a static data member of class
825   //   X (after the qualified-id of the static member) is looked up as
826   //   if the name was used in a member function of X.
827   // C++0x [basic.lookup.unqual]p14:
828   //   If a variable member of a namespace is defined outside of the
829   //   scope of its namespace then any name used in the definition of
830   //   the variable member (after the declarator-id) is looked up as
831   //   if the definition of the variable member occurred in its
832   //   namespace.
833   // Both of these imply that we should push a scope whose context
834   // is the semantic context of the declaration.  We can't use
835   // PushDeclContext here because that context is not necessarily
836   // lexically contained in the current context.  Fortunately,
837   // the containing scope should have the appropriate information.
838
839   assert(!S->getEntity() && "scope already has entity");
840
841 #ifndef NDEBUG
842   Scope *Ancestor = S->getParent();
843   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
844   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
845 #endif
846
847   CurContext = DC;
848   S->setEntity(DC);
849 }
850
851 void Sema::ExitDeclaratorContext(Scope *S) {
852   assert(S->getEntity() == CurContext && "Context imbalance!");
853
854   // Switch back to the lexical context.  The safety of this is
855   // enforced by an assert in EnterDeclaratorContext.
856   Scope *Ancestor = S->getParent();
857   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
858   CurContext = (DeclContext*) Ancestor->getEntity();
859
860   // We don't need to do anything with the scope, which is going to
861   // disappear.
862 }
863
864
865 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
866   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
867   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
868     // We assume that the caller has already called
869     // ActOnReenterTemplateScope
870     FD = TFD->getTemplatedDecl();
871   }
872   if (!FD)
873     return;
874
875   // Same implementation as PushDeclContext, but enters the context
876   // from the lexical parent, rather than the top-level class.
877   assert(CurContext == FD->getLexicalParent() &&
878     "The next DeclContext should be lexically contained in the current one.");
879   CurContext = FD;
880   S->setEntity(CurContext);
881
882   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
883     ParmVarDecl *Param = FD->getParamDecl(P);
884     // If the parameter has an identifier, then add it to the scope
885     if (Param->getIdentifier()) {
886       S->AddDecl(Param);
887       IdResolver.AddDecl(Param);
888     }
889   }
890 }
891
892
893 void Sema::ActOnExitFunctionContext() {
894   // Same implementation as PopDeclContext, but returns to the lexical parent,
895   // rather than the top-level class.
896   assert(CurContext && "DeclContext imbalance!");
897   CurContext = CurContext->getLexicalParent();
898   assert(CurContext && "Popped translation unit!");
899 }
900
901
902 /// \brief Determine whether we allow overloading of the function
903 /// PrevDecl with another declaration.
904 ///
905 /// This routine determines whether overloading is possible, not
906 /// whether some new function is actually an overload. It will return
907 /// true in C++ (where we can always provide overloads) or, as an
908 /// extension, in C when the previous function is already an
909 /// overloaded function declaration or has the "overloadable"
910 /// attribute.
911 static bool AllowOverloadingOfFunction(LookupResult &Previous,
912                                        ASTContext &Context) {
913   if (Context.getLangOpts().CPlusPlus)
914     return true;
915
916   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
917     return true;
918
919   return (Previous.getResultKind() == LookupResult::Found
920           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
921 }
922
923 /// Add this decl to the scope shadowed decl chains.
924 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
925   // Move up the scope chain until we find the nearest enclosing
926   // non-transparent context. The declaration will be introduced into this
927   // scope.
928   while (S->getEntity() &&
929          ((DeclContext *)S->getEntity())->isTransparentContext())
930     S = S->getParent();
931
932   // Add scoped declarations into their context, so that they can be
933   // found later. Declarations without a context won't be inserted
934   // into any context.
935   if (AddToContext)
936     CurContext->addDecl(D);
937
938   // Out-of-line definitions shouldn't be pushed into scope in C++.
939   // Out-of-line variable and function definitions shouldn't even in C.
940   if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
941       D->isOutOfLine() &&
942       !D->getDeclContext()->getRedeclContext()->Equals(
943         D->getLexicalDeclContext()->getRedeclContext()))
944     return;
945
946   // Template instantiations should also not be pushed into scope.
947   if (isa<FunctionDecl>(D) &&
948       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
949     return;
950
951   // If this replaces anything in the current scope, 
952   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
953                                IEnd = IdResolver.end();
954   for (; I != IEnd; ++I) {
955     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
956       S->RemoveDecl(*I);
957       IdResolver.RemoveDecl(*I);
958
959       // Should only need to replace one decl.
960       break;
961     }
962   }
963
964   S->AddDecl(D);
965   
966   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
967     // Implicitly-generated labels may end up getting generated in an order that
968     // isn't strictly lexical, which breaks name lookup. Be careful to insert
969     // the label at the appropriate place in the identifier chain.
970     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
971       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
972       if (IDC == CurContext) {
973         if (!S->isDeclScope(*I))
974           continue;
975       } else if (IDC->Encloses(CurContext))
976         break;
977     }
978     
979     IdResolver.InsertDeclAfter(I, D);
980   } else {
981     IdResolver.AddDecl(D);
982   }
983 }
984
985 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
986   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
987     TUScope->AddDecl(D);
988 }
989
990 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
991                          bool ExplicitInstantiationOrSpecialization) {
992   return IdResolver.isDeclInScope(D, Ctx, Context, S,
993                                   ExplicitInstantiationOrSpecialization);
994 }
995
996 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
997   DeclContext *TargetDC = DC->getPrimaryContext();
998   do {
999     if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1000       if (ScopeDC->getPrimaryContext() == TargetDC)
1001         return S;
1002   } while ((S = S->getParent()));
1003
1004   return 0;
1005 }
1006
1007 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1008                                             DeclContext*,
1009                                             ASTContext&);
1010
1011 /// Filters out lookup results that don't fall within the given scope
1012 /// as determined by isDeclInScope.
1013 void Sema::FilterLookupForScope(LookupResult &R,
1014                                 DeclContext *Ctx, Scope *S,
1015                                 bool ConsiderLinkage,
1016                                 bool ExplicitInstantiationOrSpecialization) {
1017   LookupResult::Filter F = R.makeFilter();
1018   while (F.hasNext()) {
1019     NamedDecl *D = F.next();
1020
1021     if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1022       continue;
1023
1024     if (ConsiderLinkage &&
1025         isOutOfScopePreviousDeclaration(D, Ctx, Context))
1026       continue;
1027     
1028     F.erase();
1029   }
1030
1031   F.done();
1032 }
1033
1034 static bool isUsingDecl(NamedDecl *D) {
1035   return isa<UsingShadowDecl>(D) ||
1036          isa<UnresolvedUsingTypenameDecl>(D) ||
1037          isa<UnresolvedUsingValueDecl>(D);
1038 }
1039
1040 /// Removes using shadow declarations from the lookup results.
1041 static void RemoveUsingDecls(LookupResult &R) {
1042   LookupResult::Filter F = R.makeFilter();
1043   while (F.hasNext())
1044     if (isUsingDecl(F.next()))
1045       F.erase();
1046
1047   F.done();
1048 }
1049
1050 /// \brief Check for this common pattern:
1051 /// @code
1052 /// class S {
1053 ///   S(const S&); // DO NOT IMPLEMENT
1054 ///   void operator=(const S&); // DO NOT IMPLEMENT
1055 /// };
1056 /// @endcode
1057 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1058   // FIXME: Should check for private access too but access is set after we get
1059   // the decl here.
1060   if (D->doesThisDeclarationHaveABody())
1061     return false;
1062
1063   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1064     return CD->isCopyConstructor();
1065   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1066     return Method->isCopyAssignmentOperator();
1067   return false;
1068 }
1069
1070 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1071   assert(D);
1072
1073   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1074     return false;
1075
1076   // Ignore class templates.
1077   if (D->getDeclContext()->isDependentContext() ||
1078       D->getLexicalDeclContext()->isDependentContext())
1079     return false;
1080
1081   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1082     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1083       return false;
1084
1085     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1086       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1087         return false;
1088     } else {
1089       // 'static inline' functions are used in headers; don't warn.
1090       if (FD->getStorageClass() == SC_Static &&
1091           FD->isInlineSpecified())
1092         return false;
1093     }
1094
1095     if (FD->doesThisDeclarationHaveABody() &&
1096         Context.DeclMustBeEmitted(FD))
1097       return false;
1098   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1099     if (!VD->isFileVarDecl() ||
1100         VD->getType().isConstant(Context) ||
1101         Context.DeclMustBeEmitted(VD))
1102       return false;
1103
1104     if (VD->isStaticDataMember() &&
1105         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1106       return false;
1107
1108   } else {
1109     return false;
1110   }
1111
1112   // Only warn for unused decls internal to the translation unit.
1113   if (D->getLinkage() == ExternalLinkage)
1114     return false;
1115
1116   return true;
1117 }
1118
1119 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1120   if (!D)
1121     return;
1122
1123   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1124     const FunctionDecl *First = FD->getFirstDeclaration();
1125     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1126       return; // First should already be in the vector.
1127   }
1128
1129   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1130     const VarDecl *First = VD->getFirstDeclaration();
1131     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1132       return; // First should already be in the vector.
1133   }
1134
1135    if (ShouldWarnIfUnusedFileScopedDecl(D))
1136      UnusedFileScopedDecls.push_back(D);
1137  }
1138
1139 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1140   if (D->isInvalidDecl())
1141     return false;
1142
1143   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1144     return false;
1145
1146   if (isa<LabelDecl>(D))
1147     return true;
1148   
1149   // White-list anything that isn't a local variable.
1150   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1151       !D->getDeclContext()->isFunctionOrMethod())
1152     return false;
1153
1154   // Types of valid local variables should be complete, so this should succeed.
1155   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1156
1157     // White-list anything with an __attribute__((unused)) type.
1158     QualType Ty = VD->getType();
1159
1160     // Only look at the outermost level of typedef.
1161     if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1162       if (TT->getDecl()->hasAttr<UnusedAttr>())
1163         return false;
1164     }
1165
1166     // If we failed to complete the type for some reason, or if the type is
1167     // dependent, don't diagnose the variable. 
1168     if (Ty->isIncompleteType() || Ty->isDependentType())
1169       return false;
1170
1171     if (const TagType *TT = Ty->getAs<TagType>()) {
1172       const TagDecl *Tag = TT->getDecl();
1173       if (Tag->hasAttr<UnusedAttr>())
1174         return false;
1175
1176       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1177         if (!RD->hasTrivialDestructor())
1178           return false;
1179
1180         if (const Expr *Init = VD->getInit()) {
1181           const CXXConstructExpr *Construct =
1182             dyn_cast<CXXConstructExpr>(Init);
1183           if (Construct && !Construct->isElidable()) {
1184             CXXConstructorDecl *CD = Construct->getConstructor();
1185             if (!CD->isTrivial())
1186               return false;
1187           }
1188         }
1189       }
1190     }
1191
1192     // TODO: __attribute__((unused)) templates?
1193   }
1194   
1195   return true;
1196 }
1197
1198 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1199                                      FixItHint &Hint) {
1200   if (isa<LabelDecl>(D)) {
1201     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1202                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1203     if (AfterColon.isInvalid())
1204       return;
1205     Hint = FixItHint::CreateRemoval(CharSourceRange::
1206                                     getCharRange(D->getLocStart(), AfterColon));
1207   }
1208   return;
1209 }
1210
1211 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1212 /// unless they are marked attr(unused).
1213 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1214   FixItHint Hint;
1215   if (!ShouldDiagnoseUnusedDecl(D))
1216     return;
1217   
1218   GenerateFixForUnusedDecl(D, Context, Hint);
1219
1220   unsigned DiagID;
1221   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1222     DiagID = diag::warn_unused_exception_param;
1223   else if (isa<LabelDecl>(D))
1224     DiagID = diag::warn_unused_label;
1225   else
1226     DiagID = diag::warn_unused_variable;
1227
1228   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1229 }
1230
1231 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1232   // Verify that we have no forward references left.  If so, there was a goto
1233   // or address of a label taken, but no definition of it.  Label fwd
1234   // definitions are indicated with a null substmt.
1235   if (L->getStmt() == 0)
1236     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1237 }
1238
1239 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1240   if (S->decl_empty()) return;
1241   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1242          "Scope shouldn't contain decls!");
1243
1244   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1245        I != E; ++I) {
1246     Decl *TmpD = (*I);
1247     assert(TmpD && "This decl didn't get pushed??");
1248
1249     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1250     NamedDecl *D = cast<NamedDecl>(TmpD);
1251
1252     if (!D->getDeclName()) continue;
1253
1254     // Diagnose unused variables in this scope.
1255     if (!S->hasErrorOccurred())
1256       DiagnoseUnusedDecl(D);
1257     
1258     // If this was a forward reference to a label, verify it was defined.
1259     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1260       CheckPoppedLabel(LD, *this);
1261     
1262     // Remove this name from our lexical scope.
1263     IdResolver.RemoveDecl(D);
1264   }
1265 }
1266
1267 void Sema::ActOnStartFunctionDeclarator() {
1268   ++InFunctionDeclarator;
1269 }
1270
1271 void Sema::ActOnEndFunctionDeclarator() {
1272   assert(InFunctionDeclarator);
1273   --InFunctionDeclarator;
1274 }
1275
1276 /// \brief Look for an Objective-C class in the translation unit.
1277 ///
1278 /// \param Id The name of the Objective-C class we're looking for. If
1279 /// typo-correction fixes this name, the Id will be updated
1280 /// to the fixed name.
1281 ///
1282 /// \param IdLoc The location of the name in the translation unit.
1283 ///
1284 /// \param TypoCorrection If true, this routine will attempt typo correction
1285 /// if there is no class with the given name.
1286 ///
1287 /// \returns The declaration of the named Objective-C class, or NULL if the
1288 /// class could not be found.
1289 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1290                                               SourceLocation IdLoc,
1291                                               bool DoTypoCorrection) {
1292   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1293   // creation from this context.
1294   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1295
1296   if (!IDecl && DoTypoCorrection) {
1297     // Perform typo correction at the given location, but only if we
1298     // find an Objective-C class name.
1299     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1300     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1301                                        LookupOrdinaryName, TUScope, NULL,
1302                                        Validator)) {
1303       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1304       Diag(IdLoc, diag::err_undef_interface_suggest)
1305         << Id << IDecl->getDeclName() 
1306         << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1307       Diag(IDecl->getLocation(), diag::note_previous_decl)
1308         << IDecl->getDeclName();
1309       
1310       Id = IDecl->getIdentifier();
1311     }
1312   }
1313   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1314   // This routine must always return a class definition, if any.
1315   if (Def && Def->getDefinition())
1316       Def = Def->getDefinition();
1317   return Def;
1318 }
1319
1320 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1321 /// from S, where a non-field would be declared. This routine copes
1322 /// with the difference between C and C++ scoping rules in structs and
1323 /// unions. For example, the following code is well-formed in C but
1324 /// ill-formed in C++:
1325 /// @code
1326 /// struct S6 {
1327 ///   enum { BAR } e;
1328 /// };
1329 ///
1330 /// void test_S6() {
1331 ///   struct S6 a;
1332 ///   a.e = BAR;
1333 /// }
1334 /// @endcode
1335 /// For the declaration of BAR, this routine will return a different
1336 /// scope. The scope S will be the scope of the unnamed enumeration
1337 /// within S6. In C++, this routine will return the scope associated
1338 /// with S6, because the enumeration's scope is a transparent
1339 /// context but structures can contain non-field names. In C, this
1340 /// routine will return the translation unit scope, since the
1341 /// enumeration's scope is a transparent context and structures cannot
1342 /// contain non-field names.
1343 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1344   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1345          (S->getEntity() &&
1346           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1347          (S->isClassScope() && !getLangOpts().CPlusPlus))
1348     S = S->getParent();
1349   return S;
1350 }
1351
1352 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1353 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1354 /// if we're creating this built-in in anticipation of redeclaring the
1355 /// built-in.
1356 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1357                                      Scope *S, bool ForRedeclaration,
1358                                      SourceLocation Loc) {
1359   Builtin::ID BID = (Builtin::ID)bid;
1360
1361   ASTContext::GetBuiltinTypeError Error;
1362   QualType R = Context.GetBuiltinType(BID, Error);
1363   switch (Error) {
1364   case ASTContext::GE_None:
1365     // Okay
1366     break;
1367
1368   case ASTContext::GE_Missing_stdio:
1369     if (ForRedeclaration)
1370       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1371         << Context.BuiltinInfo.GetName(BID);
1372     return 0;
1373
1374   case ASTContext::GE_Missing_setjmp:
1375     if (ForRedeclaration)
1376       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1377         << Context.BuiltinInfo.GetName(BID);
1378     return 0;
1379
1380   case ASTContext::GE_Missing_ucontext:
1381     if (ForRedeclaration)
1382       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1383         << Context.BuiltinInfo.GetName(BID);
1384     return 0;
1385   }
1386
1387   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1388     Diag(Loc, diag::ext_implicit_lib_function_decl)
1389       << Context.BuiltinInfo.GetName(BID)
1390       << R;
1391     if (Context.BuiltinInfo.getHeaderName(BID) &&
1392         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1393           != DiagnosticsEngine::Ignored)
1394       Diag(Loc, diag::note_please_include_header)
1395         << Context.BuiltinInfo.getHeaderName(BID)
1396         << Context.BuiltinInfo.GetName(BID);
1397   }
1398
1399   FunctionDecl *New = FunctionDecl::Create(Context,
1400                                            Context.getTranslationUnitDecl(),
1401                                            Loc, Loc, II, R, /*TInfo=*/0,
1402                                            SC_Extern,
1403                                            SC_None, false,
1404                                            /*hasPrototype=*/true);
1405   New->setImplicit();
1406
1407   // Create Decl objects for each parameter, adding them to the
1408   // FunctionDecl.
1409   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1410     SmallVector<ParmVarDecl*, 16> Params;
1411     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1412       ParmVarDecl *parm =
1413         ParmVarDecl::Create(Context, New, SourceLocation(),
1414                             SourceLocation(), 0,
1415                             FT->getArgType(i), /*TInfo=*/0,
1416                             SC_None, SC_None, 0);
1417       parm->setScopeInfo(0, i);
1418       Params.push_back(parm);
1419     }
1420     New->setParams(Params);
1421   }
1422
1423   AddKnownFunctionAttributes(New);
1424
1425   // TUScope is the translation-unit scope to insert this function into.
1426   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1427   // relate Scopes to DeclContexts, and probably eliminate CurContext
1428   // entirely, but we're not there yet.
1429   DeclContext *SavedContext = CurContext;
1430   CurContext = Context.getTranslationUnitDecl();
1431   PushOnScopeChains(New, TUScope);
1432   CurContext = SavedContext;
1433   return New;
1434 }
1435
1436 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1437   QualType OldType;
1438   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1439     OldType = OldTypedef->getUnderlyingType();
1440   else
1441     OldType = Context.getTypeDeclType(Old);
1442   QualType NewType = New->getUnderlyingType();
1443
1444   if (NewType->isVariablyModifiedType()) {
1445     // Must not redefine a typedef with a variably-modified type.
1446     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1447     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1448       << Kind << NewType;
1449     if (Old->getLocation().isValid())
1450       Diag(Old->getLocation(), diag::note_previous_definition);
1451     New->setInvalidDecl();
1452     return true;    
1453   }
1454   
1455   if (OldType != NewType &&
1456       !OldType->isDependentType() &&
1457       !NewType->isDependentType() &&
1458       !Context.hasSameType(OldType, NewType)) { 
1459     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1460     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1461       << Kind << NewType << OldType;
1462     if (Old->getLocation().isValid())
1463       Diag(Old->getLocation(), diag::note_previous_definition);
1464     New->setInvalidDecl();
1465     return true;
1466   }
1467   return false;
1468 }
1469
1470 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1471 /// same name and scope as a previous declaration 'Old'.  Figure out
1472 /// how to resolve this situation, merging decls or emitting
1473 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1474 ///
1475 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1476   // If the new decl is known invalid already, don't bother doing any
1477   // merging checks.
1478   if (New->isInvalidDecl()) return;
1479
1480   // Allow multiple definitions for ObjC built-in typedefs.
1481   // FIXME: Verify the underlying types are equivalent!
1482   if (getLangOpts().ObjC1) {
1483     const IdentifierInfo *TypeID = New->getIdentifier();
1484     switch (TypeID->getLength()) {
1485     default: break;
1486     case 2:
1487       if (!TypeID->isStr("id"))
1488         break;
1489       Context.setObjCIdRedefinitionType(New->getUnderlyingType());
1490       // Install the built-in type for 'id', ignoring the current definition.
1491       New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1492       return;
1493     case 5:
1494       if (!TypeID->isStr("Class"))
1495         break;
1496       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1497       // Install the built-in type for 'Class', ignoring the current definition.
1498       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1499       return;
1500     case 3:
1501       if (!TypeID->isStr("SEL"))
1502         break;
1503       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1504       // Install the built-in type for 'SEL', ignoring the current definition.
1505       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1506       return;
1507     }
1508     // Fall through - the typedef name was not a builtin type.
1509   }
1510
1511   // Verify the old decl was also a type.
1512   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1513   if (!Old) {
1514     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1515       << New->getDeclName();
1516
1517     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1518     if (OldD->getLocation().isValid())
1519       Diag(OldD->getLocation(), diag::note_previous_definition);
1520
1521     return New->setInvalidDecl();
1522   }
1523
1524   // If the old declaration is invalid, just give up here.
1525   if (Old->isInvalidDecl())
1526     return New->setInvalidDecl();
1527
1528   // If the typedef types are not identical, reject them in all languages and
1529   // with any extensions enabled.
1530   if (isIncompatibleTypedef(Old, New))
1531     return;
1532
1533   // The types match.  Link up the redeclaration chain if the old
1534   // declaration was a typedef.
1535   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1536     New->setPreviousDeclaration(Typedef);
1537
1538   if (getLangOpts().MicrosoftExt)
1539     return;
1540
1541   if (getLangOpts().CPlusPlus) {
1542     // C++ [dcl.typedef]p2:
1543     //   In a given non-class scope, a typedef specifier can be used to
1544     //   redefine the name of any type declared in that scope to refer
1545     //   to the type to which it already refers.
1546     if (!isa<CXXRecordDecl>(CurContext))
1547       return;
1548
1549     // C++0x [dcl.typedef]p4:
1550     //   In a given class scope, a typedef specifier can be used to redefine 
1551     //   any class-name declared in that scope that is not also a typedef-name
1552     //   to refer to the type to which it already refers.
1553     //
1554     // This wording came in via DR424, which was a correction to the
1555     // wording in DR56, which accidentally banned code like:
1556     //
1557     //   struct S {
1558     //     typedef struct A { } A;
1559     //   };
1560     //
1561     // in the C++03 standard. We implement the C++0x semantics, which
1562     // allow the above but disallow
1563     //
1564     //   struct S {
1565     //     typedef int I;
1566     //     typedef int I;
1567     //   };
1568     //
1569     // since that was the intent of DR56.
1570     if (!isa<TypedefNameDecl>(Old))
1571       return;
1572
1573     Diag(New->getLocation(), diag::err_redefinition)
1574       << New->getDeclName();
1575     Diag(Old->getLocation(), diag::note_previous_definition);
1576     return New->setInvalidDecl();
1577   }
1578
1579   // Modules always permit redefinition of typedefs, as does C11.
1580   if (getLangOpts().Modules || getLangOpts().C11)
1581     return;
1582   
1583   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1584   // is normally mapped to an error, but can be controlled with
1585   // -Wtypedef-redefinition.  If either the original or the redefinition is
1586   // in a system header, don't emit this for compatibility with GCC.
1587   if (getDiagnostics().getSuppressSystemWarnings() &&
1588       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1589        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1590     return;
1591
1592   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1593     << New->getDeclName();
1594   Diag(Old->getLocation(), diag::note_previous_definition);
1595   return;
1596 }
1597
1598 /// DeclhasAttr - returns true if decl Declaration already has the target
1599 /// attribute.
1600 static bool
1601 DeclHasAttr(const Decl *D, const Attr *A) {
1602   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1603   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1604   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1605     if ((*i)->getKind() == A->getKind()) {
1606       if (Ann) {
1607         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1608           return true;
1609         continue;
1610       }
1611       // FIXME: Don't hardcode this check
1612       if (OA && isa<OwnershipAttr>(*i))
1613         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1614       return true;
1615     }
1616
1617   return false;
1618 }
1619
1620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1621 void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1622                                bool MergeDeprecation) {
1623   if (!Old->hasAttrs())
1624     return;
1625
1626   bool foundAny = New->hasAttrs();
1627
1628   // Ensure that any moving of objects within the allocated map is done before
1629   // we process them.
1630   if (!foundAny) New->setAttrs(AttrVec());
1631
1632   for (specific_attr_iterator<InheritableAttr>
1633          i = Old->specific_attr_begin<InheritableAttr>(),
1634          e = Old->specific_attr_end<InheritableAttr>(); 
1635        i != e; ++i) {
1636     // Ignore deprecated/unavailable/availability attributes if requested.
1637     if (!MergeDeprecation &&
1638         (isa<DeprecatedAttr>(*i) || 
1639          isa<UnavailableAttr>(*i) ||
1640          isa<AvailabilityAttr>(*i)))
1641       continue;
1642
1643     if (!DeclHasAttr(New, *i)) {
1644       InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
1645       newAttr->setInherited(true);
1646       New->addAttr(newAttr);
1647       foundAny = true;
1648     }
1649   }
1650
1651   if (!foundAny) New->dropAttrs();
1652 }
1653
1654 /// mergeParamDeclAttributes - Copy attributes from the old parameter
1655 /// to the new one.
1656 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1657                                      const ParmVarDecl *oldDecl,
1658                                      ASTContext &C) {
1659   if (!oldDecl->hasAttrs())
1660     return;
1661
1662   bool foundAny = newDecl->hasAttrs();
1663
1664   // Ensure that any moving of objects within the allocated map is
1665   // done before we process them.
1666   if (!foundAny) newDecl->setAttrs(AttrVec());
1667
1668   for (specific_attr_iterator<InheritableParamAttr>
1669        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1670        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1671     if (!DeclHasAttr(newDecl, *i)) {
1672       InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1673       newAttr->setInherited(true);
1674       newDecl->addAttr(newAttr);
1675       foundAny = true;
1676     }
1677   }
1678
1679   if (!foundAny) newDecl->dropAttrs();
1680 }
1681
1682 namespace {
1683
1684 /// Used in MergeFunctionDecl to keep track of function parameters in
1685 /// C.
1686 struct GNUCompatibleParamWarning {
1687   ParmVarDecl *OldParm;
1688   ParmVarDecl *NewParm;
1689   QualType PromotedType;
1690 };
1691
1692 }
1693
1694 /// getSpecialMember - get the special member enum for a method.
1695 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1696   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1697     if (Ctor->isDefaultConstructor())
1698       return Sema::CXXDefaultConstructor;
1699
1700     if (Ctor->isCopyConstructor())
1701       return Sema::CXXCopyConstructor;
1702
1703     if (Ctor->isMoveConstructor())
1704       return Sema::CXXMoveConstructor;
1705   } else if (isa<CXXDestructorDecl>(MD)) {
1706     return Sema::CXXDestructor;
1707   } else if (MD->isCopyAssignmentOperator()) {
1708     return Sema::CXXCopyAssignment;
1709   } else if (MD->isMoveAssignmentOperator()) {
1710     return Sema::CXXMoveAssignment;
1711   }
1712
1713   return Sema::CXXInvalid;
1714 }
1715
1716 /// canRedefineFunction - checks if a function can be redefined. Currently,
1717 /// only extern inline functions can be redefined, and even then only in
1718 /// GNU89 mode.
1719 static bool canRedefineFunction(const FunctionDecl *FD,
1720                                 const LangOptions& LangOpts) {
1721   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1722           !LangOpts.CPlusPlus &&
1723           FD->isInlineSpecified() &&
1724           FD->getStorageClass() == SC_Extern);
1725 }
1726
1727 /// MergeFunctionDecl - We just parsed a function 'New' from
1728 /// declarator D which has the same name and scope as a previous
1729 /// declaration 'Old'.  Figure out how to resolve this situation,
1730 /// merging decls or emitting diagnostics as appropriate.
1731 ///
1732 /// In C++, New and Old must be declarations that are not
1733 /// overloaded. Use IsOverload to determine whether New and Old are
1734 /// overloaded, and to select the Old declaration that New should be
1735 /// merged with.
1736 ///
1737 /// Returns true if there was an error, false otherwise.
1738 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1739   // Verify the old decl was also a function.
1740   FunctionDecl *Old = 0;
1741   if (FunctionTemplateDecl *OldFunctionTemplate
1742         = dyn_cast<FunctionTemplateDecl>(OldD))
1743     Old = OldFunctionTemplate->getTemplatedDecl();
1744   else
1745     Old = dyn_cast<FunctionDecl>(OldD);
1746   if (!Old) {
1747     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1748       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1749       Diag(Shadow->getTargetDecl()->getLocation(),
1750            diag::note_using_decl_target);
1751       Diag(Shadow->getUsingDecl()->getLocation(),
1752            diag::note_using_decl) << 0;
1753       return true;
1754     }
1755
1756     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1757       << New->getDeclName();
1758     Diag(OldD->getLocation(), diag::note_previous_definition);
1759     return true;
1760   }
1761
1762   // Determine whether the previous declaration was a definition,
1763   // implicit declaration, or a declaration.
1764   diag::kind PrevDiag;
1765   if (Old->isThisDeclarationADefinition())
1766     PrevDiag = diag::note_previous_definition;
1767   else if (Old->isImplicit())
1768     PrevDiag = diag::note_previous_implicit_declaration;
1769   else
1770     PrevDiag = diag::note_previous_declaration;
1771
1772   QualType OldQType = Context.getCanonicalType(Old->getType());
1773   QualType NewQType = Context.getCanonicalType(New->getType());
1774
1775   // Don't complain about this if we're in GNU89 mode and the old function
1776   // is an extern inline function.
1777   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1778       New->getStorageClass() == SC_Static &&
1779       Old->getStorageClass() != SC_Static &&
1780       !canRedefineFunction(Old, getLangOpts())) {
1781     if (getLangOpts().MicrosoftExt) {
1782       Diag(New->getLocation(), diag::warn_static_non_static) << New;
1783       Diag(Old->getLocation(), PrevDiag);
1784     } else {
1785       Diag(New->getLocation(), diag::err_static_non_static) << New;
1786       Diag(Old->getLocation(), PrevDiag);
1787       return true;
1788     }
1789   }
1790
1791   // If a function is first declared with a calling convention, but is
1792   // later declared or defined without one, the second decl assumes the
1793   // calling convention of the first.
1794   //
1795   // For the new decl, we have to look at the NON-canonical type to tell the
1796   // difference between a function that really doesn't have a calling
1797   // convention and one that is declared cdecl. That's because in
1798   // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1799   // because it is the default calling convention.
1800   //
1801   // Note also that we DO NOT return at this point, because we still have
1802   // other tests to run.
1803   const FunctionType *OldType = cast<FunctionType>(OldQType);
1804   const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1805   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1806   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1807   bool RequiresAdjustment = false;
1808   if (OldTypeInfo.getCC() != CC_Default &&
1809       NewTypeInfo.getCC() == CC_Default) {
1810     NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1811     RequiresAdjustment = true;
1812   } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1813                                      NewTypeInfo.getCC())) {
1814     // Calling conventions really aren't compatible, so complain.
1815     Diag(New->getLocation(), diag::err_cconv_change)
1816       << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1817       << (OldTypeInfo.getCC() == CC_Default)
1818       << (OldTypeInfo.getCC() == CC_Default ? "" :
1819           FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1820     Diag(Old->getLocation(), diag::note_previous_declaration);
1821     return true;
1822   }
1823
1824   // FIXME: diagnose the other way around?
1825   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1826     NewTypeInfo = NewTypeInfo.withNoReturn(true);
1827     RequiresAdjustment = true;
1828   }
1829
1830   // Merge regparm attribute.
1831   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1832       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1833     if (NewTypeInfo.getHasRegParm()) {
1834       Diag(New->getLocation(), diag::err_regparm_mismatch)
1835         << NewType->getRegParmType()
1836         << OldType->getRegParmType();
1837       Diag(Old->getLocation(), diag::note_previous_declaration);      
1838       return true;
1839     }
1840
1841     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1842     RequiresAdjustment = true;
1843   }
1844
1845   // Merge ns_returns_retained attribute.
1846   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1847     if (NewTypeInfo.getProducesResult()) {
1848       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1849       Diag(Old->getLocation(), diag::note_previous_declaration);      
1850       return true;
1851     }
1852     
1853     NewTypeInfo = NewTypeInfo.withProducesResult(true);
1854     RequiresAdjustment = true;
1855   }
1856   
1857   if (RequiresAdjustment) {
1858     NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1859     New->setType(QualType(NewType, 0));
1860     NewQType = Context.getCanonicalType(New->getType());
1861   }
1862   
1863   if (getLangOpts().CPlusPlus) {
1864     // (C++98 13.1p2):
1865     //   Certain function declarations cannot be overloaded:
1866     //     -- Function declarations that differ only in the return type
1867     //        cannot be overloaded.
1868     QualType OldReturnType = OldType->getResultType();
1869     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1870     QualType ResQT;
1871     if (OldReturnType != NewReturnType) {
1872       if (NewReturnType->isObjCObjectPointerType()
1873           && OldReturnType->isObjCObjectPointerType())
1874         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1875       if (ResQT.isNull()) {
1876         if (New->isCXXClassMember() && New->isOutOfLine())
1877           Diag(New->getLocation(),
1878                diag::err_member_def_does_not_match_ret_type) << New;
1879         else
1880           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1881         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1882         return true;
1883       }
1884       else
1885         NewQType = ResQT;
1886     }
1887
1888     const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1889     CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1890     if (OldMethod && NewMethod) {
1891       // Preserve triviality.
1892       NewMethod->setTrivial(OldMethod->isTrivial());
1893
1894       // MSVC allows explicit template specialization at class scope:
1895       // 2 CXMethodDecls referring to the same function will be injected.
1896       // We don't want a redeclartion error.
1897       bool IsClassScopeExplicitSpecialization =
1898                               OldMethod->isFunctionTemplateSpecialization() &&
1899                               NewMethod->isFunctionTemplateSpecialization();
1900       bool isFriend = NewMethod->getFriendObjectKind();
1901
1902       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1903           !IsClassScopeExplicitSpecialization) {
1904         //    -- Member function declarations with the same name and the
1905         //       same parameter types cannot be overloaded if any of them
1906         //       is a static member function declaration.
1907         if (OldMethod->isStatic() || NewMethod->isStatic()) {
1908           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1909           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1910           return true;
1911         }
1912       
1913         // C++ [class.mem]p1:
1914         //   [...] A member shall not be declared twice in the
1915         //   member-specification, except that a nested class or member
1916         //   class template can be declared and then later defined.
1917         unsigned NewDiag;
1918         if (isa<CXXConstructorDecl>(OldMethod))
1919           NewDiag = diag::err_constructor_redeclared;
1920         else if (isa<CXXDestructorDecl>(NewMethod))
1921           NewDiag = diag::err_destructor_redeclared;
1922         else if (isa<CXXConversionDecl>(NewMethod))
1923           NewDiag = diag::err_conv_function_redeclared;
1924         else
1925           NewDiag = diag::err_member_redeclared;
1926
1927         Diag(New->getLocation(), NewDiag);
1928         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1929
1930       // Complain if this is an explicit declaration of a special
1931       // member that was initially declared implicitly.
1932       //
1933       // As an exception, it's okay to befriend such methods in order
1934       // to permit the implicit constructor/destructor/operator calls.
1935       } else if (OldMethod->isImplicit()) {
1936         if (isFriend) {
1937           NewMethod->setImplicit();
1938         } else {
1939           Diag(NewMethod->getLocation(),
1940                diag::err_definition_of_implicitly_declared_member) 
1941             << New << getSpecialMember(OldMethod);
1942           return true;
1943         }
1944       } else if (OldMethod->isExplicitlyDefaulted()) {
1945         Diag(NewMethod->getLocation(),
1946              diag::err_definition_of_explicitly_defaulted_member)
1947           << getSpecialMember(OldMethod);
1948         return true;
1949       }
1950     }
1951
1952     // (C++98 8.3.5p3):
1953     //   All declarations for a function shall agree exactly in both the
1954     //   return type and the parameter-type-list.
1955     // We also want to respect all the extended bits except noreturn.
1956
1957     // noreturn should now match unless the old type info didn't have it.
1958     QualType OldQTypeForComparison = OldQType;
1959     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1960       assert(OldQType == QualType(OldType, 0));
1961       const FunctionType *OldTypeForComparison
1962         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1963       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1964       assert(OldQTypeForComparison.isCanonical());
1965     }
1966
1967     if (OldQTypeForComparison == NewQType)
1968       return MergeCompatibleFunctionDecls(New, Old, S);
1969
1970     // Fall through for conflicting redeclarations and redefinitions.
1971   }
1972
1973   // C: Function types need to be compatible, not identical. This handles
1974   // duplicate function decls like "void f(int); void f(enum X);" properly.
1975   if (!getLangOpts().CPlusPlus &&
1976       Context.typesAreCompatible(OldQType, NewQType)) {
1977     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1978     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1979     const FunctionProtoType *OldProto = 0;
1980     if (isa<FunctionNoProtoType>(NewFuncType) &&
1981         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1982       // The old declaration provided a function prototype, but the
1983       // new declaration does not. Merge in the prototype.
1984       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1985       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1986                                                  OldProto->arg_type_end());
1987       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1988                                          ParamTypes.data(), ParamTypes.size(),
1989                                          OldProto->getExtProtoInfo());
1990       New->setType(NewQType);
1991       New->setHasInheritedPrototype();
1992
1993       // Synthesize a parameter for each argument type.
1994       SmallVector<ParmVarDecl*, 16> Params;
1995       for (FunctionProtoType::arg_type_iterator
1996              ParamType = OldProto->arg_type_begin(),
1997              ParamEnd = OldProto->arg_type_end();
1998            ParamType != ParamEnd; ++ParamType) {
1999         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2000                                                  SourceLocation(),
2001                                                  SourceLocation(), 0,
2002                                                  *ParamType, /*TInfo=*/0,
2003                                                  SC_None, SC_None,
2004                                                  0);
2005         Param->setScopeInfo(0, Params.size());
2006         Param->setImplicit();
2007         Params.push_back(Param);
2008       }
2009
2010       New->setParams(Params);
2011     }
2012
2013     return MergeCompatibleFunctionDecls(New, Old, S);
2014   }
2015
2016   // GNU C permits a K&R definition to follow a prototype declaration
2017   // if the declared types of the parameters in the K&R definition
2018   // match the types in the prototype declaration, even when the
2019   // promoted types of the parameters from the K&R definition differ
2020   // from the types in the prototype. GCC then keeps the types from
2021   // the prototype.
2022   //
2023   // If a variadic prototype is followed by a non-variadic K&R definition,
2024   // the K&R definition becomes variadic.  This is sort of an edge case, but
2025   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2026   // C99 6.9.1p8.
2027   if (!getLangOpts().CPlusPlus &&
2028       Old->hasPrototype() && !New->hasPrototype() &&
2029       New->getType()->getAs<FunctionProtoType>() &&
2030       Old->getNumParams() == New->getNumParams()) {
2031     SmallVector<QualType, 16> ArgTypes;
2032     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2033     const FunctionProtoType *OldProto
2034       = Old->getType()->getAs<FunctionProtoType>();
2035     const FunctionProtoType *NewProto
2036       = New->getType()->getAs<FunctionProtoType>();
2037
2038     // Determine whether this is the GNU C extension.
2039     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2040                                                NewProto->getResultType());
2041     bool LooseCompatible = !MergedReturn.isNull();
2042     for (unsigned Idx = 0, End = Old->getNumParams();
2043          LooseCompatible && Idx != End; ++Idx) {
2044       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2045       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2046       if (Context.typesAreCompatible(OldParm->getType(),
2047                                      NewProto->getArgType(Idx))) {
2048         ArgTypes.push_back(NewParm->getType());
2049       } else if (Context.typesAreCompatible(OldParm->getType(),
2050                                             NewParm->getType(),
2051                                             /*CompareUnqualified=*/true)) {
2052         GNUCompatibleParamWarning Warn
2053           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2054         Warnings.push_back(Warn);
2055         ArgTypes.push_back(NewParm->getType());
2056       } else
2057         LooseCompatible = false;
2058     }
2059
2060     if (LooseCompatible) {
2061       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2062         Diag(Warnings[Warn].NewParm->getLocation(),
2063              diag::ext_param_promoted_not_compatible_with_prototype)
2064           << Warnings[Warn].PromotedType
2065           << Warnings[Warn].OldParm->getType();
2066         if (Warnings[Warn].OldParm->getLocation().isValid())
2067           Diag(Warnings[Warn].OldParm->getLocation(),
2068                diag::note_previous_declaration);
2069       }
2070
2071       New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2072                                            ArgTypes.size(),
2073                                            OldProto->getExtProtoInfo()));
2074       return MergeCompatibleFunctionDecls(New, Old, S);
2075     }
2076
2077     // Fall through to diagnose conflicting types.
2078   }
2079
2080   // A function that has already been declared has been redeclared or defined
2081   // with a different type- show appropriate diagnostic
2082   if (unsigned BuiltinID = Old->getBuiltinID()) {
2083     // The user has declared a builtin function with an incompatible
2084     // signature.
2085     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2086       // The function the user is redeclaring is a library-defined
2087       // function like 'malloc' or 'printf'. Warn about the
2088       // redeclaration, then pretend that we don't know about this
2089       // library built-in.
2090       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2091       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2092         << Old << Old->getType();
2093       New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2094       Old->setInvalidDecl();
2095       return false;
2096     }
2097
2098     PrevDiag = diag::note_previous_builtin_declaration;
2099   }
2100
2101   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2102   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2103   return true;
2104 }
2105
2106 /// \brief Completes the merge of two function declarations that are
2107 /// known to be compatible.
2108 ///
2109 /// This routine handles the merging of attributes and other
2110 /// properties of function declarations form the old declaration to
2111 /// the new declaration, once we know that New is in fact a
2112 /// redeclaration of Old.
2113 ///
2114 /// \returns false
2115 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2116                                         Scope *S) {
2117   // Merge the attributes
2118   mergeDeclAttributes(New, Old);
2119
2120   // Merge the storage class.
2121   if (Old->getStorageClass() != SC_Extern &&
2122       Old->getStorageClass() != SC_None)
2123     New->setStorageClass(Old->getStorageClass());
2124
2125   // Merge "pure" flag.
2126   if (Old->isPure())
2127     New->setPure();
2128
2129   // Merge attributes from the parameters.  These can mismatch with K&R
2130   // declarations.
2131   if (New->getNumParams() == Old->getNumParams())
2132     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2133       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2134                                Context);
2135
2136   if (getLangOpts().CPlusPlus)
2137     return MergeCXXFunctionDecl(New, Old, S);
2138
2139   return false;
2140 }
2141
2142
2143 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2144                                 ObjCMethodDecl *oldMethod) {
2145   // We don't want to merge unavailable and deprecated attributes
2146   // except from interface to implementation.
2147   bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2148
2149   // Merge the attributes.
2150   mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
2151
2152   // Merge attributes from the parameters.
2153   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2154   for (ObjCMethodDecl::param_iterator
2155          ni = newMethod->param_begin(), ne = newMethod->param_end();
2156        ni != ne; ++ni, ++oi)
2157     mergeParamDeclAttributes(*ni, *oi, Context);
2158
2159   CheckObjCMethodOverride(newMethod, oldMethod, true);
2160 }
2161
2162 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2163 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2164 /// emitting diagnostics as appropriate.
2165 ///
2166 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2167 /// to here in AddInitializerToDecl. We can't check them before the initializer
2168 /// is attached.
2169 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2170   if (New->isInvalidDecl() || Old->isInvalidDecl())
2171     return;
2172
2173   QualType MergedT;
2174   if (getLangOpts().CPlusPlus) {
2175     AutoType *AT = New->getType()->getContainedAutoType();
2176     if (AT && !AT->isDeduced()) {
2177       // We don't know what the new type is until the initializer is attached.
2178       return;
2179     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2180       // These could still be something that needs exception specs checked.
2181       return MergeVarDeclExceptionSpecs(New, Old);
2182     }
2183     // C++ [basic.link]p10:
2184     //   [...] the types specified by all declarations referring to a given
2185     //   object or function shall be identical, except that declarations for an
2186     //   array object can specify array types that differ by the presence or
2187     //   absence of a major array bound (8.3.4).
2188     else if (Old->getType()->isIncompleteArrayType() &&
2189              New->getType()->isArrayType()) {
2190       CanQual<ArrayType> OldArray
2191         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2192       CanQual<ArrayType> NewArray
2193         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2194       if (OldArray->getElementType() == NewArray->getElementType())
2195         MergedT = New->getType();
2196     } else if (Old->getType()->isArrayType() &&
2197              New->getType()->isIncompleteArrayType()) {
2198       CanQual<ArrayType> OldArray
2199         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2200       CanQual<ArrayType> NewArray
2201         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2202       if (OldArray->getElementType() == NewArray->getElementType())
2203         MergedT = Old->getType();
2204     } else if (New->getType()->isObjCObjectPointerType()
2205                && Old->getType()->isObjCObjectPointerType()) {
2206         MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2207                                                         Old->getType());
2208     }
2209   } else {
2210     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2211   }
2212   if (MergedT.isNull()) {
2213     Diag(New->getLocation(), diag::err_redefinition_different_type)
2214       << New->getDeclName();
2215     Diag(Old->getLocation(), diag::note_previous_definition);
2216     return New->setInvalidDecl();
2217   }
2218   New->setType(MergedT);
2219 }
2220
2221 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2222 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2223 /// situation, merging decls or emitting diagnostics as appropriate.
2224 ///
2225 /// Tentative definition rules (C99 6.9.2p2) are checked by
2226 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2227 /// definitions here, since the initializer hasn't been attached.
2228 ///
2229 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2230   // If the new decl is already invalid, don't do any other checking.
2231   if (New->isInvalidDecl())
2232     return;
2233
2234   // Verify the old decl was also a variable.
2235   VarDecl *Old = 0;
2236   if (!Previous.isSingleResult() ||
2237       !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2238     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2239       << New->getDeclName();
2240     Diag(Previous.getRepresentativeDecl()->getLocation(),
2241          diag::note_previous_definition);
2242     return New->setInvalidDecl();
2243   }
2244
2245   // C++ [class.mem]p1:
2246   //   A member shall not be declared twice in the member-specification [...]
2247   // 
2248   // Here, we need only consider static data members.
2249   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2250     Diag(New->getLocation(), diag::err_duplicate_member) 
2251       << New->getIdentifier();
2252     Diag(Old->getLocation(), diag::note_previous_declaration);
2253     New->setInvalidDecl();
2254   }
2255   
2256   mergeDeclAttributes(New, Old);
2257   // Warn if an already-declared variable is made a weak_import in a subsequent 
2258   // declaration
2259   if (New->getAttr<WeakImportAttr>() &&
2260       Old->getStorageClass() == SC_None &&
2261       !Old->getAttr<WeakImportAttr>()) {
2262     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2263     Diag(Old->getLocation(), diag::note_previous_definition);
2264     // Remove weak_import attribute on new declaration.
2265     New->dropAttr<WeakImportAttr>();
2266   }
2267
2268   // Merge the types.
2269   MergeVarDeclTypes(New, Old);
2270   if (New->isInvalidDecl())
2271     return;
2272
2273   // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2274   if (New->getStorageClass() == SC_Static &&
2275       (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2276     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2277     Diag(Old->getLocation(), diag::note_previous_definition);
2278     return New->setInvalidDecl();
2279   }
2280   // C99 6.2.2p4:
2281   //   For an identifier declared with the storage-class specifier
2282   //   extern in a scope in which a prior declaration of that
2283   //   identifier is visible,23) if the prior declaration specifies
2284   //   internal or external linkage, the linkage of the identifier at
2285   //   the later declaration is the same as the linkage specified at
2286   //   the prior declaration. If no prior declaration is visible, or
2287   //   if the prior declaration specifies no linkage, then the
2288   //   identifier has external linkage.
2289   if (New->hasExternalStorage() && Old->hasLinkage())
2290     /* Okay */;
2291   else if (New->getStorageClass() != SC_Static &&
2292            Old->getStorageClass() == SC_Static) {
2293     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2294     Diag(Old->getLocation(), diag::note_previous_definition);
2295     return New->setInvalidDecl();
2296   }
2297
2298   // Check if extern is followed by non-extern and vice-versa.
2299   if (New->hasExternalStorage() &&
2300       !Old->hasLinkage() && Old->isLocalVarDecl()) {
2301     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2302     Diag(Old->getLocation(), diag::note_previous_definition);
2303     return New->setInvalidDecl();
2304   }
2305   if (Old->hasExternalStorage() &&
2306       !New->hasLinkage() && New->isLocalVarDecl()) {
2307     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2308     Diag(Old->getLocation(), diag::note_previous_definition);
2309     return New->setInvalidDecl();
2310   }
2311
2312   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2313
2314   // FIXME: The test for external storage here seems wrong? We still
2315   // need to check for mismatches.
2316   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2317       // Don't complain about out-of-line definitions of static members.
2318       !(Old->getLexicalDeclContext()->isRecord() &&
2319         !New->getLexicalDeclContext()->isRecord())) {
2320     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2321     Diag(Old->getLocation(), diag::note_previous_definition);
2322     return New->setInvalidDecl();
2323   }
2324
2325   if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2326     Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2327     Diag(Old->getLocation(), diag::note_previous_definition);
2328   } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2329     Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2330     Diag(Old->getLocation(), diag::note_previous_definition);
2331   }
2332
2333   // C++ doesn't have tentative definitions, so go right ahead and check here.
2334   const VarDecl *Def;
2335   if (getLangOpts().CPlusPlus &&
2336       New->isThisDeclarationADefinition() == VarDecl::Definition &&
2337       (Def = Old->getDefinition())) {
2338     Diag(New->getLocation(), diag::err_redefinition)
2339       << New->getDeclName();
2340     Diag(Def->getLocation(), diag::note_previous_definition);
2341     New->setInvalidDecl();
2342     return;
2343   }
2344   // c99 6.2.2 P4.
2345   // For an identifier declared with the storage-class specifier extern in a
2346   // scope in which a prior declaration of that identifier is visible, if 
2347   // the prior declaration specifies internal or external linkage, the linkage 
2348   // of the identifier at the later declaration is the same as the linkage 
2349   // specified at the prior declaration.
2350   // FIXME. revisit this code.
2351   if (New->hasExternalStorage() &&
2352       Old->getLinkage() == InternalLinkage &&
2353       New->getDeclContext() == Old->getDeclContext())
2354     New->setStorageClass(Old->getStorageClass());
2355
2356   // Keep a chain of previous declarations.
2357   New->setPreviousDeclaration(Old);
2358
2359   // Inherit access appropriately.
2360   New->setAccess(Old->getAccess());
2361 }
2362
2363 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2364 /// no declarator (e.g. "struct foo;") is parsed.
2365 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2366                                        DeclSpec &DS) {
2367   return ParsedFreeStandingDeclSpec(S, AS, DS,
2368                                     MultiTemplateParamsArg(*this, 0, 0));
2369 }
2370
2371 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2372 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2373 /// parameters to cope with template friend declarations.
2374 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2375                                        DeclSpec &DS,
2376                                        MultiTemplateParamsArg TemplateParams) {
2377   Decl *TagD = 0;
2378   TagDecl *Tag = 0;
2379   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2380       DS.getTypeSpecType() == DeclSpec::TST_struct ||
2381       DS.getTypeSpecType() == DeclSpec::TST_union ||
2382       DS.getTypeSpecType() == DeclSpec::TST_enum) {
2383     TagD = DS.getRepAsDecl();
2384
2385     if (!TagD) // We probably had an error
2386       return 0;
2387
2388     // Note that the above type specs guarantee that the
2389     // type rep is a Decl, whereas in many of the others
2390     // it's a Type.
2391     if (isa<TagDecl>(TagD))
2392       Tag = cast<TagDecl>(TagD);
2393     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2394       Tag = CTD->getTemplatedDecl();
2395   }
2396
2397   if (Tag) {
2398     Tag->setFreeStanding();
2399     if (Tag->isInvalidDecl())
2400       return Tag;
2401   }
2402
2403   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2404     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2405     // or incomplete types shall not be restrict-qualified."
2406     if (TypeQuals & DeclSpec::TQ_restrict)
2407       Diag(DS.getRestrictSpecLoc(),
2408            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2409            << DS.getSourceRange();
2410   }
2411
2412   if (DS.isConstexprSpecified()) {
2413     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2414     // and definitions of functions and variables.
2415     if (Tag)
2416       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2417         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2418             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2419             DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2420     else
2421       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2422     // Don't emit warnings after this error.
2423     return TagD;
2424   }
2425
2426   if (DS.isFriendSpecified()) {
2427     // If we're dealing with a decl but not a TagDecl, assume that
2428     // whatever routines created it handled the friendship aspect.
2429     if (TagD && !Tag)
2430       return 0;
2431     return ActOnFriendTypeDecl(S, DS, TemplateParams);
2432   }
2433
2434   // Track whether we warned about the fact that there aren't any
2435   // declarators.
2436   bool emittedWarning = false;
2437          
2438   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2439     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2440         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2441       if (getLangOpts().CPlusPlus ||
2442           Record->getDeclContext()->isRecord())
2443         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2444
2445       Diag(DS.getLocStart(), diag::ext_no_declarators)
2446         << DS.getSourceRange();
2447       emittedWarning = true;
2448     }
2449   }
2450
2451   // Check for Microsoft C extension: anonymous struct.
2452   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2453       CurContext->isRecord() &&
2454       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2455     // Handle 2 kinds of anonymous struct:
2456     //   struct STRUCT;
2457     // and
2458     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2459     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2460     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2461         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2462          DS.getRepAsType().get()->isStructureType())) {
2463       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2464         << DS.getSourceRange();
2465       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2466     }
2467   }
2468   
2469   if (getLangOpts().CPlusPlus && 
2470       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2471     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2472       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2473           !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2474         Diag(Enum->getLocation(), diag::ext_no_declarators)
2475           << DS.getSourceRange();
2476         emittedWarning = true;
2477       }
2478
2479   // Skip all the checks below if we have a type error.
2480   if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2481       
2482   if (!DS.isMissingDeclaratorOk()) {
2483     // Warn about typedefs of enums without names, since this is an
2484     // extension in both Microsoft and GNU.
2485     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2486         Tag && isa<EnumDecl>(Tag)) {
2487       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2488         << DS.getSourceRange();
2489       return Tag;
2490     }
2491
2492     Diag(DS.getLocStart(), diag::ext_no_declarators)
2493       << DS.getSourceRange();
2494     emittedWarning = true;
2495   }
2496
2497   // We're going to complain about a bunch of spurious specifiers;
2498   // only do this if we're declaring a tag, because otherwise we
2499   // should be getting diag::ext_no_declarators.
2500   if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2501     return TagD;
2502
2503   // Note that a linkage-specification sets a storage class, but
2504   // 'extern "C" struct foo;' is actually valid and not theoretically
2505   // useless.
2506   if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2507     if (!DS.isExternInLinkageSpec())
2508       Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2509         << DeclSpec::getSpecifierName(scs);
2510
2511   if (DS.isThreadSpecified())
2512     Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2513   if (DS.getTypeQualifiers()) {
2514     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2515       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2516     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2517       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2518     // Restrict is covered above.
2519   }
2520   if (DS.isInlineSpecified())
2521     Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2522   if (DS.isVirtualSpecified())
2523     Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2524   if (DS.isExplicitSpecified())
2525     Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2526
2527   if (DS.isModulePrivateSpecified() && 
2528       Tag && Tag->getDeclContext()->isFunctionOrMethod())
2529     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2530       << Tag->getTagKind()
2531       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2532
2533   // Warn about ignored type attributes, for example:
2534   // __attribute__((aligned)) struct A;
2535   // Attributes should be placed after tag to apply to type declaration.
2536   if (!DS.getAttributes().empty()) {
2537     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2538     if (TypeSpecType == DeclSpec::TST_class ||
2539         TypeSpecType == DeclSpec::TST_struct ||
2540         TypeSpecType == DeclSpec::TST_union ||
2541         TypeSpecType == DeclSpec::TST_enum) {
2542       AttributeList* attrs = DS.getAttributes().getList();
2543       while (attrs) {
2544         Diag(attrs->getScopeLoc(),
2545              diag::warn_declspec_attribute_ignored)
2546         << attrs->getName()
2547         << (TypeSpecType == DeclSpec::TST_class ? 0 :
2548             TypeSpecType == DeclSpec::TST_struct ? 1 :
2549             TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2550         attrs = attrs->getNext();
2551       }
2552     }
2553   }
2554
2555   return TagD;
2556 }
2557
2558 /// We are trying to inject an anonymous member into the given scope;
2559 /// check if there's an existing declaration that can't be overloaded.
2560 ///
2561 /// \return true if this is a forbidden redeclaration
2562 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2563                                          Scope *S,
2564                                          DeclContext *Owner,
2565                                          DeclarationName Name,
2566                                          SourceLocation NameLoc,
2567                                          unsigned diagnostic) {
2568   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2569                  Sema::ForRedeclaration);
2570   if (!SemaRef.LookupName(R, S)) return false;
2571
2572   if (R.getAsSingle<TagDecl>())
2573     return false;
2574
2575   // Pick a representative declaration.
2576   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2577   assert(PrevDecl && "Expected a non-null Decl");
2578
2579   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2580     return false;
2581
2582   SemaRef.Diag(NameLoc, diagnostic) << Name;
2583   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2584
2585   return true;
2586 }
2587
2588 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
2589 /// anonymous struct or union AnonRecord into the owning context Owner
2590 /// and scope S. This routine will be invoked just after we realize
2591 /// that an unnamed union or struct is actually an anonymous union or
2592 /// struct, e.g.,
2593 ///
2594 /// @code
2595 /// union {
2596 ///   int i;
2597 ///   float f;
2598 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2599 ///    // f into the surrounding scope.x
2600 /// @endcode
2601 ///
2602 /// This routine is recursive, injecting the names of nested anonymous
2603 /// structs/unions into the owning context and scope as well.
2604 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2605                                                 DeclContext *Owner,
2606                                                 RecordDecl *AnonRecord,
2607                                                 AccessSpecifier AS,
2608                               SmallVector<NamedDecl*, 2> &Chaining,
2609                                                       bool MSAnonStruct) {
2610   unsigned diagKind
2611     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2612                             : diag::err_anonymous_struct_member_redecl;
2613
2614   bool Invalid = false;
2615
2616   // Look every FieldDecl and IndirectFieldDecl with a name.
2617   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2618                                DEnd = AnonRecord->decls_end();
2619        D != DEnd; ++D) {
2620     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2621         cast<NamedDecl>(*D)->getDeclName()) {
2622       ValueDecl *VD = cast<ValueDecl>(*D);
2623       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2624                                        VD->getLocation(), diagKind)) {
2625         // C++ [class.union]p2:
2626         //   The names of the members of an anonymous union shall be
2627         //   distinct from the names of any other entity in the
2628         //   scope in which the anonymous union is declared.
2629         Invalid = true;
2630       } else {
2631         // C++ [class.union]p2:
2632         //   For the purpose of name lookup, after the anonymous union
2633         //   definition, the members of the anonymous union are
2634         //   considered to have been defined in the scope in which the
2635         //   anonymous union is declared.
2636         unsigned OldChainingSize = Chaining.size();
2637         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2638           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2639                PE = IF->chain_end(); PI != PE; ++PI)
2640             Chaining.push_back(*PI);
2641         else
2642           Chaining.push_back(VD);
2643
2644         assert(Chaining.size() >= 2);
2645         NamedDecl **NamedChain =
2646           new (SemaRef.Context)NamedDecl*[Chaining.size()];
2647         for (unsigned i = 0; i < Chaining.size(); i++)
2648           NamedChain[i] = Chaining[i];
2649
2650         IndirectFieldDecl* IndirectField =
2651           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2652                                     VD->getIdentifier(), VD->getType(),
2653                                     NamedChain, Chaining.size());
2654
2655         IndirectField->setAccess(AS);
2656         IndirectField->setImplicit();
2657         SemaRef.PushOnScopeChains(IndirectField, S);
2658
2659         // That includes picking up the appropriate access specifier.
2660         if (AS != AS_none) IndirectField->setAccess(AS);
2661
2662         Chaining.resize(OldChainingSize);
2663       }
2664     }
2665   }
2666
2667   return Invalid;
2668 }
2669
2670 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2671 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
2672 /// illegal input values are mapped to SC_None.
2673 static StorageClass
2674 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2675   switch (StorageClassSpec) {
2676   case DeclSpec::SCS_unspecified:    return SC_None;
2677   case DeclSpec::SCS_extern:         return SC_Extern;
2678   case DeclSpec::SCS_static:         return SC_Static;
2679   case DeclSpec::SCS_auto:           return SC_Auto;
2680   case DeclSpec::SCS_register:       return SC_Register;
2681   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2682     // Illegal SCSs map to None: error reporting is up to the caller.
2683   case DeclSpec::SCS_mutable:        // Fall through.
2684   case DeclSpec::SCS_typedef:        return SC_None;
2685   }
2686   llvm_unreachable("unknown storage class specifier");
2687 }
2688
2689 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2690 /// a StorageClass. Any error reporting is up to the caller:
2691 /// illegal input values are mapped to SC_None.
2692 static StorageClass
2693 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2694   switch (StorageClassSpec) {
2695   case DeclSpec::SCS_unspecified:    return SC_None;
2696   case DeclSpec::SCS_extern:         return SC_Extern;
2697   case DeclSpec::SCS_static:         return SC_Static;
2698   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2699     // Illegal SCSs map to None: error reporting is up to the caller.
2700   case DeclSpec::SCS_auto:           // Fall through.
2701   case DeclSpec::SCS_mutable:        // Fall through.
2702   case DeclSpec::SCS_register:       // Fall through.
2703   case DeclSpec::SCS_typedef:        return SC_None;
2704   }
2705   llvm_unreachable("unknown storage class specifier");
2706 }
2707
2708 /// BuildAnonymousStructOrUnion - Handle the declaration of an
2709 /// anonymous structure or union. Anonymous unions are a C++ feature
2710 /// (C++ [class.union]) and a C11 feature; anonymous structures
2711 /// are a C11 feature and GNU C++ extension.
2712 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2713                                              AccessSpecifier AS,
2714                                              RecordDecl *Record) {
2715   DeclContext *Owner = Record->getDeclContext();
2716
2717   // Diagnose whether this anonymous struct/union is an extension.
2718   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2719     Diag(Record->getLocation(), diag::ext_anonymous_union);
2720   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2721     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
2722   else if (!Record->isUnion() && !getLangOpts().C11)
2723     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
2724
2725   // C and C++ require different kinds of checks for anonymous
2726   // structs/unions.
2727   bool Invalid = false;
2728   if (getLangOpts().CPlusPlus) {
2729     const char* PrevSpec = 0;
2730     unsigned DiagID;
2731     if (Record->isUnion()) {
2732       // C++ [class.union]p6:
2733       //   Anonymous unions declared in a named namespace or in the
2734       //   global namespace shall be declared static.
2735       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2736           (isa<TranslationUnitDecl>(Owner) ||
2737            (isa<NamespaceDecl>(Owner) &&
2738             cast<NamespaceDecl>(Owner)->getDeclName()))) {
2739         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2740           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
2741   
2742         // Recover by adding 'static'.
2743         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2744                                PrevSpec, DiagID);
2745       }
2746       // C++ [class.union]p6:
2747       //   A storage class is not allowed in a declaration of an
2748       //   anonymous union in a class scope.
2749       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2750                isa<RecordDecl>(Owner)) {
2751         Diag(DS.getStorageClassSpecLoc(),
2752              diag::err_anonymous_union_with_storage_spec)
2753           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2754   
2755         // Recover by removing the storage specifier.
2756         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 
2757                                SourceLocation(),
2758                                PrevSpec, DiagID);
2759       }
2760     }
2761
2762     // Ignore const/volatile/restrict qualifiers.
2763     if (DS.getTypeQualifiers()) {
2764       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2765         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2766           << Record->isUnion() << 0 
2767           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2768       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2769         Diag(DS.getVolatileSpecLoc(), 
2770              diag::ext_anonymous_struct_union_qualified)
2771           << Record->isUnion() << 1
2772           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2773       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2774         Diag(DS.getRestrictSpecLoc(), 
2775              diag::ext_anonymous_struct_union_qualified)
2776           << Record->isUnion() << 2 
2777           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2778
2779       DS.ClearTypeQualifiers();
2780     }
2781
2782     // C++ [class.union]p2:
2783     //   The member-specification of an anonymous union shall only
2784     //   define non-static data members. [Note: nested types and
2785     //   functions cannot be declared within an anonymous union. ]
2786     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2787                                  MemEnd = Record->decls_end();
2788          Mem != MemEnd; ++Mem) {
2789       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2790         // C++ [class.union]p3:
2791         //   An anonymous union shall not have private or protected
2792         //   members (clause 11).
2793         assert(FD->getAccess() != AS_none);
2794         if (FD->getAccess() != AS_public) {
2795           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2796             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2797           Invalid = true;
2798         }
2799
2800         // C++ [class.union]p1
2801         //   An object of a class with a non-trivial constructor, a non-trivial
2802         //   copy constructor, a non-trivial destructor, or a non-trivial copy
2803         //   assignment operator cannot be a member of a union, nor can an
2804         //   array of such objects.
2805         if (CheckNontrivialField(FD))
2806           Invalid = true;
2807       } else if ((*Mem)->isImplicit()) {
2808         // Any implicit members are fine.
2809       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2810         // This is a type that showed up in an
2811         // elaborated-type-specifier inside the anonymous struct or
2812         // union, but which actually declares a type outside of the
2813         // anonymous struct or union. It's okay.
2814       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2815         if (!MemRecord->isAnonymousStructOrUnion() &&
2816             MemRecord->getDeclName()) {
2817           // Visual C++ allows type definition in anonymous struct or union.
2818           if (getLangOpts().MicrosoftExt)
2819             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2820               << (int)Record->isUnion();
2821           else {
2822             // This is a nested type declaration.
2823             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2824               << (int)Record->isUnion();
2825             Invalid = true;
2826           }
2827         }
2828       } else if (isa<AccessSpecDecl>(*Mem)) {
2829         // Any access specifier is fine.
2830       } else {
2831         // We have something that isn't a non-static data
2832         // member. Complain about it.
2833         unsigned DK = diag::err_anonymous_record_bad_member;
2834         if (isa<TypeDecl>(*Mem))
2835           DK = diag::err_anonymous_record_with_type;
2836         else if (isa<FunctionDecl>(*Mem))
2837           DK = diag::err_anonymous_record_with_function;
2838         else if (isa<VarDecl>(*Mem))
2839           DK = diag::err_anonymous_record_with_static;
2840         
2841         // Visual C++ allows type definition in anonymous struct or union.
2842         if (getLangOpts().MicrosoftExt &&
2843             DK == diag::err_anonymous_record_with_type)
2844           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
2845             << (int)Record->isUnion();
2846         else {
2847           Diag((*Mem)->getLocation(), DK)
2848               << (int)Record->isUnion();
2849           Invalid = true;
2850         }
2851       }
2852     }
2853   }
2854
2855   if (!Record->isUnion() && !Owner->isRecord()) {
2856     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2857       << (int)getLangOpts().CPlusPlus;
2858     Invalid = true;
2859   }
2860
2861   // Mock up a declarator.
2862   Declarator Dc(DS, Declarator::MemberContext);
2863   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2864   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2865
2866   // Create a declaration for this anonymous struct/union.
2867   NamedDecl *Anon = 0;
2868   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2869     Anon = FieldDecl::Create(Context, OwningClass,
2870                              DS.getLocStart(),
2871                              Record->getLocation(),
2872                              /*IdentifierInfo=*/0,
2873                              Context.getTypeDeclType(Record),
2874                              TInfo,
2875                              /*BitWidth=*/0, /*Mutable=*/false,
2876                              /*HasInit=*/false);
2877     Anon->setAccess(AS);
2878     if (getLangOpts().CPlusPlus)
2879       FieldCollector->Add(cast<FieldDecl>(Anon));
2880   } else {
2881     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2882     assert(SCSpec != DeclSpec::SCS_typedef &&
2883            "Parser allowed 'typedef' as storage class VarDecl.");
2884     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2885     if (SCSpec == DeclSpec::SCS_mutable) {
2886       // mutable can only appear on non-static class members, so it's always
2887       // an error here
2888       Diag(Record->getLocation(), diag::err_mutable_nonmember);
2889       Invalid = true;
2890       SC = SC_None;
2891     }
2892     SCSpec = DS.getStorageClassSpecAsWritten();
2893     VarDecl::StorageClass SCAsWritten
2894       = StorageClassSpecToVarDeclStorageClass(SCSpec);
2895
2896     Anon = VarDecl::Create(Context, Owner,
2897                            DS.getLocStart(),
2898                            Record->getLocation(), /*IdentifierInfo=*/0,
2899                            Context.getTypeDeclType(Record),
2900                            TInfo, SC, SCAsWritten);
2901
2902     // Default-initialize the implicit variable. This initialization will be
2903     // trivial in almost all cases, except if a union member has an in-class
2904     // initializer:
2905     //   union { int n = 0; };
2906     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
2907   }
2908   Anon->setImplicit();
2909
2910   // Add the anonymous struct/union object to the current
2911   // context. We'll be referencing this object when we refer to one of
2912   // its members.
2913   Owner->addDecl(Anon);
2914   
2915   // Inject the members of the anonymous struct/union into the owning
2916   // context and into the identifier resolver chain for name lookup
2917   // purposes.
2918   SmallVector<NamedDecl*, 2> Chain;
2919   Chain.push_back(Anon);
2920
2921   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2922                                           Chain, false))
2923     Invalid = true;
2924
2925   // Mark this as an anonymous struct/union type. Note that we do not
2926   // do this until after we have already checked and injected the
2927   // members of this anonymous struct/union type, because otherwise
2928   // the members could be injected twice: once by DeclContext when it
2929   // builds its lookup table, and once by
2930   // InjectAnonymousStructOrUnionMembers.
2931   Record->setAnonymousStructOrUnion(true);
2932
2933   if (Invalid)
2934     Anon->setInvalidDecl();
2935
2936   return Anon;
2937 }
2938
2939 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2940 /// Microsoft C anonymous structure.
2941 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2942 /// Example:
2943 ///
2944 /// struct A { int a; };
2945 /// struct B { struct A; int b; };
2946 ///
2947 /// void foo() {
2948 ///   B var;
2949 ///   var.a = 3; 
2950 /// }
2951 ///
2952 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2953                                            RecordDecl *Record) {
2954   
2955   // If there is no Record, get the record via the typedef.
2956   if (!Record)
2957     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2958
2959   // Mock up a declarator.
2960   Declarator Dc(DS, Declarator::TypeNameContext);
2961   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2962   assert(TInfo && "couldn't build declarator info for anonymous struct");
2963
2964   // Create a declaration for this anonymous struct.
2965   NamedDecl* Anon = FieldDecl::Create(Context,
2966                              cast<RecordDecl>(CurContext),
2967                              DS.getLocStart(),
2968                              DS.getLocStart(),
2969                              /*IdentifierInfo=*/0,
2970                              Context.getTypeDeclType(Record),
2971                              TInfo,
2972                              /*BitWidth=*/0, /*Mutable=*/false,
2973                              /*HasInit=*/false);
2974   Anon->setImplicit();
2975
2976   // Add the anonymous struct object to the current context.
2977   CurContext->addDecl(Anon);
2978
2979   // Inject the members of the anonymous struct into the current
2980   // context and into the identifier resolver chain for name lookup
2981   // purposes.
2982   SmallVector<NamedDecl*, 2> Chain;
2983   Chain.push_back(Anon);
2984
2985   RecordDecl *RecordDef = Record->getDefinition();
2986   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2987                                                         RecordDef, AS_none,
2988                                                         Chain, true))
2989     Anon->setInvalidDecl();
2990
2991   return Anon;
2992 }
2993
2994 /// GetNameForDeclarator - Determine the full declaration name for the
2995 /// given Declarator.
2996 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2997   return GetNameFromUnqualifiedId(D.getName());
2998 }
2999
3000 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3001 DeclarationNameInfo
3002 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3003   DeclarationNameInfo NameInfo;
3004   NameInfo.setLoc(Name.StartLocation);
3005
3006   switch (Name.getKind()) {
3007
3008   case UnqualifiedId::IK_ImplicitSelfParam:
3009   case UnqualifiedId::IK_Identifier:
3010     NameInfo.setName(Name.Identifier);
3011     NameInfo.setLoc(Name.StartLocation);
3012     return NameInfo;
3013
3014   case UnqualifiedId::IK_OperatorFunctionId:
3015     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3016                                            Name.OperatorFunctionId.Operator));
3017     NameInfo.setLoc(Name.StartLocation);
3018     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3019       = Name.OperatorFunctionId.SymbolLocations[0];
3020     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3021       = Name.EndLocation.getRawEncoding();
3022     return NameInfo;
3023
3024   case UnqualifiedId::IK_LiteralOperatorId:
3025     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3026                                                            Name.Identifier));
3027     NameInfo.setLoc(Name.StartLocation);
3028     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3029     return NameInfo;
3030
3031   case UnqualifiedId::IK_ConversionFunctionId: {
3032     TypeSourceInfo *TInfo;
3033     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3034     if (Ty.isNull())
3035       return DeclarationNameInfo();
3036     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3037                                                Context.getCanonicalType(Ty)));
3038     NameInfo.setLoc(Name.StartLocation);
3039     NameInfo.setNamedTypeInfo(TInfo);
3040     return NameInfo;
3041   }
3042
3043   case UnqualifiedId::IK_ConstructorName: {
3044     TypeSourceInfo *TInfo;
3045     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3046     if (Ty.isNull())
3047       return DeclarationNameInfo();
3048     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3049                                               Context.getCanonicalType(Ty)));
3050     NameInfo.setLoc(Name.StartLocation);
3051     NameInfo.setNamedTypeInfo(TInfo);
3052     return NameInfo;
3053   }
3054
3055   case UnqualifiedId::IK_ConstructorTemplateId: {
3056     // In well-formed code, we can only have a constructor
3057     // template-id that refers to the current context, so go there
3058     // to find the actual type being constructed.
3059     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3060     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3061       return DeclarationNameInfo();
3062
3063     // Determine the type of the class being constructed.
3064     QualType CurClassType = Context.getTypeDeclType(CurClass);
3065
3066     // FIXME: Check two things: that the template-id names the same type as
3067     // CurClassType, and that the template-id does not occur when the name
3068     // was qualified.
3069
3070     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3071                                     Context.getCanonicalType(CurClassType)));
3072     NameInfo.setLoc(Name.StartLocation);
3073     // FIXME: should we retrieve TypeSourceInfo?
3074     NameInfo.setNamedTypeInfo(0);
3075     return NameInfo;
3076   }
3077
3078   case UnqualifiedId::IK_DestructorName: {
3079     TypeSourceInfo *TInfo;
3080     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3081     if (Ty.isNull())
3082       return DeclarationNameInfo();
3083     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3084                                               Context.getCanonicalType(Ty)));
3085     NameInfo.setLoc(Name.StartLocation);
3086     NameInfo.setNamedTypeInfo(TInfo);
3087     return NameInfo;
3088   }
3089
3090   case UnqualifiedId::IK_TemplateId: {
3091     TemplateName TName = Name.TemplateId->Template.get();
3092     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3093     return Context.getNameForTemplate(TName, TNameLoc);
3094   }
3095
3096   } // switch (Name.getKind())
3097
3098   llvm_unreachable("Unknown name kind");
3099 }
3100
3101 static QualType getCoreType(QualType Ty) {
3102   do {
3103     if (Ty->isPointerType() || Ty->isReferenceType())
3104       Ty = Ty->getPointeeType();
3105     else if (Ty->isArrayType())
3106       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3107     else
3108       return Ty.withoutLocalFastQualifiers();
3109   } while (true);
3110 }
3111
3112 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3113 /// and Definition have "nearly" matching parameters. This heuristic is
3114 /// used to improve diagnostics in the case where an out-of-line function
3115 /// definition doesn't match any declaration within the class or namespace.
3116 /// Also sets Params to the list of indices to the parameters that differ
3117 /// between the declaration and the definition. If hasSimilarParameters
3118 /// returns true and Params is empty, then all of the parameters match.
3119 static bool hasSimilarParameters(ASTContext &Context,
3120                                      FunctionDecl *Declaration,
3121                                      FunctionDecl *Definition,
3122                                      llvm::SmallVectorImpl<unsigned> &Params) {
3123   Params.clear();
3124   if (Declaration->param_size() != Definition->param_size())
3125     return false;
3126   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3127     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3128     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3129
3130     // The parameter types are identical
3131     if (Context.hasSameType(DefParamTy, DeclParamTy))
3132       continue;
3133
3134     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3135     QualType DefParamBaseTy = getCoreType(DefParamTy);
3136     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3137     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3138
3139     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3140         (DeclTyName && DeclTyName == DefTyName))
3141       Params.push_back(Idx);
3142     else  // The two parameters aren't even close
3143       return false;
3144   }
3145
3146   return true;
3147 }
3148
3149 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3150 /// declarator needs to be rebuilt in the current instantiation.
3151 /// Any bits of declarator which appear before the name are valid for
3152 /// consideration here.  That's specifically the type in the decl spec
3153 /// and the base type in any member-pointer chunks.
3154 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3155                                                     DeclarationName Name) {
3156   // The types we specifically need to rebuild are:
3157   //   - typenames, typeofs, and decltypes
3158   //   - types which will become injected class names
3159   // Of course, we also need to rebuild any type referencing such a
3160   // type.  It's safest to just say "dependent", but we call out a
3161   // few cases here.
3162
3163   DeclSpec &DS = D.getMutableDeclSpec();
3164   switch (DS.getTypeSpecType()) {
3165   case DeclSpec::TST_typename:
3166   case DeclSpec::TST_typeofType:
3167   case DeclSpec::TST_decltype:
3168   case DeclSpec::TST_underlyingType:
3169   case DeclSpec::TST_atomic: {
3170     // Grab the type from the parser.
3171     TypeSourceInfo *TSI = 0;
3172     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3173     if (T.isNull() || !T->isDependentType()) break;
3174
3175     // Make sure there's a type source info.  This isn't really much
3176     // of a waste; most dependent types should have type source info
3177     // attached already.
3178     if (!TSI)
3179       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3180
3181     // Rebuild the type in the current instantiation.
3182     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3183     if (!TSI) return true;
3184
3185     // Store the new type back in the decl spec.
3186     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3187     DS.UpdateTypeRep(LocType);
3188     break;
3189   }
3190
3191   case DeclSpec::TST_typeofExpr: {
3192     Expr *E = DS.getRepAsExpr();
3193     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3194     if (Result.isInvalid()) return true;
3195     DS.UpdateExprRep(Result.get());
3196     break;
3197   }
3198
3199   default:
3200     // Nothing to do for these decl specs.
3201     break;
3202   }
3203
3204   // It doesn't matter what order we do this in.
3205   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3206     DeclaratorChunk &Chunk = D.getTypeObject(I);
3207
3208     // The only type information in the declarator which can come
3209     // before the declaration name is the base type of a member
3210     // pointer.
3211     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3212       continue;
3213
3214     // Rebuild the scope specifier in-place.
3215     CXXScopeSpec &SS = Chunk.Mem.Scope();
3216     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3217       return true;
3218   }
3219
3220   return false;
3221 }
3222
3223 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3224   D.setFunctionDefinitionKind(FDK_Declaration);
3225   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3226
3227   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3228       Dcl->getDeclContext()->isFileContext())
3229     Dcl->setTopLevelDeclInObjCContainer();
3230
3231   return Dcl;
3232 }
3233
3234 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3235 ///   If T is the name of a class, then each of the following shall have a 
3236 ///   name different from T:
3237 ///     - every static data member of class T;
3238 ///     - every member function of class T
3239 ///     - every member of class T that is itself a type;
3240 /// \returns true if the declaration name violates these rules.
3241 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3242                                    DeclarationNameInfo NameInfo) {
3243   DeclarationName Name = NameInfo.getName();
3244
3245   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 
3246     if (Record->getIdentifier() && Record->getDeclName() == Name) {
3247       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3248       return true;
3249     }
3250
3251   return false;
3252 }
3253
3254 /// \brief Diagnose a declaration whose declarator-id has the given 
3255 /// nested-name-specifier.
3256 ///
3257 /// \param SS The nested-name-specifier of the declarator-id.
3258 ///
3259 /// \param DC The declaration context to which the nested-name-specifier 
3260 /// resolves.
3261 ///
3262 /// \param Name The name of the entity being declared.
3263 ///
3264 /// \param Loc The location of the name of the entity being declared.
3265 ///
3266 /// \returns true if we cannot safely recover from this error, false otherwise.
3267 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3268                                         DeclarationName Name,
3269                                       SourceLocation Loc) {
3270   DeclContext *Cur = CurContext;
3271   while (isa<LinkageSpecDecl>(Cur))
3272     Cur = Cur->getParent();
3273   
3274   // C++ [dcl.meaning]p1:
3275   //   A declarator-id shall not be qualified except for the definition
3276   //   of a member function (9.3) or static data member (9.4) outside of
3277   //   its class, the definition or explicit instantiation of a function 
3278   //   or variable member of a namespace outside of its namespace, or the
3279   //   definition of an explicit specialization outside of its namespace,
3280   //   or the declaration of a friend function that is a member of 
3281   //   another class or namespace (11.3). [...]
3282     
3283   // The user provided a superfluous scope specifier that refers back to the
3284   // class or namespaces in which the entity is already declared.
3285   //
3286   // class X {
3287   //   void X::f();
3288   // };
3289   if (Cur->Equals(DC)) {
3290     Diag(Loc, diag::warn_member_extra_qualification)
3291       << Name << FixItHint::CreateRemoval(SS.getRange());
3292     SS.clear();
3293     return false;
3294   } 
3295
3296   // Check whether the qualifying scope encloses the scope of the original
3297   // declaration.
3298   if (!Cur->Encloses(DC)) {
3299     if (Cur->isRecord())
3300       Diag(Loc, diag::err_member_qualification)
3301         << Name << SS.getRange();
3302     else if (isa<TranslationUnitDecl>(DC))
3303       Diag(Loc, diag::err_invalid_declarator_global_scope)
3304         << Name << SS.getRange();
3305     else if (isa<FunctionDecl>(Cur))
3306       Diag(Loc, diag::err_invalid_declarator_in_function) 
3307         << Name << SS.getRange();
3308     else
3309       Diag(Loc, diag::err_invalid_declarator_scope)
3310       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3311     
3312     return true;
3313   }
3314
3315   if (Cur->isRecord()) {
3316     // Cannot qualify members within a class.
3317     Diag(Loc, diag::err_member_qualification)
3318       << Name << SS.getRange();
3319     SS.clear();
3320     
3321     // C++ constructors and destructors with incorrect scopes can break
3322     // our AST invariants by having the wrong underlying types. If
3323     // that's the case, then drop this declaration entirely.
3324     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3325          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3326         !Context.hasSameType(Name.getCXXNameType(),
3327                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3328       return true;
3329     
3330     return false;
3331   }
3332   
3333   // C++11 [dcl.meaning]p1:
3334   //   [...] "The nested-name-specifier of the qualified declarator-id shall
3335   //   not begin with a decltype-specifer"
3336   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3337   while (SpecLoc.getPrefix())
3338     SpecLoc = SpecLoc.getPrefix();
3339   if (dyn_cast_or_null<DecltypeType>(
3340         SpecLoc.getNestedNameSpecifier()->getAsType()))
3341     Diag(Loc, diag::err_decltype_in_declarator)
3342       << SpecLoc.getTypeLoc().getSourceRange();
3343
3344   return false;
3345 }
3346
3347 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3348                              MultiTemplateParamsArg TemplateParamLists) {
3349   // TODO: consider using NameInfo for diagnostic.
3350   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3351   DeclarationName Name = NameInfo.getName();
3352
3353   // All of these full declarators require an identifier.  If it doesn't have
3354   // one, the ParsedFreeStandingDeclSpec action should be used.
3355   if (!Name) {
3356     if (!D.isInvalidType())  // Reject this if we think it is valid.
3357       Diag(D.getDeclSpec().getLocStart(),
3358            diag::err_declarator_need_ident)
3359         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3360     return 0;
3361   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3362     return 0;
3363
3364   // The scope passed in may not be a decl scope.  Zip up the scope tree until
3365   // we find one that is.
3366   while ((S->getFlags() & Scope::DeclScope) == 0 ||
3367          (S->getFlags() & Scope::TemplateParamScope) != 0)
3368     S = S->getParent();
3369
3370   DeclContext *DC = CurContext;
3371   if (D.getCXXScopeSpec().isInvalid())
3372     D.setInvalidType();
3373   else if (D.getCXXScopeSpec().isSet()) {
3374     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 
3375                                         UPPC_DeclarationQualifier))
3376       return 0;
3377
3378     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3379     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3380     if (!DC) {
3381       // If we could not compute the declaration context, it's because the
3382       // declaration context is dependent but does not refer to a class,
3383       // class template, or class template partial specialization. Complain
3384       // and return early, to avoid the coming semantic disaster.
3385       Diag(D.getIdentifierLoc(),
3386            diag::err_template_qualified_declarator_no_match)
3387         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3388         << D.getCXXScopeSpec().getRange();
3389       return 0;
3390     }
3391     bool IsDependentContext = DC->isDependentContext();
3392
3393     if (!IsDependentContext && 
3394         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3395       return 0;
3396
3397     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3398       Diag(D.getIdentifierLoc(),
3399            diag::err_member_def_undefined_record)
3400         << Name << DC << D.getCXXScopeSpec().getRange();
3401       D.setInvalidType();
3402     } else if (!D.getDeclSpec().isFriendSpecified()) {
3403       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3404                                       Name, D.getIdentifierLoc())) {
3405         if (DC->isRecord())
3406           return 0;
3407         
3408         D.setInvalidType();
3409       }
3410     }
3411
3412     // Check whether we need to rebuild the type of the given
3413     // declaration in the current instantiation.
3414     if (EnteringContext && IsDependentContext &&
3415         TemplateParamLists.size() != 0) {
3416       ContextRAII SavedContext(*this, DC);
3417       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3418         D.setInvalidType();
3419     }
3420   }
3421
3422   if (DiagnoseClassNameShadow(DC, NameInfo))
3423     // If this is a typedef, we'll end up spewing multiple diagnostics.
3424     // Just return early; it's safer.
3425     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3426       return 0;
3427   
3428   NamedDecl *New;
3429
3430   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3431   QualType R = TInfo->getType();
3432
3433   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3434                                       UPPC_DeclarationType))
3435     D.setInvalidType();
3436
3437   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3438                         ForRedeclaration);
3439
3440   // See if this is a redefinition of a variable in the same scope.
3441   if (!D.getCXXScopeSpec().isSet()) {
3442     bool IsLinkageLookup = false;
3443
3444     // If the declaration we're planning to build will be a function
3445     // or object with linkage, then look for another declaration with
3446     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3447     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3448       /* Do nothing*/;
3449     else if (R->isFunctionType()) {
3450       if (CurContext->isFunctionOrMethod() ||
3451           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3452         IsLinkageLookup = true;
3453     } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3454       IsLinkageLookup = true;
3455     else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3456              D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3457       IsLinkageLookup = true;
3458
3459     if (IsLinkageLookup)
3460       Previous.clear(LookupRedeclarationWithLinkage);
3461
3462     LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3463   } else { // Something like "int foo::x;"
3464     LookupQualifiedName(Previous, DC);
3465
3466     // C++ [dcl.meaning]p1:
3467     //   When the declarator-id is qualified, the declaration shall refer to a 
3468     //  previously declared member of the class or namespace to which the 
3469     //  qualifier refers (or, in the case of a namespace, of an element of the
3470     //  inline namespace set of that namespace (7.3.1)) or to a specialization
3471     //  thereof; [...] 
3472     //
3473     // Note that we already checked the context above, and that we do not have
3474     // enough information to make sure that Previous contains the declaration
3475     // we want to match. For example, given:
3476     //
3477     //   class X {
3478     //     void f();
3479     //     void f(float);
3480     //   };
3481     //
3482     //   void X::f(int) { } // ill-formed
3483     //
3484     // In this case, Previous will point to the overload set
3485     // containing the two f's declared in X, but neither of them
3486     // matches.
3487     
3488     // C++ [dcl.meaning]p1:
3489     //   [...] the member shall not merely have been introduced by a 
3490     //   using-declaration in the scope of the class or namespace nominated by 
3491     //   the nested-name-specifier of the declarator-id.
3492     RemoveUsingDecls(Previous);
3493   }
3494
3495   if (Previous.isSingleResult() &&
3496       Previous.getFoundDecl()->isTemplateParameter()) {
3497     // Maybe we will complain about the shadowed template parameter.
3498     if (!D.isInvalidType())
3499       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3500                                       Previous.getFoundDecl());
3501
3502     // Just pretend that we didn't see the previous declaration.
3503     Previous.clear();
3504   }
3505
3506   // In C++, the previous declaration we find might be a tag type
3507   // (class or enum). In this case, the new declaration will hide the
3508   // tag type. Note that this does does not apply if we're declaring a
3509   // typedef (C++ [dcl.typedef]p4).
3510   if (Previous.isSingleTagDecl() &&
3511       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3512     Previous.clear();
3513
3514   bool AddToScope = true;
3515   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3516     if (TemplateParamLists.size()) {
3517       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3518       return 0;
3519     }
3520
3521     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3522   } else if (R->isFunctionType()) {
3523     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3524                                   move(TemplateParamLists),
3525                                   AddToScope);
3526   } else {
3527     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3528                                   move(TemplateParamLists));
3529   }
3530
3531   if (New == 0)
3532     return 0;
3533
3534   // If this has an identifier and is not an invalid redeclaration or 
3535   // function template specialization, add it to the scope stack.
3536   if (New->getDeclName() && AddToScope &&
3537        !(D.isRedeclaration() && New->isInvalidDecl()))
3538     PushOnScopeChains(New, S);
3539
3540   return New;
3541 }
3542
3543 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3544 /// types into constant array types in certain situations which would otherwise
3545 /// be errors (for GCC compatibility).
3546 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3547                                                     ASTContext &Context,
3548                                                     bool &SizeIsNegative,
3549                                                     llvm::APSInt &Oversized) {
3550   // This method tries to turn a variable array into a constant
3551   // array even when the size isn't an ICE.  This is necessary
3552   // for compatibility with code that depends on gcc's buggy
3553   // constant expression folding, like struct {char x[(int)(char*)2];}
3554   SizeIsNegative = false;
3555   Oversized = 0;
3556   
3557   if (T->isDependentType())
3558     return QualType();
3559   
3560   QualifierCollector Qs;
3561   const Type *Ty = Qs.strip(T);
3562
3563   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3564     QualType Pointee = PTy->getPointeeType();
3565     QualType FixedType =
3566         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3567                                             Oversized);
3568     if (FixedType.isNull()) return FixedType;
3569     FixedType = Context.getPointerType(FixedType);
3570     return Qs.apply(Context, FixedType);
3571   }
3572   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3573     QualType Inner = PTy->getInnerType();
3574     QualType FixedType =
3575         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3576                                             Oversized);
3577     if (FixedType.isNull()) return FixedType;
3578     FixedType = Context.getParenType(FixedType);
3579     return Qs.apply(Context, FixedType);
3580   }
3581
3582   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3583   if (!VLATy)
3584     return QualType();
3585   // FIXME: We should probably handle this case
3586   if (VLATy->getElementType()->isVariablyModifiedType())
3587     return QualType();
3588
3589   llvm::APSInt Res;
3590   if (!VLATy->getSizeExpr() ||
3591       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3592     return QualType();
3593
3594   // Check whether the array size is negative.
3595   if (Res.isSigned() && Res.isNegative()) {
3596     SizeIsNegative = true;
3597     return QualType();
3598   }
3599
3600   // Check whether the array is too large to be addressed.
3601   unsigned ActiveSizeBits
3602     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3603                                               Res);
3604   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3605     Oversized = Res;
3606     return QualType();
3607   }
3608   
3609   return Context.getConstantArrayType(VLATy->getElementType(),
3610                                       Res, ArrayType::Normal, 0);
3611 }
3612
3613 /// \brief Register the given locally-scoped external C declaration so
3614 /// that it can be found later for redeclarations
3615 void
3616 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3617                                        const LookupResult &Previous,
3618                                        Scope *S) {
3619   assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3620          "Decl is not a locally-scoped decl!");
3621   // Note that we have a locally-scoped external with this name.
3622   LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3623
3624   if (!Previous.isSingleResult())
3625     return;
3626
3627   NamedDecl *PrevDecl = Previous.getFoundDecl();
3628
3629   // If there was a previous declaration of this variable, it may be
3630   // in our identifier chain. Update the identifier chain with the new
3631   // declaration.
3632   if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3633     // The previous declaration was found on the identifer resolver
3634     // chain, so remove it from its scope.
3635
3636     if (S->isDeclScope(PrevDecl)) {
3637       // Special case for redeclarations in the SAME scope.
3638       // Because this declaration is going to be added to the identifier chain
3639       // later, we should temporarily take it OFF the chain.
3640       IdResolver.RemoveDecl(ND);
3641
3642     } else {
3643       // Find the scope for the original declaration.
3644       while (S && !S->isDeclScope(PrevDecl))
3645         S = S->getParent();
3646     }
3647
3648     if (S)
3649       S->RemoveDecl(PrevDecl);
3650   }
3651 }
3652
3653 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3654 Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3655   if (ExternalSource) {
3656     // Load locally-scoped external decls from the external source.
3657     SmallVector<NamedDecl *, 4> Decls;
3658     ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3659     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3660       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3661         = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3662       if (Pos == LocallyScopedExternalDecls.end())
3663         LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3664     }
3665   }
3666   
3667   return LocallyScopedExternalDecls.find(Name);
3668 }
3669
3670 /// \brief Diagnose function specifiers on a declaration of an identifier that
3671 /// does not identify a function.
3672 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3673   // FIXME: We should probably indicate the identifier in question to avoid
3674   // confusion for constructs like "inline int a(), b;"
3675   if (D.getDeclSpec().isInlineSpecified())
3676     Diag(D.getDeclSpec().getInlineSpecLoc(),
3677          diag::err_inline_non_function);
3678
3679   if (D.getDeclSpec().isVirtualSpecified())
3680     Diag(D.getDeclSpec().getVirtualSpecLoc(),
3681          diag::err_virtual_non_function);
3682
3683   if (D.getDeclSpec().isExplicitSpecified())
3684     Diag(D.getDeclSpec().getExplicitSpecLoc(),
3685          diag::err_explicit_non_function);
3686 }
3687
3688 NamedDecl*
3689 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3690                              TypeSourceInfo *TInfo, LookupResult &Previous) {
3691   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3692   if (D.getCXXScopeSpec().isSet()) {
3693     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3694       << D.getCXXScopeSpec().getRange();
3695     D.setInvalidType();
3696     // Pretend we didn't see the scope specifier.
3697     DC = CurContext;
3698     Previous.clear();
3699   }
3700
3701   if (getLangOpts().CPlusPlus) {
3702     // Check that there are no default arguments (C++ only).
3703     CheckExtraCXXDefaultArguments(D);
3704   }
3705
3706   DiagnoseFunctionSpecifiers(D);
3707
3708   if (D.getDeclSpec().isThreadSpecified())
3709     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3710   if (D.getDeclSpec().isConstexprSpecified())
3711     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3712       << 1;
3713
3714   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3715     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3716       << D.getName().getSourceRange();
3717     return 0;
3718   }
3719
3720   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
3721   if (!NewTD) return 0;
3722
3723   // Handle attributes prior to checking for duplicates in MergeVarDecl
3724   ProcessDeclAttributes(S, NewTD, D);
3725
3726   CheckTypedefForVariablyModifiedType(S, NewTD);
3727
3728   bool Redeclaration = D.isRedeclaration();
3729   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3730   D.setRedeclaration(Redeclaration);
3731   return ND;
3732 }
3733
3734 void
3735 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
3736   // C99 6.7.7p2: If a typedef name specifies a variably modified type
3737   // then it shall have block scope.
3738   // Note that variably modified types must be fixed before merging the decl so
3739   // that redeclarations will match.
3740   QualType T = NewTD->getUnderlyingType();
3741   if (T->isVariablyModifiedType()) {
3742     getCurFunction()->setHasBranchProtectedScope();
3743
3744     if (S->getFnParent() == 0) {
3745       bool SizeIsNegative;
3746       llvm::APSInt Oversized;
3747       QualType FixedTy =
3748           TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3749                                               Oversized);
3750       if (!FixedTy.isNull()) {
3751         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
3752         NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
3753       } else {
3754         if (SizeIsNegative)
3755           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
3756         else if (T->isVariableArrayType())
3757           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
3758         else if (Oversized.getBoolValue())
3759           Diag(NewTD->getLocation(), diag::err_array_too_large) 
3760             << Oversized.toString(10);
3761         else
3762           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
3763         NewTD->setInvalidDecl();
3764       }
3765     }
3766   }
3767 }
3768
3769
3770 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3771 /// declares a typedef-name, either using the 'typedef' type specifier or via
3772 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3773 NamedDecl*
3774 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3775                            LookupResult &Previous, bool &Redeclaration) {
3776   // Merge the decl with the existing one if appropriate. If the decl is
3777   // in an outer scope, it isn't the same thing.
3778   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
3779                        /*ExplicitInstantiationOrSpecialization=*/false);
3780   if (!Previous.empty()) {
3781     Redeclaration = true;
3782     MergeTypedefNameDecl(NewTD, Previous);
3783   }
3784
3785   // If this is the C FILE type, notify the AST context.
3786   if (IdentifierInfo *II = NewTD->getIdentifier())
3787     if (!NewTD->isInvalidDecl() &&
3788         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
3789       if (II->isStr("FILE"))
3790         Context.setFILEDecl(NewTD);
3791       else if (II->isStr("jmp_buf"))
3792         Context.setjmp_bufDecl(NewTD);
3793       else if (II->isStr("sigjmp_buf"))
3794         Context.setsigjmp_bufDecl(NewTD);
3795       else if (II->isStr("ucontext_t"))
3796         Context.setucontext_tDecl(NewTD);
3797       else if (II->isStr("__builtin_va_list"))
3798         Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
3799     }
3800
3801   return NewTD;
3802 }
3803
3804 /// \brief Determines whether the given declaration is an out-of-scope
3805 /// previous declaration.
3806 ///
3807 /// This routine should be invoked when name lookup has found a
3808 /// previous declaration (PrevDecl) that is not in the scope where a
3809 /// new declaration by the same name is being introduced. If the new
3810 /// declaration occurs in a local scope, previous declarations with
3811 /// linkage may still be considered previous declarations (C99
3812 /// 6.2.2p4-5, C++ [basic.link]p6).
3813 ///
3814 /// \param PrevDecl the previous declaration found by name
3815 /// lookup
3816 ///
3817 /// \param DC the context in which the new declaration is being
3818 /// declared.
3819 ///
3820 /// \returns true if PrevDecl is an out-of-scope previous declaration
3821 /// for a new delcaration with the same name.
3822 static bool
3823 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3824                                 ASTContext &Context) {
3825   if (!PrevDecl)
3826     return false;
3827
3828   if (!PrevDecl->hasLinkage())
3829     return false;
3830
3831   if (Context.getLangOpts().CPlusPlus) {
3832     // C++ [basic.link]p6:
3833     //   If there is a visible declaration of an entity with linkage
3834     //   having the same name and type, ignoring entities declared
3835     //   outside the innermost enclosing namespace scope, the block
3836     //   scope declaration declares that same entity and receives the
3837     //   linkage of the previous declaration.
3838     DeclContext *OuterContext = DC->getRedeclContext();
3839     if (!OuterContext->isFunctionOrMethod())
3840       // This rule only applies to block-scope declarations.
3841       return false;
3842     
3843     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3844     if (PrevOuterContext->isRecord())
3845       // We found a member function: ignore it.
3846       return false;
3847     
3848     // Find the innermost enclosing namespace for the new and
3849     // previous declarations.
3850     OuterContext = OuterContext->getEnclosingNamespaceContext();
3851     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
3852
3853     // The previous declaration is in a different namespace, so it
3854     // isn't the same function.
3855     if (!OuterContext->Equals(PrevOuterContext))
3856       return false;
3857   }
3858
3859   return true;
3860 }
3861
3862 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3863   CXXScopeSpec &SS = D.getCXXScopeSpec();
3864   if (!SS.isSet()) return;
3865   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
3866 }
3867
3868 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3869   QualType type = decl->getType();
3870   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3871   if (lifetime == Qualifiers::OCL_Autoreleasing) {
3872     // Various kinds of declaration aren't allowed to be __autoreleasing.
3873     unsigned kind = -1U;
3874     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3875       if (var->hasAttr<BlocksAttr>())
3876         kind = 0; // __block
3877       else if (!var->hasLocalStorage())
3878         kind = 1; // global
3879     } else if (isa<ObjCIvarDecl>(decl)) {
3880       kind = 3; // ivar
3881     } else if (isa<FieldDecl>(decl)) {
3882       kind = 2; // field
3883     }
3884
3885     if (kind != -1U) {
3886       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3887         << kind;
3888     }
3889   } else if (lifetime == Qualifiers::OCL_None) {
3890     // Try to infer lifetime.
3891     if (!type->isObjCLifetimeType())
3892       return false;
3893
3894     lifetime = type->getObjCARCImplicitLifetime();
3895     type = Context.getLifetimeQualifiedType(type, lifetime);
3896     decl->setType(type);
3897   }
3898   
3899   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3900     // Thread-local variables cannot have lifetime.
3901     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3902         var->isThreadSpecified()) {
3903       Diag(var->getLocation(), diag::err_arc_thread_ownership)
3904         << var->getType();
3905       return true;
3906     }
3907   }
3908   
3909   return false;
3910 }
3911
3912 NamedDecl*
3913 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3914                               TypeSourceInfo *TInfo, LookupResult &Previous,
3915                               MultiTemplateParamsArg TemplateParamLists) {
3916   QualType R = TInfo->getType();
3917   DeclarationName Name = GetNameForDeclarator(D).getName();
3918
3919   // Check that there are no default arguments (C++ only).
3920   if (getLangOpts().CPlusPlus)
3921     CheckExtraCXXDefaultArguments(D);
3922
3923   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3924   assert(SCSpec != DeclSpec::SCS_typedef &&
3925          "Parser allowed 'typedef' as storage class VarDecl.");
3926   VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3927   if (SCSpec == DeclSpec::SCS_mutable) {
3928     // mutable can only appear on non-static class members, so it's always
3929     // an error here
3930     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
3931     D.setInvalidType();
3932     SC = SC_None;
3933   }
3934   SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3935   VarDecl::StorageClass SCAsWritten
3936     = StorageClassSpecToVarDeclStorageClass(SCSpec);
3937
3938   IdentifierInfo *II = Name.getAsIdentifierInfo();
3939   if (!II) {
3940     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3941       << Name;
3942     return 0;
3943   }
3944
3945   DiagnoseFunctionSpecifiers(D);
3946
3947   if (!DC->isRecord() && S->getFnParent() == 0) {
3948     // C99 6.9p2: The storage-class specifiers auto and register shall not
3949     // appear in the declaration specifiers in an external declaration.
3950     if (SC == SC_Auto || SC == SC_Register) {
3951
3952       // If this is a register variable with an asm label specified, then this
3953       // is a GNU extension.
3954       if (SC == SC_Register && D.getAsmLabel())
3955         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3956       else
3957         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
3958       D.setInvalidType();
3959     }
3960   }
3961   
3962   if (getLangOpts().OpenCL) {
3963     // Set up the special work-group-local storage class for variables in the
3964     // OpenCL __local address space.
3965     if (R.getAddressSpace() == LangAS::opencl_local)
3966       SC = SC_OpenCLWorkGroupLocal;
3967   }
3968
3969   bool isExplicitSpecialization = false;
3970   VarDecl *NewVD;
3971   if (!getLangOpts().CPlusPlus) {
3972     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
3973                             D.getIdentifierLoc(), II,
3974                             R, TInfo, SC, SCAsWritten);
3975   
3976     if (D.isInvalidType())
3977       NewVD->setInvalidDecl();
3978   } else {
3979     if (DC->isRecord() && !CurContext->isRecord()) {
3980       // This is an out-of-line definition of a static data member.
3981       if (SC == SC_Static) {
3982         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3983              diag::err_static_out_of_line)
3984           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3985       } else if (SC == SC_None)
3986         SC = SC_Static;
3987     }
3988     if (SC == SC_Static && CurContext->isRecord()) {
3989       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3990         if (RD->isLocalClass())
3991           Diag(D.getIdentifierLoc(),
3992                diag::err_static_data_member_not_allowed_in_local_class)
3993             << Name << RD->getDeclName();
3994
3995         // C++98 [class.union]p1: If a union contains a static data member,
3996         // the program is ill-formed. C++11 drops this restriction.
3997         if (RD->isUnion())
3998           Diag(D.getIdentifierLoc(),
3999                getLangOpts().CPlusPlus0x
4000                  ? diag::warn_cxx98_compat_static_data_member_in_union
4001                  : diag::ext_static_data_member_in_union) << Name;
4002         // We conservatively disallow static data members in anonymous structs.
4003         else if (!RD->getDeclName())
4004           Diag(D.getIdentifierLoc(),
4005                diag::err_static_data_member_not_allowed_in_anon_struct)
4006             << Name << RD->isUnion();
4007       }
4008     }
4009
4010     // Match up the template parameter lists with the scope specifier, then
4011     // determine whether we have a template or a template specialization.
4012     isExplicitSpecialization = false;
4013     bool Invalid = false;
4014     if (TemplateParameterList *TemplateParams
4015         = MatchTemplateParametersToScopeSpecifier(
4016                                   D.getDeclSpec().getLocStart(),
4017                                                   D.getIdentifierLoc(),
4018                                                   D.getCXXScopeSpec(),
4019                                                   TemplateParamLists.get(),
4020                                                   TemplateParamLists.size(),
4021                                                   /*never a friend*/ false,
4022                                                   isExplicitSpecialization,
4023                                                   Invalid)) {
4024       if (TemplateParams->size() > 0) {
4025         // There is no such thing as a variable template.
4026         Diag(D.getIdentifierLoc(), diag::err_template_variable)
4027           << II
4028           << SourceRange(TemplateParams->getTemplateLoc(),
4029                          TemplateParams->getRAngleLoc());
4030         return 0;
4031       } else {
4032         // There is an extraneous 'template<>' for this variable. Complain
4033         // about it, but allow the declaration of the variable.
4034         Diag(TemplateParams->getTemplateLoc(),
4035              diag::err_template_variable_noparams)
4036           << II
4037           << SourceRange(TemplateParams->getTemplateLoc(),
4038                          TemplateParams->getRAngleLoc());
4039       }
4040     }
4041
4042     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4043                             D.getIdentifierLoc(), II,
4044                             R, TInfo, SC, SCAsWritten);
4045
4046     // If this decl has an auto type in need of deduction, make a note of the
4047     // Decl so we can diagnose uses of it in its own initializer.
4048     if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4049         R->getContainedAutoType())
4050       ParsingInitForAutoVars.insert(NewVD);
4051
4052     if (D.isInvalidType() || Invalid)
4053       NewVD->setInvalidDecl();
4054
4055     SetNestedNameSpecifier(NewVD, D);
4056
4057     if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4058       NewVD->setTemplateParameterListsInfo(Context,
4059                                            TemplateParamLists.size(),
4060                                            TemplateParamLists.release());
4061     }
4062
4063     if (D.getDeclSpec().isConstexprSpecified())
4064       NewVD->setConstexpr(true);
4065   }
4066
4067   // Set the lexical context. If the declarator has a C++ scope specifier, the
4068   // lexical context will be different from the semantic context.
4069   NewVD->setLexicalDeclContext(CurContext);
4070
4071   if (D.getDeclSpec().isThreadSpecified()) {
4072     if (NewVD->hasLocalStorage())
4073       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4074     else if (!Context.getTargetInfo().isTLSSupported())
4075       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4076     else
4077       NewVD->setThreadSpecified(true);
4078   }
4079
4080   if (D.getDeclSpec().isModulePrivateSpecified()) {
4081     if (isExplicitSpecialization)
4082       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4083         << 2
4084         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4085     else if (NewVD->hasLocalStorage())
4086       Diag(NewVD->getLocation(), diag::err_module_private_local)
4087         << 0 << NewVD->getDeclName()
4088         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4089         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4090     else
4091       NewVD->setModulePrivate();
4092   }
4093
4094   // Handle attributes prior to checking for duplicates in MergeVarDecl
4095   ProcessDeclAttributes(S, NewVD, D);
4096
4097   // In auto-retain/release, infer strong retension for variables of
4098   // retainable type.
4099   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4100     NewVD->setInvalidDecl();
4101
4102   // Handle GNU asm-label extension (encoded as an attribute).
4103   if (Expr *E = (Expr*)D.getAsmLabel()) {
4104     // The parser guarantees this is a string.
4105     StringLiteral *SE = cast<StringLiteral>(E);
4106     StringRef Label = SE->getString();
4107     if (S->getFnParent() != 0) {
4108       switch (SC) {
4109       case SC_None:
4110       case SC_Auto:
4111         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4112         break;
4113       case SC_Register:
4114         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4115           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4116         break;
4117       case SC_Static:
4118       case SC_Extern:
4119       case SC_PrivateExtern:
4120       case SC_OpenCLWorkGroupLocal:
4121         break;
4122       }
4123     }
4124
4125     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4126                                                 Context, Label));
4127   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4128     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4129       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4130     if (I != ExtnameUndeclaredIdentifiers.end()) {
4131       NewVD->addAttr(I->second);
4132       ExtnameUndeclaredIdentifiers.erase(I);
4133     }
4134   }
4135
4136   // Diagnose shadowed variables before filtering for scope.
4137   if (!D.getCXXScopeSpec().isSet())
4138     CheckShadow(S, NewVD, Previous);
4139
4140   // Don't consider existing declarations that are in a different
4141   // scope and are out-of-semantic-context declarations (if the new
4142   // declaration has linkage).
4143   FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4144                        isExplicitSpecialization);
4145   
4146   if (!getLangOpts().CPlusPlus) {
4147     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4148   } else {
4149     // Merge the decl with the existing one if appropriate.
4150     if (!Previous.empty()) {
4151       if (Previous.isSingleResult() &&
4152           isa<FieldDecl>(Previous.getFoundDecl()) &&
4153           D.getCXXScopeSpec().isSet()) {
4154         // The user tried to define a non-static data member
4155         // out-of-line (C++ [dcl.meaning]p1).
4156         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4157           << D.getCXXScopeSpec().getRange();
4158         Previous.clear();
4159         NewVD->setInvalidDecl();
4160       }
4161     } else if (D.getCXXScopeSpec().isSet()) {
4162       // No previous declaration in the qualifying scope.
4163       Diag(D.getIdentifierLoc(), diag::err_no_member)
4164         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4165         << D.getCXXScopeSpec().getRange();
4166       NewVD->setInvalidDecl();
4167     }
4168
4169     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4170
4171     // This is an explicit specialization of a static data member. Check it.
4172     if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4173         CheckMemberSpecialization(NewVD, Previous))
4174       NewVD->setInvalidDecl();
4175   }
4176   
4177   // attributes declared post-definition are currently ignored
4178   // FIXME: This should be handled in attribute merging, not
4179   // here.
4180   if (Previous.isSingleResult()) {
4181     VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4182     if (Def && (Def = Def->getDefinition()) &&
4183         Def != NewVD && D.hasAttributes()) {
4184       Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4185       Diag(Def->getLocation(), diag::note_previous_definition);
4186     }
4187   }
4188
4189   // If this is a locally-scoped extern C variable, update the map of
4190   // such variables.
4191   if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4192       !NewVD->isInvalidDecl())
4193     RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4194
4195   // If there's a #pragma GCC visibility in scope, and this isn't a class
4196   // member, set the visibility of this variable.
4197   if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4198     AddPushedVisibilityAttribute(NewVD);
4199   
4200   MarkUnusedFileScopedDecl(NewVD);
4201
4202   return NewVD;
4203 }
4204
4205 /// \brief Diagnose variable or built-in function shadowing.  Implements
4206 /// -Wshadow.
4207 ///
4208 /// This method is called whenever a VarDecl is added to a "useful"
4209 /// scope.
4210 ///
4211 /// \param S the scope in which the shadowing name is being declared
4212 /// \param R the lookup of the name
4213 ///
4214 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4215   // Return if warning is ignored.
4216   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4217         DiagnosticsEngine::Ignored)
4218     return;
4219
4220   // Don't diagnose declarations at file scope.
4221   if (D->hasGlobalStorage())
4222     return;
4223
4224   DeclContext *NewDC = D->getDeclContext();
4225
4226   // Only diagnose if we're shadowing an unambiguous field or variable.
4227   if (R.getResultKind() != LookupResult::Found)
4228     return;
4229
4230   NamedDecl* ShadowedDecl = R.getFoundDecl();
4231   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4232     return;
4233
4234   // Fields are not shadowed by variables in C++ static methods.
4235   if (isa<FieldDecl>(ShadowedDecl))
4236     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4237       if (MD->isStatic())
4238         return;
4239
4240   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4241     if (shadowedVar->isExternC()) {
4242       // For shadowing external vars, make sure that we point to the global
4243       // declaration, not a locally scoped extern declaration.
4244       for (VarDecl::redecl_iterator
4245              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4246            I != E; ++I)
4247         if (I->isFileVarDecl()) {
4248           ShadowedDecl = *I;
4249           break;
4250         }
4251     }
4252
4253   DeclContext *OldDC = ShadowedDecl->getDeclContext();
4254
4255   // Only warn about certain kinds of shadowing for class members.
4256   if (NewDC && NewDC->isRecord()) {
4257     // In particular, don't warn about shadowing non-class members.
4258     if (!OldDC->isRecord())
4259       return;
4260
4261     // TODO: should we warn about static data members shadowing
4262     // static data members from base classes?
4263     
4264     // TODO: don't diagnose for inaccessible shadowed members.
4265     // This is hard to do perfectly because we might friend the
4266     // shadowing context, but that's just a false negative.
4267   }
4268
4269   // Determine what kind of declaration we're shadowing.
4270   unsigned Kind;
4271   if (isa<RecordDecl>(OldDC)) {
4272     if (isa<FieldDecl>(ShadowedDecl))
4273       Kind = 3; // field
4274     else
4275       Kind = 2; // static data member
4276   } else if (OldDC->isFileContext())
4277     Kind = 1; // global
4278   else
4279     Kind = 0; // local
4280
4281   DeclarationName Name = R.getLookupName();
4282
4283   // Emit warning and note.
4284   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4285   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4286 }
4287
4288 /// \brief Check -Wshadow without the advantage of a previous lookup.
4289 void Sema::CheckShadow(Scope *S, VarDecl *D) {
4290   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4291         DiagnosticsEngine::Ignored)
4292     return;
4293
4294   LookupResult R(*this, D->getDeclName(), D->getLocation(),
4295                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4296   LookupName(R, S);
4297   CheckShadow(S, D, R);
4298 }
4299
4300 /// \brief Perform semantic checking on a newly-created variable
4301 /// declaration.
4302 ///
4303 /// This routine performs all of the type-checking required for a
4304 /// variable declaration once it has been built. It is used both to
4305 /// check variables after they have been parsed and their declarators
4306 /// have been translated into a declaration, and to check variables
4307 /// that have been instantiated from a template.
4308 ///
4309 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4310 ///
4311 /// Returns true if the variable declaration is a redeclaration.
4312 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4313                                     LookupResult &Previous) {
4314   // If the decl is already known invalid, don't check it.
4315   if (NewVD->isInvalidDecl())
4316     return false;
4317
4318   QualType T = NewVD->getType();
4319
4320   if (T->isObjCObjectType()) {
4321     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4322       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4323     T = Context.getObjCObjectPointerType(T);
4324     NewVD->setType(T);
4325   }
4326
4327   // Emit an error if an address space was applied to decl with local storage.
4328   // This includes arrays of objects with address space qualifiers, but not
4329   // automatic variables that point to other address spaces.
4330   // ISO/IEC TR 18037 S5.1.2
4331   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4332     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4333     NewVD->setInvalidDecl();
4334     return false;
4335   }
4336
4337   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4338       && !NewVD->hasAttr<BlocksAttr>()) {
4339     if (getLangOpts().getGC() != LangOptions::NonGC)
4340       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4341     else
4342       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4343   }
4344   
4345   bool isVM = T->isVariablyModifiedType();
4346   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4347       NewVD->hasAttr<BlocksAttr>())
4348     getCurFunction()->setHasBranchProtectedScope();
4349
4350   if ((isVM && NewVD->hasLinkage()) ||
4351       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4352     bool SizeIsNegative;
4353     llvm::APSInt Oversized;
4354     QualType FixedTy =
4355         TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4356                                             Oversized);
4357
4358     if (FixedTy.isNull() && T->isVariableArrayType()) {
4359       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4360       // FIXME: This won't give the correct result for
4361       // int a[10][n];
4362       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4363
4364       if (NewVD->isFileVarDecl())
4365         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4366         << SizeRange;
4367       else if (NewVD->getStorageClass() == SC_Static)
4368         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4369         << SizeRange;
4370       else
4371         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4372         << SizeRange;
4373       NewVD->setInvalidDecl();
4374       return false;
4375     }
4376
4377     if (FixedTy.isNull()) {
4378       if (NewVD->isFileVarDecl())
4379         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4380       else
4381         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4382       NewVD->setInvalidDecl();
4383       return false;
4384     }
4385
4386     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4387     NewVD->setType(FixedTy);
4388   }
4389
4390   if (Previous.empty() && NewVD->isExternC()) {
4391     // Since we did not find anything by this name and we're declaring
4392     // an extern "C" variable, look for a non-visible extern "C"
4393     // declaration with the same name.
4394     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4395       = findLocallyScopedExternalDecl(NewVD->getDeclName());
4396     if (Pos != LocallyScopedExternalDecls.end())
4397       Previous.addDecl(Pos->second);
4398   }
4399
4400   if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4401     Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4402       << T;
4403     NewVD->setInvalidDecl();
4404     return false;
4405   }
4406
4407   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4408     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4409     NewVD->setInvalidDecl();
4410     return false;
4411   }
4412
4413   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4414     Diag(NewVD->getLocation(), diag::err_block_on_vm);
4415     NewVD->setInvalidDecl();
4416     return false;
4417   }
4418
4419   if (NewVD->isConstexpr() && !T->isDependentType() &&
4420       RequireLiteralType(NewVD->getLocation(), T,
4421                          PDiag(diag::err_constexpr_var_non_literal))) {
4422     NewVD->setInvalidDecl();
4423     return false;
4424   }
4425
4426   if (!Previous.empty()) {
4427     MergeVarDecl(NewVD, Previous);
4428     return true;
4429   }
4430   return false;
4431 }
4432
4433 /// \brief Data used with FindOverriddenMethod
4434 struct FindOverriddenMethodData {
4435   Sema *S;
4436   CXXMethodDecl *Method;
4437 };
4438
4439 /// \brief Member lookup function that determines whether a given C++
4440 /// method overrides a method in a base class, to be used with
4441 /// CXXRecordDecl::lookupInBases().
4442 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4443                                  CXXBasePath &Path,
4444                                  void *UserData) {
4445   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4446
4447   FindOverriddenMethodData *Data 
4448     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4449   
4450   DeclarationName Name = Data->Method->getDeclName();
4451   
4452   // FIXME: Do we care about other names here too?
4453   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4454     // We really want to find the base class destructor here.
4455     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4456     CanQualType CT = Data->S->Context.getCanonicalType(T);
4457     
4458     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4459   }    
4460   
4461   for (Path.Decls = BaseRecord->lookup(Name);
4462        Path.Decls.first != Path.Decls.second;
4463        ++Path.Decls.first) {
4464     NamedDecl *D = *Path.Decls.first;
4465     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4466       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4467         return true;
4468     }
4469   }
4470   
4471   return false;
4472 }
4473
4474 static bool hasDelayedExceptionSpec(CXXMethodDecl *Method) {
4475   const FunctionProtoType *Proto =Method->getType()->getAs<FunctionProtoType>();
4476   return Proto && Proto->getExceptionSpecType() == EST_Delayed;
4477 }
4478
4479 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4480 /// and if so, check that it's a valid override and remember it.
4481 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4482   // Look for virtual methods in base classes that this method might override.
4483   CXXBasePaths Paths;
4484   FindOverriddenMethodData Data;
4485   Data.Method = MD;
4486   Data.S = this;
4487   bool AddedAny = false;
4488   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4489     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4490          E = Paths.found_decls_end(); I != E; ++I) {
4491       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4492         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4493         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4494             (hasDelayedExceptionSpec(MD) ||
4495              !CheckOverridingFunctionExceptionSpec(MD, OldMD)) &&
4496             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4497           AddedAny = true;
4498         }
4499       }
4500     }
4501   }
4502   
4503   return AddedAny;
4504 }
4505
4506 namespace {
4507   // Struct for holding all of the extra arguments needed by
4508   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4509   struct ActOnFDArgs {
4510     Scope *S;
4511     Declarator &D;
4512     MultiTemplateParamsArg TemplateParamLists;
4513     bool AddToScope;
4514   };
4515 }
4516
4517 namespace {
4518
4519 // Callback to only accept typo corrections that have a non-zero edit distance.
4520 // Also only accept corrections that have the same parent decl.
4521 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4522  public:
4523   DifferentNameValidatorCCC(CXXRecordDecl *Parent)
4524       : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4525
4526   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4527     if (candidate.getEditDistance() == 0)
4528       return false;
4529
4530     if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4531       CXXRecordDecl *Parent = MD->getParent();
4532       return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4533     }
4534
4535     return !ExpectedParent;
4536   }
4537
4538  private:
4539   CXXRecordDecl *ExpectedParent;
4540 };
4541
4542 }
4543
4544 /// \brief Generate diagnostics for an invalid function redeclaration.
4545 ///
4546 /// This routine handles generating the diagnostic messages for an invalid
4547 /// function redeclaration, including finding possible similar declarations
4548 /// or performing typo correction if there are no previous declarations with
4549 /// the same name.
4550 ///
4551 /// Returns a NamedDecl iff typo correction was performed and substituting in
4552 /// the new declaration name does not cause new errors.
4553 static NamedDecl* DiagnoseInvalidRedeclaration(
4554     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4555     ActOnFDArgs &ExtraArgs) {
4556   NamedDecl *Result = NULL;
4557   DeclarationName Name = NewFD->getDeclName();
4558   DeclContext *NewDC = NewFD->getDeclContext();
4559   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4560                     Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4561   llvm::SmallVector<unsigned, 1> MismatchedParams;
4562   llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4563   TypoCorrection Correction;
4564   bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4565                        ExtraArgs.D.getDeclSpec().isFriendSpecified());
4566   unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4567                                   : diag::err_member_def_does_not_match;
4568
4569   NewFD->setInvalidDecl();
4570   SemaRef.LookupQualifiedName(Prev, NewDC);
4571   assert(!Prev.isAmbiguous() &&
4572          "Cannot have an ambiguity in previous-declaration lookup");
4573   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4574   DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
4575   if (!Prev.empty()) {
4576     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4577          Func != FuncEnd; ++Func) {
4578       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4579       if (FD &&
4580           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4581         // Add 1 to the index so that 0 can mean the mismatch didn't
4582         // involve a parameter
4583         unsigned ParamNum =
4584             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4585         NearMatches.push_back(std::make_pair(FD, ParamNum));
4586       }
4587     }
4588   // If the qualified name lookup yielded nothing, try typo correction
4589   } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4590                                          Prev.getLookupKind(), 0, 0,
4591                                          Validator, NewDC))) {
4592     // Trap errors.
4593     Sema::SFINAETrap Trap(SemaRef);
4594
4595     // Set up everything for the call to ActOnFunctionDeclarator
4596     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4597                               ExtraArgs.D.getIdentifierLoc());
4598     Previous.clear();
4599     Previous.setLookupName(Correction.getCorrection());
4600     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4601                                     CDeclEnd = Correction.end();
4602          CDecl != CDeclEnd; ++CDecl) {
4603       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4604       if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4605                                      MismatchedParams)) {
4606         Previous.addDecl(FD);
4607       }
4608     }
4609     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4610     // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4611     // pieces need to verify the typo-corrected C++ declaraction and hopefully
4612     // eliminate the need for the parameter pack ExtraArgs.
4613     Result = SemaRef.ActOnFunctionDeclarator(
4614         ExtraArgs.S, ExtraArgs.D,
4615         Correction.getCorrectionDecl()->getDeclContext(),
4616         NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4617         ExtraArgs.AddToScope);
4618     if (Trap.hasErrorOccurred()) {
4619       // Pretend the typo correction never occurred
4620       ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4621                                 ExtraArgs.D.getIdentifierLoc());
4622       ExtraArgs.D.setRedeclaration(wasRedeclaration);
4623       Previous.clear();
4624       Previous.setLookupName(Name);
4625       Result = NULL;
4626     } else {
4627       for (LookupResult::iterator Func = Previous.begin(),
4628                                FuncEnd = Previous.end();
4629            Func != FuncEnd; ++Func) {
4630         if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4631           NearMatches.push_back(std::make_pair(FD, 0));
4632       }
4633     }
4634     if (NearMatches.empty()) {
4635       // Ignore the correction if it didn't yield any close FunctionDecl matches
4636       Correction = TypoCorrection();
4637     } else {
4638       DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4639                              : diag::err_member_def_does_not_match_suggest;
4640     }
4641   }
4642
4643   if (Correction)
4644     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4645         << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
4646         << FixItHint::CreateReplacement(
4647             NewFD->getLocation(),
4648             Correction.getAsString(SemaRef.getLangOpts()));
4649   else
4650     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4651         << Name << NewDC << NewFD->getLocation();
4652
4653   bool NewFDisConst = false;
4654   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4655     NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4656
4657   for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4658        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4659        NearMatch != NearMatchEnd; ++NearMatch) {
4660     FunctionDecl *FD = NearMatch->first;
4661     bool FDisConst = false;
4662     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4663       FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
4664
4665     if (unsigned Idx = NearMatch->second) {
4666       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4667       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4668       if (Loc.isInvalid()) Loc = FD->getLocation();
4669       SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
4670           << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4671     } else if (Correction) {
4672       SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
4673           << Correction.getQuoted(SemaRef.getLangOpts());
4674     } else if (FDisConst != NewFDisConst) {
4675       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
4676           << NewFDisConst << FD->getSourceRange().getEnd();
4677     } else
4678       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
4679   }
4680   return Result;
4681 }
4682
4683 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 
4684                                                           Declarator &D) {
4685   switch (D.getDeclSpec().getStorageClassSpec()) {
4686   default: llvm_unreachable("Unknown storage class!");
4687   case DeclSpec::SCS_auto:
4688   case DeclSpec::SCS_register:
4689   case DeclSpec::SCS_mutable:
4690     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4691                  diag::err_typecheck_sclass_func);
4692     D.setInvalidType();
4693     break;
4694   case DeclSpec::SCS_unspecified: break;
4695   case DeclSpec::SCS_extern: return SC_Extern;
4696   case DeclSpec::SCS_static: {
4697     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4698       // C99 6.7.1p5:
4699       //   The declaration of an identifier for a function that has
4700       //   block scope shall have no explicit storage-class specifier
4701       //   other than extern
4702       // See also (C++ [dcl.stc]p4).
4703       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4704                    diag::err_static_block_func);
4705       break;
4706     } else
4707       return SC_Static;
4708   }
4709   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4710   }
4711
4712   // No explicit storage class has already been returned
4713   return SC_None;
4714 }
4715
4716 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4717                                            DeclContext *DC, QualType &R,
4718                                            TypeSourceInfo *TInfo,
4719                                            FunctionDecl::StorageClass SC,
4720                                            bool &IsVirtualOkay) {
4721   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4722   DeclarationName Name = NameInfo.getName();
4723
4724   FunctionDecl *NewFD = 0;
4725   bool isInline = D.getDeclSpec().isInlineSpecified();
4726   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4727   FunctionDecl::StorageClass SCAsWritten
4728     = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4729
4730   if (!SemaRef.getLangOpts().CPlusPlus) {
4731     // Determine whether the function was written with a
4732     // prototype. This true when:
4733     //   - there is a prototype in the declarator, or
4734     //   - the type R of the function is some kind of typedef or other reference
4735     //     to a type name (which eventually refers to a function type).
4736     bool HasPrototype =
4737       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4738       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4739
4740     NewFD = FunctionDecl::Create(SemaRef.Context, DC, 
4741                                  D.getLocStart(), NameInfo, R, 
4742                                  TInfo, SC, SCAsWritten, isInline, 
4743                                  HasPrototype);
4744     if (D.isInvalidType())
4745       NewFD->setInvalidDecl();
4746
4747     // Set the lexical context.
4748     NewFD->setLexicalDeclContext(SemaRef.CurContext);
4749
4750     return NewFD;
4751   }
4752
4753   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4754   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4755
4756   // Check that the return type is not an abstract class type.
4757   // For record types, this is done by the AbstractClassUsageDiagnoser once
4758   // the class has been completely parsed.
4759   if (!DC->isRecord() &&
4760       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4761                                      R->getAs<FunctionType>()->getResultType(),
4762                                      diag::err_abstract_type_in_decl,
4763                                      SemaRef.AbstractReturnType))
4764     D.setInvalidType();
4765
4766   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4767     // This is a C++ constructor declaration.
4768     assert(DC->isRecord() &&
4769            "Constructors can only be declared in a member context");
4770
4771     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4772     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4773                                       D.getLocStart(), NameInfo,
4774                                       R, TInfo, isExplicit, isInline,
4775                                       /*isImplicitlyDeclared=*/false,
4776                                       isConstexpr);
4777
4778   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4779     // This is a C++ destructor declaration.
4780     if (DC->isRecord()) {
4781       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4782       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4783       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4784                                         SemaRef.Context, Record,
4785                                         D.getLocStart(),
4786                                         NameInfo, R, TInfo, isInline,
4787                                         /*isImplicitlyDeclared=*/false);
4788
4789       // If the class is complete, then we now create the implicit exception
4790       // specification. If the class is incomplete or dependent, we can't do
4791       // it yet.
4792       if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
4793           Record->getDefinition() && !Record->isBeingDefined() &&
4794           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4795         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4796       }
4797
4798       IsVirtualOkay = true;
4799       return NewDD;
4800
4801     } else {
4802       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4803       D.setInvalidType();
4804
4805       // Create a FunctionDecl to satisfy the function definition parsing
4806       // code path.
4807       return FunctionDecl::Create(SemaRef.Context, DC,
4808                                   D.getLocStart(),
4809                                   D.getIdentifierLoc(), Name, R, TInfo,
4810                                   SC, SCAsWritten, isInline,
4811                                   /*hasPrototype=*/true, isConstexpr);
4812     }
4813
4814   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4815     if (!DC->isRecord()) {
4816       SemaRef.Diag(D.getIdentifierLoc(),
4817            diag::err_conv_function_not_member);
4818       return 0;
4819     }
4820
4821     SemaRef.CheckConversionDeclarator(D, R, SC);
4822     IsVirtualOkay = true;
4823     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4824                                      D.getLocStart(), NameInfo,
4825                                      R, TInfo, isInline, isExplicit,
4826                                      isConstexpr, SourceLocation());
4827
4828   } else if (DC->isRecord()) {
4829     // If the name of the function is the same as the name of the record,
4830     // then this must be an invalid constructor that has a return type.
4831     // (The parser checks for a return type and makes the declarator a
4832     // constructor if it has no return type).
4833     if (Name.getAsIdentifierInfo() &&
4834         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4835       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4836         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4837         << SourceRange(D.getIdentifierLoc());
4838       return 0;
4839     }
4840
4841     bool isStatic = SC == SC_Static;
4842
4843     // [class.free]p1:
4844     // Any allocation function for a class T is a static member
4845     // (even if not explicitly declared static).
4846     if (Name.getCXXOverloadedOperator() == OO_New ||
4847         Name.getCXXOverloadedOperator() == OO_Array_New)
4848       isStatic = true;
4849
4850     // [class.free]p6 Any deallocation function for a class X is a static member
4851     // (even if not explicitly declared static).
4852     if (Name.getCXXOverloadedOperator() == OO_Delete ||
4853         Name.getCXXOverloadedOperator() == OO_Array_Delete)
4854       isStatic = true;
4855
4856     IsVirtualOkay = !isStatic;
4857
4858     // This is a C++ method declaration.
4859     return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4860                                  D.getLocStart(), NameInfo, R,
4861                                  TInfo, isStatic, SCAsWritten, isInline,
4862                                  isConstexpr, SourceLocation());
4863
4864   } else {
4865     // Determine whether the function was written with a
4866     // prototype. This true when:
4867     //   - we're in C++ (where every function has a prototype),
4868     return FunctionDecl::Create(SemaRef.Context, DC,
4869                                 D.getLocStart(),
4870                                 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4871                                 true/*HasPrototype*/, isConstexpr);
4872   }
4873 }
4874
4875 NamedDecl*
4876 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4877                               TypeSourceInfo *TInfo, LookupResult &Previous,
4878                               MultiTemplateParamsArg TemplateParamLists,
4879                               bool &AddToScope) {
4880   QualType R = TInfo->getType();
4881
4882   assert(R.getTypePtr()->isFunctionType());
4883
4884   // TODO: consider using NameInfo for diagnostic.
4885   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4886   DeclarationName Name = NameInfo.getName();
4887   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
4888
4889   if (D.getDeclSpec().isThreadSpecified())
4890     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4891
4892   // Do not allow returning a objc interface by-value.
4893   if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
4894     Diag(D.getIdentifierLoc(),
4895          diag::err_object_cannot_be_passed_returned_by_value) << 0
4896     << R->getAs<FunctionType>()->getResultType()
4897     << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4898
4899     QualType T = R->getAs<FunctionType>()->getResultType();
4900     T = Context.getObjCObjectPointerType(T);
4901     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4902       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4903       R = Context.getFunctionType(T, FPT->arg_type_begin(),
4904                                   FPT->getNumArgs(), EPI);
4905     }
4906     else if (isa<FunctionNoProtoType>(R))
4907       R = Context.getFunctionNoProtoType(T);
4908   }
4909
4910   bool isFriend = false;
4911   FunctionTemplateDecl *FunctionTemplate = 0;
4912   bool isExplicitSpecialization = false;
4913   bool isFunctionTemplateSpecialization = false;
4914   bool isDependentClassScopeExplicitSpecialization = false;
4915   bool isVirtualOkay = false;
4916
4917   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4918                                               isVirtualOkay);
4919   if (!NewFD) return 0;
4920
4921   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4922     NewFD->setTopLevelDeclInObjCContainer();
4923
4924   if (getLangOpts().CPlusPlus) {
4925     bool isInline = D.getDeclSpec().isInlineSpecified();
4926     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4927     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4928     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4929     isFriend = D.getDeclSpec().isFriendSpecified();
4930     if (isFriend && !isInline && D.isFunctionDefinition()) {
4931       // C++ [class.friend]p5
4932       //   A function can be defined in a friend declaration of a
4933       //   class . . . . Such a function is implicitly inline.
4934       NewFD->setImplicitlyInline();
4935     }
4936
4937     SetNestedNameSpecifier(NewFD, D);
4938     isExplicitSpecialization = false;
4939     isFunctionTemplateSpecialization = false;
4940     if (D.isInvalidType())
4941       NewFD->setInvalidDecl();
4942     
4943     // Set the lexical context. If the declarator has a C++
4944     // scope specifier, or is the object of a friend declaration, the
4945     // lexical context will be different from the semantic context.
4946     NewFD->setLexicalDeclContext(CurContext);
4947         
4948     // Match up the template parameter lists with the scope specifier, then
4949     // determine whether we have a template or a template specialization.
4950     bool Invalid = false;
4951     if (TemplateParameterList *TemplateParams
4952           = MatchTemplateParametersToScopeSpecifier(
4953                                   D.getDeclSpec().getLocStart(),
4954                                   D.getIdentifierLoc(),
4955                                   D.getCXXScopeSpec(),
4956                                   TemplateParamLists.get(),
4957                                   TemplateParamLists.size(),
4958                                   isFriend,
4959                                   isExplicitSpecialization,
4960                                   Invalid)) {
4961       if (TemplateParams->size() > 0) {
4962         // This is a function template
4963
4964         // Check that we can declare a template here.
4965         if (CheckTemplateDeclScope(S, TemplateParams))
4966           return 0;
4967
4968         // A destructor cannot be a template.
4969         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4970           Diag(NewFD->getLocation(), diag::err_destructor_template);
4971           return 0;
4972         }
4973         
4974         // If we're adding a template to a dependent context, we may need to 
4975         // rebuilding some of the types used within the template parameter list,
4976         // now that we know what the current instantiation is.
4977         if (DC->isDependentContext()) {
4978           ContextRAII SavedContext(*this, DC);
4979           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4980             Invalid = true;
4981         }
4982         
4983
4984         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4985                                                         NewFD->getLocation(),
4986                                                         Name, TemplateParams,
4987                                                         NewFD);
4988         FunctionTemplate->setLexicalDeclContext(CurContext);
4989         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4990
4991         // For source fidelity, store the other template param lists.
4992         if (TemplateParamLists.size() > 1) {
4993           NewFD->setTemplateParameterListsInfo(Context,
4994                                                TemplateParamLists.size() - 1,
4995                                                TemplateParamLists.release());
4996         }
4997       } else {
4998         // This is a function template specialization.
4999         isFunctionTemplateSpecialization = true;
5000         // For source fidelity, store all the template param lists.
5001         NewFD->setTemplateParameterListsInfo(Context,
5002                                              TemplateParamLists.size(),
5003                                              TemplateParamLists.release());
5004
5005         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5006         if (isFriend) {
5007           // We want to remove the "template<>", found here.
5008           SourceRange RemoveRange = TemplateParams->getSourceRange();
5009
5010           // If we remove the template<> and the name is not a
5011           // template-id, we're actually silently creating a problem:
5012           // the friend declaration will refer to an untemplated decl,
5013           // and clearly the user wants a template specialization.  So
5014           // we need to insert '<>' after the name.
5015           SourceLocation InsertLoc;
5016           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5017             InsertLoc = D.getName().getSourceRange().getEnd();
5018             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5019           }
5020
5021           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5022             << Name << RemoveRange
5023             << FixItHint::CreateRemoval(RemoveRange)
5024             << FixItHint::CreateInsertion(InsertLoc, "<>");
5025         }
5026       }
5027     }
5028     else {
5029       // All template param lists were matched against the scope specifier:
5030       // this is NOT (an explicit specialization of) a template.
5031       if (TemplateParamLists.size() > 0)
5032         // For source fidelity, store all the template param lists.
5033         NewFD->setTemplateParameterListsInfo(Context,
5034                                              TemplateParamLists.size(),
5035                                              TemplateParamLists.release());
5036     }
5037
5038     if (Invalid) {
5039       NewFD->setInvalidDecl();
5040       if (FunctionTemplate)
5041         FunctionTemplate->setInvalidDecl();
5042     }
5043
5044     // If we see "T var();" at block scope, where T is a class type, it is
5045     // probably an attempt to initialize a variable, not a function declaration.
5046     // We don't catch this case earlier, since there is no ambiguity here.
5047     if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5048         CurContext->isFunctionOrMethod() &&
5049         D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5050         D.getDeclSpec().getStorageClassSpecAsWritten()
5051           == DeclSpec::SCS_unspecified) {
5052       QualType T = R->getAs<FunctionType>()->getResultType();
5053       DeclaratorChunk &C = D.getTypeObject(0);
5054       if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
5055           !C.Fun.TrailingReturnType &&
5056           C.Fun.getExceptionSpecType() == EST_None) {
5057         SourceRange ParenRange(C.Loc, C.EndLoc);
5058         Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5059
5060         // If the declaration looks like:
5061         //   T var1,
5062         //   f();
5063         // and name lookup finds a function named 'f', then the ',' was
5064         // probably intended to be a ';'.
5065         if (!D.isFirstDeclarator() && D.getIdentifier()) {
5066           FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5067           FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5068           if (Comma.getFileID() != Name.getFileID() ||
5069               Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5070             LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5071                                 LookupOrdinaryName);
5072             if (LookupName(Result, S))
5073               Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5074                 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5075           }
5076         }
5077         const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5078         // Empty parens mean value-initialization, and no parens mean default
5079         // initialization. These are equivalent if the default constructor is
5080         // user-provided, or if zero-initialization is a no-op.
5081         if (RD && RD->hasDefinition() &&
5082             (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
5083           Diag(C.Loc, diag::note_empty_parens_default_ctor)
5084             << FixItHint::CreateRemoval(ParenRange);
5085         else if (const char *Init = getFixItZeroInitializerForType(T))
5086           Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5087             << FixItHint::CreateReplacement(ParenRange, Init);
5088         else if (LangOpts.CPlusPlus0x)
5089           Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5090             << FixItHint::CreateReplacement(ParenRange, "{}");
5091       }
5092     }
5093
5094     // C++ [dcl.fct.spec]p5:
5095     //   The virtual specifier shall only be used in declarations of
5096     //   nonstatic class member functions that appear within a
5097     //   member-specification of a class declaration; see 10.3.
5098     //
5099     if (isVirtual && !NewFD->isInvalidDecl()) {
5100       if (!isVirtualOkay) {
5101         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5102              diag::err_virtual_non_function);
5103       } else if (!CurContext->isRecord()) {
5104         // 'virtual' was specified outside of the class.
5105         Diag(D.getDeclSpec().getVirtualSpecLoc(), 
5106              diag::err_virtual_out_of_class)
5107           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5108       } else if (NewFD->getDescribedFunctionTemplate()) {
5109         // C++ [temp.mem]p3:
5110         //  A member function template shall not be virtual.
5111         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5112              diag::err_virtual_member_function_template)
5113           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5114       } else {
5115         // Okay: Add virtual to the method.
5116         NewFD->setVirtualAsWritten(true);
5117       }
5118     }
5119
5120     // C++ [dcl.fct.spec]p3:
5121     //  The inline specifier shall not appear on a block scope function 
5122     //  declaration.
5123     if (isInline && !NewFD->isInvalidDecl()) {
5124       if (CurContext->isFunctionOrMethod()) {
5125         // 'inline' is not allowed on block scope function declaration.
5126         Diag(D.getDeclSpec().getInlineSpecLoc(), 
5127              diag::err_inline_declaration_block_scope) << Name
5128           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5129       }
5130     }
5131
5132     // C++ [dcl.fct.spec]p6:
5133     //  The explicit specifier shall be used only in the declaration of a
5134     //  constructor or conversion function within its class definition; 
5135     //  see 12.3.1 and 12.3.2.
5136     if (isExplicit && !NewFD->isInvalidDecl()) {
5137       if (!CurContext->isRecord()) {
5138         // 'explicit' was specified outside of the class.
5139         Diag(D.getDeclSpec().getExplicitSpecLoc(), 
5140              diag::err_explicit_out_of_class)
5141           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5142       } else if (!isa<CXXConstructorDecl>(NewFD) && 
5143                  !isa<CXXConversionDecl>(NewFD)) {
5144         // 'explicit' was specified on a function that wasn't a constructor
5145         // or conversion function.
5146         Diag(D.getDeclSpec().getExplicitSpecLoc(),
5147              diag::err_explicit_non_ctor_or_conv_function)
5148           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5149       }      
5150     }
5151
5152     if (isConstexpr) {
5153       // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5154       // are implicitly inline.
5155       NewFD->setImplicitlyInline();
5156
5157       // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5158       // be either constructors or to return a literal type. Therefore,
5159       // destructors cannot be declared constexpr.
5160       if (isa<CXXDestructorDecl>(NewFD))
5161         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5162     }
5163
5164     // If __module_private__ was specified, mark the function accordingly.
5165     if (D.getDeclSpec().isModulePrivateSpecified()) {
5166       if (isFunctionTemplateSpecialization) {
5167         SourceLocation ModulePrivateLoc
5168           = D.getDeclSpec().getModulePrivateSpecLoc();
5169         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5170           << 0
5171           << FixItHint::CreateRemoval(ModulePrivateLoc);
5172       } else {
5173         NewFD->setModulePrivate();
5174         if (FunctionTemplate)
5175           FunctionTemplate->setModulePrivate();
5176       }
5177     }
5178
5179     if (isFriend) {
5180       // For now, claim that the objects have no previous declaration.
5181       if (FunctionTemplate) {
5182         FunctionTemplate->setObjectOfFriendDecl(false);
5183         FunctionTemplate->setAccess(AS_public);
5184       }
5185       NewFD->setObjectOfFriendDecl(false);
5186       NewFD->setAccess(AS_public);
5187     }
5188
5189     // If a function is defined as defaulted or deleted, mark it as such now.
5190     switch (D.getFunctionDefinitionKind()) {
5191       case FDK_Declaration:
5192       case FDK_Definition:
5193         break;
5194         
5195       case FDK_Defaulted:
5196         NewFD->setDefaulted();
5197         break;
5198         
5199       case FDK_Deleted:
5200         NewFD->setDeletedAsWritten();
5201         break;
5202     }
5203
5204     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5205         D.isFunctionDefinition()) {
5206       // C++ [class.mfct]p2:
5207       //   A member function may be defined (8.4) in its class definition, in 
5208       //   which case it is an inline member function (7.1.2)
5209       NewFD->setImplicitlyInline();
5210     }
5211
5212     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5213         !CurContext->isRecord()) {
5214       // C++ [class.static]p1:
5215       //   A data or function member of a class may be declared static
5216       //   in a class definition, in which case it is a static member of
5217       //   the class.
5218
5219       // Complain about the 'static' specifier if it's on an out-of-line
5220       // member function definition.
5221       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5222            diag::err_static_out_of_line)
5223         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5224     }
5225   }
5226
5227   // Filter out previous declarations that don't match the scope.
5228   FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5229                        isExplicitSpecialization ||
5230                        isFunctionTemplateSpecialization);
5231   
5232   // Handle GNU asm-label extension (encoded as an attribute).
5233   if (Expr *E = (Expr*) D.getAsmLabel()) {
5234     // The parser guarantees this is a string.
5235     StringLiteral *SE = cast<StringLiteral>(E);
5236     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5237                                                 SE->getString()));
5238   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5239     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5240       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5241     if (I != ExtnameUndeclaredIdentifiers.end()) {
5242       NewFD->addAttr(I->second);
5243       ExtnameUndeclaredIdentifiers.erase(I);
5244     }
5245   }
5246
5247   // Copy the parameter declarations from the declarator D to the function
5248   // declaration NewFD, if they are available.  First scavenge them into Params.
5249   SmallVector<ParmVarDecl*, 16> Params;
5250   if (D.isFunctionDeclarator()) {
5251     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5252
5253     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5254     // function that takes no arguments, not a function that takes a
5255     // single void argument.
5256     // We let through "const void" here because Sema::GetTypeForDeclarator
5257     // already checks for that case.
5258     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5259         FTI.ArgInfo[0].Param &&
5260         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5261       // Empty arg list, don't push any params.
5262       ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5263
5264       // In C++, the empty parameter-type-list must be spelled "void"; a
5265       // typedef of void is not permitted.
5266       if (getLangOpts().CPlusPlus &&
5267           Param->getType().getUnqualifiedType() != Context.VoidTy) {
5268         bool IsTypeAlias = false;
5269         if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5270           IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5271         else if (const TemplateSpecializationType *TST =
5272                    Param->getType()->getAs<TemplateSpecializationType>())
5273           IsTypeAlias = TST->isTypeAlias();
5274         Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5275           << IsTypeAlias;
5276       }
5277     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5278       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5279         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5280         assert(Param->getDeclContext() != NewFD && "Was set before ?");
5281         Param->setDeclContext(NewFD);
5282         Params.push_back(Param);
5283
5284         if (Param->isInvalidDecl())
5285           NewFD->setInvalidDecl();
5286       }
5287     }
5288
5289   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5290     // When we're declaring a function with a typedef, typeof, etc as in the
5291     // following example, we'll need to synthesize (unnamed)
5292     // parameters for use in the declaration.
5293     //
5294     // @code
5295     // typedef void fn(int);
5296     // fn f;
5297     // @endcode
5298
5299     // Synthesize a parameter for each argument type.
5300     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5301          AE = FT->arg_type_end(); AI != AE; ++AI) {
5302       ParmVarDecl *Param =
5303         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5304       Param->setScopeInfo(0, Params.size());
5305       Params.push_back(Param);
5306     }
5307   } else {
5308     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5309            "Should not need args for typedef of non-prototype fn");
5310   }
5311
5312   // Finally, we know we have the right number of parameters, install them.
5313   NewFD->setParams(Params);
5314
5315   // Find all anonymous symbols defined during the declaration of this function
5316   // and add to NewFD. This lets us track decls such 'enum Y' in:
5317   //
5318   //   void f(enum Y {AA} x) {}
5319   //
5320   // which would otherwise incorrectly end up in the translation unit scope.
5321   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5322   DeclsInPrototypeScope.clear();
5323
5324   // Process the non-inheritable attributes on this declaration.
5325   ProcessDeclAttributes(S, NewFD, D,
5326                         /*NonInheritable=*/true, /*Inheritable=*/false);
5327
5328   // Functions returning a variably modified type violate C99 6.7.5.2p2
5329   // because all functions have linkage.
5330   if (!NewFD->isInvalidDecl() &&
5331       NewFD->getResultType()->isVariablyModifiedType()) {
5332     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5333     NewFD->setInvalidDecl();
5334   }
5335
5336   if (!getLangOpts().CPlusPlus) {
5337     // Perform semantic checking on the function declaration.
5338     bool isExplicitSpecialization=false;
5339     if (!NewFD->isInvalidDecl()) {
5340       if (NewFD->isMain())
5341         CheckMain(NewFD, D.getDeclSpec());
5342       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5343                                                   isExplicitSpecialization));
5344     }
5345     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5346             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5347            "previous declaration set still overloaded");
5348   } else {
5349     // If the declarator is a template-id, translate the parser's template 
5350     // argument list into our AST format.
5351     bool HasExplicitTemplateArgs = false;
5352     TemplateArgumentListInfo TemplateArgs;
5353     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5354       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5355       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5356       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5357       ASTTemplateArgsPtr TemplateArgsPtr(*this,
5358                                          TemplateId->getTemplateArgs(),
5359                                          TemplateId->NumArgs);
5360       translateTemplateArguments(TemplateArgsPtr,
5361                                  TemplateArgs);
5362       TemplateArgsPtr.release();
5363     
5364       HasExplicitTemplateArgs = true;
5365     
5366       if (NewFD->isInvalidDecl()) {
5367         HasExplicitTemplateArgs = false;
5368       } else if (FunctionTemplate) {
5369         // Function template with explicit template arguments.
5370         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5371           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5372
5373         HasExplicitTemplateArgs = false;
5374       } else if (!isFunctionTemplateSpecialization && 
5375                  !D.getDeclSpec().isFriendSpecified()) {
5376         // We have encountered something that the user meant to be a 
5377         // specialization (because it has explicitly-specified template
5378         // arguments) but that was not introduced with a "template<>" (or had
5379         // too few of them).
5380         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5381           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5382           << FixItHint::CreateInsertion(
5383                                     D.getDeclSpec().getLocStart(),
5384                                         "template<> ");
5385         isFunctionTemplateSpecialization = true;
5386       } else {
5387         // "friend void foo<>(int);" is an implicit specialization decl.
5388         isFunctionTemplateSpecialization = true;
5389       }
5390     } else if (isFriend && isFunctionTemplateSpecialization) {
5391       // This combination is only possible in a recovery case;  the user
5392       // wrote something like:
5393       //   template <> friend void foo(int);
5394       // which we're recovering from as if the user had written:
5395       //   friend void foo<>(int);
5396       // Go ahead and fake up a template id.
5397       HasExplicitTemplateArgs = true;
5398         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5399       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5400     }
5401
5402     // If it's a friend (and only if it's a friend), it's possible
5403     // that either the specialized function type or the specialized
5404     // template is dependent, and therefore matching will fail.  In
5405     // this case, don't check the specialization yet.
5406     bool InstantiationDependent = false;
5407     if (isFunctionTemplateSpecialization && isFriend &&
5408         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5409          TemplateSpecializationType::anyDependentTemplateArguments(
5410             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5411             InstantiationDependent))) {
5412       assert(HasExplicitTemplateArgs &&
5413              "friend function specialization without template args");
5414       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5415                                                        Previous))
5416         NewFD->setInvalidDecl();
5417     } else if (isFunctionTemplateSpecialization) {
5418       if (CurContext->isDependentContext() && CurContext->isRecord() 
5419           && !isFriend) {
5420         isDependentClassScopeExplicitSpecialization = true;
5421         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 
5422           diag::ext_function_specialization_in_class :
5423           diag::err_function_specialization_in_class)
5424           << NewFD->getDeclName();
5425       } else if (CheckFunctionTemplateSpecialization(NewFD,
5426                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5427                                                      Previous))
5428         NewFD->setInvalidDecl();
5429       
5430       // C++ [dcl.stc]p1:
5431       //   A storage-class-specifier shall not be specified in an explicit
5432       //   specialization (14.7.3)
5433       if (SC != SC_None) {
5434         if (SC != NewFD->getStorageClass())
5435           Diag(NewFD->getLocation(),
5436                diag::err_explicit_specialization_inconsistent_storage_class)
5437             << SC
5438             << FixItHint::CreateRemoval(
5439                                       D.getDeclSpec().getStorageClassSpecLoc());
5440             
5441         else
5442           Diag(NewFD->getLocation(), 
5443                diag::ext_explicit_specialization_storage_class)
5444             << FixItHint::CreateRemoval(
5445                                       D.getDeclSpec().getStorageClassSpecLoc());
5446       }
5447       
5448     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5449       if (CheckMemberSpecialization(NewFD, Previous))
5450           NewFD->setInvalidDecl();
5451     }
5452
5453     // Perform semantic checking on the function declaration.
5454     if (!isDependentClassScopeExplicitSpecialization) {
5455       if (NewFD->isInvalidDecl()) {
5456         // If this is a class member, mark the class invalid immediately.
5457         // This avoids some consistency errors later.
5458         if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5459           methodDecl->getParent()->setInvalidDecl();
5460       } else {
5461         if (NewFD->isMain()) 
5462           CheckMain(NewFD, D.getDeclSpec());
5463         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5464                                                     isExplicitSpecialization));
5465       }
5466     }
5467
5468     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5469             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5470            "previous declaration set still overloaded");
5471
5472     NamedDecl *PrincipalDecl = (FunctionTemplate
5473                                 ? cast<NamedDecl>(FunctionTemplate)
5474                                 : NewFD);
5475
5476     if (isFriend && D.isRedeclaration()) {
5477       AccessSpecifier Access = AS_public;
5478       if (!NewFD->isInvalidDecl())
5479         Access = NewFD->getPreviousDecl()->getAccess();
5480
5481       NewFD->setAccess(Access);
5482       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5483
5484       PrincipalDecl->setObjectOfFriendDecl(true);
5485     }
5486
5487     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5488         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5489       PrincipalDecl->setNonMemberOperator();
5490
5491     // If we have a function template, check the template parameter
5492     // list. This will check and merge default template arguments.
5493     if (FunctionTemplate) {
5494       FunctionTemplateDecl *PrevTemplate = 
5495                                      FunctionTemplate->getPreviousDecl();
5496       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5497                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5498                             D.getDeclSpec().isFriendSpecified()
5499                               ? (D.isFunctionDefinition()
5500                                    ? TPC_FriendFunctionTemplateDefinition
5501                                    : TPC_FriendFunctionTemplate)
5502                               : (D.getCXXScopeSpec().isSet() && 
5503                                  DC && DC->isRecord() && 
5504                                  DC->isDependentContext())
5505                                   ? TPC_ClassTemplateMember
5506                                   : TPC_FunctionTemplate);
5507     }
5508
5509     if (NewFD->isInvalidDecl()) {
5510       // Ignore all the rest of this.
5511     } else if (!D.isRedeclaration()) {
5512       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5513                                        AddToScope };
5514       // Fake up an access specifier if it's supposed to be a class member.
5515       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5516         NewFD->setAccess(AS_public);
5517
5518       // Qualified decls generally require a previous declaration.
5519       if (D.getCXXScopeSpec().isSet()) {
5520         // ...with the major exception of templated-scope or
5521         // dependent-scope friend declarations.
5522
5523         // TODO: we currently also suppress this check in dependent
5524         // contexts because (1) the parameter depth will be off when
5525         // matching friend templates and (2) we might actually be
5526         // selecting a friend based on a dependent factor.  But there
5527         // are situations where these conditions don't apply and we
5528         // can actually do this check immediately.
5529         if (isFriend &&
5530             (TemplateParamLists.size() ||
5531              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5532              CurContext->isDependentContext())) {
5533           // ignore these
5534         } else {
5535           // The user tried to provide an out-of-line definition for a
5536           // function that is a member of a class or namespace, but there
5537           // was no such member function declared (C++ [class.mfct]p2,
5538           // C++ [namespace.memdef]p2). For example:
5539           //
5540           // class X {
5541           //   void f() const;
5542           // };
5543           //
5544           // void X::f() { } // ill-formed
5545           //
5546           // Complain about this problem, and attempt to suggest close
5547           // matches (e.g., those that differ only in cv-qualifiers and
5548           // whether the parameter types are references).
5549
5550           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5551                                                                NewFD,
5552                                                                ExtraArgs)) {
5553             AddToScope = ExtraArgs.AddToScope;
5554             return Result;
5555           }
5556         }
5557
5558         // Unqualified local friend declarations are required to resolve
5559         // to something.
5560       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5561         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5562                                                              NewFD,
5563                                                              ExtraArgs)) {
5564           AddToScope = ExtraArgs.AddToScope;
5565           return Result;
5566         }
5567       }
5568
5569     } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5570                !isFriend && !isFunctionTemplateSpecialization &&
5571                !isExplicitSpecialization) {
5572       // An out-of-line member function declaration must also be a
5573       // definition (C++ [dcl.meaning]p1).
5574       // Note that this is not the case for explicit specializations of
5575       // function templates or member functions of class templates, per
5576       // C++ [temp.expl.spec]p2. We also allow these declarations as an 
5577       // extension for compatibility with old SWIG code which likes to 
5578       // generate them.
5579       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5580         << D.getCXXScopeSpec().getRange();
5581     }
5582   }
5583  
5584  
5585   // Handle attributes. We need to have merged decls when handling attributes
5586   // (for example to check for conflicts, etc).
5587   // FIXME: This needs to happen before we merge declarations. Then,
5588   // let attribute merging cope with attribute conflicts.
5589   ProcessDeclAttributes(S, NewFD, D,
5590                         /*NonInheritable=*/false, /*Inheritable=*/true);
5591
5592   // attributes declared post-definition are currently ignored
5593   // FIXME: This should happen during attribute merging
5594   if (D.isRedeclaration() && Previous.isSingleResult()) {
5595     const FunctionDecl *Def;
5596     FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5597     if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5598       Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5599       Diag(Def->getLocation(), diag::note_previous_definition);
5600     }
5601   }
5602
5603   AddKnownFunctionAttributes(NewFD);
5604
5605   if (NewFD->hasAttr<OverloadableAttr>() && 
5606       !NewFD->getType()->getAs<FunctionProtoType>()) {
5607     Diag(NewFD->getLocation(),
5608          diag::err_attribute_overloadable_no_prototype)
5609       << NewFD;
5610
5611     // Turn this into a variadic function with no parameters.
5612     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5613     FunctionProtoType::ExtProtoInfo EPI;
5614     EPI.Variadic = true;
5615     EPI.ExtInfo = FT->getExtInfo();
5616
5617     QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5618     NewFD->setType(R);
5619   }
5620
5621   // If there's a #pragma GCC visibility in scope, and this isn't a class
5622   // member, set the visibility of this function.
5623   if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5624     AddPushedVisibilityAttribute(NewFD);
5625
5626   // If there's a #pragma clang arc_cf_code_audited in scope, consider
5627   // marking the function.
5628   AddCFAuditedAttribute(NewFD);
5629
5630   // If this is a locally-scoped extern C function, update the
5631   // map of such names.
5632   if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5633       && !NewFD->isInvalidDecl())
5634     RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5635
5636   // Set this FunctionDecl's range up to the right paren.
5637   NewFD->setRangeEnd(D.getSourceRange().getEnd());
5638
5639   if (getLangOpts().CPlusPlus) {
5640     if (FunctionTemplate) {
5641       if (NewFD->isInvalidDecl())
5642         FunctionTemplate->setInvalidDecl();
5643       return FunctionTemplate;
5644     }
5645   }
5646
5647   MarkUnusedFileScopedDecl(NewFD);
5648
5649   if (getLangOpts().CUDA)
5650     if (IdentifierInfo *II = NewFD->getIdentifier())
5651       if (!NewFD->isInvalidDecl() &&
5652           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5653         if (II->isStr("cudaConfigureCall")) {
5654           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5655             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5656
5657           Context.setcudaConfigureCallDecl(NewFD);
5658         }
5659       }
5660   
5661   // Here we have an function template explicit specialization at class scope.
5662   // The actually specialization will be postponed to template instatiation
5663   // time via the ClassScopeFunctionSpecializationDecl node.
5664   if (isDependentClassScopeExplicitSpecialization) {
5665     ClassScopeFunctionSpecializationDecl *NewSpec =
5666                          ClassScopeFunctionSpecializationDecl::Create(
5667                                 Context, CurContext,  SourceLocation(), 
5668                                 cast<CXXMethodDecl>(NewFD));
5669     CurContext->addDecl(NewSpec);
5670     AddToScope = false;
5671   }
5672
5673   return NewFD;
5674 }
5675
5676 /// \brief Perform semantic checking of a new function declaration.
5677 ///
5678 /// Performs semantic analysis of the new function declaration
5679 /// NewFD. This routine performs all semantic checking that does not
5680 /// require the actual declarator involved in the declaration, and is
5681 /// used both for the declaration of functions as they are parsed
5682 /// (called via ActOnDeclarator) and for the declaration of functions
5683 /// that have been instantiated via C++ template instantiation (called
5684 /// via InstantiateDecl).
5685 ///
5686 /// \param IsExplicitSpecialiation whether this new function declaration is
5687 /// an explicit specialization of the previous declaration.
5688 ///
5689 /// This sets NewFD->isInvalidDecl() to true if there was an error.
5690 ///
5691 /// Returns true if the function declaration is a redeclaration.
5692 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5693                                     LookupResult &Previous,
5694                                     bool IsExplicitSpecialization) {
5695   assert(!NewFD->getResultType()->isVariablyModifiedType() 
5696          && "Variably modified return types are not handled here");
5697
5698   // Check for a previous declaration of this name.
5699   if (Previous.empty() && NewFD->isExternC()) {
5700     // Since we did not find anything by this name and we're declaring
5701     // an extern "C" function, look for a non-visible extern "C"
5702     // declaration with the same name.
5703     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5704       = findLocallyScopedExternalDecl(NewFD->getDeclName());
5705     if (Pos != LocallyScopedExternalDecls.end())
5706       Previous.addDecl(Pos->second);
5707   }
5708
5709   bool Redeclaration = false;
5710
5711   // Merge or overload the declaration with an existing declaration of
5712   // the same name, if appropriate.
5713   if (!Previous.empty()) {
5714     // Determine whether NewFD is an overload of PrevDecl or
5715     // a declaration that requires merging. If it's an overload,
5716     // there's no more work to do here; we'll just add the new
5717     // function to the scope.
5718
5719     NamedDecl *OldDecl = 0;
5720     if (!AllowOverloadingOfFunction(Previous, Context)) {
5721       Redeclaration = true;
5722       OldDecl = Previous.getFoundDecl();
5723     } else {
5724       switch (CheckOverload(S, NewFD, Previous, OldDecl,
5725                             /*NewIsUsingDecl*/ false)) {
5726       case Ovl_Match:
5727         Redeclaration = true;
5728         break;
5729
5730       case Ovl_NonFunction:
5731         Redeclaration = true;
5732         break;
5733
5734       case Ovl_Overload:
5735         Redeclaration = false;
5736         break;
5737       }
5738
5739       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5740         // If a function name is overloadable in C, then every function
5741         // with that name must be marked "overloadable".
5742         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5743           << Redeclaration << NewFD;
5744         NamedDecl *OverloadedDecl = 0;
5745         if (Redeclaration)
5746           OverloadedDecl = OldDecl;
5747         else if (!Previous.empty())
5748           OverloadedDecl = Previous.getRepresentativeDecl();
5749         if (OverloadedDecl)
5750           Diag(OverloadedDecl->getLocation(),
5751                diag::note_attribute_overloadable_prev_overload);
5752         NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5753                                                         Context));
5754       }
5755     }
5756
5757     if (Redeclaration) {
5758       // NewFD and OldDecl represent declarations that need to be
5759       // merged.
5760       if (MergeFunctionDecl(NewFD, OldDecl, S)) {
5761         NewFD->setInvalidDecl();
5762         return Redeclaration;
5763       }
5764
5765       Previous.clear();
5766       Previous.addDecl(OldDecl);
5767
5768       if (FunctionTemplateDecl *OldTemplateDecl
5769                                     = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5770         NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5771         FunctionTemplateDecl *NewTemplateDecl
5772           = NewFD->getDescribedFunctionTemplate();
5773         assert(NewTemplateDecl && "Template/non-template mismatch");
5774         if (CXXMethodDecl *Method 
5775               = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5776           Method->setAccess(OldTemplateDecl->getAccess());
5777           NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5778         }
5779         
5780         // If this is an explicit specialization of a member that is a function
5781         // template, mark it as a member specialization.
5782         if (IsExplicitSpecialization && 
5783             NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5784           NewTemplateDecl->setMemberSpecialization();
5785           assert(OldTemplateDecl->isMemberSpecialization());
5786         }
5787         
5788       } else {
5789         if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5790           NewFD->setAccess(OldDecl->getAccess());
5791         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5792       }
5793     }
5794   }
5795
5796   // Semantic checking for this function declaration (in isolation).
5797   if (getLangOpts().CPlusPlus) {
5798     // C++-specific checks.
5799     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5800       CheckConstructor(Constructor);
5801     } else if (CXXDestructorDecl *Destructor = 
5802                 dyn_cast<CXXDestructorDecl>(NewFD)) {
5803       CXXRecordDecl *Record = Destructor->getParent();
5804       QualType ClassType = Context.getTypeDeclType(Record);
5805       
5806       // FIXME: Shouldn't we be able to perform this check even when the class
5807       // type is dependent? Both gcc and edg can handle that.
5808       if (!ClassType->isDependentType()) {
5809         DeclarationName Name
5810           = Context.DeclarationNames.getCXXDestructorName(
5811                                         Context.getCanonicalType(ClassType));
5812         if (NewFD->getDeclName() != Name) {
5813           Diag(NewFD->getLocation(), diag::err_destructor_name);
5814           NewFD->setInvalidDecl();
5815           return Redeclaration;
5816         }
5817       }
5818     } else if (CXXConversionDecl *Conversion
5819                = dyn_cast<CXXConversionDecl>(NewFD)) {
5820       ActOnConversionDeclarator(Conversion);
5821     }
5822
5823     // Find any virtual functions that this function overrides.
5824     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5825       if (!Method->isFunctionTemplateSpecialization() && 
5826           !Method->getDescribedFunctionTemplate()) {
5827         if (AddOverriddenMethods(Method->getParent(), Method)) {
5828           // If the function was marked as "static", we have a problem.
5829           if (NewFD->getStorageClass() == SC_Static) {
5830             Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5831               << NewFD->getDeclName();
5832             for (CXXMethodDecl::method_iterator 
5833                       Overridden = Method->begin_overridden_methods(),
5834                    OverriddenEnd = Method->end_overridden_methods();
5835                  Overridden != OverriddenEnd;
5836                  ++Overridden) {
5837               Diag((*Overridden)->getLocation(), 
5838                    diag::note_overridden_virtual_function);
5839             }
5840           }
5841         }
5842       }
5843       
5844       if (Method->isStatic())
5845         checkThisInStaticMemberFunctionType(Method);
5846     }
5847
5848     // Extra checking for C++ overloaded operators (C++ [over.oper]).
5849     if (NewFD->isOverloadedOperator() &&
5850         CheckOverloadedOperatorDeclaration(NewFD)) {
5851       NewFD->setInvalidDecl();
5852       return Redeclaration;
5853     }
5854
5855     // Extra checking for C++0x literal operators (C++0x [over.literal]).
5856     if (NewFD->getLiteralIdentifier() &&
5857         CheckLiteralOperatorDeclaration(NewFD)) {
5858       NewFD->setInvalidDecl();
5859       return Redeclaration;
5860     }
5861
5862     // In C++, check default arguments now that we have merged decls. Unless
5863     // the lexical context is the class, because in this case this is done
5864     // during delayed parsing anyway.
5865     if (!CurContext->isRecord())
5866       CheckCXXDefaultArguments(NewFD);
5867     
5868     // If this function declares a builtin function, check the type of this
5869     // declaration against the expected type for the builtin. 
5870     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5871       ASTContext::GetBuiltinTypeError Error;
5872       QualType T = Context.GetBuiltinType(BuiltinID, Error);
5873       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5874         // The type of this function differs from the type of the builtin,
5875         // so forget about the builtin entirely.
5876         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5877       }
5878     }
5879   
5880     // If this function is declared as being extern "C", then check to see if 
5881     // the function returns a UDT (class, struct, or union type) that is not C
5882     // compatible, and if it does, warn the user.
5883     if (NewFD->isExternC()) {
5884       QualType R = NewFD->getResultType();
5885       if (!R.isPODType(Context) && 
5886           !R->isVoidType())
5887         Diag( NewFD->getLocation(), diag::warn_return_value_udt ) 
5888           << NewFD << R;
5889     }
5890   }
5891   return Redeclaration;
5892 }
5893
5894 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5895   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
5896   //   static or constexpr is ill-formed.
5897   // C99 6.7.4p4:  In a hosted environment, the inline function specifier
5898   //   shall not appear in a declaration of main.
5899   // static main is not an error under C99, but we should warn about it.
5900   if (FD->getStorageClass() == SC_Static)
5901     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 
5902          ? diag::err_static_main : diag::warn_static_main) 
5903       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5904   if (FD->isInlineSpecified())
5905     Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 
5906       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5907   if (FD->isConstexpr()) {
5908     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5909       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5910     FD->setConstexpr(false);
5911   }
5912
5913   QualType T = FD->getType();
5914   assert(T->isFunctionType() && "function decl is not of function type");
5915   const FunctionType* FT = T->castAs<FunctionType>();
5916
5917   // All the standards say that main() should should return 'int'.
5918   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5919     // In C and C++, main magically returns 0 if you fall off the end;
5920     // set the flag which tells us that.
5921     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5922     FD->setHasImplicitReturnZero(true);
5923
5924   // In C with GNU extensions we allow main() to have non-integer return
5925   // type, but we should warn about the extension, and we disable the
5926   // implicit-return-zero rule.
5927   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
5928     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5929
5930   // Otherwise, this is just a flat-out error.
5931   } else {
5932     Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5933     FD->setInvalidDecl(true);
5934   }
5935
5936   // Treat protoless main() as nullary.
5937   if (isa<FunctionNoProtoType>(FT)) return;
5938
5939   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5940   unsigned nparams = FTP->getNumArgs();
5941   assert(FD->getNumParams() == nparams);
5942
5943   bool HasExtraParameters = (nparams > 3);
5944
5945   // Darwin passes an undocumented fourth argument of type char**.  If
5946   // other platforms start sprouting these, the logic below will start
5947   // getting shifty.
5948   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5949     HasExtraParameters = false;
5950
5951   if (HasExtraParameters) {
5952     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5953     FD->setInvalidDecl(true);
5954     nparams = 3;
5955   }
5956
5957   // FIXME: a lot of the following diagnostics would be improved
5958   // if we had some location information about types.
5959
5960   QualType CharPP =
5961     Context.getPointerType(Context.getPointerType(Context.CharTy));
5962   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5963
5964   for (unsigned i = 0; i < nparams; ++i) {
5965     QualType AT = FTP->getArgType(i);
5966
5967     bool mismatch = true;
5968
5969     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5970       mismatch = false;
5971     else if (Expected[i] == CharPP) {
5972       // As an extension, the following forms are okay:
5973       //   char const **
5974       //   char const * const *
5975       //   char * const *
5976
5977       QualifierCollector qs;
5978       const PointerType* PT;
5979       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5980           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5981           (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5982         qs.removeConst();
5983         mismatch = !qs.empty();
5984       }
5985     }
5986
5987     if (mismatch) {
5988       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5989       // TODO: suggest replacing given type with expected type
5990       FD->setInvalidDecl(true);
5991     }
5992   }
5993
5994   if (nparams == 1 && !FD->isInvalidDecl()) {
5995     Diag(FD->getLocation(), diag::warn_main_one_arg);
5996   }
5997   
5998   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5999     Diag(FD->getLocation(), diag::err_main_template_decl);
6000     FD->setInvalidDecl();
6001   }
6002 }
6003
6004 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6005   // FIXME: Need strict checking.  In C89, we need to check for
6006   // any assignment, increment, decrement, function-calls, or
6007   // commas outside of a sizeof.  In C99, it's the same list,
6008   // except that the aforementioned are allowed in unevaluated
6009   // expressions.  Everything else falls under the
6010   // "may accept other forms of constant expressions" exception.
6011   // (We never end up here for C++, so the constant expression
6012   // rules there don't matter.)
6013   if (Init->isConstantInitializer(Context, false))
6014     return false;
6015   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6016     << Init->getSourceRange();
6017   return true;
6018 }
6019
6020 namespace {
6021   // Visits an initialization expression to see if OrigDecl is evaluated in
6022   // its own initialization and throws a warning if it does.
6023   class SelfReferenceChecker
6024       : public EvaluatedExprVisitor<SelfReferenceChecker> {
6025     Sema &S;
6026     Decl *OrigDecl;
6027     bool isRecordType;
6028     bool isPODType;
6029
6030   public:
6031     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6032
6033     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6034                                                     S(S), OrigDecl(OrigDecl) {
6035       isPODType = false;
6036       isRecordType = false;
6037       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6038         isPODType = VD->getType().isPODType(S.Context);
6039         isRecordType = VD->getType()->isRecordType();
6040       }
6041     }
6042
6043     void VisitExpr(Expr *E) {
6044       if (isa<ObjCMessageExpr>(*E)) return;
6045       if (isRecordType) {
6046         Expr *expr = E;
6047         if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6048           ValueDecl *VD = ME->getMemberDecl();
6049           if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
6050           expr = ME->getBase();
6051         }
6052         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
6053           HandleDeclRefExpr(DRE);
6054           return;
6055         }
6056       }
6057       Inherited::VisitExpr(E);
6058     }
6059
6060     void VisitMemberExpr(MemberExpr *E) {
6061       if (E->getType()->canDecayToPointerType()) return;
6062       ValueDecl *VD = E->getMemberDecl();
6063       if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
6064         if (DeclRefExpr *DRE
6065               = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6066           HandleDeclRefExpr(DRE);
6067           return;
6068         }
6069       Inherited::VisitMemberExpr(E);
6070     }
6071
6072     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6073       if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6074           (isRecordType && E->getCastKind() == CK_NoOp)) {
6075         Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6076         if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6077           SubExpr = ME->getBase()->IgnoreParenImpCasts();
6078         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6079           HandleDeclRefExpr(DRE);
6080           return;
6081         }
6082       }
6083       Inherited::VisitImplicitCastExpr(E);
6084     }
6085
6086     void VisitUnaryOperator(UnaryOperator *E) {
6087       // For POD record types, addresses of its own members are well-defined.
6088       if (isRecordType && isPODType) return;
6089       Inherited::VisitUnaryOperator(E);
6090     } 
6091     
6092     void HandleDeclRefExpr(DeclRefExpr *DRE) {
6093       Decl* ReferenceDecl = DRE->getDecl(); 
6094       if (OrigDecl != ReferenceDecl) return;
6095       LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6096                           Sema::NotForRedeclaration);
6097       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6098                             S.PDiag(diag::warn_uninit_self_reference_in_init)
6099                               << Result.getLookupName()
6100                               << OrigDecl->getLocation()
6101                               << DRE->getSourceRange());
6102     }
6103   };
6104 }
6105
6106 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6107 void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6108   SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6109 }
6110
6111 /// AddInitializerToDecl - Adds the initializer Init to the
6112 /// declaration dcl. If DirectInit is true, this is C++ direct
6113 /// initialization rather than copy initialization.
6114 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6115                                 bool DirectInit, bool TypeMayContainAuto) {
6116   // If there is no declaration, there was an error parsing it.  Just ignore
6117   // the initializer.
6118   if (RealDecl == 0 || RealDecl->isInvalidDecl())
6119     return;
6120
6121   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6122     // With declarators parsed the way they are, the parser cannot
6123     // distinguish between a normal initializer and a pure-specifier.
6124     // Thus this grotesque test.
6125     IntegerLiteral *IL;
6126     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6127         Context.getCanonicalType(IL->getType()) == Context.IntTy)
6128       CheckPureMethod(Method, Init->getSourceRange());
6129     else {
6130       Diag(Method->getLocation(), diag::err_member_function_initialization)
6131         << Method->getDeclName() << Init->getSourceRange();
6132       Method->setInvalidDecl();
6133     }
6134     return;
6135   }
6136
6137   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6138   if (!VDecl) {
6139     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6140     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6141     RealDecl->setInvalidDecl();
6142     return;
6143   }
6144
6145   // Check for self-references within variable initializers.
6146   // Variables declared within a function/method body are handled
6147   // by a dataflow analysis.
6148   if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6149     CheckSelfReference(RealDecl, Init);
6150
6151   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6152
6153   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6154   if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
6155     Expr *DeduceInit = Init;
6156     // Initializer could be a C++ direct-initializer. Deduction only works if it
6157     // contains exactly one expression.
6158     if (CXXDirectInit) {
6159       if (CXXDirectInit->getNumExprs() == 0) {
6160         // It isn't possible to write this directly, but it is possible to
6161         // end up in this situation with "auto x(some_pack...);"
6162         Diag(CXXDirectInit->getLocStart(),
6163              diag::err_auto_var_init_no_expression)
6164           << VDecl->getDeclName() << VDecl->getType()
6165           << VDecl->getSourceRange();
6166         RealDecl->setInvalidDecl();
6167         return;
6168       } else if (CXXDirectInit->getNumExprs() > 1) {
6169         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6170              diag::err_auto_var_init_multiple_expressions)
6171           << VDecl->getDeclName() << VDecl->getType()
6172           << VDecl->getSourceRange();
6173         RealDecl->setInvalidDecl();
6174         return;
6175       } else {
6176         DeduceInit = CXXDirectInit->getExpr(0);
6177       }
6178     }
6179     TypeSourceInfo *DeducedType = 0;
6180     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6181             DAR_Failed)
6182       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6183     if (!DeducedType) {
6184       RealDecl->setInvalidDecl();
6185       return;
6186     }
6187     VDecl->setTypeSourceInfo(DeducedType);
6188     VDecl->setType(DeducedType->getType());
6189     VDecl->ClearLinkageCache();
6190     
6191     // In ARC, infer lifetime.
6192     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6193       VDecl->setInvalidDecl();
6194
6195     // If this is a redeclaration, check that the type we just deduced matches
6196     // the previously declared type.
6197     if (VarDecl *Old = VDecl->getPreviousDecl())
6198       MergeVarDeclTypes(VDecl, Old);
6199   }
6200
6201   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6202     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6203     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6204     VDecl->setInvalidDecl();
6205     return;
6206   }
6207
6208   if (!VDecl->getType()->isDependentType()) {
6209     // A definition must end up with a complete type, which means it must be
6210     // complete with the restriction that an array type might be completed by
6211     // the initializer; note that later code assumes this restriction.
6212     QualType BaseDeclType = VDecl->getType();
6213     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6214       BaseDeclType = Array->getElementType();
6215     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6216                             diag::err_typecheck_decl_incomplete_type)) {
6217       RealDecl->setInvalidDecl();
6218       return;
6219     }
6220
6221     // The variable can not have an abstract class type.
6222     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6223                                diag::err_abstract_type_in_decl,
6224                                AbstractVariableType))
6225       VDecl->setInvalidDecl();
6226   }
6227
6228   const VarDecl *Def;
6229   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6230     Diag(VDecl->getLocation(), diag::err_redefinition)
6231       << VDecl->getDeclName();
6232     Diag(Def->getLocation(), diag::note_previous_definition);
6233     VDecl->setInvalidDecl();
6234     return;
6235   }
6236   
6237   const VarDecl* PrevInit = 0;
6238   if (getLangOpts().CPlusPlus) {
6239     // C++ [class.static.data]p4
6240     //   If a static data member is of const integral or const
6241     //   enumeration type, its declaration in the class definition can
6242     //   specify a constant-initializer which shall be an integral
6243     //   constant expression (5.19). In that case, the member can appear
6244     //   in integral constant expressions. The member shall still be
6245     //   defined in a namespace scope if it is used in the program and the
6246     //   namespace scope definition shall not contain an initializer.
6247     //
6248     // We already performed a redefinition check above, but for static
6249     // data members we also need to check whether there was an in-class
6250     // declaration with an initializer.
6251     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6252       Diag(VDecl->getLocation(), diag::err_redefinition) 
6253         << VDecl->getDeclName();
6254       Diag(PrevInit->getLocation(), diag::note_previous_definition);
6255       return;
6256     }  
6257
6258     if (VDecl->hasLocalStorage())
6259       getCurFunction()->setHasBranchProtectedScope();
6260
6261     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6262       VDecl->setInvalidDecl();
6263       return;
6264     }
6265   }
6266
6267   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6268   // a kernel function cannot be initialized."
6269   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6270     Diag(VDecl->getLocation(), diag::err_local_cant_init);
6271     VDecl->setInvalidDecl();
6272     return;
6273   }
6274
6275   // Get the decls type and save a reference for later, since
6276   // CheckInitializerTypes may change it.
6277   QualType DclT = VDecl->getType(), SavT = DclT;
6278   
6279   // Top-level message sends default to 'id' when we're in a debugger
6280   // and we are assigning it to a variable of 'id' type.
6281   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6282     if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6283       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6284       if (Result.isInvalid()) {
6285         VDecl->setInvalidDecl();
6286         return;
6287       }
6288       Init = Result.take();
6289     }
6290
6291   // Perform the initialization.
6292   if (!VDecl->isInvalidDecl()) {
6293     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6294     InitializationKind Kind
6295       = DirectInit ?
6296           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6297                                                            Init->getLocStart(),
6298                                                            Init->getLocEnd())
6299                         : InitializationKind::CreateDirectList(
6300                                                           VDecl->getLocation())
6301                    : InitializationKind::CreateCopy(VDecl->getLocation(),
6302                                                     Init->getLocStart());
6303
6304     Expr **Args = &Init;
6305     unsigned NumArgs = 1;
6306     if (CXXDirectInit) {
6307       Args = CXXDirectInit->getExprs();
6308       NumArgs = CXXDirectInit->getNumExprs();
6309     }
6310     InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6311     ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6312                                               MultiExprArg(*this, Args,NumArgs),
6313                                               &DclT);
6314     if (Result.isInvalid()) {
6315       VDecl->setInvalidDecl();
6316       return;
6317     }
6318
6319     Init = Result.takeAs<Expr>();
6320   }
6321
6322   // If the type changed, it means we had an incomplete type that was
6323   // completed by the initializer. For example:
6324   //   int ary[] = { 1, 3, 5 };
6325   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6326   if (!VDecl->isInvalidDecl() && (DclT != SavT))
6327     VDecl->setType(DclT);
6328
6329   // Check any implicit conversions within the expression.
6330   CheckImplicitConversions(Init, VDecl->getLocation());
6331
6332   if (!VDecl->isInvalidDecl())
6333     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6334
6335   Init = MaybeCreateExprWithCleanups(Init);
6336   // Attach the initializer to the decl.
6337   VDecl->setInit(Init);
6338
6339   if (VDecl->isLocalVarDecl()) {
6340     // C99 6.7.8p4: All the expressions in an initializer for an object that has
6341     // static storage duration shall be constant expressions or string literals.
6342     // C++ does not have this restriction.
6343     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6344         VDecl->getStorageClass() == SC_Static)
6345       CheckForConstantInitializer(Init, DclT);
6346   } else if (VDecl->isStaticDataMember() &&
6347              VDecl->getLexicalDeclContext()->isRecord()) {
6348     // This is an in-class initialization for a static data member, e.g.,
6349     //
6350     // struct S {
6351     //   static const int value = 17;
6352     // };
6353
6354     // C++ [class.mem]p4:
6355     //   A member-declarator can contain a constant-initializer only
6356     //   if it declares a static member (9.4) of const integral or
6357     //   const enumeration type, see 9.4.2.
6358     //
6359     // C++11 [class.static.data]p3:
6360     //   If a non-volatile const static data member is of integral or
6361     //   enumeration type, its declaration in the class definition can
6362     //   specify a brace-or-equal-initializer in which every initalizer-clause
6363     //   that is an assignment-expression is a constant expression. A static
6364     //   data member of literal type can be declared in the class definition
6365     //   with the constexpr specifier; if so, its declaration shall specify a
6366     //   brace-or-equal-initializer in which every initializer-clause that is
6367     //   an assignment-expression is a constant expression.
6368
6369     // Do nothing on dependent types.
6370     if (DclT->isDependentType()) {
6371
6372     // Allow any 'static constexpr' members, whether or not they are of literal
6373     // type. We separately check that every constexpr variable is of literal
6374     // type.
6375     } else if (VDecl->isConstexpr()) {
6376
6377     // Require constness.
6378     } else if (!DclT.isConstQualified()) {
6379       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6380         << Init->getSourceRange();
6381       VDecl->setInvalidDecl();
6382
6383     // We allow integer constant expressions in all cases.
6384     } else if (DclT->isIntegralOrEnumerationType()) {
6385       // Check whether the expression is a constant expression.
6386       SourceLocation Loc;
6387       if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6388         // In C++11, a non-constexpr const static data member with an
6389         // in-class initializer cannot be volatile.
6390         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6391       else if (Init->isValueDependent())
6392         ; // Nothing to check.
6393       else if (Init->isIntegerConstantExpr(Context, &Loc))
6394         ; // Ok, it's an ICE!
6395       else if (Init->isEvaluatable(Context)) {
6396         // If we can constant fold the initializer through heroics, accept it,
6397         // but report this as a use of an extension for -pedantic.
6398         Diag(Loc, diag::ext_in_class_initializer_non_constant)
6399           << Init->getSourceRange();
6400       } else {
6401         // Otherwise, this is some crazy unknown case.  Report the issue at the
6402         // location provided by the isIntegerConstantExpr failed check.
6403         Diag(Loc, diag::err_in_class_initializer_non_constant)
6404           << Init->getSourceRange();
6405         VDecl->setInvalidDecl();
6406       }
6407
6408     // We allow foldable floating-point constants as an extension.
6409     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6410       Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6411         << DclT << Init->getSourceRange();
6412       if (getLangOpts().CPlusPlus0x)
6413         Diag(VDecl->getLocation(),
6414              diag::note_in_class_initializer_float_type_constexpr)
6415           << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6416
6417       if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6418         Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6419           << Init->getSourceRange();
6420         VDecl->setInvalidDecl();
6421       }
6422
6423     // Suggest adding 'constexpr' in C++11 for literal types.
6424     } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6425       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6426         << DclT << Init->getSourceRange()
6427         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6428       VDecl->setConstexpr(true);
6429
6430     } else {
6431       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6432         << DclT << Init->getSourceRange();
6433       VDecl->setInvalidDecl();
6434     }
6435   } else if (VDecl->isFileVarDecl()) {
6436     if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6437         (!getLangOpts().CPlusPlus ||
6438          !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6439       Diag(VDecl->getLocation(), diag::warn_extern_init);
6440
6441     // C99 6.7.8p4. All file scoped initializers need to be constant.
6442     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6443       CheckForConstantInitializer(Init, DclT);
6444   }
6445
6446   // We will represent direct-initialization similarly to copy-initialization:
6447   //    int x(1);  -as-> int x = 1;
6448   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6449   //
6450   // Clients that want to distinguish between the two forms, can check for
6451   // direct initializer using VarDecl::getInitStyle().
6452   // A major benefit is that clients that don't particularly care about which
6453   // exactly form was it (like the CodeGen) can handle both cases without
6454   // special case code.
6455
6456   // C++ 8.5p11:
6457   // The form of initialization (using parentheses or '=') is generally
6458   // insignificant, but does matter when the entity being initialized has a
6459   // class type.
6460   if (CXXDirectInit) {
6461     assert(DirectInit && "Call-style initializer must be direct init.");
6462     VDecl->setInitStyle(VarDecl::CallInit);
6463   } else if (DirectInit) {
6464     // This must be list-initialization. No other way is direct-initialization.
6465     VDecl->setInitStyle(VarDecl::ListInit);
6466   }
6467
6468   CheckCompleteVariableDeclaration(VDecl);
6469 }
6470
6471 /// ActOnInitializerError - Given that there was an error parsing an
6472 /// initializer for the given declaration, try to return to some form
6473 /// of sanity.
6474 void Sema::ActOnInitializerError(Decl *D) {
6475   // Our main concern here is re-establishing invariants like "a
6476   // variable's type is either dependent or complete".
6477   if (!D || D->isInvalidDecl()) return;
6478
6479   VarDecl *VD = dyn_cast<VarDecl>(D);
6480   if (!VD) return;
6481
6482   // Auto types are meaningless if we can't make sense of the initializer.
6483   if (ParsingInitForAutoVars.count(D)) {
6484     D->setInvalidDecl();
6485     return;
6486   }
6487
6488   QualType Ty = VD->getType();
6489   if (Ty->isDependentType()) return;
6490
6491   // Require a complete type.
6492   if (RequireCompleteType(VD->getLocation(), 
6493                           Context.getBaseElementType(Ty),
6494                           diag::err_typecheck_decl_incomplete_type)) {
6495     VD->setInvalidDecl();
6496     return;
6497   }
6498
6499   // Require an abstract type.
6500   if (RequireNonAbstractType(VD->getLocation(), Ty,
6501                              diag::err_abstract_type_in_decl,
6502                              AbstractVariableType)) {
6503     VD->setInvalidDecl();
6504     return;
6505   }
6506
6507   // Don't bother complaining about constructors or destructors,
6508   // though.
6509 }
6510
6511 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6512                                   bool TypeMayContainAuto) {
6513   // If there is no declaration, there was an error parsing it. Just ignore it.
6514   if (RealDecl == 0)
6515     return;
6516
6517   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6518     QualType Type = Var->getType();
6519
6520     // C++11 [dcl.spec.auto]p3
6521     if (TypeMayContainAuto && Type->getContainedAutoType()) {
6522       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6523         << Var->getDeclName() << Type;
6524       Var->setInvalidDecl();
6525       return;
6526     }
6527
6528     // C++11 [class.static.data]p3: A static data member can be declared with
6529     // the constexpr specifier; if so, its declaration shall specify
6530     // a brace-or-equal-initializer.
6531     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6532     // the definition of a variable [...] or the declaration of a static data
6533     // member.
6534     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6535       if (Var->isStaticDataMember())
6536         Diag(Var->getLocation(),
6537              diag::err_constexpr_static_mem_var_requires_init)
6538           << Var->getDeclName();
6539       else
6540         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
6541       Var->setInvalidDecl();
6542       return;
6543     }
6544
6545     switch (Var->isThisDeclarationADefinition()) {
6546     case VarDecl::Definition:
6547       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6548         break;
6549
6550       // We have an out-of-line definition of a static data member
6551       // that has an in-class initializer, so we type-check this like
6552       // a declaration. 
6553       //
6554       // Fall through
6555       
6556     case VarDecl::DeclarationOnly:
6557       // It's only a declaration. 
6558
6559       // Block scope. C99 6.7p7: If an identifier for an object is
6560       // declared with no linkage (C99 6.2.2p6), the type for the
6561       // object shall be complete.
6562       if (!Type->isDependentType() && Var->isLocalVarDecl() && 
6563           !Var->getLinkage() && !Var->isInvalidDecl() &&
6564           RequireCompleteType(Var->getLocation(), Type,
6565                               diag::err_typecheck_decl_incomplete_type))
6566         Var->setInvalidDecl();
6567
6568       // Make sure that the type is not abstract.
6569       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6570           RequireNonAbstractType(Var->getLocation(), Type,
6571                                  diag::err_abstract_type_in_decl,
6572                                  AbstractVariableType))
6573         Var->setInvalidDecl();
6574       return;
6575
6576     case VarDecl::TentativeDefinition:
6577       // File scope. C99 6.9.2p2: A declaration of an identifier for an
6578       // object that has file scope without an initializer, and without a
6579       // storage-class specifier or with the storage-class specifier "static",
6580       // constitutes a tentative definition. Note: A tentative definition with
6581       // external linkage is valid (C99 6.2.2p5).
6582       if (!Var->isInvalidDecl()) {
6583         if (const IncompleteArrayType *ArrayT
6584                                     = Context.getAsIncompleteArrayType(Type)) {
6585           if (RequireCompleteType(Var->getLocation(),
6586                                   ArrayT->getElementType(),
6587                                   diag::err_illegal_decl_array_incomplete_type))
6588             Var->setInvalidDecl();
6589         } else if (Var->getStorageClass() == SC_Static) {
6590           // C99 6.9.2p3: If the declaration of an identifier for an object is
6591           // a tentative definition and has internal linkage (C99 6.2.2p3), the
6592           // declared type shall not be an incomplete type.
6593           // NOTE: code such as the following
6594           //     static struct s;
6595           //     struct s { int a; };
6596           // is accepted by gcc. Hence here we issue a warning instead of
6597           // an error and we do not invalidate the static declaration.
6598           // NOTE: to avoid multiple warnings, only check the first declaration.
6599           if (Var->getPreviousDecl() == 0)
6600             RequireCompleteType(Var->getLocation(), Type,
6601                                 diag::ext_typecheck_decl_incomplete_type);
6602         }
6603       }
6604
6605       // Record the tentative definition; we're done.
6606       if (!Var->isInvalidDecl())
6607         TentativeDefinitions.push_back(Var);
6608       return;
6609     }
6610
6611     // Provide a specific diagnostic for uninitialized variable
6612     // definitions with incomplete array type.
6613     if (Type->isIncompleteArrayType()) {
6614       Diag(Var->getLocation(),
6615            diag::err_typecheck_incomplete_array_needs_initializer);
6616       Var->setInvalidDecl();
6617       return;
6618     }
6619
6620     // Provide a specific diagnostic for uninitialized variable
6621     // definitions with reference type.
6622     if (Type->isReferenceType()) {
6623       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6624         << Var->getDeclName()
6625         << SourceRange(Var->getLocation(), Var->getLocation());
6626       Var->setInvalidDecl();
6627       return;
6628     }
6629
6630     // Do not attempt to type-check the default initializer for a
6631     // variable with dependent type.
6632     if (Type->isDependentType())
6633       return;
6634
6635     if (Var->isInvalidDecl())
6636       return;
6637
6638     if (RequireCompleteType(Var->getLocation(), 
6639                             Context.getBaseElementType(Type),
6640                             diag::err_typecheck_decl_incomplete_type)) {
6641       Var->setInvalidDecl();
6642       return;
6643     }
6644
6645     // The variable can not have an abstract class type.
6646     if (RequireNonAbstractType(Var->getLocation(), Type,
6647                                diag::err_abstract_type_in_decl,
6648                                AbstractVariableType)) {
6649       Var->setInvalidDecl();
6650       return;
6651     }
6652
6653     // Check for jumps past the implicit initializer.  C++0x
6654     // clarifies that this applies to a "variable with automatic
6655     // storage duration", not a "local variable".
6656     // C++11 [stmt.dcl]p3
6657     //   A program that jumps from a point where a variable with automatic
6658     //   storage duration is not in scope to a point where it is in scope is
6659     //   ill-formed unless the variable has scalar type, class type with a
6660     //   trivial default constructor and a trivial destructor, a cv-qualified
6661     //   version of one of these types, or an array of one of the preceding
6662     //   types and is declared without an initializer.
6663     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
6664       if (const RecordType *Record
6665             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6666         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6667         // Mark the function for further checking even if the looser rules of
6668         // C++11 do not require such checks, so that we can diagnose
6669         // incompatibilities with C++98.
6670         if (!CXXRecord->isPOD())
6671           getCurFunction()->setHasBranchProtectedScope();
6672       }
6673     }
6674     
6675     // C++03 [dcl.init]p9:
6676     //   If no initializer is specified for an object, and the
6677     //   object is of (possibly cv-qualified) non-POD class type (or
6678     //   array thereof), the object shall be default-initialized; if
6679     //   the object is of const-qualified type, the underlying class
6680     //   type shall have a user-declared default
6681     //   constructor. Otherwise, if no initializer is specified for
6682     //   a non- static object, the object and its subobjects, if
6683     //   any, have an indeterminate initial value); if the object
6684     //   or any of its subobjects are of const-qualified type, the
6685     //   program is ill-formed.
6686     // C++0x [dcl.init]p11:
6687     //   If no initializer is specified for an object, the object is
6688     //   default-initialized; [...].
6689     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6690     InitializationKind Kind
6691       = InitializationKind::CreateDefault(Var->getLocation());
6692     
6693     InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6694     ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6695                                       MultiExprArg(*this, 0, 0));
6696     if (Init.isInvalid())
6697       Var->setInvalidDecl();
6698     else if (Init.get()) {
6699       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6700       // This is important for template substitution.
6701       Var->setInitStyle(VarDecl::CallInit);
6702     }
6703
6704     CheckCompleteVariableDeclaration(Var);
6705   }
6706 }
6707
6708 void Sema::ActOnCXXForRangeDecl(Decl *D) {
6709   VarDecl *VD = dyn_cast<VarDecl>(D);
6710   if (!VD) {
6711     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6712     D->setInvalidDecl();
6713     return;
6714   }
6715
6716   VD->setCXXForRangeDecl(true);
6717
6718   // for-range-declaration cannot be given a storage class specifier.
6719   int Error = -1;
6720   switch (VD->getStorageClassAsWritten()) {
6721   case SC_None:
6722     break;
6723   case SC_Extern:
6724     Error = 0;
6725     break;
6726   case SC_Static:
6727     Error = 1;
6728     break;
6729   case SC_PrivateExtern:
6730     Error = 2;
6731     break;
6732   case SC_Auto:
6733     Error = 3;
6734     break;
6735   case SC_Register:
6736     Error = 4;
6737     break;
6738   case SC_OpenCLWorkGroupLocal:
6739     llvm_unreachable("Unexpected storage class");
6740   }
6741   if (VD->isConstexpr())
6742     Error = 5;
6743   if (Error != -1) {
6744     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6745       << VD->getDeclName() << Error;
6746     D->setInvalidDecl();
6747   }
6748 }
6749
6750 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6751   if (var->isInvalidDecl()) return;
6752
6753   // In ARC, don't allow jumps past the implicit initialization of a
6754   // local retaining variable.
6755   if (getLangOpts().ObjCAutoRefCount &&
6756       var->hasLocalStorage()) {
6757     switch (var->getType().getObjCLifetime()) {
6758     case Qualifiers::OCL_None:
6759     case Qualifiers::OCL_ExplicitNone:
6760     case Qualifiers::OCL_Autoreleasing:
6761       break;
6762
6763     case Qualifiers::OCL_Weak:
6764     case Qualifiers::OCL_Strong:
6765       getCurFunction()->setHasBranchProtectedScope();
6766       break;
6767     }
6768   }
6769
6770   // All the following checks are C++ only.
6771   if (!getLangOpts().CPlusPlus) return;
6772
6773   QualType baseType = Context.getBaseElementType(var->getType());
6774   if (baseType->isDependentType()) return;
6775
6776   // __block variables might require us to capture a copy-initializer.
6777   if (var->hasAttr<BlocksAttr>()) {
6778     // It's currently invalid to ever have a __block variable with an
6779     // array type; should we diagnose that here?
6780
6781     // Regardless, we don't want to ignore array nesting when
6782     // constructing this copy.
6783     QualType type = var->getType();
6784
6785     if (type->isStructureOrClassType()) {
6786       SourceLocation poi = var->getLocation();
6787       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
6788       ExprResult result =
6789         PerformCopyInitialization(
6790                         InitializedEntity::InitializeBlock(poi, type, false),
6791                                   poi, Owned(varRef));
6792       if (!result.isInvalid()) {
6793         result = MaybeCreateExprWithCleanups(result);
6794         Expr *init = result.takeAs<Expr>();
6795         Context.setBlockVarCopyInits(var, init);
6796       }
6797     }
6798   }
6799
6800   Expr *Init = var->getInit();
6801   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6802
6803   if (!var->getDeclContext()->isDependentContext() && Init) {
6804     if (IsGlobal && !var->isConstexpr() &&
6805         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6806                                             var->getLocation())
6807           != DiagnosticsEngine::Ignored &&
6808         !Init->isConstantInitializer(Context, baseType->isReferenceType()))
6809       Diag(var->getLocation(), diag::warn_global_constructor)
6810         << Init->getSourceRange();
6811
6812     if (var->isConstexpr()) {
6813       llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6814       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6815         SourceLocation DiagLoc = var->getLocation();
6816         // If the note doesn't add any useful information other than a source
6817         // location, fold it into the primary diagnostic.
6818         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6819               diag::note_invalid_subexpr_in_const_expr) {
6820           DiagLoc = Notes[0].first;
6821           Notes.clear();
6822         }
6823         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6824           << var << Init->getSourceRange();
6825         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6826           Diag(Notes[I].first, Notes[I].second);
6827       }
6828     } else if (var->isUsableInConstantExpressions(Context)) {
6829       // Check whether the initializer of a const variable of integral or
6830       // enumeration type is an ICE now, since we can't tell whether it was
6831       // initialized by a constant expression if we check later.
6832       var->checkInitIsICE();
6833     }
6834   }
6835
6836   // Require the destructor.
6837   if (const RecordType *recordType = baseType->getAs<RecordType>())
6838     FinalizeVarWithDestructor(var, recordType);
6839 }
6840
6841 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6842 /// any semantic actions necessary after any initializer has been attached.
6843 void
6844 Sema::FinalizeDeclaration(Decl *ThisDecl) {
6845   // Note that we are no longer parsing the initializer for this declaration.
6846   ParsingInitForAutoVars.erase(ThisDecl);
6847 }
6848
6849 Sema::DeclGroupPtrTy
6850 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6851                               Decl **Group, unsigned NumDecls) {
6852   SmallVector<Decl*, 8> Decls;
6853
6854   if (DS.isTypeSpecOwned())
6855     Decls.push_back(DS.getRepAsDecl());
6856
6857   for (unsigned i = 0; i != NumDecls; ++i)
6858     if (Decl *D = Group[i])
6859       Decls.push_back(D);
6860
6861   return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6862                               DS.getTypeSpecType() == DeclSpec::TST_auto);
6863 }
6864
6865 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
6866 /// group, performing any necessary semantic checking.
6867 Sema::DeclGroupPtrTy
6868 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6869                            bool TypeMayContainAuto) {
6870   // C++0x [dcl.spec.auto]p7:
6871   //   If the type deduced for the template parameter U is not the same in each
6872   //   deduction, the program is ill-formed.
6873   // FIXME: When initializer-list support is added, a distinction is needed
6874   // between the deduced type U and the deduced type which 'auto' stands for.
6875   //   auto a = 0, b = { 1, 2, 3 };
6876   // is legal because the deduced type U is 'int' in both cases.
6877   if (TypeMayContainAuto && NumDecls > 1) {
6878     QualType Deduced;
6879     CanQualType DeducedCanon;
6880     VarDecl *DeducedDecl = 0;
6881     for (unsigned i = 0; i != NumDecls; ++i) {
6882       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6883         AutoType *AT = D->getType()->getContainedAutoType();
6884         // Don't reissue diagnostics when instantiating a template.
6885         if (AT && D->isInvalidDecl())
6886           break;
6887         if (AT && AT->isDeduced()) {
6888           QualType U = AT->getDeducedType();
6889           CanQualType UCanon = Context.getCanonicalType(U);
6890           if (Deduced.isNull()) {
6891             Deduced = U;
6892             DeducedCanon = UCanon;
6893             DeducedDecl = D;
6894           } else if (DeducedCanon != UCanon) {
6895             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6896                  diag::err_auto_different_deductions)
6897               << Deduced << DeducedDecl->getDeclName()
6898               << U << D->getDeclName()
6899               << DeducedDecl->getInit()->getSourceRange()
6900               << D->getInit()->getSourceRange();
6901             D->setInvalidDecl();
6902             break;
6903           }
6904         }
6905       }
6906     }
6907   }
6908
6909   return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6910 }
6911
6912
6913 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6914 /// to introduce parameters into function prototype scope.
6915 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6916   const DeclSpec &DS = D.getDeclSpec();
6917
6918   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6919   // C++03 [dcl.stc]p2 also permits 'auto'.
6920   VarDecl::StorageClass StorageClass = SC_None;
6921   VarDecl::StorageClass StorageClassAsWritten = SC_None;
6922   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6923     StorageClass = SC_Register;
6924     StorageClassAsWritten = SC_Register;
6925   } else if (getLangOpts().CPlusPlus &&
6926              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6927     StorageClass = SC_Auto;
6928     StorageClassAsWritten = SC_Auto;
6929   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6930     Diag(DS.getStorageClassSpecLoc(),
6931          diag::err_invalid_storage_class_in_func_decl);
6932     D.getMutableDeclSpec().ClearStorageClassSpecs();
6933   }
6934
6935   if (D.getDeclSpec().isThreadSpecified())
6936     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6937   if (D.getDeclSpec().isConstexprSpecified())
6938     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6939       << 0;
6940
6941   DiagnoseFunctionSpecifiers(D);
6942
6943   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6944   QualType parmDeclType = TInfo->getType();
6945
6946   if (getLangOpts().CPlusPlus) {
6947     // Check that there are no default arguments inside the type of this
6948     // parameter.
6949     CheckExtraCXXDefaultArguments(D);
6950     
6951     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6952     if (D.getCXXScopeSpec().isSet()) {
6953       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6954         << D.getCXXScopeSpec().getRange();
6955       D.getCXXScopeSpec().clear();
6956     }
6957   }
6958
6959   // Ensure we have a valid name
6960   IdentifierInfo *II = 0;
6961   if (D.hasName()) {
6962     II = D.getIdentifier();
6963     if (!II) {
6964       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6965         << GetNameForDeclarator(D).getName().getAsString();
6966       D.setInvalidType(true);
6967     }
6968   }
6969
6970   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6971   if (II) {
6972     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6973                    ForRedeclaration);
6974     LookupName(R, S);
6975     if (R.isSingleResult()) {
6976       NamedDecl *PrevDecl = R.getFoundDecl();
6977       if (PrevDecl->isTemplateParameter()) {
6978         // Maybe we will complain about the shadowed template parameter.
6979         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6980         // Just pretend that we didn't see the previous declaration.
6981         PrevDecl = 0;
6982       } else if (S->isDeclScope(PrevDecl)) {
6983         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6984         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6985
6986         // Recover by removing the name
6987         II = 0;
6988         D.SetIdentifier(0, D.getIdentifierLoc());
6989         D.setInvalidType(true);
6990       }
6991     }
6992   }
6993
6994   // Temporarily put parameter variables in the translation unit, not
6995   // the enclosing context.  This prevents them from accidentally
6996   // looking like class members in C++.
6997   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6998                                     D.getLocStart(),
6999                                     D.getIdentifierLoc(), II,
7000                                     parmDeclType, TInfo,
7001                                     StorageClass, StorageClassAsWritten);
7002
7003   if (D.isInvalidType())
7004     New->setInvalidDecl();
7005
7006   assert(S->isFunctionPrototypeScope());
7007   assert(S->getFunctionPrototypeDepth() >= 1);
7008   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7009                     S->getNextFunctionPrototypeIndex());
7010   
7011   // Add the parameter declaration into this scope.
7012   S->AddDecl(New);
7013   if (II)
7014     IdResolver.AddDecl(New);
7015
7016   ProcessDeclAttributes(S, New, D);
7017
7018   if (D.getDeclSpec().isModulePrivateSpecified())
7019     Diag(New->getLocation(), diag::err_module_private_local)
7020       << 1 << New->getDeclName()
7021       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7022       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7023
7024   if (New->hasAttr<BlocksAttr>()) {
7025     Diag(New->getLocation(), diag::err_block_on_nonlocal);
7026   }
7027   return New;
7028 }
7029
7030 /// \brief Synthesizes a variable for a parameter arising from a
7031 /// typedef.
7032 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7033                                               SourceLocation Loc,
7034                                               QualType T) {
7035   /* FIXME: setting StartLoc == Loc.
7036      Would it be worth to modify callers so as to provide proper source
7037      location for the unnamed parameters, embedding the parameter's type? */
7038   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7039                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
7040                                            SC_None, SC_None, 0);
7041   Param->setImplicit();
7042   return Param;
7043 }
7044
7045 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7046                                     ParmVarDecl * const *ParamEnd) {
7047   // Don't diagnose unused-parameter errors in template instantiations; we
7048   // will already have done so in the template itself.
7049   if (!ActiveTemplateInstantiations.empty())
7050     return;
7051
7052   for (; Param != ParamEnd; ++Param) {
7053     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7054         !(*Param)->hasAttr<UnusedAttr>()) {
7055       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7056         << (*Param)->getDeclName();
7057     }
7058   }
7059 }
7060
7061 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7062                                                   ParmVarDecl * const *ParamEnd,
7063                                                   QualType ReturnTy,
7064                                                   NamedDecl *D) {
7065   if (LangOpts.NumLargeByValueCopy == 0) // No check.
7066     return;
7067
7068   // Warn if the return value is pass-by-value and larger than the specified
7069   // threshold.
7070   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7071     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7072     if (Size > LangOpts.NumLargeByValueCopy)
7073       Diag(D->getLocation(), diag::warn_return_value_size)
7074           << D->getDeclName() << Size;
7075   }
7076
7077   // Warn if any parameter is pass-by-value and larger than the specified
7078   // threshold.
7079   for (; Param != ParamEnd; ++Param) {
7080     QualType T = (*Param)->getType();
7081     if (T->isDependentType() || !T.isPODType(Context))
7082       continue;
7083     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7084     if (Size > LangOpts.NumLargeByValueCopy)
7085       Diag((*Param)->getLocation(), diag::warn_parameter_size)
7086           << (*Param)->getDeclName() << Size;
7087   }
7088 }
7089
7090 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7091                                   SourceLocation NameLoc, IdentifierInfo *Name,
7092                                   QualType T, TypeSourceInfo *TSInfo,
7093                                   VarDecl::StorageClass StorageClass,
7094                                   VarDecl::StorageClass StorageClassAsWritten) {
7095   // In ARC, infer a lifetime qualifier for appropriate parameter types.
7096   if (getLangOpts().ObjCAutoRefCount &&
7097       T.getObjCLifetime() == Qualifiers::OCL_None &&
7098       T->isObjCLifetimeType()) {
7099
7100     Qualifiers::ObjCLifetime lifetime;
7101
7102     // Special cases for arrays:
7103     //   - if it's const, use __unsafe_unretained
7104     //   - otherwise, it's an error
7105     if (T->isArrayType()) {
7106       if (!T.isConstQualified()) {
7107         DelayedDiagnostics.add(
7108             sema::DelayedDiagnostic::makeForbiddenType(
7109             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7110       }
7111       lifetime = Qualifiers::OCL_ExplicitNone;
7112     } else {
7113       lifetime = T->getObjCARCImplicitLifetime();
7114     }
7115     T = Context.getLifetimeQualifiedType(T, lifetime);
7116   }
7117
7118   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7119                                          Context.getAdjustedParameterType(T), 
7120                                          TSInfo,
7121                                          StorageClass, StorageClassAsWritten,
7122                                          0);
7123
7124   // Parameters can not be abstract class types.
7125   // For record types, this is done by the AbstractClassUsageDiagnoser once
7126   // the class has been completely parsed.
7127   if (!CurContext->isRecord() &&
7128       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7129                              AbstractParamType))
7130     New->setInvalidDecl();
7131
7132   // Parameter declarators cannot be interface types. All ObjC objects are
7133   // passed by reference.
7134   if (T->isObjCObjectType()) {
7135     Diag(NameLoc,
7136          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7137       << FixItHint::CreateInsertion(NameLoc, "*");
7138     T = Context.getObjCObjectPointerType(T);
7139     New->setType(T);
7140   }
7141
7142   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
7143   // duration shall not be qualified by an address-space qualifier."
7144   // Since all parameters have automatic store duration, they can not have
7145   // an address space.
7146   if (T.getAddressSpace() != 0) {
7147     Diag(NameLoc, diag::err_arg_with_address_space);
7148     New->setInvalidDecl();
7149   }   
7150
7151   return New;
7152 }
7153
7154 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7155                                            SourceLocation LocAfterDecls) {
7156   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7157
7158   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7159   // for a K&R function.
7160   if (!FTI.hasPrototype) {
7161     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7162       --i;
7163       if (FTI.ArgInfo[i].Param == 0) {
7164         SmallString<256> Code;
7165         llvm::raw_svector_ostream(Code) << "  int "
7166                                         << FTI.ArgInfo[i].Ident->getName()
7167                                         << ";\n";
7168         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7169           << FTI.ArgInfo[i].Ident
7170           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7171
7172         // Implicitly declare the argument as type 'int' for lack of a better
7173         // type.
7174         AttributeFactory attrs;
7175         DeclSpec DS(attrs);
7176         const char* PrevSpec; // unused
7177         unsigned DiagID; // unused
7178         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7179                            PrevSpec, DiagID);
7180         Declarator ParamD(DS, Declarator::KNRTypeListContext);
7181         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7182         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7183       }
7184     }
7185   }
7186 }
7187
7188 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
7189   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7190   assert(D.isFunctionDeclarator() && "Not a function declarator!");
7191   Scope *ParentScope = FnBodyScope->getParent();
7192
7193   D.setFunctionDefinitionKind(FDK_Definition);
7194   Decl *DP = HandleDeclarator(ParentScope, D,
7195                               MultiTemplateParamsArg(*this));
7196   return ActOnStartOfFunctionDef(FnBodyScope, DP);
7197 }
7198
7199 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7200   // Don't warn about invalid declarations.
7201   if (FD->isInvalidDecl())
7202     return false;
7203
7204   // Or declarations that aren't global.
7205   if (!FD->isGlobal())
7206     return false;
7207
7208   // Don't warn about C++ member functions.
7209   if (isa<CXXMethodDecl>(FD))
7210     return false;
7211
7212   // Don't warn about 'main'.
7213   if (FD->isMain())
7214     return false;
7215
7216   // Don't warn about inline functions.
7217   if (FD->isInlined())
7218     return false;
7219
7220   // Don't warn about function templates.
7221   if (FD->getDescribedFunctionTemplate())
7222     return false;
7223
7224   // Don't warn about function template specializations.
7225   if (FD->isFunctionTemplateSpecialization())
7226     return false;
7227
7228   bool MissingPrototype = true;
7229   for (const FunctionDecl *Prev = FD->getPreviousDecl();
7230        Prev; Prev = Prev->getPreviousDecl()) {
7231     // Ignore any declarations that occur in function or method
7232     // scope, because they aren't visible from the header.
7233     if (Prev->getDeclContext()->isFunctionOrMethod())
7234       continue;
7235       
7236     MissingPrototype = !Prev->getType()->isFunctionProtoType();
7237     break;
7238   }
7239     
7240   return MissingPrototype;
7241 }
7242
7243 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7244   // Don't complain if we're in GNU89 mode and the previous definition
7245   // was an extern inline function.
7246   const FunctionDecl *Definition;
7247   if (FD->isDefined(Definition) &&
7248       !canRedefineFunction(Definition, getLangOpts())) {
7249     if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7250         Definition->getStorageClass() == SC_Extern)
7251       Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7252         << FD->getDeclName() << getLangOpts().CPlusPlus;
7253     else
7254       Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7255     Diag(Definition->getLocation(), diag::note_previous_definition);
7256   }
7257 }
7258
7259 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7260   // Clear the last template instantiation error context.
7261   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7262   
7263   if (!D)
7264     return D;
7265   FunctionDecl *FD = 0;
7266
7267   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7268     FD = FunTmpl->getTemplatedDecl();
7269   else
7270     FD = cast<FunctionDecl>(D);
7271
7272   // Enter a new function scope
7273   PushFunctionScope();
7274
7275   // See if this is a redefinition.
7276   if (!FD->isLateTemplateParsed())
7277     CheckForFunctionRedefinition(FD);
7278
7279   // Builtin functions cannot be defined.
7280   if (unsigned BuiltinID = FD->getBuiltinID()) {
7281     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7282       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7283       FD->setInvalidDecl();
7284     }
7285   }
7286
7287   // The return type of a function definition must be complete
7288   // (C99 6.9.1p3, C++ [dcl.fct]p6).
7289   QualType ResultType = FD->getResultType();
7290   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7291       !FD->isInvalidDecl() &&
7292       RequireCompleteType(FD->getLocation(), ResultType,
7293                           diag::err_func_def_incomplete_result))
7294     FD->setInvalidDecl();
7295
7296   // GNU warning -Wmissing-prototypes:
7297   //   Warn if a global function is defined without a previous
7298   //   prototype declaration. This warning is issued even if the
7299   //   definition itself provides a prototype. The aim is to detect
7300   //   global functions that fail to be declared in header files.
7301   if (ShouldWarnAboutMissingPrototype(FD))
7302     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7303
7304   if (FnBodyScope)
7305     PushDeclContext(FnBodyScope, FD);
7306
7307   // Check the validity of our function parameters
7308   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7309                            /*CheckParameterNames=*/true);
7310
7311   // Introduce our parameters into the function scope
7312   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7313     ParmVarDecl *Param = FD->getParamDecl(p);
7314     Param->setOwningFunction(FD);
7315
7316     // If this has an identifier, add it to the scope stack.
7317     if (Param->getIdentifier() && FnBodyScope) {
7318       CheckShadow(FnBodyScope, Param);
7319
7320       PushOnScopeChains(Param, FnBodyScope);
7321     }
7322   }
7323
7324   // If we had any tags defined in the function prototype,
7325   // introduce them into the function scope.
7326   if (FnBodyScope) {
7327     for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7328            E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7329       NamedDecl *D = *I;
7330
7331       // Some of these decls (like enums) may have been pinned to the translation unit
7332       // for lack of a real context earlier. If so, remove from the translation unit
7333       // and reattach to the current context.
7334       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7335         // Is the decl actually in the context?
7336         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7337                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7338           if (*DI == D) {  
7339             Context.getTranslationUnitDecl()->removeDecl(D);
7340             break;
7341           }
7342         }
7343         // Either way, reassign the lexical decl context to our FunctionDecl.
7344         D->setLexicalDeclContext(CurContext);
7345       }
7346
7347       // If the decl has a non-null name, make accessible in the current scope.
7348       if (!D->getName().empty())
7349         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7350
7351       // Similarly, dive into enums and fish their constants out, making them
7352       // accessible in this scope.
7353       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7354         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7355                EE = ED->enumerator_end(); EI != EE; ++EI)
7356           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7357       }
7358     }
7359   }
7360
7361   // Ensure that the function's exception specification is instantiated.
7362   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7363     ResolveExceptionSpec(D->getLocation(), FPT);
7364
7365   // Checking attributes of current function definition
7366   // dllimport attribute.
7367   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7368   if (DA && (!FD->getAttr<DLLExportAttr>())) {
7369     // dllimport attribute cannot be directly applied to definition.
7370     // Microsoft accepts dllimport for functions defined within class scope. 
7371     if (!DA->isInherited() &&
7372         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7373       Diag(FD->getLocation(),
7374            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7375         << "dllimport";
7376       FD->setInvalidDecl();
7377       return FD;
7378     }
7379
7380     // Visual C++ appears to not think this is an issue, so only issue
7381     // a warning when Microsoft extensions are disabled.
7382     if (!LangOpts.MicrosoftExt) {
7383       // If a symbol previously declared dllimport is later defined, the
7384       // attribute is ignored in subsequent references, and a warning is
7385       // emitted.
7386       Diag(FD->getLocation(),
7387            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7388         << FD->getName() << "dllimport";
7389     }
7390   }
7391   return FD;
7392 }
7393
7394 /// \brief Given the set of return statements within a function body,
7395 /// compute the variables that are subject to the named return value 
7396 /// optimization.
7397 ///
7398 /// Each of the variables that is subject to the named return value 
7399 /// optimization will be marked as NRVO variables in the AST, and any
7400 /// return statement that has a marked NRVO variable as its NRVO candidate can
7401 /// use the named return value optimization.
7402 ///
7403 /// This function applies a very simplistic algorithm for NRVO: if every return
7404 /// statement in the function has the same NRVO candidate, that candidate is
7405 /// the NRVO variable.
7406 ///
7407 /// FIXME: Employ a smarter algorithm that accounts for multiple return 
7408 /// statements and the lifetimes of the NRVO candidates. We should be able to
7409 /// find a maximal set of NRVO variables.
7410 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7411   ReturnStmt **Returns = Scope->Returns.data();
7412
7413   const VarDecl *NRVOCandidate = 0;
7414   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7415     if (!Returns[I]->getNRVOCandidate())
7416       return;
7417     
7418     if (!NRVOCandidate)
7419       NRVOCandidate = Returns[I]->getNRVOCandidate();
7420     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7421       return;
7422   }
7423   
7424   if (NRVOCandidate)
7425     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7426 }
7427
7428 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7429   return ActOnFinishFunctionBody(D, move(BodyArg), false);
7430 }
7431
7432 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7433                                     bool IsInstantiation) {
7434   FunctionDecl *FD = 0;
7435   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7436   if (FunTmpl)
7437     FD = FunTmpl->getTemplatedDecl();
7438   else
7439     FD = dyn_cast_or_null<FunctionDecl>(dcl);
7440
7441   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7442   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7443
7444   if (FD) {
7445     FD->setBody(Body);
7446
7447     // If the function implicitly returns zero (like 'main') or is naked,
7448     // don't complain about missing return statements.
7449     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
7450       WP.disableCheckFallThrough();
7451
7452     // MSVC permits the use of pure specifier (=0) on function definition,
7453     // defined at class scope, warn about this non standard construct.
7454     if (getLangOpts().MicrosoftExt && FD->isPure())
7455       Diag(FD->getLocation(), diag::warn_pure_function_definition);
7456
7457     if (!FD->isInvalidDecl()) {
7458       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7459       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7460                                              FD->getResultType(), FD);
7461       
7462       // If this is a constructor, we need a vtable.
7463       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7464         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7465       
7466       computeNRVO(Body, getCurFunction());
7467     }
7468     
7469     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7470            "Function parsing confused");
7471   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7472     assert(MD == getCurMethodDecl() && "Method parsing confused");
7473     MD->setBody(Body);
7474     if (Body)
7475       MD->setEndLoc(Body->getLocEnd());
7476     if (!MD->isInvalidDecl()) {
7477       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7478       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7479                                              MD->getResultType(), MD);
7480       
7481       if (Body)
7482         computeNRVO(Body, getCurFunction());
7483     }
7484     if (ObjCShouldCallSuperDealloc) {
7485       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7486       ObjCShouldCallSuperDealloc = false;
7487     }
7488     if (ObjCShouldCallSuperFinalize) {
7489       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7490       ObjCShouldCallSuperFinalize = false;
7491     }
7492   } else {
7493     return 0;
7494   }
7495
7496   assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7497          "ObjC methods, which should have been handled in the block above.");
7498   assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7499          "ObjC methods, which should have been handled in the block above.");
7500
7501   // Verify and clean out per-function state.
7502   if (Body) {
7503     // C++ constructors that have function-try-blocks can't have return
7504     // statements in the handlers of that block. (C++ [except.handle]p14)
7505     // Verify this.
7506     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7507       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7508     
7509     // Verify that gotos and switch cases don't jump into scopes illegally.
7510     if (getCurFunction()->NeedsScopeChecking() &&
7511         !dcl->isInvalidDecl() &&
7512         !hasAnyUnrecoverableErrorsInThisFunction())
7513       DiagnoseInvalidJumps(Body);
7514
7515     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7516       if (!Destructor->getParent()->isDependentType())
7517         CheckDestructor(Destructor);
7518
7519       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7520                                              Destructor->getParent());
7521     }
7522     
7523     // If any errors have occurred, clear out any temporaries that may have
7524     // been leftover. This ensures that these temporaries won't be picked up for
7525     // deletion in some later function.
7526     if (PP.getDiagnostics().hasErrorOccurred() ||
7527         PP.getDiagnostics().getSuppressAllDiagnostics()) {
7528       DiscardCleanupsInEvaluationContext();
7529     } else if (!isa<FunctionTemplateDecl>(dcl)) {
7530       // Since the body is valid, issue any analysis-based warnings that are
7531       // enabled.
7532       ActivePolicy = &WP;
7533     }
7534
7535     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7536         (!CheckConstexprFunctionDecl(FD) ||
7537          !CheckConstexprFunctionBody(FD, Body)))
7538       FD->setInvalidDecl();
7539
7540     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
7541     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7542     assert(MaybeODRUseExprs.empty() &&
7543            "Leftover expressions for odr-use checking");
7544   }
7545   
7546   if (!IsInstantiation)
7547     PopDeclContext();
7548
7549   PopFunctionScopeInfo(ActivePolicy, dcl);
7550   
7551   // If any errors have occurred, clear out any temporaries that may have
7552   // been leftover. This ensures that these temporaries won't be picked up for
7553   // deletion in some later function.
7554   if (getDiagnostics().hasErrorOccurred()) {
7555     DiscardCleanupsInEvaluationContext();
7556   }
7557
7558   return dcl;
7559 }
7560
7561
7562 /// When we finish delayed parsing of an attribute, we must attach it to the
7563 /// relevant Decl.
7564 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7565                                        ParsedAttributes &Attrs) {
7566   // Always attach attributes to the underlying decl.
7567   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7568     D = TD->getTemplatedDecl();
7569   ProcessDeclAttributeList(S, D, Attrs.getList());  
7570   
7571   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
7572     if (Method->isStatic())
7573       checkThisInStaticMemberFunctionAttributes(Method);
7574 }
7575
7576
7577 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7578 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7579 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7580                                           IdentifierInfo &II, Scope *S) {
7581   // Before we produce a declaration for an implicitly defined
7582   // function, see whether there was a locally-scoped declaration of
7583   // this name as a function or variable. If so, use that
7584   // (non-visible) declaration, and complain about it.
7585   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7586     = findLocallyScopedExternalDecl(&II);
7587   if (Pos != LocallyScopedExternalDecls.end()) {
7588     Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7589     Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7590     return Pos->second;
7591   }
7592
7593   // Extension in C99.  Legal in C90, but warn about it.
7594   unsigned diag_id;
7595   if (II.getName().startswith("__builtin_"))
7596     diag_id = diag::warn_builtin_unknown;
7597   else if (getLangOpts().C99)
7598     diag_id = diag::ext_implicit_function_decl;
7599   else
7600     diag_id = diag::warn_implicit_function_decl;
7601   Diag(Loc, diag_id) << &II;
7602
7603   // Because typo correction is expensive, only do it if the implicit
7604   // function declaration is going to be treated as an error.
7605   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7606     TypoCorrection Corrected;
7607     DeclFilterCCC<FunctionDecl> Validator;
7608     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
7609                                       LookupOrdinaryName, S, 0, Validator))) {
7610       std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7611       std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
7612       FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
7613
7614       Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7615           << FixItHint::CreateReplacement(Loc, CorrectedStr);
7616
7617       if (Func->getLocation().isValid()
7618           && !II.getName().startswith("__builtin_"))
7619         Diag(Func->getLocation(), diag::note_previous_decl)
7620             << CorrectedQuotedStr;
7621     }
7622   }
7623
7624   // Set a Declarator for the implicit definition: int foo();
7625   const char *Dummy;
7626   AttributeFactory attrFactory;
7627   DeclSpec DS(attrFactory);
7628   unsigned DiagID;
7629   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7630   (void)Error; // Silence warning.
7631   assert(!Error && "Error setting up implicit decl!");
7632   Declarator D(DS, Declarator::BlockContext);
7633   D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7634                                              0, 0, true, SourceLocation(),
7635                                              SourceLocation(), SourceLocation(),
7636                                              SourceLocation(),
7637                                              EST_None, SourceLocation(),
7638                                              0, 0, 0, 0, Loc, Loc, D),
7639                 DS.getAttributes(),
7640                 SourceLocation());
7641   D.SetIdentifier(&II, Loc);
7642
7643   // Insert this function into translation-unit scope.
7644
7645   DeclContext *PrevDC = CurContext;
7646   CurContext = Context.getTranslationUnitDecl();
7647
7648   FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7649   FD->setImplicit();
7650
7651   CurContext = PrevDC;
7652
7653   AddKnownFunctionAttributes(FD);
7654
7655   return FD;
7656 }
7657
7658 /// \brief Adds any function attributes that we know a priori based on
7659 /// the declaration of this function.
7660 ///
7661 /// These attributes can apply both to implicitly-declared builtins
7662 /// (like __builtin___printf_chk) or to library-declared functions
7663 /// like NSLog or printf.
7664 ///
7665 /// We need to check for duplicate attributes both here and where user-written
7666 /// attributes are applied to declarations.
7667 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7668   if (FD->isInvalidDecl())
7669     return;
7670
7671   // If this is a built-in function, map its builtin attributes to
7672   // actual attributes.
7673   if (unsigned BuiltinID = FD->getBuiltinID()) {
7674     // Handle printf-formatting attributes.
7675     unsigned FormatIdx;
7676     bool HasVAListArg;
7677     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7678       if (!FD->getAttr<FormatAttr>()) {
7679         const char *fmt = "printf";
7680         unsigned int NumParams = FD->getNumParams();
7681         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7682             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7683           fmt = "NSString";
7684         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7685                                                fmt, FormatIdx+1,
7686                                                HasVAListArg ? 0 : FormatIdx+2));
7687       }
7688     }
7689     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7690                                              HasVAListArg)) {
7691      if (!FD->getAttr<FormatAttr>())
7692        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7693                                               "scanf", FormatIdx+1,
7694                                               HasVAListArg ? 0 : FormatIdx+2));
7695     }
7696
7697     // Mark const if we don't care about errno and that is the only
7698     // thing preventing the function from being const. This allows
7699     // IRgen to use LLVM intrinsics for such functions.
7700     if (!getLangOpts().MathErrno &&
7701         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7702       if (!FD->getAttr<ConstAttr>())
7703         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7704     }
7705
7706     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7707         !FD->getAttr<ReturnsTwiceAttr>())
7708       FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7709     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7710       FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7711     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7712       FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7713   }
7714
7715   IdentifierInfo *Name = FD->getIdentifier();
7716   if (!Name)
7717     return;
7718   if ((!getLangOpts().CPlusPlus &&
7719        FD->getDeclContext()->isTranslationUnit()) ||
7720       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7721        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7722        LinkageSpecDecl::lang_c)) {
7723     // Okay: this could be a libc/libm/Objective-C function we know
7724     // about.
7725   } else
7726     return;
7727
7728   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7729     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7730     // target-specific builtins, perhaps?
7731     if (!FD->getAttr<FormatAttr>())
7732       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7733                                              "printf", 2,
7734                                              Name->isStr("vasprintf") ? 0 : 3));
7735   }
7736 }
7737
7738 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7739                                     TypeSourceInfo *TInfo) {
7740   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7741   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7742
7743   if (!TInfo) {
7744     assert(D.isInvalidType() && "no declarator info for valid type");
7745     TInfo = Context.getTrivialTypeSourceInfo(T);
7746   }
7747
7748   // Scope manipulation handled by caller.
7749   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7750                                            D.getLocStart(),
7751                                            D.getIdentifierLoc(),
7752                                            D.getIdentifier(),
7753                                            TInfo);
7754
7755   // Bail out immediately if we have an invalid declaration.
7756   if (D.isInvalidType()) {
7757     NewTD->setInvalidDecl();
7758     return NewTD;
7759   }
7760
7761   if (D.getDeclSpec().isModulePrivateSpecified()) {
7762     if (CurContext->isFunctionOrMethod())
7763       Diag(NewTD->getLocation(), diag::err_module_private_local)
7764         << 2 << NewTD->getDeclName()
7765         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7766         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7767     else
7768       NewTD->setModulePrivate();
7769   }
7770   
7771   // C++ [dcl.typedef]p8:
7772   //   If the typedef declaration defines an unnamed class (or
7773   //   enum), the first typedef-name declared by the declaration
7774   //   to be that class type (or enum type) is used to denote the
7775   //   class type (or enum type) for linkage purposes only.
7776   // We need to check whether the type was declared in the declaration.
7777   switch (D.getDeclSpec().getTypeSpecType()) {
7778   case TST_enum:
7779   case TST_struct:
7780   case TST_union:
7781   case TST_class: {
7782     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7783
7784     // Do nothing if the tag is not anonymous or already has an
7785     // associated typedef (from an earlier typedef in this decl group).
7786     if (tagFromDeclSpec->getIdentifier()) break;
7787     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7788
7789     // A well-formed anonymous tag must always be a TUK_Definition.
7790     assert(tagFromDeclSpec->isThisDeclarationADefinition());
7791
7792     // The type must match the tag exactly;  no qualifiers allowed.
7793     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7794       break;
7795
7796     // Otherwise, set this is the anon-decl typedef for the tag.
7797     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7798     break;
7799   }
7800     
7801   default:
7802     break;
7803   }
7804
7805   return NewTD;
7806 }
7807
7808
7809 /// \brief Check that this is a valid underlying type for an enum declaration.
7810 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
7811   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7812   QualType T = TI->getType();
7813
7814   if (T->isDependentType() || T->isIntegralType(Context))
7815     return false;
7816
7817   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
7818   return true;
7819 }
7820
7821 /// Check whether this is a valid redeclaration of a previous enumeration.
7822 /// \return true if the redeclaration was invalid.
7823 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
7824                                   QualType EnumUnderlyingTy,
7825                                   const EnumDecl *Prev) {
7826   bool IsFixed = !EnumUnderlyingTy.isNull();
7827
7828   if (IsScoped != Prev->isScoped()) {
7829     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
7830       << Prev->isScoped();
7831     Diag(Prev->getLocation(), diag::note_previous_use);
7832     return true;
7833   }
7834
7835   if (IsFixed && Prev->isFixed()) {
7836     if (!EnumUnderlyingTy->isDependentType() &&
7837         !Prev->getIntegerType()->isDependentType() &&
7838         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
7839                                         Prev->getIntegerType())) {
7840       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
7841         << EnumUnderlyingTy << Prev->getIntegerType();
7842       Diag(Prev->getLocation(), diag::note_previous_use);
7843       return true;
7844     }
7845   } else if (IsFixed != Prev->isFixed()) {
7846     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
7847       << Prev->isFixed();
7848     Diag(Prev->getLocation(), diag::note_previous_use);
7849     return true;
7850   }
7851
7852   return false;
7853 }
7854
7855 /// \brief Determine whether a tag with a given kind is acceptable
7856 /// as a redeclaration of the given tag declaration.
7857 ///
7858 /// \returns true if the new tag kind is acceptable, false otherwise.
7859 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7860                                         TagTypeKind NewTag, bool isDefinition,
7861                                         SourceLocation NewTagLoc,
7862                                         const IdentifierInfo &Name) {
7863   // C++ [dcl.type.elab]p3:
7864   //   The class-key or enum keyword present in the
7865   //   elaborated-type-specifier shall agree in kind with the
7866   //   declaration to which the name in the elaborated-type-specifier
7867   //   refers. This rule also applies to the form of
7868   //   elaborated-type-specifier that declares a class-name or
7869   //   friend class since it can be construed as referring to the
7870   //   definition of the class. Thus, in any
7871   //   elaborated-type-specifier, the enum keyword shall be used to
7872   //   refer to an enumeration (7.2), the union class-key shall be
7873   //   used to refer to a union (clause 9), and either the class or
7874   //   struct class-key shall be used to refer to a class (clause 9)
7875   //   declared using the class or struct class-key.
7876   TagTypeKind OldTag = Previous->getTagKind();
7877   if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7878     if (OldTag == NewTag)
7879       return true;
7880
7881   if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7882       (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7883     // Warn about the struct/class tag mismatch.
7884     bool isTemplate = false;
7885     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7886       isTemplate = Record->getDescribedClassTemplate();
7887
7888     if (!ActiveTemplateInstantiations.empty()) {
7889       // In a template instantiation, do not offer fix-its for tag mismatches
7890       // since they usually mess up the template instead of fixing the problem.
7891       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7892         << (NewTag == TTK_Class) << isTemplate << &Name;
7893       return true;
7894     }
7895
7896     if (isDefinition) {
7897       // On definitions, check previous tags and issue a fix-it for each
7898       // one that doesn't match the current tag.
7899       if (Previous->getDefinition()) {
7900         // Don't suggest fix-its for redefinitions.
7901         return true;
7902       }
7903
7904       bool previousMismatch = false;
7905       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7906            E(Previous->redecls_end()); I != E; ++I) {
7907         if (I->getTagKind() != NewTag) {
7908           if (!previousMismatch) {
7909             previousMismatch = true;
7910             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7911               << (NewTag == TTK_Class) << isTemplate << &Name;
7912           }
7913           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7914             << (NewTag == TTK_Class)
7915             << FixItHint::CreateReplacement(I->getInnerLocStart(),
7916                                             NewTag == TTK_Class?
7917                                             "class" : "struct");
7918         }
7919       }
7920       return true;
7921     }
7922
7923     // Check for a previous definition.  If current tag and definition
7924     // are same type, do nothing.  If no definition, but disagree with
7925     // with previous tag type, give a warning, but no fix-it.
7926     const TagDecl *Redecl = Previous->getDefinition() ?
7927                             Previous->getDefinition() : Previous;
7928     if (Redecl->getTagKind() == NewTag) {
7929       return true;
7930     }
7931
7932     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7933       << (NewTag == TTK_Class)
7934       << isTemplate << &Name;
7935     Diag(Redecl->getLocation(), diag::note_previous_use);
7936
7937     // If there is a previous defintion, suggest a fix-it.
7938     if (Previous->getDefinition()) {
7939         Diag(NewTagLoc, diag::note_struct_class_suggestion)
7940           << (Redecl->getTagKind() == TTK_Class)
7941           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7942                         Redecl->getTagKind() == TTK_Class? "class" : "struct");
7943     }
7944
7945     return true;
7946   }
7947   return false;
7948 }
7949
7950 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
7951 /// former case, Name will be non-null.  In the later case, Name will be null.
7952 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7953 /// reference/declaration/definition of a tag.
7954 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7955                      SourceLocation KWLoc, CXXScopeSpec &SS,
7956                      IdentifierInfo *Name, SourceLocation NameLoc,
7957                      AttributeList *Attr, AccessSpecifier AS,
7958                      SourceLocation ModulePrivateLoc,
7959                      MultiTemplateParamsArg TemplateParameterLists,
7960                      bool &OwnedDecl, bool &IsDependent,
7961                      SourceLocation ScopedEnumKWLoc,
7962                      bool ScopedEnumUsesClassTag,
7963                      TypeResult UnderlyingType) {
7964   // If this is not a definition, it must have a name.
7965   IdentifierInfo *OrigName = Name;
7966   assert((Name != 0 || TUK == TUK_Definition) &&
7967          "Nameless record must be a definition!");
7968   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7969
7970   OwnedDecl = false;
7971   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7972   bool ScopedEnum = ScopedEnumKWLoc.isValid();
7973
7974   // FIXME: Check explicit specializations more carefully.
7975   bool isExplicitSpecialization = false;
7976   bool Invalid = false;
7977
7978   // We only need to do this matching if we have template parameters
7979   // or a scope specifier, which also conveniently avoids this work
7980   // for non-C++ cases.
7981   if (TemplateParameterLists.size() > 0 ||
7982       (SS.isNotEmpty() && TUK != TUK_Reference)) {
7983     if (TemplateParameterList *TemplateParams
7984           = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7985                                                 TemplateParameterLists.get(),
7986                                                 TemplateParameterLists.size(),
7987                                                     TUK == TUK_Friend,
7988                                                     isExplicitSpecialization,
7989                                                     Invalid)) {
7990       if (TemplateParams->size() > 0) {
7991         // This is a declaration or definition of a class template (which may
7992         // be a member of another template).
7993
7994         if (Invalid)
7995           return 0;
7996
7997         OwnedDecl = false;
7998         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7999                                                SS, Name, NameLoc, Attr,
8000                                                TemplateParams, AS,
8001                                                ModulePrivateLoc,
8002                                            TemplateParameterLists.size() - 1,
8003                  (TemplateParameterList**) TemplateParameterLists.release());
8004         return Result.get();
8005       } else {
8006         // The "template<>" header is extraneous.
8007         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8008           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8009         isExplicitSpecialization = true;
8010       }
8011     }
8012   }
8013
8014   // Figure out the underlying type if this a enum declaration. We need to do
8015   // this early, because it's needed to detect if this is an incompatible
8016   // redeclaration.
8017   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8018
8019   if (Kind == TTK_Enum) {
8020     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8021       // No underlying type explicitly specified, or we failed to parse the
8022       // type, default to int.
8023       EnumUnderlying = Context.IntTy.getTypePtr();
8024     else if (UnderlyingType.get()) {
8025       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8026       // integral type; any cv-qualification is ignored.
8027       TypeSourceInfo *TI = 0;
8028       GetTypeFromParser(UnderlyingType.get(), &TI);
8029       EnumUnderlying = TI;
8030
8031       if (CheckEnumUnderlyingType(TI))
8032         // Recover by falling back to int.
8033         EnumUnderlying = Context.IntTy.getTypePtr();
8034
8035       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8036                                           UPPC_FixedUnderlyingType))
8037         EnumUnderlying = Context.IntTy.getTypePtr();
8038
8039     } else if (getLangOpts().MicrosoftMode)
8040       // Microsoft enums are always of int type.
8041       EnumUnderlying = Context.IntTy.getTypePtr();
8042   }
8043
8044   DeclContext *SearchDC = CurContext;
8045   DeclContext *DC = CurContext;
8046   bool isStdBadAlloc = false;
8047
8048   RedeclarationKind Redecl = ForRedeclaration;
8049   if (TUK == TUK_Friend || TUK == TUK_Reference)
8050     Redecl = NotForRedeclaration;
8051
8052   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8053
8054   if (Name && SS.isNotEmpty()) {
8055     // We have a nested-name tag ('struct foo::bar').
8056
8057     // Check for invalid 'foo::'.
8058     if (SS.isInvalid()) {
8059       Name = 0;
8060       goto CreateNewDecl;
8061     }
8062
8063     // If this is a friend or a reference to a class in a dependent
8064     // context, don't try to make a decl for it.
8065     if (TUK == TUK_Friend || TUK == TUK_Reference) {
8066       DC = computeDeclContext(SS, false);
8067       if (!DC) {
8068         IsDependent = true;
8069         return 0;
8070       }
8071     } else {
8072       DC = computeDeclContext(SS, true);
8073       if (!DC) {
8074         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8075           << SS.getRange();
8076         return 0;
8077       }
8078     }
8079
8080     if (RequireCompleteDeclContext(SS, DC))
8081       return 0;
8082
8083     SearchDC = DC;
8084     // Look-up name inside 'foo::'.
8085     LookupQualifiedName(Previous, DC);
8086
8087     if (Previous.isAmbiguous())
8088       return 0;
8089
8090     if (Previous.empty()) {
8091       // Name lookup did not find anything. However, if the
8092       // nested-name-specifier refers to the current instantiation,
8093       // and that current instantiation has any dependent base
8094       // classes, we might find something at instantiation time: treat
8095       // this as a dependent elaborated-type-specifier.
8096       // But this only makes any sense for reference-like lookups.
8097       if (Previous.wasNotFoundInCurrentInstantiation() &&
8098           (TUK == TUK_Reference || TUK == TUK_Friend)) {
8099         IsDependent = true;
8100         return 0;
8101       }
8102
8103       // A tag 'foo::bar' must already exist.
8104       Diag(NameLoc, diag::err_not_tag_in_scope) 
8105         << Kind << Name << DC << SS.getRange();
8106       Name = 0;
8107       Invalid = true;
8108       goto CreateNewDecl;
8109     }
8110   } else if (Name) {
8111     // If this is a named struct, check to see if there was a previous forward
8112     // declaration or definition.
8113     // FIXME: We're looking into outer scopes here, even when we
8114     // shouldn't be. Doing so can result in ambiguities that we
8115     // shouldn't be diagnosing.
8116     LookupName(Previous, S);
8117
8118     if (Previous.isAmbiguous() && 
8119         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8120       LookupResult::Filter F = Previous.makeFilter();
8121       while (F.hasNext()) {
8122         NamedDecl *ND = F.next();
8123         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8124           F.erase();
8125       }
8126       F.done();
8127     }
8128     
8129     // Note:  there used to be some attempt at recovery here.
8130     if (Previous.isAmbiguous())
8131       return 0;
8132
8133     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8134       // FIXME: This makes sure that we ignore the contexts associated
8135       // with C structs, unions, and enums when looking for a matching
8136       // tag declaration or definition. See the similar lookup tweak
8137       // in Sema::LookupName; is there a better way to deal with this?
8138       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8139         SearchDC = SearchDC->getParent();
8140     }
8141   } else if (S->isFunctionPrototypeScope()) {
8142     // If this is an enum declaration in function prototype scope, set its
8143     // initial context to the translation unit.
8144     // FIXME: [citation needed]
8145     SearchDC = Context.getTranslationUnitDecl();
8146   }
8147
8148   if (Previous.isSingleResult() &&
8149       Previous.getFoundDecl()->isTemplateParameter()) {
8150     // Maybe we will complain about the shadowed template parameter.
8151     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8152     // Just pretend that we didn't see the previous declaration.
8153     Previous.clear();
8154   }
8155
8156   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8157       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8158     // This is a declaration of or a reference to "std::bad_alloc".
8159     isStdBadAlloc = true;
8160     
8161     if (Previous.empty() && StdBadAlloc) {
8162       // std::bad_alloc has been implicitly declared (but made invisible to
8163       // name lookup). Fill in this implicit declaration as the previous 
8164       // declaration, so that the declarations get chained appropriately.
8165       Previous.addDecl(getStdBadAlloc());
8166     }
8167   }
8168
8169   // If we didn't find a previous declaration, and this is a reference
8170   // (or friend reference), move to the correct scope.  In C++, we
8171   // also need to do a redeclaration lookup there, just in case
8172   // there's a shadow friend decl.
8173   if (Name && Previous.empty() &&
8174       (TUK == TUK_Reference || TUK == TUK_Friend)) {
8175     if (Invalid) goto CreateNewDecl;
8176     assert(SS.isEmpty());
8177
8178     if (TUK == TUK_Reference) {
8179       // C++ [basic.scope.pdecl]p5:
8180       //   -- for an elaborated-type-specifier of the form
8181       //
8182       //          class-key identifier
8183       //
8184       //      if the elaborated-type-specifier is used in the
8185       //      decl-specifier-seq or parameter-declaration-clause of a
8186       //      function defined in namespace scope, the identifier is
8187       //      declared as a class-name in the namespace that contains
8188       //      the declaration; otherwise, except as a friend
8189       //      declaration, the identifier is declared in the smallest
8190       //      non-class, non-function-prototype scope that contains the
8191       //      declaration.
8192       //
8193       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8194       // C structs and unions.
8195       //
8196       // It is an error in C++ to declare (rather than define) an enum
8197       // type, including via an elaborated type specifier.  We'll
8198       // diagnose that later; for now, declare the enum in the same
8199       // scope as we would have picked for any other tag type.
8200       //
8201       // GNU C also supports this behavior as part of its incomplete
8202       // enum types extension, while GNU C++ does not.
8203       //
8204       // Find the context where we'll be declaring the tag.
8205       // FIXME: We would like to maintain the current DeclContext as the
8206       // lexical context,
8207       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8208         SearchDC = SearchDC->getParent();
8209
8210       // Find the scope where we'll be declaring the tag.
8211       while (S->isClassScope() ||
8212              (getLangOpts().CPlusPlus &&
8213               S->isFunctionPrototypeScope()) ||
8214              ((S->getFlags() & Scope::DeclScope) == 0) ||
8215              (S->getEntity() &&
8216               ((DeclContext *)S->getEntity())->isTransparentContext()))
8217         S = S->getParent();
8218     } else {
8219       assert(TUK == TUK_Friend);
8220       // C++ [namespace.memdef]p3:
8221       //   If a friend declaration in a non-local class first declares a
8222       //   class or function, the friend class or function is a member of
8223       //   the innermost enclosing namespace.
8224       SearchDC = SearchDC->getEnclosingNamespaceContext();
8225     }
8226
8227     // In C++, we need to do a redeclaration lookup to properly
8228     // diagnose some problems.
8229     if (getLangOpts().CPlusPlus) {
8230       Previous.setRedeclarationKind(ForRedeclaration);
8231       LookupQualifiedName(Previous, SearchDC);
8232     }
8233   }
8234
8235   if (!Previous.empty()) {
8236     NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8237
8238     // It's okay to have a tag decl in the same scope as a typedef
8239     // which hides a tag decl in the same scope.  Finding this
8240     // insanity with a redeclaration lookup can only actually happen
8241     // in C++.
8242     //
8243     // This is also okay for elaborated-type-specifiers, which is
8244     // technically forbidden by the current standard but which is
8245     // okay according to the likely resolution of an open issue;
8246     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8247     if (getLangOpts().CPlusPlus) {
8248       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8249         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8250           TagDecl *Tag = TT->getDecl();
8251           if (Tag->getDeclName() == Name &&
8252               Tag->getDeclContext()->getRedeclContext()
8253                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
8254             PrevDecl = Tag;
8255             Previous.clear();
8256             Previous.addDecl(Tag);
8257             Previous.resolveKind();
8258           }
8259         }
8260       }
8261     }
8262
8263     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8264       // If this is a use of a previous tag, or if the tag is already declared
8265       // in the same scope (so that the definition/declaration completes or
8266       // rementions the tag), reuse the decl.
8267       if (TUK == TUK_Reference || TUK == TUK_Friend ||
8268           isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8269         // Make sure that this wasn't declared as an enum and now used as a
8270         // struct or something similar.
8271         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8272                                           TUK == TUK_Definition, KWLoc,
8273                                           *Name)) {
8274           bool SafeToContinue
8275             = (PrevTagDecl->getTagKind() != TTK_Enum &&
8276                Kind != TTK_Enum);
8277           if (SafeToContinue)
8278             Diag(KWLoc, diag::err_use_with_wrong_tag)
8279               << Name
8280               << FixItHint::CreateReplacement(SourceRange(KWLoc),
8281                                               PrevTagDecl->getKindName());
8282           else
8283             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8284           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8285
8286           if (SafeToContinue)
8287             Kind = PrevTagDecl->getTagKind();
8288           else {
8289             // Recover by making this an anonymous redefinition.
8290             Name = 0;
8291             Previous.clear();
8292             Invalid = true;
8293           }
8294         }
8295
8296         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8297           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8298
8299           // If this is an elaborated-type-specifier for a scoped enumeration,
8300           // the 'class' keyword is not necessary and not permitted.
8301           if (TUK == TUK_Reference || TUK == TUK_Friend) {
8302             if (ScopedEnum)
8303               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8304                 << PrevEnum->isScoped()
8305                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8306             return PrevTagDecl;
8307           }
8308
8309           QualType EnumUnderlyingTy;
8310           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8311             EnumUnderlyingTy = TI->getType();
8312           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8313             EnumUnderlyingTy = QualType(T, 0);
8314
8315           // All conflicts with previous declarations are recovered by
8316           // returning the previous declaration, unless this is a definition,
8317           // in which case we want the caller to bail out.
8318           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8319                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
8320             return TUK == TUK_Declaration ? PrevTagDecl : 0;
8321         }
8322
8323         if (!Invalid) {
8324           // If this is a use, just return the declaration we found.
8325
8326           // FIXME: In the future, return a variant or some other clue
8327           // for the consumer of this Decl to know it doesn't own it.
8328           // For our current ASTs this shouldn't be a problem, but will
8329           // need to be changed with DeclGroups.
8330           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8331                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8332             return PrevTagDecl;
8333
8334           // Diagnose attempts to redefine a tag.
8335           if (TUK == TUK_Definition) {
8336             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8337               // If we're defining a specialization and the previous definition
8338               // is from an implicit instantiation, don't emit an error
8339               // here; we'll catch this in the general case below.
8340               bool IsExplicitSpecializationAfterInstantiation = false;
8341               if (isExplicitSpecialization) {
8342                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8343                   IsExplicitSpecializationAfterInstantiation =
8344                     RD->getTemplateSpecializationKind() !=
8345                     TSK_ExplicitSpecialization;
8346                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8347                   IsExplicitSpecializationAfterInstantiation =
8348                     ED->getTemplateSpecializationKind() !=
8349                     TSK_ExplicitSpecialization;
8350               }
8351
8352               if (!IsExplicitSpecializationAfterInstantiation) {
8353                 // A redeclaration in function prototype scope in C isn't
8354                 // visible elsewhere, so merely issue a warning.
8355                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
8356                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8357                 else
8358                   Diag(NameLoc, diag::err_redefinition) << Name;
8359                 Diag(Def->getLocation(), diag::note_previous_definition);
8360                 // If this is a redefinition, recover by making this
8361                 // struct be anonymous, which will make any later
8362                 // references get the previous definition.
8363                 Name = 0;
8364                 Previous.clear();
8365                 Invalid = true;
8366               }
8367             } else {
8368               // If the type is currently being defined, complain
8369               // about a nested redefinition.
8370               const TagType *Tag
8371                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
8372               if (Tag->isBeingDefined()) {
8373                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
8374                 Diag(PrevTagDecl->getLocation(),
8375                      diag::note_previous_definition);
8376                 Name = 0;
8377                 Previous.clear();
8378                 Invalid = true;
8379               }
8380             }
8381
8382             // Okay, this is definition of a previously declared or referenced
8383             // tag PrevDecl. We're going to create a new Decl for it.
8384           }
8385         }
8386         // If we get here we have (another) forward declaration or we
8387         // have a definition.  Just create a new decl.
8388
8389       } else {
8390         // If we get here, this is a definition of a new tag type in a nested
8391         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8392         // new decl/type.  We set PrevDecl to NULL so that the entities
8393         // have distinct types.
8394         Previous.clear();
8395       }
8396       // If we get here, we're going to create a new Decl. If PrevDecl
8397       // is non-NULL, it's a definition of the tag declared by
8398       // PrevDecl. If it's NULL, we have a new definition.
8399
8400
8401     // Otherwise, PrevDecl is not a tag, but was found with tag
8402     // lookup.  This is only actually possible in C++, where a few
8403     // things like templates still live in the tag namespace.
8404     } else {
8405       // Use a better diagnostic if an elaborated-type-specifier
8406       // found the wrong kind of type on the first
8407       // (non-redeclaration) lookup.
8408       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8409           !Previous.isForRedeclaration()) {
8410         unsigned Kind = 0;
8411         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8412         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8413         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8414         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8415         Diag(PrevDecl->getLocation(), diag::note_declared_at);
8416         Invalid = true;
8417
8418       // Otherwise, only diagnose if the declaration is in scope.
8419       } else if (!isDeclInScope(PrevDecl, SearchDC, S, 
8420                                 isExplicitSpecialization)) {
8421         // do nothing
8422
8423       // Diagnose implicit declarations introduced by elaborated types.
8424       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8425         unsigned Kind = 0;
8426         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8427         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8428         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8429         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8430         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8431         Invalid = true;
8432
8433       // Otherwise it's a declaration.  Call out a particularly common
8434       // case here.
8435       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8436         unsigned Kind = 0;
8437         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8438         Diag(NameLoc, diag::err_tag_definition_of_typedef)
8439           << Name << Kind << TND->getUnderlyingType();
8440         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8441         Invalid = true;
8442
8443       // Otherwise, diagnose.
8444       } else {
8445         // The tag name clashes with something else in the target scope,
8446         // issue an error and recover by making this tag be anonymous.
8447         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8448         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8449         Name = 0;
8450         Invalid = true;
8451       }
8452
8453       // The existing declaration isn't relevant to us; we're in a
8454       // new scope, so clear out the previous declaration.
8455       Previous.clear();
8456     }
8457   }
8458
8459 CreateNewDecl:
8460
8461   TagDecl *PrevDecl = 0;
8462   if (Previous.isSingleResult())
8463     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8464
8465   // If there is an identifier, use the location of the identifier as the
8466   // location of the decl, otherwise use the location of the struct/union
8467   // keyword.
8468   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8469
8470   // Otherwise, create a new declaration. If there is a previous
8471   // declaration of the same entity, the two will be linked via
8472   // PrevDecl.
8473   TagDecl *New;
8474
8475   bool IsForwardReference = false;
8476   if (Kind == TTK_Enum) {
8477     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8478     // enum X { A, B, C } D;    D should chain to X.
8479     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8480                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8481                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8482     // If this is an undefined enum, warn.
8483     if (TUK != TUK_Definition && !Invalid) {
8484       TagDecl *Def;
8485       if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8486         // C++0x: 7.2p2: opaque-enum-declaration.
8487         // Conflicts are diagnosed above. Do nothing.
8488       }
8489       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8490         Diag(Loc, diag::ext_forward_ref_enum_def)
8491           << New;
8492         Diag(Def->getLocation(), diag::note_previous_definition);
8493       } else {
8494         unsigned DiagID = diag::ext_forward_ref_enum;
8495         if (getLangOpts().MicrosoftMode)
8496           DiagID = diag::ext_ms_forward_ref_enum;
8497         else if (getLangOpts().CPlusPlus)
8498           DiagID = diag::err_forward_ref_enum;
8499         Diag(Loc, DiagID);
8500         
8501         // If this is a forward-declared reference to an enumeration, make a 
8502         // note of it; we won't actually be introducing the declaration into
8503         // the declaration context.
8504         if (TUK == TUK_Reference)
8505           IsForwardReference = true;
8506       }
8507     }
8508
8509     if (EnumUnderlying) {
8510       EnumDecl *ED = cast<EnumDecl>(New);
8511       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8512         ED->setIntegerTypeSourceInfo(TI);
8513       else
8514         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8515       ED->setPromotionType(ED->getIntegerType());
8516     }
8517
8518   } else {
8519     // struct/union/class
8520
8521     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8522     // struct X { int A; } D;    D should chain to X.
8523     if (getLangOpts().CPlusPlus) {
8524       // FIXME: Look for a way to use RecordDecl for simple structs.
8525       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8526                                   cast_or_null<CXXRecordDecl>(PrevDecl));
8527
8528       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8529         StdBadAlloc = cast<CXXRecordDecl>(New);
8530     } else
8531       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8532                                cast_or_null<RecordDecl>(PrevDecl));
8533   }
8534
8535   // Maybe add qualifier info.
8536   if (SS.isNotEmpty()) {
8537     if (SS.isSet()) {
8538       // If this is either a declaration or a definition, check the 
8539       // nested-name-specifier against the current context. We don't do this
8540       // for explicit specializations, because they have similar checking
8541       // (with more specific diagnostics) in the call to 
8542       // CheckMemberSpecialization, below.
8543       if (!isExplicitSpecialization &&
8544           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8545           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8546         Invalid = true;
8547
8548       New->setQualifierInfo(SS.getWithLocInContext(Context));
8549       if (TemplateParameterLists.size() > 0) {
8550         New->setTemplateParameterListsInfo(Context,
8551                                            TemplateParameterLists.size(),
8552                     (TemplateParameterList**) TemplateParameterLists.release());
8553       }
8554     }
8555     else
8556       Invalid = true;
8557   }
8558
8559   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8560     // Add alignment attributes if necessary; these attributes are checked when
8561     // the ASTContext lays out the structure.
8562     //
8563     // It is important for implementing the correct semantics that this
8564     // happen here (in act on tag decl). The #pragma pack stack is
8565     // maintained as a result of parser callbacks which can occur at
8566     // many points during the parsing of a struct declaration (because
8567     // the #pragma tokens are effectively skipped over during the
8568     // parsing of the struct).
8569     AddAlignmentAttributesForRecord(RD);
8570     
8571     AddMsStructLayoutForRecord(RD);
8572   }
8573
8574   if (ModulePrivateLoc.isValid()) {
8575     if (isExplicitSpecialization)
8576       Diag(New->getLocation(), diag::err_module_private_specialization)
8577         << 2
8578         << FixItHint::CreateRemoval(ModulePrivateLoc);
8579     // __module_private__ does not apply to local classes. However, we only
8580     // diagnose this as an error when the declaration specifiers are
8581     // freestanding. Here, we just ignore the __module_private__.
8582     else if (!SearchDC->isFunctionOrMethod())
8583       New->setModulePrivate();
8584   }
8585   
8586   // If this is a specialization of a member class (of a class template),
8587   // check the specialization.
8588   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8589     Invalid = true;
8590            
8591   if (Invalid)
8592     New->setInvalidDecl();
8593
8594   if (Attr)
8595     ProcessDeclAttributeList(S, New, Attr);
8596
8597   // If we're declaring or defining a tag in function prototype scope
8598   // in C, note that this type can only be used within the function.
8599   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
8600     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8601
8602   // Set the lexical context. If the tag has a C++ scope specifier, the
8603   // lexical context will be different from the semantic context.
8604   New->setLexicalDeclContext(CurContext);
8605
8606   // Mark this as a friend decl if applicable.
8607   // In Microsoft mode, a friend declaration also acts as a forward
8608   // declaration so we always pass true to setObjectOfFriendDecl to make
8609   // the tag name visible.
8610   if (TUK == TUK_Friend)
8611     New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8612                                getLangOpts().MicrosoftExt);
8613
8614   // Set the access specifier.
8615   if (!Invalid && SearchDC->isRecord())
8616     SetMemberAccessSpecifier(New, PrevDecl, AS);
8617
8618   if (TUK == TUK_Definition)
8619     New->startDefinition();
8620
8621   // If this has an identifier, add it to the scope stack.
8622   if (TUK == TUK_Friend) {
8623     // We might be replacing an existing declaration in the lookup tables;
8624     // if so, borrow its access specifier.
8625     if (PrevDecl)
8626       New->setAccess(PrevDecl->getAccess());
8627
8628     DeclContext *DC = New->getDeclContext()->getRedeclContext();
8629     DC->makeDeclVisibleInContext(New);
8630     if (Name) // can be null along some error paths
8631       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8632         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8633   } else if (Name) {
8634     S = getNonFieldDeclScope(S);
8635     PushOnScopeChains(New, S, !IsForwardReference);
8636     if (IsForwardReference)
8637       SearchDC->makeDeclVisibleInContext(New);
8638
8639   } else {
8640     CurContext->addDecl(New);
8641   }
8642
8643   // If this is the C FILE type, notify the AST context.
8644   if (IdentifierInfo *II = New->getIdentifier())
8645     if (!New->isInvalidDecl() &&
8646         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8647         II->isStr("FILE"))
8648       Context.setFILEDecl(New);
8649
8650   // If we were in function prototype scope (and not in C++ mode), add this
8651   // tag to the list of decls to inject into the function definition scope.
8652   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
8653       InFunctionDeclarator && Name)
8654     DeclsInPrototypeScope.push_back(New);
8655
8656   OwnedDecl = true;
8657   return New;
8658 }
8659
8660 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8661   AdjustDeclIfTemplate(TagD);
8662   TagDecl *Tag = cast<TagDecl>(TagD);
8663   
8664   // Enter the tag context.
8665   PushDeclContext(S, Tag);
8666 }
8667
8668 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8669   assert(isa<ObjCContainerDecl>(IDecl) && 
8670          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8671   DeclContext *OCD = cast<DeclContext>(IDecl);
8672   assert(getContainingDC(OCD) == CurContext &&
8673       "The next DeclContext should be lexically contained in the current one.");
8674   CurContext = OCD;
8675   return IDecl;
8676 }
8677
8678 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8679                                            SourceLocation FinalLoc,
8680                                            SourceLocation LBraceLoc) {
8681   AdjustDeclIfTemplate(TagD);
8682   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8683
8684   FieldCollector->StartClass();
8685
8686   if (!Record->getIdentifier())
8687     return;
8688
8689   if (FinalLoc.isValid())
8690     Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8691     
8692   // C++ [class]p2:
8693   //   [...] The class-name is also inserted into the scope of the
8694   //   class itself; this is known as the injected-class-name. For
8695   //   purposes of access checking, the injected-class-name is treated
8696   //   as if it were a public member name.
8697   CXXRecordDecl *InjectedClassName
8698     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8699                             Record->getLocStart(), Record->getLocation(),
8700                             Record->getIdentifier(),
8701                             /*PrevDecl=*/0,
8702                             /*DelayTypeCreation=*/true);
8703   Context.getTypeDeclType(InjectedClassName, Record);
8704   InjectedClassName->setImplicit();
8705   InjectedClassName->setAccess(AS_public);
8706   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8707       InjectedClassName->setDescribedClassTemplate(Template);
8708   PushOnScopeChains(InjectedClassName, S);
8709   assert(InjectedClassName->isInjectedClassName() &&
8710          "Broken injected-class-name");
8711 }
8712
8713 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8714                                     SourceLocation RBraceLoc) {
8715   AdjustDeclIfTemplate(TagD);
8716   TagDecl *Tag = cast<TagDecl>(TagD);
8717   Tag->setRBraceLoc(RBraceLoc);
8718
8719   // Make sure we "complete" the definition even it is invalid.
8720   if (Tag->isBeingDefined()) {
8721     assert(Tag->isInvalidDecl() && "We should already have completed it");
8722     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8723       RD->completeDefinition();
8724   }
8725
8726   if (isa<CXXRecordDecl>(Tag))
8727     FieldCollector->FinishClass();
8728
8729   // Exit this scope of this tag's definition.
8730   PopDeclContext();
8731                                           
8732   // Notify the consumer that we've defined a tag.
8733   Consumer.HandleTagDeclDefinition(Tag);
8734 }
8735
8736 void Sema::ActOnObjCContainerFinishDefinition() {
8737   // Exit this scope of this interface definition.
8738   PopDeclContext();
8739 }
8740
8741 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8742   assert(DC == CurContext && "Mismatch of container contexts");
8743   OriginalLexicalContext = DC;
8744   ActOnObjCContainerFinishDefinition();
8745 }
8746
8747 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8748   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8749   OriginalLexicalContext = 0;
8750 }
8751
8752 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8753   AdjustDeclIfTemplate(TagD);
8754   TagDecl *Tag = cast<TagDecl>(TagD);
8755   Tag->setInvalidDecl();
8756
8757   // Make sure we "complete" the definition even it is invalid.
8758   if (Tag->isBeingDefined()) {
8759     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8760       RD->completeDefinition();
8761   }
8762
8763   // We're undoing ActOnTagStartDefinition here, not
8764   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8765   // the FieldCollector.
8766
8767   PopDeclContext();  
8768 }
8769
8770 // Note that FieldName may be null for anonymous bitfields.
8771 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8772                                 IdentifierInfo *FieldName,
8773                                 QualType FieldTy, Expr *BitWidth,
8774                                 bool *ZeroWidth) {
8775   // Default to true; that shouldn't confuse checks for emptiness
8776   if (ZeroWidth)
8777     *ZeroWidth = true;
8778
8779   // C99 6.7.2.1p4 - verify the field type.
8780   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8781   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8782     // Handle incomplete types with specific error.
8783     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8784       return ExprError();
8785     if (FieldName)
8786       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8787         << FieldName << FieldTy << BitWidth->getSourceRange();
8788     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8789       << FieldTy << BitWidth->getSourceRange();
8790   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8791                                              UPPC_BitFieldWidth))
8792     return ExprError();
8793
8794   // If the bit-width is type- or value-dependent, don't try to check
8795   // it now.
8796   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8797     return Owned(BitWidth);
8798
8799   llvm::APSInt Value;
8800   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8801   if (ICE.isInvalid())
8802     return ICE;
8803   BitWidth = ICE.take();
8804
8805   if (Value != 0 && ZeroWidth)
8806     *ZeroWidth = false;
8807
8808   // Zero-width bitfield is ok for anonymous field.
8809   if (Value == 0 && FieldName)
8810     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8811
8812   if (Value.isSigned() && Value.isNegative()) {
8813     if (FieldName)
8814       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8815                << FieldName << Value.toString(10);
8816     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8817       << Value.toString(10);
8818   }
8819
8820   if (!FieldTy->isDependentType()) {
8821     uint64_t TypeSize = Context.getTypeSize(FieldTy);
8822     if (Value.getZExtValue() > TypeSize) {
8823       if (!getLangOpts().CPlusPlus) {
8824         if (FieldName) 
8825           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8826             << FieldName << (unsigned)Value.getZExtValue() 
8827             << (unsigned)TypeSize;
8828         
8829         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8830           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8831       }
8832       
8833       if (FieldName)
8834         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8835           << FieldName << (unsigned)Value.getZExtValue() 
8836           << (unsigned)TypeSize;
8837       else
8838         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8839           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;        
8840     }
8841   }
8842
8843   return Owned(BitWidth);
8844 }
8845
8846 /// ActOnField - Each field of a C struct/union is passed into this in order
8847 /// to create a FieldDecl object for it.
8848 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8849                        Declarator &D, Expr *BitfieldWidth) {
8850   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8851                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8852                                /*HasInit=*/false, AS_public);
8853   return Res;
8854 }
8855
8856 /// HandleField - Analyze a field of a C struct or a C++ data member.
8857 ///
8858 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8859                              SourceLocation DeclStart,
8860                              Declarator &D, Expr *BitWidth, bool HasInit,
8861                              AccessSpecifier AS) {
8862   IdentifierInfo *II = D.getIdentifier();
8863   SourceLocation Loc = DeclStart;
8864   if (II) Loc = D.getIdentifierLoc();
8865
8866   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8867   QualType T = TInfo->getType();
8868   if (getLangOpts().CPlusPlus) {
8869     CheckExtraCXXDefaultArguments(D);
8870
8871     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8872                                         UPPC_DataMemberType)) {
8873       D.setInvalidType();
8874       T = Context.IntTy;
8875       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8876     }
8877   }
8878
8879   DiagnoseFunctionSpecifiers(D);
8880
8881   if (D.getDeclSpec().isThreadSpecified())
8882     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8883   if (D.getDeclSpec().isConstexprSpecified())
8884     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8885       << 2;
8886   
8887   // Check to see if this name was declared as a member previously
8888   NamedDecl *PrevDecl = 0;
8889   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8890   LookupName(Previous, S);
8891   switch (Previous.getResultKind()) {
8892     case LookupResult::Found:
8893     case LookupResult::FoundUnresolvedValue:
8894       PrevDecl = Previous.getAsSingle<NamedDecl>();
8895       break;
8896       
8897     case LookupResult::FoundOverloaded:
8898       PrevDecl = Previous.getRepresentativeDecl();
8899       break;
8900       
8901     case LookupResult::NotFound:
8902     case LookupResult::NotFoundInCurrentInstantiation:
8903     case LookupResult::Ambiguous:
8904       break;
8905   }
8906   Previous.suppressDiagnostics();
8907
8908   if (PrevDecl && PrevDecl->isTemplateParameter()) {
8909     // Maybe we will complain about the shadowed template parameter.
8910     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8911     // Just pretend that we didn't see the previous declaration.
8912     PrevDecl = 0;
8913   }
8914
8915   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8916     PrevDecl = 0;
8917
8918   bool Mutable
8919     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8920   SourceLocation TSSL = D.getLocStart();
8921   FieldDecl *NewFD
8922     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8923                      TSSL, AS, PrevDecl, &D);
8924
8925   if (NewFD->isInvalidDecl())
8926     Record->setInvalidDecl();
8927
8928   if (D.getDeclSpec().isModulePrivateSpecified())
8929     NewFD->setModulePrivate();
8930   
8931   if (NewFD->isInvalidDecl() && PrevDecl) {
8932     // Don't introduce NewFD into scope; there's already something
8933     // with the same name in the same scope.
8934   } else if (II) {
8935     PushOnScopeChains(NewFD, S);
8936   } else
8937     Record->addDecl(NewFD);
8938
8939   return NewFD;
8940 }
8941
8942 /// \brief Build a new FieldDecl and check its well-formedness.
8943 ///
8944 /// This routine builds a new FieldDecl given the fields name, type,
8945 /// record, etc. \p PrevDecl should refer to any previous declaration
8946 /// with the same name and in the same scope as the field to be
8947 /// created.
8948 ///
8949 /// \returns a new FieldDecl.
8950 ///
8951 /// \todo The Declarator argument is a hack. It will be removed once
8952 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8953                                 TypeSourceInfo *TInfo,
8954                                 RecordDecl *Record, SourceLocation Loc,
8955                                 bool Mutable, Expr *BitWidth, bool HasInit,
8956                                 SourceLocation TSSL,
8957                                 AccessSpecifier AS, NamedDecl *PrevDecl,
8958                                 Declarator *D) {
8959   IdentifierInfo *II = Name.getAsIdentifierInfo();
8960   bool InvalidDecl = false;
8961   if (D) InvalidDecl = D->isInvalidType();
8962
8963   // If we receive a broken type, recover by assuming 'int' and
8964   // marking this declaration as invalid.
8965   if (T.isNull()) {
8966     InvalidDecl = true;
8967     T = Context.IntTy;
8968   }
8969
8970   QualType EltTy = Context.getBaseElementType(T);
8971   if (!EltTy->isDependentType()) {
8972     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8973       // Fields of incomplete type force their record to be invalid.
8974       Record->setInvalidDecl();
8975       InvalidDecl = true;
8976     } else {
8977       NamedDecl *Def;
8978       EltTy->isIncompleteType(&Def);
8979       if (Def && Def->isInvalidDecl()) {
8980         Record->setInvalidDecl();
8981         InvalidDecl = true;
8982       }
8983     }
8984   }
8985
8986   // C99 6.7.2.1p8: A member of a structure or union may have any type other
8987   // than a variably modified type.
8988   if (!InvalidDecl && T->isVariablyModifiedType()) {
8989     bool SizeIsNegative;
8990     llvm::APSInt Oversized;
8991     QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8992                                                            SizeIsNegative,
8993                                                            Oversized);
8994     if (!FixedTy.isNull()) {
8995       Diag(Loc, diag::warn_illegal_constant_array_size);
8996       T = FixedTy;
8997     } else {
8998       if (SizeIsNegative)
8999         Diag(Loc, diag::err_typecheck_negative_array_size);
9000       else if (Oversized.getBoolValue())
9001         Diag(Loc, diag::err_array_too_large)
9002           << Oversized.toString(10);
9003       else
9004         Diag(Loc, diag::err_typecheck_field_variable_size);
9005       InvalidDecl = true;
9006     }
9007   }
9008
9009   // Fields can not have abstract class types
9010   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9011                                              diag::err_abstract_type_in_decl,
9012                                              AbstractFieldType))
9013     InvalidDecl = true;
9014
9015   bool ZeroWidth = false;
9016   // If this is declared as a bit-field, check the bit-field.
9017   if (!InvalidDecl && BitWidth) {
9018     BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9019     if (!BitWidth) {
9020       InvalidDecl = true;
9021       BitWidth = 0;
9022       ZeroWidth = false;
9023     }
9024   }
9025
9026   // Check that 'mutable' is consistent with the type of the declaration.
9027   if (!InvalidDecl && Mutable) {
9028     unsigned DiagID = 0;
9029     if (T->isReferenceType())
9030       DiagID = diag::err_mutable_reference;
9031     else if (T.isConstQualified())
9032       DiagID = diag::err_mutable_const;
9033
9034     if (DiagID) {
9035       SourceLocation ErrLoc = Loc;
9036       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9037         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9038       Diag(ErrLoc, DiagID);
9039       Mutable = false;
9040       InvalidDecl = true;
9041     }
9042   }
9043
9044   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9045                                        BitWidth, Mutable, HasInit);
9046   if (InvalidDecl)
9047     NewFD->setInvalidDecl();
9048
9049   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9050     Diag(Loc, diag::err_duplicate_member) << II;
9051     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9052     NewFD->setInvalidDecl();
9053   }
9054
9055   if (!InvalidDecl && getLangOpts().CPlusPlus) {
9056     if (Record->isUnion()) {
9057       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9058         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9059         if (RDecl->getDefinition()) {
9060           // C++ [class.union]p1: An object of a class with a non-trivial
9061           // constructor, a non-trivial copy constructor, a non-trivial
9062           // destructor, or a non-trivial copy assignment operator
9063           // cannot be a member of a union, nor can an array of such
9064           // objects.
9065           if (CheckNontrivialField(NewFD))
9066             NewFD->setInvalidDecl();
9067         }
9068       }
9069
9070       // C++ [class.union]p1: If a union contains a member of reference type,
9071       // the program is ill-formed.
9072       if (EltTy->isReferenceType()) {
9073         Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9074           << NewFD->getDeclName() << EltTy;
9075         NewFD->setInvalidDecl();
9076       }
9077     }
9078   }
9079
9080   // FIXME: We need to pass in the attributes given an AST
9081   // representation, not a parser representation.
9082   if (D)
9083     // FIXME: What to pass instead of TUScope?
9084     ProcessDeclAttributes(TUScope, NewFD, *D);
9085
9086   // In auto-retain/release, infer strong retension for fields of
9087   // retainable type.
9088   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9089     NewFD->setInvalidDecl();
9090
9091   if (T.isObjCGCWeak())
9092     Diag(Loc, diag::warn_attribute_weak_on_field);
9093
9094   NewFD->setAccess(AS);
9095   return NewFD;
9096 }
9097
9098 bool Sema::CheckNontrivialField(FieldDecl *FD) {
9099   assert(FD);
9100   assert(getLangOpts().CPlusPlus && "valid check only for C++");
9101
9102   if (FD->isInvalidDecl())
9103     return true;
9104
9105   QualType EltTy = Context.getBaseElementType(FD->getType());
9106   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9107     CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9108     if (RDecl->getDefinition()) {
9109       // We check for copy constructors before constructors
9110       // because otherwise we'll never get complaints about
9111       // copy constructors.
9112
9113       CXXSpecialMember member = CXXInvalid;
9114       if (!RDecl->hasTrivialCopyConstructor())
9115         member = CXXCopyConstructor;
9116       else if (!RDecl->hasTrivialDefaultConstructor())
9117         member = CXXDefaultConstructor;
9118       else if (!RDecl->hasTrivialCopyAssignment())
9119         member = CXXCopyAssignment;
9120       else if (!RDecl->hasTrivialDestructor())
9121         member = CXXDestructor;
9122
9123       if (member != CXXInvalid) {
9124         if (!getLangOpts().CPlusPlus0x &&
9125             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9126           // Objective-C++ ARC: it is an error to have a non-trivial field of
9127           // a union. However, system headers in Objective-C programs 
9128           // occasionally have Objective-C lifetime objects within unions,
9129           // and rather than cause the program to fail, we make those 
9130           // members unavailable.
9131           SourceLocation Loc = FD->getLocation();
9132           if (getSourceManager().isInSystemHeader(Loc)) {
9133             if (!FD->hasAttr<UnavailableAttr>())
9134               FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9135                                   "this system field has retaining ownership"));
9136             return false;
9137           }
9138         }
9139
9140         Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9141                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9142                diag::err_illegal_union_or_anon_struct_member)
9143           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9144         DiagnoseNontrivial(RT, member);
9145         return !getLangOpts().CPlusPlus0x;
9146       }
9147     }
9148   }
9149   
9150   return false;
9151 }
9152
9153 /// If the given constructor is user-provided, produce a diagnostic explaining
9154 /// that it makes the class non-trivial.
9155 static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9156                                                CXXConstructorDecl *CD,
9157                                                Sema::CXXSpecialMember CSM) {
9158   if (!CD->isUserProvided())
9159     return false;
9160
9161   SourceLocation CtorLoc = CD->getLocation();
9162   S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9163   return true;
9164 }
9165
9166 /// DiagnoseNontrivial - Given that a class has a non-trivial
9167 /// special member, figure out why.
9168 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9169   QualType QT(T, 0U);
9170   CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9171
9172   // Check whether the member was user-declared.
9173   switch (member) {
9174   case CXXInvalid:
9175     break;
9176
9177   case CXXDefaultConstructor:
9178     if (RD->hasUserDeclaredConstructor()) {
9179       typedef CXXRecordDecl::ctor_iterator ctor_iter;
9180       for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9181         if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
9182           return;
9183
9184       // No user-provided constructors; look for constructor templates.
9185       typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9186           tmpl_iter;
9187       for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9188            TI != TE; ++TI) {
9189         CXXConstructorDecl *CD =
9190             dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9191         if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9192           return;
9193       }
9194     }
9195     break;
9196
9197   case CXXCopyConstructor:
9198     if (RD->hasUserDeclaredCopyConstructor()) {
9199       SourceLocation CtorLoc =
9200         RD->getCopyConstructor(0)->getLocation();
9201       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9202       return;
9203     }
9204     break;
9205
9206   case CXXMoveConstructor:
9207     if (RD->hasUserDeclaredMoveConstructor()) {
9208       SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9209       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9210       return;
9211     }
9212     break;
9213
9214   case CXXCopyAssignment:
9215     if (RD->hasUserDeclaredCopyAssignment()) {
9216       // FIXME: this should use the location of the copy
9217       // assignment, not the type.
9218       SourceLocation TyLoc = RD->getLocStart();
9219       Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9220       return;
9221     }
9222     break;
9223
9224   case CXXMoveAssignment:
9225     if (RD->hasUserDeclaredMoveAssignment()) {
9226       SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9227       Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9228       return;
9229     }
9230     break;
9231
9232   case CXXDestructor:
9233     if (RD->hasUserDeclaredDestructor()) {
9234       SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9235       Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9236       return;
9237     }
9238     break;
9239   }
9240
9241   typedef CXXRecordDecl::base_class_iterator base_iter;
9242
9243   // Virtual bases and members inhibit trivial copying/construction,
9244   // but not trivial destruction.
9245   if (member != CXXDestructor) {
9246     // Check for virtual bases.  vbases includes indirect virtual bases,
9247     // so we just iterate through the direct bases.
9248     for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9249       if (bi->isVirtual()) {
9250         SourceLocation BaseLoc = bi->getLocStart();
9251         Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9252         return;
9253       }
9254
9255     // Check for virtual methods.
9256     typedef CXXRecordDecl::method_iterator meth_iter;
9257     for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9258          ++mi) {
9259       if (mi->isVirtual()) {
9260         SourceLocation MLoc = mi->getLocStart();
9261         Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9262         return;
9263       }
9264     }
9265   }
9266
9267   bool (CXXRecordDecl::*hasTrivial)() const;
9268   switch (member) {
9269   case CXXDefaultConstructor:
9270     hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
9271   case CXXCopyConstructor:
9272     hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9273   case CXXCopyAssignment:
9274     hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9275   case CXXDestructor:
9276     hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9277   default:
9278     llvm_unreachable("unexpected special member");
9279   }
9280
9281   // Check for nontrivial bases (and recurse).
9282   for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9283     const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9284     assert(BaseRT && "Don't know how to handle dependent bases");
9285     CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9286     if (!(BaseRecTy->*hasTrivial)()) {
9287       SourceLocation BaseLoc = bi->getLocStart();
9288       Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9289       DiagnoseNontrivial(BaseRT, member);
9290       return;
9291     }
9292   }
9293
9294   // Check for nontrivial members (and recurse).
9295   typedef RecordDecl::field_iterator field_iter;
9296   for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9297        ++fi) {
9298     QualType EltTy = Context.getBaseElementType((*fi)->getType());
9299     if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9300       CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9301
9302       if (!(EltRD->*hasTrivial)()) {
9303         SourceLocation FLoc = (*fi)->getLocation();
9304         Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9305         DiagnoseNontrivial(EltRT, member);
9306         return;
9307       }
9308     }
9309     
9310     if (EltTy->isObjCLifetimeType()) {
9311       switch (EltTy.getObjCLifetime()) {
9312       case Qualifiers::OCL_None:
9313       case Qualifiers::OCL_ExplicitNone:
9314         break;
9315           
9316       case Qualifiers::OCL_Autoreleasing:
9317       case Qualifiers::OCL_Weak:
9318       case Qualifiers::OCL_Strong:
9319         Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
9320           << QT << EltTy.getObjCLifetime();
9321         return;
9322       }
9323     }
9324   }
9325
9326   llvm_unreachable("found no explanation for non-trivial member");
9327 }
9328
9329 /// TranslateIvarVisibility - Translate visibility from a token ID to an
9330 ///  AST enum value.
9331 static ObjCIvarDecl::AccessControl
9332 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9333   switch (ivarVisibility) {
9334   default: llvm_unreachable("Unknown visitibility kind");
9335   case tok::objc_private: return ObjCIvarDecl::Private;
9336   case tok::objc_public: return ObjCIvarDecl::Public;
9337   case tok::objc_protected: return ObjCIvarDecl::Protected;
9338   case tok::objc_package: return ObjCIvarDecl::Package;
9339   }
9340 }
9341
9342 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
9343 /// in order to create an IvarDecl object for it.
9344 Decl *Sema::ActOnIvar(Scope *S,
9345                                 SourceLocation DeclStart,
9346                                 Declarator &D, Expr *BitfieldWidth,
9347                                 tok::ObjCKeywordKind Visibility) {
9348
9349   IdentifierInfo *II = D.getIdentifier();
9350   Expr *BitWidth = (Expr*)BitfieldWidth;
9351   SourceLocation Loc = DeclStart;
9352   if (II) Loc = D.getIdentifierLoc();
9353
9354   // FIXME: Unnamed fields can be handled in various different ways, for
9355   // example, unnamed unions inject all members into the struct namespace!
9356
9357   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9358   QualType T = TInfo->getType();
9359
9360   if (BitWidth) {
9361     // 6.7.2.1p3, 6.7.2.1p4
9362     BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9363     if (!BitWidth)
9364       D.setInvalidType();
9365   } else {
9366     // Not a bitfield.
9367
9368     // validate II.
9369
9370   }
9371   if (T->isReferenceType()) {
9372     Diag(Loc, diag::err_ivar_reference_type);
9373     D.setInvalidType();
9374   }
9375   // C99 6.7.2.1p8: A member of a structure or union may have any type other
9376   // than a variably modified type.
9377   else if (T->isVariablyModifiedType()) {
9378     Diag(Loc, diag::err_typecheck_ivar_variable_size);
9379     D.setInvalidType();
9380   }
9381
9382   // Get the visibility (access control) for this ivar.
9383   ObjCIvarDecl::AccessControl ac =
9384     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9385                                         : ObjCIvarDecl::None;
9386   // Must set ivar's DeclContext to its enclosing interface.
9387   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9388   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9389     return 0;
9390   ObjCContainerDecl *EnclosingContext;
9391   if (ObjCImplementationDecl *IMPDecl =
9392       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9393     if (!LangOpts.ObjCNonFragileABI2) {
9394     // Case of ivar declared in an implementation. Context is that of its class.
9395       EnclosingContext = IMPDecl->getClassInterface();
9396       assert(EnclosingContext && "Implementation has no class interface!");
9397     }
9398     else
9399       EnclosingContext = EnclosingDecl;
9400   } else {
9401     if (ObjCCategoryDecl *CDecl = 
9402         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9403       if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9404         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
9405         return 0;
9406       }
9407     }
9408     EnclosingContext = EnclosingDecl;
9409   }
9410
9411   // Construct the decl.
9412   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9413                                              DeclStart, Loc, II, T,
9414                                              TInfo, ac, (Expr *)BitfieldWidth);
9415
9416   if (II) {
9417     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
9418                                            ForRedeclaration);
9419     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
9420         && !isa<TagDecl>(PrevDecl)) {
9421       Diag(Loc, diag::err_duplicate_member) << II;
9422       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9423       NewID->setInvalidDecl();
9424     }
9425   }
9426
9427   // Process attributes attached to the ivar.
9428   ProcessDeclAttributes(S, NewID, D);
9429
9430   if (D.isInvalidType())
9431     NewID->setInvalidDecl();
9432
9433   // In ARC, infer 'retaining' for ivars of retainable type.
9434   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9435     NewID->setInvalidDecl();
9436
9437   if (D.getDeclSpec().isModulePrivateSpecified())
9438     NewID->setModulePrivate();
9439   
9440   if (II) {
9441     // FIXME: When interfaces are DeclContexts, we'll need to add
9442     // these to the interface.
9443     S->AddDecl(NewID);
9444     IdResolver.AddDecl(NewID);
9445   }
9446
9447   return NewID;
9448 }
9449
9450 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 
9451 /// class and class extensions. For every class @interface and class 
9452 /// extension @interface, if the last ivar is a bitfield of any type, 
9453 /// then add an implicit `char :0` ivar to the end of that interface.
9454 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9455                              SmallVectorImpl<Decl *> &AllIvarDecls) {
9456   if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9457     return;
9458   
9459   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9460   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9461   
9462   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9463     return;
9464   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9465   if (!ID) {
9466     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9467       if (!CD->IsClassExtension())
9468         return;
9469     }
9470     // No need to add this to end of @implementation.
9471     else
9472       return;
9473   }
9474   // All conditions are met. Add a new bitfield to the tail end of ivars.
9475   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9476   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9477
9478   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9479                               DeclLoc, DeclLoc, 0,
9480                               Context.CharTy, 
9481                               Context.getTrivialTypeSourceInfo(Context.CharTy,
9482                                                                DeclLoc),
9483                               ObjCIvarDecl::Private, BW,
9484                               true);
9485   AllIvarDecls.push_back(Ivar);
9486 }
9487
9488 void Sema::ActOnFields(Scope* S,
9489                        SourceLocation RecLoc, Decl *EnclosingDecl,
9490                        llvm::ArrayRef<Decl *> Fields,
9491                        SourceLocation LBrac, SourceLocation RBrac,
9492                        AttributeList *Attr) {
9493   assert(EnclosingDecl && "missing record or interface decl");
9494
9495   // If the decl this is being inserted into is invalid, then it may be a
9496   // redeclaration or some other bogus case.  Don't try to add fields to it.
9497   if (EnclosingDecl->isInvalidDecl())
9498     return;
9499
9500   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9501
9502   // Start counting up the number of named members; make sure to include
9503   // members of anonymous structs and unions in the total.
9504   unsigned NumNamedMembers = 0;
9505   if (Record) {
9506     for (RecordDecl::decl_iterator i = Record->decls_begin(),
9507                                    e = Record->decls_end(); i != e; i++) {
9508       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9509         if (IFD->getDeclName())
9510           ++NumNamedMembers;
9511     }
9512   }
9513
9514   // Verify that all the fields are okay.
9515   SmallVector<FieldDecl*, 32> RecFields;
9516
9517   bool ARCErrReported = false;
9518   for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9519        i != end; ++i) {
9520     FieldDecl *FD = cast<FieldDecl>(*i);
9521
9522     // Get the type for the field.
9523     const Type *FDTy = FD->getType().getTypePtr();
9524
9525     if (!FD->isAnonymousStructOrUnion()) {
9526       // Remember all fields written by the user.
9527       RecFields.push_back(FD);
9528     }
9529
9530     // If the field is already invalid for some reason, don't emit more
9531     // diagnostics about it.
9532     if (FD->isInvalidDecl()) {
9533       EnclosingDecl->setInvalidDecl();
9534       continue;
9535     }
9536
9537     // C99 6.7.2.1p2:
9538     //   A structure or union shall not contain a member with
9539     //   incomplete or function type (hence, a structure shall not
9540     //   contain an instance of itself, but may contain a pointer to
9541     //   an instance of itself), except that the last member of a
9542     //   structure with more than one named member may have incomplete
9543     //   array type; such a structure (and any union containing,
9544     //   possibly recursively, a member that is such a structure)
9545     //   shall not be a member of a structure or an element of an
9546     //   array.
9547     if (FDTy->isFunctionType()) {
9548       // Field declared as a function.
9549       Diag(FD->getLocation(), diag::err_field_declared_as_function)
9550         << FD->getDeclName();
9551       FD->setInvalidDecl();
9552       EnclosingDecl->setInvalidDecl();
9553       continue;
9554     } else if (FDTy->isIncompleteArrayType() && Record && 
9555                ((i + 1 == Fields.end() && !Record->isUnion()) ||
9556                 ((getLangOpts().MicrosoftExt ||
9557                   getLangOpts().CPlusPlus) &&
9558                  (i + 1 == Fields.end() || Record->isUnion())))) {
9559       // Flexible array member.
9560       // Microsoft and g++ is more permissive regarding flexible array.
9561       // It will accept flexible array in union and also
9562       // as the sole element of a struct/class.
9563       if (getLangOpts().MicrosoftExt) {
9564         if (Record->isUnion()) 
9565           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9566             << FD->getDeclName();
9567         else if (Fields.size() == 1) 
9568           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9569             << FD->getDeclName() << Record->getTagKind();
9570       } else if (getLangOpts().CPlusPlus) {
9571         if (Record->isUnion()) 
9572           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9573             << FD->getDeclName();
9574         else if (Fields.size() == 1) 
9575           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9576             << FD->getDeclName() << Record->getTagKind();
9577       } else if (!getLangOpts().C99) {
9578       if (Record->isUnion())
9579         Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9580           << FD->getDeclName();
9581       else
9582         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9583           << FD->getDeclName() << Record->getTagKind();
9584       } else if (NumNamedMembers < 1) {
9585         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9586           << FD->getDeclName();
9587         FD->setInvalidDecl();
9588         EnclosingDecl->setInvalidDecl();
9589         continue;
9590       }
9591       if (!FD->getType()->isDependentType() &&
9592           !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9593         Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9594           << FD->getDeclName() << FD->getType();
9595         FD->setInvalidDecl();
9596         EnclosingDecl->setInvalidDecl();
9597         continue;
9598       }
9599       // Okay, we have a legal flexible array member at the end of the struct.
9600       if (Record)
9601         Record->setHasFlexibleArrayMember(true);
9602     } else if (!FDTy->isDependentType() &&
9603                RequireCompleteType(FD->getLocation(), FD->getType(),
9604                                    diag::err_field_incomplete)) {
9605       // Incomplete type
9606       FD->setInvalidDecl();
9607       EnclosingDecl->setInvalidDecl();
9608       continue;
9609     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9610       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9611         // If this is a member of a union, then entire union becomes "flexible".
9612         if (Record && Record->isUnion()) {
9613           Record->setHasFlexibleArrayMember(true);
9614         } else {
9615           // If this is a struct/class and this is not the last element, reject
9616           // it.  Note that GCC supports variable sized arrays in the middle of
9617           // structures.
9618           if (i + 1 != Fields.end())
9619             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9620               << FD->getDeclName() << FD->getType();
9621           else {
9622             // We support flexible arrays at the end of structs in
9623             // other structs as an extension.
9624             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9625               << FD->getDeclName();
9626             if (Record)
9627               Record->setHasFlexibleArrayMember(true);
9628           }
9629         }
9630       }
9631       if (Record && FDTTy->getDecl()->hasObjectMember())
9632         Record->setHasObjectMember(true);
9633     } else if (FDTy->isObjCObjectType()) {
9634       /// A field cannot be an Objective-c object
9635       Diag(FD->getLocation(), diag::err_statically_allocated_object)
9636         << FixItHint::CreateInsertion(FD->getLocation(), "*");
9637       QualType T = Context.getObjCObjectPointerType(FD->getType());
9638       FD->setType(T);
9639     } 
9640     else if (!getLangOpts().CPlusPlus) {
9641       if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
9642         // It's an error in ARC if a field has lifetime.
9643         // We don't want to report this in a system header, though,
9644         // so we just make the field unavailable.
9645         // FIXME: that's really not sufficient; we need to make the type
9646         // itself invalid to, say, initialize or copy.
9647         QualType T = FD->getType();
9648         Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9649         if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9650           SourceLocation loc = FD->getLocation();
9651           if (getSourceManager().isInSystemHeader(loc)) {
9652             if (!FD->hasAttr<UnavailableAttr>()) {
9653               FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9654                                 "this system field has retaining ownership"));
9655             }
9656           } else {
9657             Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 
9658               << T->isBlockPointerType();
9659           }
9660           ARCErrReported = true;
9661         }
9662       }
9663       else if (getLangOpts().ObjC1 &&
9664                getLangOpts().getGC() != LangOptions::NonGC &&
9665                Record && !Record->hasObjectMember()) {
9666         if (FD->getType()->isObjCObjectPointerType() ||
9667             FD->getType().isObjCGCStrong())
9668           Record->setHasObjectMember(true);
9669         else if (Context.getAsArrayType(FD->getType())) {
9670           QualType BaseType = Context.getBaseElementType(FD->getType());
9671           if (BaseType->isRecordType() && 
9672               BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9673             Record->setHasObjectMember(true);
9674           else if (BaseType->isObjCObjectPointerType() ||
9675                    BaseType.isObjCGCStrong())
9676                  Record->setHasObjectMember(true);
9677         }
9678       }
9679     }
9680     // Keep track of the number of named members.
9681     if (FD->getIdentifier())
9682       ++NumNamedMembers;
9683   }
9684
9685   // Okay, we successfully defined 'Record'.
9686   if (Record) {
9687     bool Completed = false;
9688     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9689       if (!CXXRecord->isInvalidDecl()) {
9690         // Set access bits correctly on the directly-declared conversions.
9691         UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9692         for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 
9693              I != E; ++I)
9694           Convs->setAccess(I, (*I)->getAccess());
9695         
9696         if (!CXXRecord->isDependentType()) {
9697           // Objective-C Automatic Reference Counting:
9698           //   If a class has a non-static data member of Objective-C pointer
9699           //   type (or array thereof), it is a non-POD type and its
9700           //   default constructor (if any), copy constructor, copy assignment
9701           //   operator, and destructor are non-trivial.
9702           //
9703           // This rule is also handled by CXXRecordDecl::completeDefinition(). 
9704           // However, here we check whether this particular class is only 
9705           // non-POD because of the presence of an Objective-C pointer member. 
9706           // If so, objects of this type cannot be shared between code compiled 
9707           // with instant objects and code compiled with manual retain/release.
9708           if (getLangOpts().ObjCAutoRefCount &&
9709               CXXRecord->hasObjectMember() && 
9710               CXXRecord->getLinkage() == ExternalLinkage) {
9711             if (CXXRecord->isPOD()) {
9712               Diag(CXXRecord->getLocation(), 
9713                    diag::warn_arc_non_pod_class_with_object_member)
9714                << CXXRecord;
9715             } else {
9716               // FIXME: Fix-Its would be nice here, but finding a good location
9717               // for them is going to be tricky.
9718               if (CXXRecord->hasTrivialCopyConstructor())
9719                 Diag(CXXRecord->getLocation(), 
9720                      diag::warn_arc_trivial_member_function_with_object_member)
9721                   << CXXRecord << 0;
9722               if (CXXRecord->hasTrivialCopyAssignment())
9723                 Diag(CXXRecord->getLocation(), 
9724                      diag::warn_arc_trivial_member_function_with_object_member)
9725                 << CXXRecord << 1;
9726               if (CXXRecord->hasTrivialDestructor())
9727                 Diag(CXXRecord->getLocation(), 
9728                      diag::warn_arc_trivial_member_function_with_object_member)
9729                 << CXXRecord << 2;
9730             }
9731           }
9732           
9733           // Adjust user-defined destructor exception spec.
9734           if (getLangOpts().CPlusPlus0x &&
9735               CXXRecord->hasUserDeclaredDestructor())
9736             AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9737
9738           // Add any implicitly-declared members to this class.
9739           AddImplicitlyDeclaredMembersToClass(CXXRecord);
9740
9741           // If we have virtual base classes, we may end up finding multiple 
9742           // final overriders for a given virtual function. Check for this 
9743           // problem now.
9744           if (CXXRecord->getNumVBases()) {
9745             CXXFinalOverriderMap FinalOverriders;
9746             CXXRecord->getFinalOverriders(FinalOverriders);
9747             
9748             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
9749                                              MEnd = FinalOverriders.end();
9750                  M != MEnd; ++M) {
9751               for (OverridingMethods::iterator SO = M->second.begin(), 
9752                                             SOEnd = M->second.end();
9753                    SO != SOEnd; ++SO) {
9754                 assert(SO->second.size() > 0 && 
9755                        "Virtual function without overridding functions?");
9756                 if (SO->second.size() == 1)
9757                   continue;
9758                 
9759                 // C++ [class.virtual]p2:
9760                 //   In a derived class, if a virtual member function of a base
9761                 //   class subobject has more than one final overrider the
9762                 //   program is ill-formed.
9763                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9764                   << (NamedDecl *)M->first << Record;
9765                 Diag(M->first->getLocation(), 
9766                      diag::note_overridden_virtual_function);
9767                 for (OverridingMethods::overriding_iterator 
9768                           OM = SO->second.begin(), 
9769                        OMEnd = SO->second.end();
9770                      OM != OMEnd; ++OM)
9771                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
9772                     << (NamedDecl *)M->first << OM->Method->getParent();
9773                 
9774                 Record->setInvalidDecl();
9775               }
9776             }
9777             CXXRecord->completeDefinition(&FinalOverriders);
9778             Completed = true;
9779           }
9780         }
9781       }
9782     }
9783     
9784     if (!Completed)
9785       Record->completeDefinition();
9786
9787   } else {
9788     ObjCIvarDecl **ClsFields =
9789       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9790     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9791       ID->setEndOfDefinitionLoc(RBrac);
9792       // Add ivar's to class's DeclContext.
9793       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9794         ClsFields[i]->setLexicalDeclContext(ID);
9795         ID->addDecl(ClsFields[i]);
9796       }
9797       // Must enforce the rule that ivars in the base classes may not be
9798       // duplicates.
9799       if (ID->getSuperClass())
9800         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9801     } else if (ObjCImplementationDecl *IMPDecl =
9802                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9803       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9804       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9805         // Ivar declared in @implementation never belongs to the implementation.
9806         // Only it is in implementation's lexical context.
9807         ClsFields[I]->setLexicalDeclContext(IMPDecl);
9808       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9809       IMPDecl->setIvarLBraceLoc(LBrac);
9810       IMPDecl->setIvarRBraceLoc(RBrac);
9811     } else if (ObjCCategoryDecl *CDecl = 
9812                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9813       // case of ivars in class extension; all other cases have been
9814       // reported as errors elsewhere.
9815       // FIXME. Class extension does not have a LocEnd field.
9816       // CDecl->setLocEnd(RBrac);
9817       // Add ivar's to class extension's DeclContext.
9818       // Diagnose redeclaration of private ivars.
9819       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9820       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9821         if (IDecl) {
9822           if (const ObjCIvarDecl *ClsIvar = 
9823               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9824             Diag(ClsFields[i]->getLocation(), 
9825                  diag::err_duplicate_ivar_declaration); 
9826             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9827             continue;
9828           }
9829           for (const ObjCCategoryDecl *ClsExtDecl = 
9830                 IDecl->getFirstClassExtension();
9831                ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9832             if (const ObjCIvarDecl *ClsExtIvar = 
9833                 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9834               Diag(ClsFields[i]->getLocation(), 
9835                    diag::err_duplicate_ivar_declaration); 
9836               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9837               continue;
9838             }
9839           }
9840         }
9841         ClsFields[i]->setLexicalDeclContext(CDecl);
9842         CDecl->addDecl(ClsFields[i]);
9843       }
9844       CDecl->setIvarLBraceLoc(LBrac);
9845       CDecl->setIvarRBraceLoc(RBrac);
9846     }
9847   }
9848
9849   if (Attr)
9850     ProcessDeclAttributeList(S, Record, Attr);
9851
9852   // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9853   // set the visibility of this record.
9854   if (Record && !Record->getDeclContext()->isRecord())
9855     AddPushedVisibilityAttribute(Record);
9856 }
9857
9858 /// \brief Determine whether the given integral value is representable within
9859 /// the given type T.
9860 static bool isRepresentableIntegerValue(ASTContext &Context,
9861                                         llvm::APSInt &Value,
9862                                         QualType T) {
9863   assert(T->isIntegralType(Context) && "Integral type required!");
9864   unsigned BitWidth = Context.getIntWidth(T);
9865   
9866   if (Value.isUnsigned() || Value.isNonNegative()) {
9867     if (T->isSignedIntegerOrEnumerationType()) 
9868       --BitWidth;
9869     return Value.getActiveBits() <= BitWidth;
9870   }  
9871   return Value.getMinSignedBits() <= BitWidth;
9872 }
9873
9874 // \brief Given an integral type, return the next larger integral type
9875 // (or a NULL type of no such type exists).
9876 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9877   // FIXME: Int128/UInt128 support, which also needs to be introduced into 
9878   // enum checking below.
9879   assert(T->isIntegralType(Context) && "Integral type required!");
9880   const unsigned NumTypes = 4;
9881   QualType SignedIntegralTypes[NumTypes] = { 
9882     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9883   };
9884   QualType UnsignedIntegralTypes[NumTypes] = { 
9885     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 
9886     Context.UnsignedLongLongTy
9887   };
9888   
9889   unsigned BitWidth = Context.getTypeSize(T);
9890   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9891                                                         : UnsignedIntegralTypes;
9892   for (unsigned I = 0; I != NumTypes; ++I)
9893     if (Context.getTypeSize(Types[I]) > BitWidth)
9894       return Types[I];
9895   
9896   return QualType();
9897 }
9898
9899 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9900                                           EnumConstantDecl *LastEnumConst,
9901                                           SourceLocation IdLoc,
9902                                           IdentifierInfo *Id,
9903                                           Expr *Val) {
9904   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9905   llvm::APSInt EnumVal(IntWidth);
9906   QualType EltTy;
9907
9908   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9909     Val = 0;
9910
9911   if (Val)
9912     Val = DefaultLvalueConversion(Val).take();
9913
9914   if (Val) {
9915     if (Enum->isDependentType() || Val->isTypeDependent())
9916       EltTy = Context.DependentTy;
9917     else {
9918       SourceLocation ExpLoc;
9919       if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9920           !getLangOpts().MicrosoftMode) {
9921         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9922         // constant-expression in the enumerator-definition shall be a converted
9923         // constant expression of the underlying type.
9924         EltTy = Enum->getIntegerType();
9925         ExprResult Converted =
9926           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9927                                            CCEK_Enumerator);
9928         if (Converted.isInvalid())
9929           Val = 0;
9930         else
9931           Val = Converted.take();
9932       } else if (!Val->isValueDependent() &&
9933                  !(Val = VerifyIntegerConstantExpression(Val,
9934                                                          &EnumVal).take())) {
9935         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9936       } else {
9937         if (Enum->isFixed()) {
9938           EltTy = Enum->getIntegerType();
9939
9940           // In Obj-C and Microsoft mode, require the enumeration value to be
9941           // representable in the underlying type of the enumeration. In C++11,
9942           // we perform a non-narrowing conversion as part of converted constant
9943           // expression checking.
9944           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9945             if (getLangOpts().MicrosoftMode) {
9946               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9947               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9948             } else
9949               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
9950           } else
9951             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9952         } else if (getLangOpts().CPlusPlus) {
9953           // C++11 [dcl.enum]p5:
9954           //   If the underlying type is not fixed, the type of each enumerator
9955           //   is the type of its initializing value:
9956           //     - If an initializer is specified for an enumerator, the 
9957           //       initializing value has the same type as the expression.
9958           EltTy = Val->getType();
9959         } else {
9960           // C99 6.7.2.2p2:
9961           //   The expression that defines the value of an enumeration constant
9962           //   shall be an integer constant expression that has a value
9963           //   representable as an int.
9964
9965           // Complain if the value is not representable in an int.
9966           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9967             Diag(IdLoc, diag::ext_enum_value_not_int)
9968               << EnumVal.toString(10) << Val->getSourceRange()
9969               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9970           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9971             // Force the type of the expression to 'int'.
9972             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9973           }
9974           EltTy = Val->getType();
9975         }
9976       }
9977     }
9978   }
9979
9980   if (!Val) {
9981     if (Enum->isDependentType())
9982       EltTy = Context.DependentTy;
9983     else if (!LastEnumConst) {
9984       // C++0x [dcl.enum]p5:
9985       //   If the underlying type is not fixed, the type of each enumerator
9986       //   is the type of its initializing value:
9987       //     - If no initializer is specified for the first enumerator, the 
9988       //       initializing value has an unspecified integral type.
9989       //
9990       // GCC uses 'int' for its unspecified integral type, as does 
9991       // C99 6.7.2.2p3.
9992       if (Enum->isFixed()) {
9993         EltTy = Enum->getIntegerType();
9994       }
9995       else {
9996         EltTy = Context.IntTy;
9997       }
9998     } else {
9999       // Assign the last value + 1.
10000       EnumVal = LastEnumConst->getInitVal();
10001       ++EnumVal;
10002       EltTy = LastEnumConst->getType();
10003
10004       // Check for overflow on increment.
10005       if (EnumVal < LastEnumConst->getInitVal()) {
10006         // C++0x [dcl.enum]p5:
10007         //   If the underlying type is not fixed, the type of each enumerator
10008         //   is the type of its initializing value:
10009         //
10010         //     - Otherwise the type of the initializing value is the same as
10011         //       the type of the initializing value of the preceding enumerator
10012         //       unless the incremented value is not representable in that type,
10013         //       in which case the type is an unspecified integral type 
10014         //       sufficient to contain the incremented value. If no such type
10015         //       exists, the program is ill-formed.
10016         QualType T = getNextLargerIntegralType(Context, EltTy);
10017         if (T.isNull() || Enum->isFixed()) {
10018           // There is no integral type larger enough to represent this 
10019           // value. Complain, then allow the value to wrap around.
10020           EnumVal = LastEnumConst->getInitVal();
10021           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10022           ++EnumVal;
10023           if (Enum->isFixed())
10024             // When the underlying type is fixed, this is ill-formed.
10025             Diag(IdLoc, diag::err_enumerator_wrapped)
10026               << EnumVal.toString(10)
10027               << EltTy;
10028           else
10029             Diag(IdLoc, diag::warn_enumerator_too_large)
10030               << EnumVal.toString(10);
10031         } else {
10032           EltTy = T;
10033         }
10034         
10035         // Retrieve the last enumerator's value, extent that type to the
10036         // type that is supposed to be large enough to represent the incremented
10037         // value, then increment.
10038         EnumVal = LastEnumConst->getInitVal();
10039         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10040         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10041         ++EnumVal;        
10042         
10043         // If we're not in C++, diagnose the overflow of enumerator values,
10044         // which in C99 means that the enumerator value is not representable in
10045         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10046         // permits enumerator values that are representable in some larger
10047         // integral type.
10048         if (!getLangOpts().CPlusPlus && !T.isNull())
10049           Diag(IdLoc, diag::warn_enum_value_overflow);
10050       } else if (!getLangOpts().CPlusPlus &&
10051                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10052         // Enforce C99 6.7.2.2p2 even when we compute the next value.
10053         Diag(IdLoc, diag::ext_enum_value_not_int)
10054           << EnumVal.toString(10) << 1;
10055       }
10056     }
10057   }
10058
10059   if (!EltTy->isDependentType()) {
10060     // Make the enumerator value match the signedness and size of the 
10061     // enumerator's type.
10062     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10063     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10064   }
10065   
10066   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10067                                   Val, EnumVal);
10068 }
10069
10070
10071 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10072                               SourceLocation IdLoc, IdentifierInfo *Id,
10073                               AttributeList *Attr,
10074                               SourceLocation EqualLoc, Expr *Val) {
10075   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10076   EnumConstantDecl *LastEnumConst =
10077     cast_or_null<EnumConstantDecl>(lastEnumConst);
10078
10079   // The scope passed in may not be a decl scope.  Zip up the scope tree until
10080   // we find one that is.
10081   S = getNonFieldDeclScope(S);
10082
10083   // Verify that there isn't already something declared with this name in this
10084   // scope.
10085   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10086                                          ForRedeclaration);
10087   if (PrevDecl && PrevDecl->isTemplateParameter()) {
10088     // Maybe we will complain about the shadowed template parameter.
10089     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10090     // Just pretend that we didn't see the previous declaration.
10091     PrevDecl = 0;
10092   }
10093
10094   if (PrevDecl) {
10095     // When in C++, we may get a TagDecl with the same name; in this case the
10096     // enum constant will 'hide' the tag.
10097     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10098            "Received TagDecl when not in C++!");
10099     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10100       if (isa<EnumConstantDecl>(PrevDecl))
10101         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10102       else
10103         Diag(IdLoc, diag::err_redefinition) << Id;
10104       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10105       return 0;
10106     }
10107   }
10108
10109   // C++ [class.mem]p13:
10110   //   If T is the name of a class, then each of the following shall have a 
10111   //   name different from T:
10112   //     - every enumerator of every member of class T that is an enumerated 
10113   //       type
10114   if (CXXRecordDecl *Record
10115                       = dyn_cast<CXXRecordDecl>(
10116                              TheEnumDecl->getDeclContext()->getRedeclContext()))
10117     if (Record->getIdentifier() && Record->getIdentifier() == Id)
10118       Diag(IdLoc, diag::err_member_name_of_class) << Id;
10119   
10120   EnumConstantDecl *New =
10121     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10122
10123   if (New) {
10124     // Process attributes.
10125     if (Attr) ProcessDeclAttributeList(S, New, Attr);
10126
10127     // Register this decl in the current scope stack.
10128     New->setAccess(TheEnumDecl->getAccess());
10129     PushOnScopeChains(New, S);
10130   }
10131
10132   return New;
10133 }
10134
10135 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10136                          SourceLocation RBraceLoc, Decl *EnumDeclX,
10137                          Decl **Elements, unsigned NumElements,
10138                          Scope *S, AttributeList *Attr) {
10139   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10140   QualType EnumType = Context.getTypeDeclType(Enum);
10141
10142   if (Attr)
10143     ProcessDeclAttributeList(S, Enum, Attr);
10144
10145   if (Enum->isDependentType()) {
10146     for (unsigned i = 0; i != NumElements; ++i) {
10147       EnumConstantDecl *ECD =
10148         cast_or_null<EnumConstantDecl>(Elements[i]);
10149       if (!ECD) continue;
10150
10151       ECD->setType(EnumType);
10152     }
10153
10154     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10155     return;
10156   }
10157
10158   // TODO: If the result value doesn't fit in an int, it must be a long or long
10159   // long value.  ISO C does not support this, but GCC does as an extension,
10160   // emit a warning.
10161   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10162   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10163   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10164
10165   // Verify that all the values are okay, compute the size of the values, and
10166   // reverse the list.
10167   unsigned NumNegativeBits = 0;
10168   unsigned NumPositiveBits = 0;
10169
10170   // Keep track of whether all elements have type int.
10171   bool AllElementsInt = true;
10172
10173   for (unsigned i = 0; i != NumElements; ++i) {
10174     EnumConstantDecl *ECD =
10175       cast_or_null<EnumConstantDecl>(Elements[i]);
10176     if (!ECD) continue;  // Already issued a diagnostic.
10177
10178     const llvm::APSInt &InitVal = ECD->getInitVal();
10179
10180     // Keep track of the size of positive and negative values.
10181     if (InitVal.isUnsigned() || InitVal.isNonNegative())
10182       NumPositiveBits = std::max(NumPositiveBits,
10183                                  (unsigned)InitVal.getActiveBits());
10184     else
10185       NumNegativeBits = std::max(NumNegativeBits,
10186                                  (unsigned)InitVal.getMinSignedBits());
10187
10188     // Keep track of whether every enum element has type int (very commmon).
10189     if (AllElementsInt)
10190       AllElementsInt = ECD->getType() == Context.IntTy;
10191   }
10192
10193   // Figure out the type that should be used for this enum.
10194   QualType BestType;
10195   unsigned BestWidth;
10196
10197   // C++0x N3000 [conv.prom]p3:
10198   //   An rvalue of an unscoped enumeration type whose underlying
10199   //   type is not fixed can be converted to an rvalue of the first
10200   //   of the following types that can represent all the values of
10201   //   the enumeration: int, unsigned int, long int, unsigned long
10202   //   int, long long int, or unsigned long long int.
10203   // C99 6.4.4.3p2:
10204   //   An identifier declared as an enumeration constant has type int.
10205   // The C99 rule is modified by a gcc extension 
10206   QualType BestPromotionType;
10207
10208   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10209   // -fshort-enums is the equivalent to specifying the packed attribute on all
10210   // enum definitions.
10211   if (LangOpts.ShortEnums)
10212     Packed = true;
10213
10214   if (Enum->isFixed()) {
10215     BestType = Enum->getIntegerType();
10216     if (BestType->isPromotableIntegerType())
10217       BestPromotionType = Context.getPromotedIntegerType(BestType);
10218     else
10219       BestPromotionType = BestType;
10220     // We don't need to set BestWidth, because BestType is going to be the type
10221     // of the enumerators, but we do anyway because otherwise some compilers
10222     // warn that it might be used uninitialized.
10223     BestWidth = CharWidth;
10224   }
10225   else if (NumNegativeBits) {
10226     // If there is a negative value, figure out the smallest integer type (of
10227     // int/long/longlong) that fits.
10228     // If it's packed, check also if it fits a char or a short.
10229     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10230       BestType = Context.SignedCharTy;
10231       BestWidth = CharWidth;
10232     } else if (Packed && NumNegativeBits <= ShortWidth &&
10233                NumPositiveBits < ShortWidth) {
10234       BestType = Context.ShortTy;
10235       BestWidth = ShortWidth;
10236     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10237       BestType = Context.IntTy;
10238       BestWidth = IntWidth;
10239     } else {
10240       BestWidth = Context.getTargetInfo().getLongWidth();
10241
10242       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10243         BestType = Context.LongTy;
10244       } else {
10245         BestWidth = Context.getTargetInfo().getLongLongWidth();
10246
10247         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10248           Diag(Enum->getLocation(), diag::warn_enum_too_large);
10249         BestType = Context.LongLongTy;
10250       }
10251     }
10252     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10253   } else {
10254     // If there is no negative value, figure out the smallest type that fits
10255     // all of the enumerator values.
10256     // If it's packed, check also if it fits a char or a short.
10257     if (Packed && NumPositiveBits <= CharWidth) {
10258       BestType = Context.UnsignedCharTy;
10259       BestPromotionType = Context.IntTy;
10260       BestWidth = CharWidth;
10261     } else if (Packed && NumPositiveBits <= ShortWidth) {
10262       BestType = Context.UnsignedShortTy;
10263       BestPromotionType = Context.IntTy;
10264       BestWidth = ShortWidth;
10265     } else if (NumPositiveBits <= IntWidth) {
10266       BestType = Context.UnsignedIntTy;
10267       BestWidth = IntWidth;
10268       BestPromotionType
10269         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10270                            ? Context.UnsignedIntTy : Context.IntTy;
10271     } else if (NumPositiveBits <=
10272                (BestWidth = Context.getTargetInfo().getLongWidth())) {
10273       BestType = Context.UnsignedLongTy;
10274       BestPromotionType
10275         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10276                            ? Context.UnsignedLongTy : Context.LongTy;
10277     } else {
10278       BestWidth = Context.getTargetInfo().getLongLongWidth();
10279       assert(NumPositiveBits <= BestWidth &&
10280              "How could an initializer get larger than ULL?");
10281       BestType = Context.UnsignedLongLongTy;
10282       BestPromotionType
10283         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10284                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
10285     }
10286   }
10287
10288   // Loop over all of the enumerator constants, changing their types to match
10289   // the type of the enum if needed.
10290   for (unsigned i = 0; i != NumElements; ++i) {
10291     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10292     if (!ECD) continue;  // Already issued a diagnostic.
10293
10294     // Standard C says the enumerators have int type, but we allow, as an
10295     // extension, the enumerators to be larger than int size.  If each
10296     // enumerator value fits in an int, type it as an int, otherwise type it the
10297     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
10298     // that X has type 'int', not 'unsigned'.
10299
10300     // Determine whether the value fits into an int.
10301     llvm::APSInt InitVal = ECD->getInitVal();
10302
10303     // If it fits into an integer type, force it.  Otherwise force it to match
10304     // the enum decl type.
10305     QualType NewTy;
10306     unsigned NewWidth;
10307     bool NewSign;
10308     if (!getLangOpts().CPlusPlus &&
10309         !Enum->isFixed() &&
10310         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10311       NewTy = Context.IntTy;
10312       NewWidth = IntWidth;
10313       NewSign = true;
10314     } else if (ECD->getType() == BestType) {
10315       // Already the right type!
10316       if (getLangOpts().CPlusPlus)
10317         // C++ [dcl.enum]p4: Following the closing brace of an
10318         // enum-specifier, each enumerator has the type of its
10319         // enumeration.
10320         ECD->setType(EnumType);
10321       continue;
10322     } else {
10323       NewTy = BestType;
10324       NewWidth = BestWidth;
10325       NewSign = BestType->isSignedIntegerOrEnumerationType();
10326     }
10327
10328     // Adjust the APSInt value.
10329     InitVal = InitVal.extOrTrunc(NewWidth);
10330     InitVal.setIsSigned(NewSign);
10331     ECD->setInitVal(InitVal);
10332
10333     // Adjust the Expr initializer and type.
10334     if (ECD->getInitExpr() &&
10335         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10336       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10337                                                 CK_IntegralCast,
10338                                                 ECD->getInitExpr(),
10339                                                 /*base paths*/ 0,
10340                                                 VK_RValue));
10341     if (getLangOpts().CPlusPlus)
10342       // C++ [dcl.enum]p4: Following the closing brace of an
10343       // enum-specifier, each enumerator has the type of its
10344       // enumeration.
10345       ECD->setType(EnumType);
10346     else
10347       ECD->setType(NewTy);
10348   }
10349
10350   Enum->completeDefinition(BestType, BestPromotionType,
10351                            NumPositiveBits, NumNegativeBits);
10352
10353   // If we're declaring a function, ensure this decl isn't forgotten about -
10354   // it needs to go into the function scope.
10355   if (InFunctionDeclarator)
10356     DeclsInPrototypeScope.push_back(Enum);
10357
10358 }
10359
10360 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10361                                   SourceLocation StartLoc,
10362                                   SourceLocation EndLoc) {
10363   StringLiteral *AsmString = cast<StringLiteral>(expr);
10364
10365   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10366                                                    AsmString, StartLoc,
10367                                                    EndLoc);
10368   CurContext->addDecl(New);
10369   return New;
10370 }
10371
10372 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 
10373                                    SourceLocation ImportLoc, 
10374                                    ModuleIdPath Path) {
10375   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 
10376                                                 Module::AllVisible,
10377                                                 /*IsIncludeDirective=*/false);
10378   if (!Mod)
10379     return true;
10380   
10381   llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10382   Module *ModCheck = Mod;
10383   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10384     // If we've run out of module parents, just drop the remaining identifiers.
10385     // We need the length to be consistent.
10386     if (!ModCheck)
10387       break;
10388     ModCheck = ModCheck->Parent;
10389     
10390     IdentifierLocs.push_back(Path[I].second);
10391   }
10392
10393   ImportDecl *Import = ImportDecl::Create(Context, 
10394                                           Context.getTranslationUnitDecl(),
10395                                           AtLoc.isValid()? AtLoc : ImportLoc, 
10396                                           Mod, IdentifierLocs);
10397   Context.getTranslationUnitDecl()->addDecl(Import);
10398   return Import;
10399 }
10400
10401 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10402                                       IdentifierInfo* AliasName,
10403                                       SourceLocation PragmaLoc,
10404                                       SourceLocation NameLoc,
10405                                       SourceLocation AliasNameLoc) {
10406   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10407                                     LookupOrdinaryName);
10408   AsmLabelAttr *Attr =
10409      ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
10410
10411   if (PrevDecl) 
10412     PrevDecl->addAttr(Attr);
10413   else 
10414     (void)ExtnameUndeclaredIdentifiers.insert(
10415       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10416 }
10417
10418 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10419                              SourceLocation PragmaLoc,
10420                              SourceLocation NameLoc) {
10421   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
10422
10423   if (PrevDecl) {
10424     PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
10425   } else {
10426     (void)WeakUndeclaredIdentifiers.insert(
10427       std::pair<IdentifierInfo*,WeakInfo>
10428         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
10429   }
10430 }
10431
10432 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10433                                 IdentifierInfo* AliasName,
10434                                 SourceLocation PragmaLoc,
10435                                 SourceLocation NameLoc,
10436                                 SourceLocation AliasNameLoc) {
10437   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10438                                     LookupOrdinaryName);
10439   WeakInfo W = WeakInfo(Name, NameLoc);
10440
10441   if (PrevDecl) {
10442     if (!PrevDecl->hasAttr<AliasAttr>())
10443       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
10444         DeclApplyPragmaWeak(TUScope, ND, W);
10445   } else {
10446     (void)WeakUndeclaredIdentifiers.insert(
10447       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
10448   }
10449 }
10450
10451 Decl *Sema::getObjCDeclContext() const {
10452   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10453 }
10454
10455 AvailabilityResult Sema::getCurContextAvailability() const {
10456   const Decl *D = cast<Decl>(getCurLexicalContext());
10457   // A category implicitly has the availability of the interface.
10458   if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10459     D = CatD->getClassInterface();
10460   
10461   return D->getAvailability();
10462 }