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