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 "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <functional>
47 using namespace clang;
48 using namespace sema;
49 
50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51   if (OwnedType) {
52     Decl *Group[2] = { OwnedType, Ptr };
53     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54   }
55 
56   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57 }
58 
59 namespace {
60 
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62  public:
63   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
65     WantExpressionKeywords = false;
66     WantCXXNamedCasts = false;
67     WantRemainingKeywords = false;
68   }
69 
70   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71     if (NamedDecl *ND = candidate.getCorrectionDecl())
72       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73           (AllowInvalidDecl || !ND->isInvalidDecl());
74     else
75       return !WantClassName && candidate.isKeyword();
76   }
77 
78  private:
79   bool AllowInvalidDecl;
80   bool WantClassName;
81 };
82 
83 }
84 
85 /// \brief Determine whether the token kind starts a simple-type-specifier.
86 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87   switch (Kind) {
88   // FIXME: Take into account the current language when deciding whether a
89   // token kind is a valid type specifier
90   case tok::kw_short:
91   case tok::kw_long:
92   case tok::kw___int64:
93   case tok::kw___int128:
94   case tok::kw_signed:
95   case tok::kw_unsigned:
96   case tok::kw_void:
97   case tok::kw_char:
98   case tok::kw_int:
99   case tok::kw_half:
100   case tok::kw_float:
101   case tok::kw_double:
102   case tok::kw_wchar_t:
103   case tok::kw_bool:
104   case tok::kw___underlying_type:
105     return true;
106 
107   case tok::annot_typename:
108   case tok::kw_char16_t:
109   case tok::kw_char32_t:
110   case tok::kw_typeof:
111   case tok::kw_decltype:
112     return getLangOpts().CPlusPlus;
113 
114   default:
115     break;
116   }
117 
118   return false;
119 }
120 
121 /// \brief If the identifier refers to a type name within this scope,
122 /// return the declaration of that type.
123 ///
124 /// This routine performs ordinary name lookup of the identifier II
125 /// within the given scope, with optional C++ scope specifier SS, to
126 /// determine whether the name refers to a type. If so, returns an
127 /// opaque pointer (actually a QualType) corresponding to that
128 /// type. Otherwise, returns NULL.
129 ///
130 /// If name lookup results in an ambiguity, this routine will complain
131 /// and then return NULL.
132 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
133                              Scope *S, CXXScopeSpec *SS,
134                              bool isClassName, bool HasTrailingDot,
135                              ParsedType ObjectTypePtr,
136                              bool IsCtorOrDtorName,
137                              bool WantNontrivialTypeSourceInfo,
138                              IdentifierInfo **CorrectedII) {
139   // Determine where we will perform name lookup.
140   DeclContext *LookupCtx = 0;
141   if (ObjectTypePtr) {
142     QualType ObjectType = ObjectTypePtr.get();
143     if (ObjectType->isRecordType())
144       LookupCtx = computeDeclContext(ObjectType);
145   } else if (SS && SS->isNotEmpty()) {
146     LookupCtx = computeDeclContext(*SS, false);
147 
148     if (!LookupCtx) {
149       if (isDependentScopeSpecifier(*SS)) {
150         // C++ [temp.res]p3:
151         //   A qualified-id that refers to a type and in which the
152         //   nested-name-specifier depends on a template-parameter (14.6.2)
153         //   shall be prefixed by the keyword typename to indicate that the
154         //   qualified-id denotes a type, forming an
155         //   elaborated-type-specifier (7.1.5.3).
156         //
157         // We therefore do not perform any name lookup if the result would
158         // refer to a member of an unknown specialization.
159         if (!isClassName && !IsCtorOrDtorName)
160           return ParsedType();
161 
162         // We know from the grammar that this name refers to a type,
163         // so build a dependent node to describe the type.
164         if (WantNontrivialTypeSourceInfo)
165           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166 
167         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168         QualType T =
169           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170                             II, NameLoc);
171 
172           return ParsedType::make(T);
173       }
174 
175       return ParsedType();
176     }
177 
178     if (!LookupCtx->isDependentContext() &&
179         RequireCompleteDeclContext(*SS, LookupCtx))
180       return ParsedType();
181   }
182 
183   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184   // lookup for class-names.
185   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186                                       LookupOrdinaryName;
187   LookupResult Result(*this, &II, NameLoc, Kind);
188   if (LookupCtx) {
189     // Perform "qualified" name lookup into the declaration context we
190     // computed, which is either the type of the base of a member access
191     // expression or the declaration context associated with a prior
192     // nested-name-specifier.
193     LookupQualifiedName(Result, LookupCtx);
194 
195     if (ObjectTypePtr && Result.empty()) {
196       // C++ [basic.lookup.classref]p3:
197       //   If the unqualified-id is ~type-name, the type-name is looked up
198       //   in the context of the entire postfix-expression. If the type T of
199       //   the object expression is of a class type C, the type-name is also
200       //   looked up in the scope of class C. At least one of the lookups shall
201       //   find a name that refers to (possibly cv-qualified) T.
202       LookupName(Result, S);
203     }
204   } else {
205     // Perform unqualified name lookup.
206     LookupName(Result, S);
207   }
208 
209   NamedDecl *IIDecl = 0;
210   switch (Result.getResultKind()) {
211   case LookupResult::NotFound:
212   case LookupResult::NotFoundInCurrentInstantiation:
213     if (CorrectedII) {
214       TypeNameValidatorCCC Validator(true, isClassName);
215       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216                                               Kind, S, SS, Validator);
217       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218       TemplateTy Template;
219       bool MemberOfUnknownSpecialization;
220       UnqualifiedId TemplateName;
221       TemplateName.setIdentifier(NewII, NameLoc);
222       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223       CXXScopeSpec NewSS, *NewSSPtr = SS;
224       if (SS && NNS) {
225         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226         NewSSPtr = &NewSS;
227       }
228       if (Correction && (NNS || NewII != &II) &&
229           // Ignore a correction to a template type as the to-be-corrected
230           // identifier is not a template (typo correction for template names
231           // is handled elsewhere).
232           !(getLangOpts().CPlusPlus && NewSSPtr &&
233             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234                            false, Template, MemberOfUnknownSpecialization))) {
235         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236                                     isClassName, HasTrailingDot, ObjectTypePtr,
237                                     IsCtorOrDtorName,
238                                     WantNontrivialTypeSourceInfo);
239         if (Ty) {
240           std::string CorrectedStr(Correction.getAsString(getLangOpts()));
241           std::string CorrectedQuotedStr(
242               Correction.getQuoted(getLangOpts()));
243           Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
244               << Result.getLookupName() << CorrectedQuotedStr << isClassName
245               << FixItHint::CreateReplacement(SourceRange(NameLoc),
246                                               CorrectedStr);
247           if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
248             Diag(FirstDecl->getLocation(), diag::note_previous_decl)
249               << CorrectedQuotedStr;
250 
251           if (SS && NNS)
252             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
253           *CorrectedII = NewII;
254           return Ty;
255         }
256       }
257     }
258     // If typo correction failed or was not performed, fall through
259   case LookupResult::FoundOverloaded:
260   case LookupResult::FoundUnresolvedValue:
261     Result.suppressDiagnostics();
262     return ParsedType();
263 
264   case LookupResult::Ambiguous:
265     // Recover from type-hiding ambiguities by hiding the type.  We'll
266     // do the lookup again when looking for an object, and we can
267     // diagnose the error then.  If we don't do this, then the error
268     // about hiding the type will be immediately followed by an error
269     // that only makes sense if the identifier was treated like a type.
270     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
271       Result.suppressDiagnostics();
272       return ParsedType();
273     }
274 
275     // Look to see if we have a type anywhere in the list of results.
276     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
277          Res != ResEnd; ++Res) {
278       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
279         if (!IIDecl ||
280             (*Res)->getLocation().getRawEncoding() <
281               IIDecl->getLocation().getRawEncoding())
282           IIDecl = *Res;
283       }
284     }
285 
286     if (!IIDecl) {
287       // None of the entities we found is a type, so there is no way
288       // to even assume that the result is a type. In this case, don't
289       // complain about the ambiguity. The parser will either try to
290       // perform this lookup again (e.g., as an object name), which
291       // will produce the ambiguity, or will complain that it expected
292       // a type name.
293       Result.suppressDiagnostics();
294       return ParsedType();
295     }
296 
297     // We found a type within the ambiguous lookup; diagnose the
298     // ambiguity and then return that type. This might be the right
299     // answer, or it might not be, but it suppresses any attempt to
300     // perform the name lookup again.
301     break;
302 
303   case LookupResult::Found:
304     IIDecl = Result.getFoundDecl();
305     break;
306   }
307 
308   assert(IIDecl && "Didn't find decl");
309 
310   QualType T;
311   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
312     DiagnoseUseOfDecl(IIDecl, NameLoc);
313 
314     if (T.isNull())
315       T = Context.getTypeDeclType(TD);
316 
317     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
318     // constructor or destructor name (in such a case, the scope specifier
319     // will be attached to the enclosing Expr or Decl node).
320     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
321       if (WantNontrivialTypeSourceInfo) {
322         // Construct a type with type-source information.
323         TypeLocBuilder Builder;
324         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
325 
326         T = getElaboratedType(ETK_None, *SS, T);
327         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
328         ElabTL.setElaboratedKeywordLoc(SourceLocation());
329         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
330         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
331       } else {
332         T = getElaboratedType(ETK_None, *SS, T);
333       }
334     }
335   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
336     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
337     if (!HasTrailingDot)
338       T = Context.getObjCInterfaceType(IDecl);
339   }
340 
341   if (T.isNull()) {
342     // If it's not plausibly a type, suppress diagnostics.
343     Result.suppressDiagnostics();
344     return ParsedType();
345   }
346   return ParsedType::make(T);
347 }
348 
349 /// isTagName() - This method is called *for error recovery purposes only*
350 /// to determine if the specified name is a valid tag name ("struct foo").  If
351 /// so, this returns the TST for the tag corresponding to it (TST_enum,
352 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
353 /// cases in C where the user forgot to specify the tag.
354 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
355   // Do a tag name lookup in this scope.
356   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
357   LookupName(R, S, false);
358   R.suppressDiagnostics();
359   if (R.getResultKind() == LookupResult::Found)
360     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
361       switch (TD->getTagKind()) {
362       case TTK_Struct: return DeclSpec::TST_struct;
363       case TTK_Interface: return DeclSpec::TST_interface;
364       case TTK_Union:  return DeclSpec::TST_union;
365       case TTK_Class:  return DeclSpec::TST_class;
366       case TTK_Enum:   return DeclSpec::TST_enum;
367       }
368     }
369 
370   return DeclSpec::TST_unspecified;
371 }
372 
373 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
374 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
375 /// then downgrade the missing typename error to a warning.
376 /// This is needed for MSVC compatibility; Example:
377 /// @code
378 /// template<class T> class A {
379 /// public:
380 ///   typedef int TYPE;
381 /// };
382 /// template<class T> class B : public A<T> {
383 /// public:
384 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
385 /// };
386 /// @endcode
387 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
388   if (CurContext->isRecord()) {
389     const Type *Ty = SS->getScopeRep()->getAsType();
390 
391     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
392     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
393           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
394       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
395         return true;
396     return S->isFunctionPrototypeScope();
397   }
398   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
399 }
400 
401 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
402                                    SourceLocation IILoc,
403                                    Scope *S,
404                                    CXXScopeSpec *SS,
405                                    ParsedType &SuggestedType) {
406   // We don't have anything to suggest (yet).
407   SuggestedType = ParsedType();
408 
409   // There may have been a typo in the name of the type. Look up typo
410   // results, in case we have something that we can suggest.
411   TypeNameValidatorCCC Validator(false);
412   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
413                                              LookupOrdinaryName, S, SS,
414                                              Validator)) {
415     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
416     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
417 
418     if (Corrected.isKeyword()) {
419       // We corrected to a keyword.
420       IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
421       if (!isSimpleTypeSpecifier(NewII->getTokenID()))
422         CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
423       Diag(IILoc, diag::err_unknown_typename_suggest)
424         << II << CorrectedQuotedStr
425         << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
426       II = NewII;
427     } else {
428       NamedDecl *Result = Corrected.getCorrectionDecl();
429       // We found a similarly-named type or interface; suggest that.
430       if (!SS || !SS->isSet())
431         Diag(IILoc, diag::err_unknown_typename_suggest)
432           << II << CorrectedQuotedStr
433           << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
434       else if (DeclContext *DC = computeDeclContext(*SS, false))
435         Diag(IILoc, diag::err_unknown_nested_typename_suggest)
436           << II << DC << CorrectedQuotedStr << SS->getRange()
437           << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
438                                           CorrectedStr);
439       else
440         llvm_unreachable("could not have corrected a typo here");
441 
442       Diag(Result->getLocation(), diag::note_previous_decl)
443         << CorrectedQuotedStr;
444 
445       SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
446                                   false, false, ParsedType(),
447                                   /*IsCtorOrDtorName=*/false,
448                                   /*NonTrivialTypeSourceInfo=*/true);
449     }
450     return true;
451   }
452 
453   if (getLangOpts().CPlusPlus) {
454     // See if II is a class template that the user forgot to pass arguments to.
455     UnqualifiedId Name;
456     Name.setIdentifier(II, IILoc);
457     CXXScopeSpec EmptySS;
458     TemplateTy TemplateResult;
459     bool MemberOfUnknownSpecialization;
460     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
461                        Name, ParsedType(), true, TemplateResult,
462                        MemberOfUnknownSpecialization) == TNK_Type_template) {
463       TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
464       Diag(IILoc, diag::err_template_missing_args) << TplName;
465       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
466         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
467           << TplDecl->getTemplateParameters()->getSourceRange();
468       }
469       return true;
470     }
471   }
472 
473   // FIXME: Should we move the logic that tries to recover from a missing tag
474   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
475 
476   if (!SS || (!SS->isSet() && !SS->isInvalid()))
477     Diag(IILoc, diag::err_unknown_typename) << II;
478   else if (DeclContext *DC = computeDeclContext(*SS, false))
479     Diag(IILoc, diag::err_typename_nested_not_found)
480       << II << DC << SS->getRange();
481   else if (isDependentScopeSpecifier(*SS)) {
482     unsigned DiagID = diag::err_typename_missing;
483     if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
484       DiagID = diag::warn_typename_missing;
485 
486     Diag(SS->getRange().getBegin(), DiagID)
487       << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
488       << SourceRange(SS->getRange().getBegin(), IILoc)
489       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
490     SuggestedType = ActOnTypenameType(S, SourceLocation(),
491                                       *SS, *II, IILoc).get();
492   } else {
493     assert(SS && SS->isInvalid() &&
494            "Invalid scope specifier has already been diagnosed");
495   }
496 
497   return true;
498 }
499 
500 /// \brief Determine whether the given result set contains either a type name
501 /// or
502 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
503   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
504                        NextToken.is(tok::less);
505 
506   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
507     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
508       return true;
509 
510     if (CheckTemplate && isa<TemplateDecl>(*I))
511       return true;
512   }
513 
514   return false;
515 }
516 
517 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
518                                     Scope *S, CXXScopeSpec &SS,
519                                     IdentifierInfo *&Name,
520                                     SourceLocation NameLoc) {
521   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
522   SemaRef.LookupParsedName(R, S, &SS);
523   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
524     const char *TagName = 0;
525     const char *FixItTagName = 0;
526     switch (Tag->getTagKind()) {
527       case TTK_Class:
528         TagName = "class";
529         FixItTagName = "class ";
530         break;
531 
532       case TTK_Enum:
533         TagName = "enum";
534         FixItTagName = "enum ";
535         break;
536 
537       case TTK_Struct:
538         TagName = "struct";
539         FixItTagName = "struct ";
540         break;
541 
542       case TTK_Interface:
543         TagName = "__interface";
544         FixItTagName = "__interface ";
545         break;
546 
547       case TTK_Union:
548         TagName = "union";
549         FixItTagName = "union ";
550         break;
551     }
552 
553     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
554       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
555       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
556 
557     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
558          I != IEnd; ++I)
559       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
560         << Name << TagName;
561 
562     // Replace lookup results with just the tag decl.
563     Result.clear(Sema::LookupTagName);
564     SemaRef.LookupParsedName(Result, S, &SS);
565     return true;
566   }
567 
568   return false;
569 }
570 
571 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
572 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
573                                   QualType T, SourceLocation NameLoc) {
574   ASTContext &Context = S.Context;
575 
576   TypeLocBuilder Builder;
577   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
578 
579   T = S.getElaboratedType(ETK_None, SS, T);
580   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
581   ElabTL.setElaboratedKeywordLoc(SourceLocation());
582   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
583   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
584 }
585 
586 Sema::NameClassification Sema::ClassifyName(Scope *S,
587                                             CXXScopeSpec &SS,
588                                             IdentifierInfo *&Name,
589                                             SourceLocation NameLoc,
590                                             const Token &NextToken,
591                                             bool IsAddressOfOperand,
592                                             CorrectionCandidateCallback *CCC) {
593   DeclarationNameInfo NameInfo(Name, NameLoc);
594   ObjCMethodDecl *CurMethod = getCurMethodDecl();
595 
596   if (NextToken.is(tok::coloncolon)) {
597     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
598                                 QualType(), false, SS, 0, false);
599 
600   }
601 
602   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
603   LookupParsedName(Result, S, &SS, !CurMethod);
604 
605   // Perform lookup for Objective-C instance variables (including automatically
606   // synthesized instance variables), if we're in an Objective-C method.
607   // FIXME: This lookup really, really needs to be folded in to the normal
608   // unqualified lookup mechanism.
609   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
610     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
611     if (E.get() || E.isInvalid())
612       return E;
613   }
614 
615   bool SecondTry = false;
616   bool IsFilteredTemplateName = false;
617 
618 Corrected:
619   switch (Result.getResultKind()) {
620   case LookupResult::NotFound:
621     // If an unqualified-id is followed by a '(', then we have a function
622     // call.
623     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
624       // In C++, this is an ADL-only call.
625       // FIXME: Reference?
626       if (getLangOpts().CPlusPlus)
627         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
628 
629       // C90 6.3.2.2:
630       //   If the expression that precedes the parenthesized argument list in a
631       //   function call consists solely of an identifier, and if no
632       //   declaration is visible for this identifier, the identifier is
633       //   implicitly declared exactly as if, in the innermost block containing
634       //   the function call, the declaration
635       //
636       //     extern int identifier ();
637       //
638       //   appeared.
639       //
640       // We also allow this in C99 as an extension.
641       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
642         Result.addDecl(D);
643         Result.resolveKind();
644         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
645       }
646     }
647 
648     // In C, we first see whether there is a tag type by the same name, in
649     // which case it's likely that the user just forget to write "enum",
650     // "struct", or "union".
651     if (!getLangOpts().CPlusPlus && !SecondTry &&
652         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
653       break;
654     }
655 
656     // Perform typo correction to determine if there is another name that is
657     // close to this name.
658     if (!SecondTry && CCC) {
659       SecondTry = true;
660       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
661                                                  Result.getLookupKind(), S,
662                                                  &SS, *CCC)) {
663         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
664         unsigned QualifiedDiag = diag::err_no_member_suggest;
665         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
666         std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
667 
668         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
669         NamedDecl *UnderlyingFirstDecl
670           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
671         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
673           UnqualifiedDiag = diag::err_no_template_suggest;
674           QualifiedDiag = diag::err_no_member_template_suggest;
675         } else if (UnderlyingFirstDecl &&
676                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
677                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
678                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
679            UnqualifiedDiag = diag::err_unknown_typename_suggest;
680            QualifiedDiag = diag::err_unknown_nested_typename_suggest;
681          }
682 
683         if (SS.isEmpty())
684           Diag(NameLoc, UnqualifiedDiag)
685             << Name << CorrectedQuotedStr
686             << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
687         else // FIXME: is this even reachable? Test it.
688           Diag(NameLoc, QualifiedDiag)
689             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
690             << SS.getRange()
691             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
692                                             CorrectedStr);
693 
694         // Update the name, so that the caller has the new name.
695         Name = Corrected.getCorrectionAsIdentifierInfo();
696 
697         // Typo correction corrected to a keyword.
698         if (Corrected.isKeyword())
699           return Corrected.getCorrectionAsIdentifierInfo();
700 
701         // Also update the LookupResult...
702         // FIXME: This should probably go away at some point
703         Result.clear();
704         Result.setLookupName(Corrected.getCorrection());
705         if (FirstDecl) {
706           Result.addDecl(FirstDecl);
707           Diag(FirstDecl->getLocation(), diag::note_previous_decl)
708             << CorrectedQuotedStr;
709         }
710 
711         // If we found an Objective-C instance variable, let
712         // LookupInObjCMethod build the appropriate expression to
713         // reference the ivar.
714         // FIXME: This is a gross hack.
715         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
716           Result.clear();
717           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
718           return E;
719         }
720 
721         goto Corrected;
722       }
723     }
724 
725     // We failed to correct; just fall through and let the parser deal with it.
726     Result.suppressDiagnostics();
727     return NameClassification::Unknown();
728 
729   case LookupResult::NotFoundInCurrentInstantiation: {
730     // We performed name lookup into the current instantiation, and there were
731     // dependent bases, so we treat this result the same way as any other
732     // dependent nested-name-specifier.
733 
734     // C++ [temp.res]p2:
735     //   A name used in a template declaration or definition and that is
736     //   dependent on a template-parameter is assumed not to name a type
737     //   unless the applicable name lookup finds a type name or the name is
738     //   qualified by the keyword typename.
739     //
740     // FIXME: If the next token is '<', we might want to ask the parser to
741     // perform some heroics to see if we actually have a
742     // template-argument-list, which would indicate a missing 'template'
743     // keyword here.
744     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
745                                       NameInfo, IsAddressOfOperand,
746                                       /*TemplateArgs=*/0);
747   }
748 
749   case LookupResult::Found:
750   case LookupResult::FoundOverloaded:
751   case LookupResult::FoundUnresolvedValue:
752     break;
753 
754   case LookupResult::Ambiguous:
755     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
756         hasAnyAcceptableTemplateNames(Result)) {
757       // C++ [temp.local]p3:
758       //   A lookup that finds an injected-class-name (10.2) can result in an
759       //   ambiguity in certain cases (for example, if it is found in more than
760       //   one base class). If all of the injected-class-names that are found
761       //   refer to specializations of the same class template, and if the name
762       //   is followed by a template-argument-list, the reference refers to the
763       //   class template itself and not a specialization thereof, and is not
764       //   ambiguous.
765       //
766       // This filtering can make an ambiguous result into an unambiguous one,
767       // so try again after filtering out template names.
768       FilterAcceptableTemplateNames(Result);
769       if (!Result.isAmbiguous()) {
770         IsFilteredTemplateName = true;
771         break;
772       }
773     }
774 
775     // Diagnose the ambiguity and return an error.
776     return NameClassification::Error();
777   }
778 
779   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
781     // C++ [temp.names]p3:
782     //   After name lookup (3.4) finds that a name is a template-name or that
783     //   an operator-function-id or a literal- operator-id refers to a set of
784     //   overloaded functions any member of which is a function template if
785     //   this is followed by a <, the < is always taken as the delimiter of a
786     //   template-argument-list and never as the less-than operator.
787     if (!IsFilteredTemplateName)
788       FilterAcceptableTemplateNames(Result);
789 
790     if (!Result.empty()) {
791       bool IsFunctionTemplate;
792       TemplateName Template;
793       if (Result.end() - Result.begin() > 1) {
794         IsFunctionTemplate = true;
795         Template = Context.getOverloadedTemplateName(Result.begin(),
796                                                      Result.end());
797       } else {
798         TemplateDecl *TD
799           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
800         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
801 
802         if (SS.isSet() && !SS.isInvalid())
803           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
804                                                     /*TemplateKeyword=*/false,
805                                                       TD);
806         else
807           Template = TemplateName(TD);
808       }
809 
810       if (IsFunctionTemplate) {
811         // Function templates always go through overload resolution, at which
812         // point we'll perform the various checks (e.g., accessibility) we need
813         // to based on which function we selected.
814         Result.suppressDiagnostics();
815 
816         return NameClassification::FunctionTemplate(Template);
817       }
818 
819       return NameClassification::TypeTemplate(Template);
820     }
821   }
822 
823   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
824   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
825     DiagnoseUseOfDecl(Type, NameLoc);
826     QualType T = Context.getTypeDeclType(Type);
827     if (SS.isNotEmpty())
828       return buildNestedType(*this, SS, T, NameLoc);
829     return ParsedType::make(T);
830   }
831 
832   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
833   if (!Class) {
834     // FIXME: It's unfortunate that we don't have a Type node for handling this.
835     if (ObjCCompatibleAliasDecl *Alias
836                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
837       Class = Alias->getClassInterface();
838   }
839 
840   if (Class) {
841     DiagnoseUseOfDecl(Class, NameLoc);
842 
843     if (NextToken.is(tok::period)) {
844       // Interface. <something> is parsed as a property reference expression.
845       // Just return "unknown" as a fall-through for now.
846       Result.suppressDiagnostics();
847       return NameClassification::Unknown();
848     }
849 
850     QualType T = Context.getObjCInterfaceType(Class);
851     return ParsedType::make(T);
852   }
853 
854   // We can have a type template here if we're classifying a template argument.
855   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
856     return NameClassification::TypeTemplate(
857         TemplateName(cast<TemplateDecl>(FirstDecl)));
858 
859   // Check for a tag type hidden by a non-type decl in a few cases where it
860   // seems likely a type is wanted instead of the non-type that was found.
861   if (!getLangOpts().ObjC1) {
862     bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
863     if ((NextToken.is(tok::identifier) ||
864          (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
865         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
866       TypeDecl *Type = Result.getAsSingle<TypeDecl>();
867       DiagnoseUseOfDecl(Type, NameLoc);
868       QualType T = Context.getTypeDeclType(Type);
869       if (SS.isNotEmpty())
870         return buildNestedType(*this, SS, T, NameLoc);
871       return ParsedType::make(T);
872     }
873   }
874 
875   if (FirstDecl->isCXXClassMember())
876     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
877 
878   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
879   return BuildDeclarationNameExpr(SS, Result, ADL);
880 }
881 
882 // Determines the context to return to after temporarily entering a
883 // context.  This depends in an unnecessarily complicated way on the
884 // exact ordering of callbacks from the parser.
885 DeclContext *Sema::getContainingDC(DeclContext *DC) {
886 
887   // Functions defined inline within classes aren't parsed until we've
888   // finished parsing the top-level class, so the top-level class is
889   // the context we'll need to return to.
890   if (isa<FunctionDecl>(DC)) {
891     DC = DC->getLexicalParent();
892 
893     // A function not defined within a class will always return to its
894     // lexical context.
895     if (!isa<CXXRecordDecl>(DC))
896       return DC;
897 
898     // A C++ inline method/friend is parsed *after* the topmost class
899     // it was declared in is fully parsed ("complete");  the topmost
900     // class is the context we need to return to.
901     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
902       DC = RD;
903 
904     // Return the declaration context of the topmost class the inline method is
905     // declared in.
906     return DC;
907   }
908 
909   return DC->getLexicalParent();
910 }
911 
912 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
913   assert(getContainingDC(DC) == CurContext &&
914       "The next DeclContext should be lexically contained in the current one.");
915   CurContext = DC;
916   S->setEntity(DC);
917 }
918 
919 void Sema::PopDeclContext() {
920   assert(CurContext && "DeclContext imbalance!");
921 
922   CurContext = getContainingDC(CurContext);
923   assert(CurContext && "Popped translation unit!");
924 }
925 
926 /// EnterDeclaratorContext - Used when we must lookup names in the context
927 /// of a declarator's nested name specifier.
928 ///
929 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
930   // C++0x [basic.lookup.unqual]p13:
931   //   A name used in the definition of a static data member of class
932   //   X (after the qualified-id of the static member) is looked up as
933   //   if the name was used in a member function of X.
934   // C++0x [basic.lookup.unqual]p14:
935   //   If a variable member of a namespace is defined outside of the
936   //   scope of its namespace then any name used in the definition of
937   //   the variable member (after the declarator-id) is looked up as
938   //   if the definition of the variable member occurred in its
939   //   namespace.
940   // Both of these imply that we should push a scope whose context
941   // is the semantic context of the declaration.  We can't use
942   // PushDeclContext here because that context is not necessarily
943   // lexically contained in the current context.  Fortunately,
944   // the containing scope should have the appropriate information.
945 
946   assert(!S->getEntity() && "scope already has entity");
947 
948 #ifndef NDEBUG
949   Scope *Ancestor = S->getParent();
950   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
951   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
952 #endif
953 
954   CurContext = DC;
955   S->setEntity(DC);
956 }
957 
958 void Sema::ExitDeclaratorContext(Scope *S) {
959   assert(S->getEntity() == CurContext && "Context imbalance!");
960 
961   // Switch back to the lexical context.  The safety of this is
962   // enforced by an assert in EnterDeclaratorContext.
963   Scope *Ancestor = S->getParent();
964   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
965   CurContext = (DeclContext*) Ancestor->getEntity();
966 
967   // We don't need to do anything with the scope, which is going to
968   // disappear.
969 }
970 
971 
972 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
973   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
974   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
975     // We assume that the caller has already called
976     // ActOnReenterTemplateScope
977     FD = TFD->getTemplatedDecl();
978   }
979   if (!FD)
980     return;
981 
982   // Same implementation as PushDeclContext, but enters the context
983   // from the lexical parent, rather than the top-level class.
984   assert(CurContext == FD->getLexicalParent() &&
985     "The next DeclContext should be lexically contained in the current one.");
986   CurContext = FD;
987   S->setEntity(CurContext);
988 
989   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
990     ParmVarDecl *Param = FD->getParamDecl(P);
991     // If the parameter has an identifier, then add it to the scope
992     if (Param->getIdentifier()) {
993       S->AddDecl(Param);
994       IdResolver.AddDecl(Param);
995     }
996   }
997 }
998 
999 
1000 void Sema::ActOnExitFunctionContext() {
1001   // Same implementation as PopDeclContext, but returns to the lexical parent,
1002   // rather than the top-level class.
1003   assert(CurContext && "DeclContext imbalance!");
1004   CurContext = CurContext->getLexicalParent();
1005   assert(CurContext && "Popped translation unit!");
1006 }
1007 
1008 
1009 /// \brief Determine whether we allow overloading of the function
1010 /// PrevDecl with another declaration.
1011 ///
1012 /// This routine determines whether overloading is possible, not
1013 /// whether some new function is actually an overload. It will return
1014 /// true in C++ (where we can always provide overloads) or, as an
1015 /// extension, in C when the previous function is already an
1016 /// overloaded function declaration or has the "overloadable"
1017 /// attribute.
1018 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1019                                        ASTContext &Context) {
1020   if (Context.getLangOpts().CPlusPlus)
1021     return true;
1022 
1023   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1024     return true;
1025 
1026   return (Previous.getResultKind() == LookupResult::Found
1027           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1028 }
1029 
1030 /// Add this decl to the scope shadowed decl chains.
1031 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1032   // Move up the scope chain until we find the nearest enclosing
1033   // non-transparent context. The declaration will be introduced into this
1034   // scope.
1035   while (S->getEntity() &&
1036          ((DeclContext *)S->getEntity())->isTransparentContext())
1037     S = S->getParent();
1038 
1039   // Add scoped declarations into their context, so that they can be
1040   // found later. Declarations without a context won't be inserted
1041   // into any context.
1042   if (AddToContext)
1043     CurContext->addDecl(D);
1044 
1045   // Out-of-line definitions shouldn't be pushed into scope in C++.
1046   // Out-of-line variable and function definitions shouldn't even in C.
1047   if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
1048       D->isOutOfLine() &&
1049       !D->getDeclContext()->getRedeclContext()->Equals(
1050         D->getLexicalDeclContext()->getRedeclContext()))
1051     return;
1052 
1053   // Template instantiations should also not be pushed into scope.
1054   if (isa<FunctionDecl>(D) &&
1055       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1056     return;
1057 
1058   // If this replaces anything in the current scope,
1059   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1060                                IEnd = IdResolver.end();
1061   for (; I != IEnd; ++I) {
1062     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1063       S->RemoveDecl(*I);
1064       IdResolver.RemoveDecl(*I);
1065 
1066       // Should only need to replace one decl.
1067       break;
1068     }
1069   }
1070 
1071   S->AddDecl(D);
1072 
1073   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1074     // Implicitly-generated labels may end up getting generated in an order that
1075     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1076     // the label at the appropriate place in the identifier chain.
1077     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1078       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1079       if (IDC == CurContext) {
1080         if (!S->isDeclScope(*I))
1081           continue;
1082       } else if (IDC->Encloses(CurContext))
1083         break;
1084     }
1085 
1086     IdResolver.InsertDeclAfter(I, D);
1087   } else {
1088     IdResolver.AddDecl(D);
1089   }
1090 }
1091 
1092 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1093   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1094     TUScope->AddDecl(D);
1095 }
1096 
1097 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1098                          bool ExplicitInstantiationOrSpecialization) {
1099   return IdResolver.isDeclInScope(D, Ctx, Context, S,
1100                                   ExplicitInstantiationOrSpecialization);
1101 }
1102 
1103 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1104   DeclContext *TargetDC = DC->getPrimaryContext();
1105   do {
1106     if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1107       if (ScopeDC->getPrimaryContext() == TargetDC)
1108         return S;
1109   } while ((S = S->getParent()));
1110 
1111   return 0;
1112 }
1113 
1114 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1115                                             DeclContext*,
1116                                             ASTContext&);
1117 
1118 /// Filters out lookup results that don't fall within the given scope
1119 /// as determined by isDeclInScope.
1120 void Sema::FilterLookupForScope(LookupResult &R,
1121                                 DeclContext *Ctx, Scope *S,
1122                                 bool ConsiderLinkage,
1123                                 bool ExplicitInstantiationOrSpecialization) {
1124   LookupResult::Filter F = R.makeFilter();
1125   while (F.hasNext()) {
1126     NamedDecl *D = F.next();
1127 
1128     if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1129       continue;
1130 
1131     if (ConsiderLinkage &&
1132         isOutOfScopePreviousDeclaration(D, Ctx, Context))
1133       continue;
1134 
1135     F.erase();
1136   }
1137 
1138   F.done();
1139 }
1140 
1141 static bool isUsingDecl(NamedDecl *D) {
1142   return isa<UsingShadowDecl>(D) ||
1143          isa<UnresolvedUsingTypenameDecl>(D) ||
1144          isa<UnresolvedUsingValueDecl>(D);
1145 }
1146 
1147 /// Removes using shadow declarations from the lookup results.
1148 static void RemoveUsingDecls(LookupResult &R) {
1149   LookupResult::Filter F = R.makeFilter();
1150   while (F.hasNext())
1151     if (isUsingDecl(F.next()))
1152       F.erase();
1153 
1154   F.done();
1155 }
1156 
1157 /// \brief Check for this common pattern:
1158 /// @code
1159 /// class S {
1160 ///   S(const S&); // DO NOT IMPLEMENT
1161 ///   void operator=(const S&); // DO NOT IMPLEMENT
1162 /// };
1163 /// @endcode
1164 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1165   // FIXME: Should check for private access too but access is set after we get
1166   // the decl here.
1167   if (D->doesThisDeclarationHaveABody())
1168     return false;
1169 
1170   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1171     return CD->isCopyConstructor();
1172   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1173     return Method->isCopyAssignmentOperator();
1174   return false;
1175 }
1176 
1177 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1178   assert(D);
1179 
1180   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1181     return false;
1182 
1183   // Ignore class templates.
1184   if (D->getDeclContext()->isDependentContext() ||
1185       D->getLexicalDeclContext()->isDependentContext())
1186     return false;
1187 
1188   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1189     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1190       return false;
1191 
1192     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1193       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1194         return false;
1195     } else {
1196       // 'static inline' functions are used in headers; don't warn.
1197       if (FD->getStorageClass() == SC_Static &&
1198           FD->isInlineSpecified())
1199         return false;
1200     }
1201 
1202     if (FD->doesThisDeclarationHaveABody() &&
1203         Context.DeclMustBeEmitted(FD))
1204       return false;
1205   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1206     // Don't warn on variables of const-qualified or reference type, since their
1207     // values can be used even if though they're not odr-used, and because const
1208     // qualified variables can appear in headers in contexts where they're not
1209     // intended to be used.
1210     // FIXME: Use more principled rules for these exemptions.
1211     if (!VD->isFileVarDecl() ||
1212         VD->getType().isConstQualified() ||
1213         VD->getType()->isReferenceType() ||
1214         Context.DeclMustBeEmitted(VD))
1215       return false;
1216 
1217     if (VD->isStaticDataMember() &&
1218         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1219       return false;
1220 
1221   } else {
1222     return false;
1223   }
1224 
1225   // Only warn for unused decls internal to the translation unit.
1226   if (D->getLinkage() == ExternalLinkage)
1227     return false;
1228 
1229   return true;
1230 }
1231 
1232 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1233   if (!D)
1234     return;
1235 
1236   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1237     const FunctionDecl *First = FD->getFirstDeclaration();
1238     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1239       return; // First should already be in the vector.
1240   }
1241 
1242   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1243     const VarDecl *First = VD->getFirstDeclaration();
1244     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1245       return; // First should already be in the vector.
1246   }
1247 
1248   if (ShouldWarnIfUnusedFileScopedDecl(D))
1249     UnusedFileScopedDecls.push_back(D);
1250 }
1251 
1252 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1253   if (D->isInvalidDecl())
1254     return false;
1255 
1256   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1257     return false;
1258 
1259   if (isa<LabelDecl>(D))
1260     return true;
1261 
1262   // White-list anything that isn't a local variable.
1263   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1264       !D->getDeclContext()->isFunctionOrMethod())
1265     return false;
1266 
1267   // Types of valid local variables should be complete, so this should succeed.
1268   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1269 
1270     // White-list anything with an __attribute__((unused)) type.
1271     QualType Ty = VD->getType();
1272 
1273     // Only look at the outermost level of typedef.
1274     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1275       if (TT->getDecl()->hasAttr<UnusedAttr>())
1276         return false;
1277     }
1278 
1279     // If we failed to complete the type for some reason, or if the type is
1280     // dependent, don't diagnose the variable.
1281     if (Ty->isIncompleteType() || Ty->isDependentType())
1282       return false;
1283 
1284     if (const TagType *TT = Ty->getAs<TagType>()) {
1285       const TagDecl *Tag = TT->getDecl();
1286       if (Tag->hasAttr<UnusedAttr>())
1287         return false;
1288 
1289       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1290         if (!RD->hasTrivialDestructor())
1291           return false;
1292 
1293         if (const Expr *Init = VD->getInit()) {
1294           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1295             Init = Cleanups->getSubExpr();
1296           const CXXConstructExpr *Construct =
1297             dyn_cast<CXXConstructExpr>(Init);
1298           if (Construct && !Construct->isElidable()) {
1299             CXXConstructorDecl *CD = Construct->getConstructor();
1300             if (!CD->isTrivial())
1301               return false;
1302           }
1303         }
1304       }
1305     }
1306 
1307     // TODO: __attribute__((unused)) templates?
1308   }
1309 
1310   return true;
1311 }
1312 
1313 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1314                                      FixItHint &Hint) {
1315   if (isa<LabelDecl>(D)) {
1316     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1317                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1318     if (AfterColon.isInvalid())
1319       return;
1320     Hint = FixItHint::CreateRemoval(CharSourceRange::
1321                                     getCharRange(D->getLocStart(), AfterColon));
1322   }
1323   return;
1324 }
1325 
1326 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1327 /// unless they are marked attr(unused).
1328 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1329   FixItHint Hint;
1330   if (!ShouldDiagnoseUnusedDecl(D))
1331     return;
1332 
1333   GenerateFixForUnusedDecl(D, Context, Hint);
1334 
1335   unsigned DiagID;
1336   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1337     DiagID = diag::warn_unused_exception_param;
1338   else if (isa<LabelDecl>(D))
1339     DiagID = diag::warn_unused_label;
1340   else
1341     DiagID = diag::warn_unused_variable;
1342 
1343   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1344 }
1345 
1346 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1347   // Verify that we have no forward references left.  If so, there was a goto
1348   // or address of a label taken, but no definition of it.  Label fwd
1349   // definitions are indicated with a null substmt.
1350   if (L->getStmt() == 0)
1351     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1352 }
1353 
1354 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1355   if (S->decl_empty()) return;
1356   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1357          "Scope shouldn't contain decls!");
1358 
1359   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1360        I != E; ++I) {
1361     Decl *TmpD = (*I);
1362     assert(TmpD && "This decl didn't get pushed??");
1363 
1364     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1365     NamedDecl *D = cast<NamedDecl>(TmpD);
1366 
1367     if (!D->getDeclName()) continue;
1368 
1369     // Diagnose unused variables in this scope.
1370     if (!S->hasErrorOccurred())
1371       DiagnoseUnusedDecl(D);
1372 
1373     // If this was a forward reference to a label, verify it was defined.
1374     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1375       CheckPoppedLabel(LD, *this);
1376 
1377     // Remove this name from our lexical scope.
1378     IdResolver.RemoveDecl(D);
1379   }
1380 }
1381 
1382 void Sema::ActOnStartFunctionDeclarator() {
1383   ++InFunctionDeclarator;
1384 }
1385 
1386 void Sema::ActOnEndFunctionDeclarator() {
1387   assert(InFunctionDeclarator);
1388   --InFunctionDeclarator;
1389 }
1390 
1391 /// \brief Look for an Objective-C class in the translation unit.
1392 ///
1393 /// \param Id The name of the Objective-C class we're looking for. If
1394 /// typo-correction fixes this name, the Id will be updated
1395 /// to the fixed name.
1396 ///
1397 /// \param IdLoc The location of the name in the translation unit.
1398 ///
1399 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1400 /// if there is no class with the given name.
1401 ///
1402 /// \returns The declaration of the named Objective-C class, or NULL if the
1403 /// class could not be found.
1404 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1405                                               SourceLocation IdLoc,
1406                                               bool DoTypoCorrection) {
1407   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1408   // creation from this context.
1409   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1410 
1411   if (!IDecl && DoTypoCorrection) {
1412     // Perform typo correction at the given location, but only if we
1413     // find an Objective-C class name.
1414     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1415     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1416                                        LookupOrdinaryName, TUScope, NULL,
1417                                        Validator)) {
1418       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1419       Diag(IdLoc, diag::err_undef_interface_suggest)
1420         << Id << IDecl->getDeclName()
1421         << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1422       Diag(IDecl->getLocation(), diag::note_previous_decl)
1423         << IDecl->getDeclName();
1424 
1425       Id = IDecl->getIdentifier();
1426     }
1427   }
1428   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1429   // This routine must always return a class definition, if any.
1430   if (Def && Def->getDefinition())
1431       Def = Def->getDefinition();
1432   return Def;
1433 }
1434 
1435 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1436 /// from S, where a non-field would be declared. This routine copes
1437 /// with the difference between C and C++ scoping rules in structs and
1438 /// unions. For example, the following code is well-formed in C but
1439 /// ill-formed in C++:
1440 /// @code
1441 /// struct S6 {
1442 ///   enum { BAR } e;
1443 /// };
1444 ///
1445 /// void test_S6() {
1446 ///   struct S6 a;
1447 ///   a.e = BAR;
1448 /// }
1449 /// @endcode
1450 /// For the declaration of BAR, this routine will return a different
1451 /// scope. The scope S will be the scope of the unnamed enumeration
1452 /// within S6. In C++, this routine will return the scope associated
1453 /// with S6, because the enumeration's scope is a transparent
1454 /// context but structures can contain non-field names. In C, this
1455 /// routine will return the translation unit scope, since the
1456 /// enumeration's scope is a transparent context and structures cannot
1457 /// contain non-field names.
1458 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1459   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1460          (S->getEntity() &&
1461           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1462          (S->isClassScope() && !getLangOpts().CPlusPlus))
1463     S = S->getParent();
1464   return S;
1465 }
1466 
1467 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1468 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1469 /// if we're creating this built-in in anticipation of redeclaring the
1470 /// built-in.
1471 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1472                                      Scope *S, bool ForRedeclaration,
1473                                      SourceLocation Loc) {
1474   Builtin::ID BID = (Builtin::ID)bid;
1475 
1476   ASTContext::GetBuiltinTypeError Error;
1477   QualType R = Context.GetBuiltinType(BID, Error);
1478   switch (Error) {
1479   case ASTContext::GE_None:
1480     // Okay
1481     break;
1482 
1483   case ASTContext::GE_Missing_stdio:
1484     if (ForRedeclaration)
1485       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1486         << Context.BuiltinInfo.GetName(BID);
1487     return 0;
1488 
1489   case ASTContext::GE_Missing_setjmp:
1490     if (ForRedeclaration)
1491       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1492         << Context.BuiltinInfo.GetName(BID);
1493     return 0;
1494 
1495   case ASTContext::GE_Missing_ucontext:
1496     if (ForRedeclaration)
1497       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1498         << Context.BuiltinInfo.GetName(BID);
1499     return 0;
1500   }
1501 
1502   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1503     Diag(Loc, diag::ext_implicit_lib_function_decl)
1504       << Context.BuiltinInfo.GetName(BID)
1505       << R;
1506     if (Context.BuiltinInfo.getHeaderName(BID) &&
1507         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1508           != DiagnosticsEngine::Ignored)
1509       Diag(Loc, diag::note_please_include_header)
1510         << Context.BuiltinInfo.getHeaderName(BID)
1511         << Context.BuiltinInfo.GetName(BID);
1512   }
1513 
1514   FunctionDecl *New = FunctionDecl::Create(Context,
1515                                            Context.getTranslationUnitDecl(),
1516                                            Loc, Loc, II, R, /*TInfo=*/0,
1517                                            SC_Extern,
1518                                            SC_None, false,
1519                                            /*hasPrototype=*/true);
1520   New->setImplicit();
1521 
1522   // Create Decl objects for each parameter, adding them to the
1523   // FunctionDecl.
1524   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1525     SmallVector<ParmVarDecl*, 16> Params;
1526     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1527       ParmVarDecl *parm =
1528         ParmVarDecl::Create(Context, New, SourceLocation(),
1529                             SourceLocation(), 0,
1530                             FT->getArgType(i), /*TInfo=*/0,
1531                             SC_None, SC_None, 0);
1532       parm->setScopeInfo(0, i);
1533       Params.push_back(parm);
1534     }
1535     New->setParams(Params);
1536   }
1537 
1538   AddKnownFunctionAttributes(New);
1539 
1540   // TUScope is the translation-unit scope to insert this function into.
1541   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1542   // relate Scopes to DeclContexts, and probably eliminate CurContext
1543   // entirely, but we're not there yet.
1544   DeclContext *SavedContext = CurContext;
1545   CurContext = Context.getTranslationUnitDecl();
1546   PushOnScopeChains(New, TUScope);
1547   CurContext = SavedContext;
1548   return New;
1549 }
1550 
1551 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1552   QualType OldType;
1553   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1554     OldType = OldTypedef->getUnderlyingType();
1555   else
1556     OldType = Context.getTypeDeclType(Old);
1557   QualType NewType = New->getUnderlyingType();
1558 
1559   if (NewType->isVariablyModifiedType()) {
1560     // Must not redefine a typedef with a variably-modified type.
1561     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1562     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1563       << Kind << NewType;
1564     if (Old->getLocation().isValid())
1565       Diag(Old->getLocation(), diag::note_previous_definition);
1566     New->setInvalidDecl();
1567     return true;
1568   }
1569 
1570   if (OldType != NewType &&
1571       !OldType->isDependentType() &&
1572       !NewType->isDependentType() &&
1573       !Context.hasSameType(OldType, NewType)) {
1574     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1575     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1576       << Kind << NewType << OldType;
1577     if (Old->getLocation().isValid())
1578       Diag(Old->getLocation(), diag::note_previous_definition);
1579     New->setInvalidDecl();
1580     return true;
1581   }
1582   return false;
1583 }
1584 
1585 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1586 /// same name and scope as a previous declaration 'Old'.  Figure out
1587 /// how to resolve this situation, merging decls or emitting
1588 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1589 ///
1590 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1591   // If the new decl is known invalid already, don't bother doing any
1592   // merging checks.
1593   if (New->isInvalidDecl()) return;
1594 
1595   // Allow multiple definitions for ObjC built-in typedefs.
1596   // FIXME: Verify the underlying types are equivalent!
1597   if (getLangOpts().ObjC1) {
1598     const IdentifierInfo *TypeID = New->getIdentifier();
1599     switch (TypeID->getLength()) {
1600     default: break;
1601     case 2:
1602       {
1603         if (!TypeID->isStr("id"))
1604           break;
1605         QualType T = New->getUnderlyingType();
1606         if (!T->isPointerType())
1607           break;
1608         if (!T->isVoidPointerType()) {
1609           QualType PT = T->getAs<PointerType>()->getPointeeType();
1610           if (!PT->isStructureType())
1611             break;
1612         }
1613         Context.setObjCIdRedefinitionType(T);
1614         // Install the built-in type for 'id', ignoring the current definition.
1615         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1616         return;
1617       }
1618     case 5:
1619       if (!TypeID->isStr("Class"))
1620         break;
1621       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1622       // Install the built-in type for 'Class', ignoring the current definition.
1623       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1624       return;
1625     case 3:
1626       if (!TypeID->isStr("SEL"))
1627         break;
1628       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1629       // Install the built-in type for 'SEL', ignoring the current definition.
1630       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1631       return;
1632     }
1633     // Fall through - the typedef name was not a builtin type.
1634   }
1635 
1636   // Verify the old decl was also a type.
1637   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1638   if (!Old) {
1639     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1640       << New->getDeclName();
1641 
1642     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1643     if (OldD->getLocation().isValid())
1644       Diag(OldD->getLocation(), diag::note_previous_definition);
1645 
1646     return New->setInvalidDecl();
1647   }
1648 
1649   // If the old declaration is invalid, just give up here.
1650   if (Old->isInvalidDecl())
1651     return New->setInvalidDecl();
1652 
1653   // If the typedef types are not identical, reject them in all languages and
1654   // with any extensions enabled.
1655   if (isIncompatibleTypedef(Old, New))
1656     return;
1657 
1658   // The types match.  Link up the redeclaration chain if the old
1659   // declaration was a typedef.
1660   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1661     New->setPreviousDeclaration(Typedef);
1662 
1663   if (getLangOpts().MicrosoftExt)
1664     return;
1665 
1666   if (getLangOpts().CPlusPlus) {
1667     // C++ [dcl.typedef]p2:
1668     //   In a given non-class scope, a typedef specifier can be used to
1669     //   redefine the name of any type declared in that scope to refer
1670     //   to the type to which it already refers.
1671     if (!isa<CXXRecordDecl>(CurContext))
1672       return;
1673 
1674     // C++0x [dcl.typedef]p4:
1675     //   In a given class scope, a typedef specifier can be used to redefine
1676     //   any class-name declared in that scope that is not also a typedef-name
1677     //   to refer to the type to which it already refers.
1678     //
1679     // This wording came in via DR424, which was a correction to the
1680     // wording in DR56, which accidentally banned code like:
1681     //
1682     //   struct S {
1683     //     typedef struct A { } A;
1684     //   };
1685     //
1686     // in the C++03 standard. We implement the C++0x semantics, which
1687     // allow the above but disallow
1688     //
1689     //   struct S {
1690     //     typedef int I;
1691     //     typedef int I;
1692     //   };
1693     //
1694     // since that was the intent of DR56.
1695     if (!isa<TypedefNameDecl>(Old))
1696       return;
1697 
1698     Diag(New->getLocation(), diag::err_redefinition)
1699       << New->getDeclName();
1700     Diag(Old->getLocation(), diag::note_previous_definition);
1701     return New->setInvalidDecl();
1702   }
1703 
1704   // Modules always permit redefinition of typedefs, as does C11.
1705   if (getLangOpts().Modules || getLangOpts().C11)
1706     return;
1707 
1708   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1709   // is normally mapped to an error, but can be controlled with
1710   // -Wtypedef-redefinition.  If either the original or the redefinition is
1711   // in a system header, don't emit this for compatibility with GCC.
1712   if (getDiagnostics().getSuppressSystemWarnings() &&
1713       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1714        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1715     return;
1716 
1717   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1718     << New->getDeclName();
1719   Diag(Old->getLocation(), diag::note_previous_definition);
1720   return;
1721 }
1722 
1723 /// DeclhasAttr - returns true if decl Declaration already has the target
1724 /// attribute.
1725 static bool
1726 DeclHasAttr(const Decl *D, const Attr *A) {
1727   // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1728   // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1729   // responsible for making sure they are consistent.
1730   const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1731   if (AA)
1732     return false;
1733 
1734   // The following thread safety attributes can also be duplicated.
1735   switch (A->getKind()) {
1736     case attr::ExclusiveLocksRequired:
1737     case attr::SharedLocksRequired:
1738     case attr::LocksExcluded:
1739     case attr::ExclusiveLockFunction:
1740     case attr::SharedLockFunction:
1741     case attr::UnlockFunction:
1742     case attr::ExclusiveTrylockFunction:
1743     case attr::SharedTrylockFunction:
1744     case attr::GuardedBy:
1745     case attr::PtGuardedBy:
1746     case attr::AcquiredBefore:
1747     case attr::AcquiredAfter:
1748       return false;
1749     default:
1750       ;
1751   }
1752 
1753   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1754   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1755   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1756     if ((*i)->getKind() == A->getKind()) {
1757       if (Ann) {
1758         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1759           return true;
1760         continue;
1761       }
1762       // FIXME: Don't hardcode this check
1763       if (OA && isa<OwnershipAttr>(*i))
1764         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1765       return true;
1766     }
1767 
1768   return false;
1769 }
1770 
1771 bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
1772   InheritableAttr *NewAttr = NULL;
1773   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1774     NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1775                                     AA->getIntroduced(), AA->getDeprecated(),
1776                                     AA->getObsoleted(), AA->getUnavailable(),
1777                                     AA->getMessage());
1778   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1779     NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1780   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1781     NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1782   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1783     NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1784   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1785     NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1786                               FA->getFormatIdx(), FA->getFirstArg());
1787   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1788     NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1789   else if (!DeclHasAttr(D, Attr))
1790     NewAttr = cast<InheritableAttr>(Attr->clone(Context));
1791 
1792   if (NewAttr) {
1793     NewAttr->setInherited(true);
1794     D->addAttr(NewAttr);
1795     return true;
1796   }
1797 
1798   return false;
1799 }
1800 
1801 static const Decl *getDefinition(const Decl *D) {
1802   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1803     return TD->getDefinition();
1804   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1805     return VD->getDefinition();
1806   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1807     const FunctionDecl* Def;
1808     if (FD->hasBody(Def))
1809       return Def;
1810   }
1811   return NULL;
1812 }
1813 
1814 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1815   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
1816        I != E; ++I) {
1817     Attr *Attribute = *I;
1818     if (Attribute->getKind() == Kind)
1819       return true;
1820   }
1821   return false;
1822 }
1823 
1824 /// checkNewAttributesAfterDef - If we already have a definition, check that
1825 /// there are no new attributes in this declaration.
1826 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
1827   if (!New->hasAttrs())
1828     return;
1829 
1830   const Decl *Def = getDefinition(Old);
1831   if (!Def || Def == New)
1832     return;
1833 
1834   AttrVec &NewAttributes = New->getAttrs();
1835   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
1836     const Attr *NewAttribute = NewAttributes[I];
1837     if (hasAttribute(Def, NewAttribute->getKind())) {
1838       ++I;
1839       continue; // regular attr merging will take care of validating this.
1840     }
1841     S.Diag(NewAttribute->getLocation(),
1842            diag::warn_attribute_precede_definition);
1843     S.Diag(Def->getLocation(), diag::note_previous_definition);
1844     NewAttributes.erase(NewAttributes.begin() + I);
1845     --E;
1846   }
1847 }
1848 
1849 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1850 void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1851                                bool MergeDeprecation) {
1852   // attributes declared post-definition are currently ignored
1853   checkNewAttributesAfterDef(*this, New, Old);
1854 
1855   if (!Old->hasAttrs())
1856     return;
1857 
1858   bool foundAny = New->hasAttrs();
1859 
1860   // Ensure that any moving of objects within the allocated map is done before
1861   // we process them.
1862   if (!foundAny) New->setAttrs(AttrVec());
1863 
1864   for (specific_attr_iterator<InheritableAttr>
1865          i = Old->specific_attr_begin<InheritableAttr>(),
1866          e = Old->specific_attr_end<InheritableAttr>();
1867        i != e; ++i) {
1868     // Ignore deprecated/unavailable/availability attributes if requested.
1869     if (!MergeDeprecation &&
1870         (isa<DeprecatedAttr>(*i) ||
1871          isa<UnavailableAttr>(*i) ||
1872          isa<AvailabilityAttr>(*i)))
1873       continue;
1874 
1875     if (mergeDeclAttribute(New, *i))
1876       foundAny = true;
1877   }
1878 
1879   if (!foundAny) New->dropAttrs();
1880 }
1881 
1882 /// mergeParamDeclAttributes - Copy attributes from the old parameter
1883 /// to the new one.
1884 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1885                                      const ParmVarDecl *oldDecl,
1886                                      ASTContext &C) {
1887   if (!oldDecl->hasAttrs())
1888     return;
1889 
1890   bool foundAny = newDecl->hasAttrs();
1891 
1892   // Ensure that any moving of objects within the allocated map is
1893   // done before we process them.
1894   if (!foundAny) newDecl->setAttrs(AttrVec());
1895 
1896   for (specific_attr_iterator<InheritableParamAttr>
1897        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1898        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1899     if (!DeclHasAttr(newDecl, *i)) {
1900       InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1901       newAttr->setInherited(true);
1902       newDecl->addAttr(newAttr);
1903       foundAny = true;
1904     }
1905   }
1906 
1907   if (!foundAny) newDecl->dropAttrs();
1908 }
1909 
1910 namespace {
1911 
1912 /// Used in MergeFunctionDecl to keep track of function parameters in
1913 /// C.
1914 struct GNUCompatibleParamWarning {
1915   ParmVarDecl *OldParm;
1916   ParmVarDecl *NewParm;
1917   QualType PromotedType;
1918 };
1919 
1920 }
1921 
1922 /// getSpecialMember - get the special member enum for a method.
1923 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1924   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1925     if (Ctor->isDefaultConstructor())
1926       return Sema::CXXDefaultConstructor;
1927 
1928     if (Ctor->isCopyConstructor())
1929       return Sema::CXXCopyConstructor;
1930 
1931     if (Ctor->isMoveConstructor())
1932       return Sema::CXXMoveConstructor;
1933   } else if (isa<CXXDestructorDecl>(MD)) {
1934     return Sema::CXXDestructor;
1935   } else if (MD->isCopyAssignmentOperator()) {
1936     return Sema::CXXCopyAssignment;
1937   } else if (MD->isMoveAssignmentOperator()) {
1938     return Sema::CXXMoveAssignment;
1939   }
1940 
1941   return Sema::CXXInvalid;
1942 }
1943 
1944 /// canRedefineFunction - checks if a function can be redefined. Currently,
1945 /// only extern inline functions can be redefined, and even then only in
1946 /// GNU89 mode.
1947 static bool canRedefineFunction(const FunctionDecl *FD,
1948                                 const LangOptions& LangOpts) {
1949   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1950           !LangOpts.CPlusPlus &&
1951           FD->isInlineSpecified() &&
1952           FD->getStorageClass() == SC_Extern);
1953 }
1954 
1955 /// Is the given calling convention the ABI default for the given
1956 /// declaration?
1957 static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
1958   CallingConv ABIDefaultCC;
1959   if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1960     ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
1961   } else {
1962     // Free C function or a static method.
1963     ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
1964   }
1965   return ABIDefaultCC == CC;
1966 }
1967 
1968 /// MergeFunctionDecl - We just parsed a function 'New' from
1969 /// declarator D which has the same name and scope as a previous
1970 /// declaration 'Old'.  Figure out how to resolve this situation,
1971 /// merging decls or emitting diagnostics as appropriate.
1972 ///
1973 /// In C++, New and Old must be declarations that are not
1974 /// overloaded. Use IsOverload to determine whether New and Old are
1975 /// overloaded, and to select the Old declaration that New should be
1976 /// merged with.
1977 ///
1978 /// Returns true if there was an error, false otherwise.
1979 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1980   // Verify the old decl was also a function.
1981   FunctionDecl *Old = 0;
1982   if (FunctionTemplateDecl *OldFunctionTemplate
1983         = dyn_cast<FunctionTemplateDecl>(OldD))
1984     Old = OldFunctionTemplate->getTemplatedDecl();
1985   else
1986     Old = dyn_cast<FunctionDecl>(OldD);
1987   if (!Old) {
1988     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1989       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1990       Diag(Shadow->getTargetDecl()->getLocation(),
1991            diag::note_using_decl_target);
1992       Diag(Shadow->getUsingDecl()->getLocation(),
1993            diag::note_using_decl) << 0;
1994       return true;
1995     }
1996 
1997     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1998       << New->getDeclName();
1999     Diag(OldD->getLocation(), diag::note_previous_definition);
2000     return true;
2001   }
2002 
2003   // Determine whether the previous declaration was a definition,
2004   // implicit declaration, or a declaration.
2005   diag::kind PrevDiag;
2006   if (Old->isThisDeclarationADefinition())
2007     PrevDiag = diag::note_previous_definition;
2008   else if (Old->isImplicit())
2009     PrevDiag = diag::note_previous_implicit_declaration;
2010   else
2011     PrevDiag = diag::note_previous_declaration;
2012 
2013   QualType OldQType = Context.getCanonicalType(Old->getType());
2014   QualType NewQType = Context.getCanonicalType(New->getType());
2015 
2016   // Don't complain about this if we're in GNU89 mode and the old function
2017   // is an extern inline function.
2018   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2019       New->getStorageClass() == SC_Static &&
2020       Old->getStorageClass() != SC_Static &&
2021       !canRedefineFunction(Old, getLangOpts())) {
2022     if (getLangOpts().MicrosoftExt) {
2023       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2024       Diag(Old->getLocation(), PrevDiag);
2025     } else {
2026       Diag(New->getLocation(), diag::err_static_non_static) << New;
2027       Diag(Old->getLocation(), PrevDiag);
2028       return true;
2029     }
2030   }
2031 
2032   // If a function is first declared with a calling convention, but is
2033   // later declared or defined without one, the second decl assumes the
2034   // calling convention of the first.
2035   //
2036   // It's OK if a function is first declared without a calling convention,
2037   // but is later declared or defined with the default calling convention.
2038   //
2039   // For the new decl, we have to look at the NON-canonical type to tell the
2040   // difference between a function that really doesn't have a calling
2041   // convention and one that is declared cdecl. That's because in
2042   // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2043   // because it is the default calling convention.
2044   //
2045   // Note also that we DO NOT return at this point, because we still have
2046   // other tests to run.
2047   const FunctionType *OldType = cast<FunctionType>(OldQType);
2048   const FunctionType *NewType = New->getType()->getAs<FunctionType>();
2049   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2050   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2051   bool RequiresAdjustment = false;
2052   if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2053     // Fast path: nothing to do.
2054 
2055   // Inherit the CC from the previous declaration if it was specified
2056   // there but not here.
2057   } else if (NewTypeInfo.getCC() == CC_Default) {
2058     NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2059     RequiresAdjustment = true;
2060 
2061   // Don't complain about mismatches when the default CC is
2062   // effectively the same as the explict one.
2063   } else if (OldTypeInfo.getCC() == CC_Default &&
2064              isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
2065     NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2066     RequiresAdjustment = true;
2067 
2068   } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2069                                      NewTypeInfo.getCC())) {
2070     // Calling conventions really aren't compatible, so complain.
2071     Diag(New->getLocation(), diag::err_cconv_change)
2072       << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2073       << (OldTypeInfo.getCC() == CC_Default)
2074       << (OldTypeInfo.getCC() == CC_Default ? "" :
2075           FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
2076     Diag(Old->getLocation(), diag::note_previous_declaration);
2077     return true;
2078   }
2079 
2080   // FIXME: diagnose the other way around?
2081   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2082     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2083     RequiresAdjustment = true;
2084   }
2085 
2086   // Merge regparm attribute.
2087   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2088       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2089     if (NewTypeInfo.getHasRegParm()) {
2090       Diag(New->getLocation(), diag::err_regparm_mismatch)
2091         << NewType->getRegParmType()
2092         << OldType->getRegParmType();
2093       Diag(Old->getLocation(), diag::note_previous_declaration);
2094       return true;
2095     }
2096 
2097     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2098     RequiresAdjustment = true;
2099   }
2100 
2101   // Merge ns_returns_retained attribute.
2102   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2103     if (NewTypeInfo.getProducesResult()) {
2104       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2105       Diag(Old->getLocation(), diag::note_previous_declaration);
2106       return true;
2107     }
2108 
2109     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2110     RequiresAdjustment = true;
2111   }
2112 
2113   if (RequiresAdjustment) {
2114     NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2115     New->setType(QualType(NewType, 0));
2116     NewQType = Context.getCanonicalType(New->getType());
2117   }
2118 
2119   if (getLangOpts().CPlusPlus) {
2120     // (C++98 13.1p2):
2121     //   Certain function declarations cannot be overloaded:
2122     //     -- Function declarations that differ only in the return type
2123     //        cannot be overloaded.
2124     QualType OldReturnType = OldType->getResultType();
2125     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2126     QualType ResQT;
2127     if (OldReturnType != NewReturnType) {
2128       if (NewReturnType->isObjCObjectPointerType()
2129           && OldReturnType->isObjCObjectPointerType())
2130         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2131       if (ResQT.isNull()) {
2132         if (New->isCXXClassMember() && New->isOutOfLine())
2133           Diag(New->getLocation(),
2134                diag::err_member_def_does_not_match_ret_type) << New;
2135         else
2136           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2137         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2138         return true;
2139       }
2140       else
2141         NewQType = ResQT;
2142     }
2143 
2144     const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2145     CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2146     if (OldMethod && NewMethod) {
2147       // Preserve triviality.
2148       NewMethod->setTrivial(OldMethod->isTrivial());
2149 
2150       // MSVC allows explicit template specialization at class scope:
2151       // 2 CXMethodDecls referring to the same function will be injected.
2152       // We don't want a redeclartion error.
2153       bool IsClassScopeExplicitSpecialization =
2154                               OldMethod->isFunctionTemplateSpecialization() &&
2155                               NewMethod->isFunctionTemplateSpecialization();
2156       bool isFriend = NewMethod->getFriendObjectKind();
2157 
2158       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2159           !IsClassScopeExplicitSpecialization) {
2160         //    -- Member function declarations with the same name and the
2161         //       same parameter types cannot be overloaded if any of them
2162         //       is a static member function declaration.
2163         if (OldMethod->isStatic() || NewMethod->isStatic()) {
2164           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2165           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2166           return true;
2167         }
2168 
2169         // C++ [class.mem]p1:
2170         //   [...] A member shall not be declared twice in the
2171         //   member-specification, except that a nested class or member
2172         //   class template can be declared and then later defined.
2173         if (ActiveTemplateInstantiations.empty()) {
2174           unsigned NewDiag;
2175           if (isa<CXXConstructorDecl>(OldMethod))
2176             NewDiag = diag::err_constructor_redeclared;
2177           else if (isa<CXXDestructorDecl>(NewMethod))
2178             NewDiag = diag::err_destructor_redeclared;
2179           else if (isa<CXXConversionDecl>(NewMethod))
2180             NewDiag = diag::err_conv_function_redeclared;
2181           else
2182             NewDiag = diag::err_member_redeclared;
2183 
2184           Diag(New->getLocation(), NewDiag);
2185         } else {
2186           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2187             << New << New->getType();
2188         }
2189         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2190 
2191       // Complain if this is an explicit declaration of a special
2192       // member that was initially declared implicitly.
2193       //
2194       // As an exception, it's okay to befriend such methods in order
2195       // to permit the implicit constructor/destructor/operator calls.
2196       } else if (OldMethod->isImplicit()) {
2197         if (isFriend) {
2198           NewMethod->setImplicit();
2199         } else {
2200           Diag(NewMethod->getLocation(),
2201                diag::err_definition_of_implicitly_declared_member)
2202             << New << getSpecialMember(OldMethod);
2203           return true;
2204         }
2205       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2206         Diag(NewMethod->getLocation(),
2207              diag::err_definition_of_explicitly_defaulted_member)
2208           << getSpecialMember(OldMethod);
2209         return true;
2210       }
2211     }
2212 
2213     // (C++98 8.3.5p3):
2214     //   All declarations for a function shall agree exactly in both the
2215     //   return type and the parameter-type-list.
2216     // We also want to respect all the extended bits except noreturn.
2217 
2218     // noreturn should now match unless the old type info didn't have it.
2219     QualType OldQTypeForComparison = OldQType;
2220     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2221       assert(OldQType == QualType(OldType, 0));
2222       const FunctionType *OldTypeForComparison
2223         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2224       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2225       assert(OldQTypeForComparison.isCanonical());
2226     }
2227 
2228     if (OldQTypeForComparison == NewQType)
2229       return MergeCompatibleFunctionDecls(New, Old, S);
2230 
2231     // Fall through for conflicting redeclarations and redefinitions.
2232   }
2233 
2234   // C: Function types need to be compatible, not identical. This handles
2235   // duplicate function decls like "void f(int); void f(enum X);" properly.
2236   if (!getLangOpts().CPlusPlus &&
2237       Context.typesAreCompatible(OldQType, NewQType)) {
2238     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2239     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2240     const FunctionProtoType *OldProto = 0;
2241     if (isa<FunctionNoProtoType>(NewFuncType) &&
2242         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2243       // The old declaration provided a function prototype, but the
2244       // new declaration does not. Merge in the prototype.
2245       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2246       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2247                                                  OldProto->arg_type_end());
2248       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2249                                          ParamTypes.data(), ParamTypes.size(),
2250                                          OldProto->getExtProtoInfo());
2251       New->setType(NewQType);
2252       New->setHasInheritedPrototype();
2253 
2254       // Synthesize a parameter for each argument type.
2255       SmallVector<ParmVarDecl*, 16> Params;
2256       for (FunctionProtoType::arg_type_iterator
2257              ParamType = OldProto->arg_type_begin(),
2258              ParamEnd = OldProto->arg_type_end();
2259            ParamType != ParamEnd; ++ParamType) {
2260         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2261                                                  SourceLocation(),
2262                                                  SourceLocation(), 0,
2263                                                  *ParamType, /*TInfo=*/0,
2264                                                  SC_None, SC_None,
2265                                                  0);
2266         Param->setScopeInfo(0, Params.size());
2267         Param->setImplicit();
2268         Params.push_back(Param);
2269       }
2270 
2271       New->setParams(Params);
2272     }
2273 
2274     return MergeCompatibleFunctionDecls(New, Old, S);
2275   }
2276 
2277   // GNU C permits a K&R definition to follow a prototype declaration
2278   // if the declared types of the parameters in the K&R definition
2279   // match the types in the prototype declaration, even when the
2280   // promoted types of the parameters from the K&R definition differ
2281   // from the types in the prototype. GCC then keeps the types from
2282   // the prototype.
2283   //
2284   // If a variadic prototype is followed by a non-variadic K&R definition,
2285   // the K&R definition becomes variadic.  This is sort of an edge case, but
2286   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2287   // C99 6.9.1p8.
2288   if (!getLangOpts().CPlusPlus &&
2289       Old->hasPrototype() && !New->hasPrototype() &&
2290       New->getType()->getAs<FunctionProtoType>() &&
2291       Old->getNumParams() == New->getNumParams()) {
2292     SmallVector<QualType, 16> ArgTypes;
2293     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2294     const FunctionProtoType *OldProto
2295       = Old->getType()->getAs<FunctionProtoType>();
2296     const FunctionProtoType *NewProto
2297       = New->getType()->getAs<FunctionProtoType>();
2298 
2299     // Determine whether this is the GNU C extension.
2300     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2301                                                NewProto->getResultType());
2302     bool LooseCompatible = !MergedReturn.isNull();
2303     for (unsigned Idx = 0, End = Old->getNumParams();
2304          LooseCompatible && Idx != End; ++Idx) {
2305       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2306       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2307       if (Context.typesAreCompatible(OldParm->getType(),
2308                                      NewProto->getArgType(Idx))) {
2309         ArgTypes.push_back(NewParm->getType());
2310       } else if (Context.typesAreCompatible(OldParm->getType(),
2311                                             NewParm->getType(),
2312                                             /*CompareUnqualified=*/true)) {
2313         GNUCompatibleParamWarning Warn
2314           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2315         Warnings.push_back(Warn);
2316         ArgTypes.push_back(NewParm->getType());
2317       } else
2318         LooseCompatible = false;
2319     }
2320 
2321     if (LooseCompatible) {
2322       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2323         Diag(Warnings[Warn].NewParm->getLocation(),
2324              diag::ext_param_promoted_not_compatible_with_prototype)
2325           << Warnings[Warn].PromotedType
2326           << Warnings[Warn].OldParm->getType();
2327         if (Warnings[Warn].OldParm->getLocation().isValid())
2328           Diag(Warnings[Warn].OldParm->getLocation(),
2329                diag::note_previous_declaration);
2330       }
2331 
2332       New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2333                                            ArgTypes.size(),
2334                                            OldProto->getExtProtoInfo()));
2335       return MergeCompatibleFunctionDecls(New, Old, S);
2336     }
2337 
2338     // Fall through to diagnose conflicting types.
2339   }
2340 
2341   // A function that has already been declared has been redeclared or defined
2342   // with a different type- show appropriate diagnostic
2343   if (unsigned BuiltinID = Old->getBuiltinID()) {
2344     // The user has declared a builtin function with an incompatible
2345     // signature.
2346     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2347       // The function the user is redeclaring is a library-defined
2348       // function like 'malloc' or 'printf'. Warn about the
2349       // redeclaration, then pretend that we don't know about this
2350       // library built-in.
2351       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2352       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2353         << Old << Old->getType();
2354       New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2355       Old->setInvalidDecl();
2356       return false;
2357     }
2358 
2359     PrevDiag = diag::note_previous_builtin_declaration;
2360   }
2361 
2362   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2363   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2364   return true;
2365 }
2366 
2367 /// \brief Completes the merge of two function declarations that are
2368 /// known to be compatible.
2369 ///
2370 /// This routine handles the merging of attributes and other
2371 /// properties of function declarations form the old declaration to
2372 /// the new declaration, once we know that New is in fact a
2373 /// redeclaration of Old.
2374 ///
2375 /// \returns false
2376 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2377                                         Scope *S) {
2378   // Merge the attributes
2379   mergeDeclAttributes(New, Old);
2380 
2381   // Merge the storage class.
2382   if (Old->getStorageClass() != SC_Extern &&
2383       Old->getStorageClass() != SC_None)
2384     New->setStorageClass(Old->getStorageClass());
2385 
2386   // Merge "pure" flag.
2387   if (Old->isPure())
2388     New->setPure();
2389 
2390   // Merge "used" flag.
2391   if (Old->isUsed(false))
2392     New->setUsed();
2393 
2394   // Merge attributes from the parameters.  These can mismatch with K&R
2395   // declarations.
2396   if (New->getNumParams() == Old->getNumParams())
2397     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2398       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2399                                Context);
2400 
2401   if (getLangOpts().CPlusPlus)
2402     return MergeCXXFunctionDecl(New, Old, S);
2403 
2404   // Merge the function types so the we get the composite types for the return
2405   // and argument types.
2406   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2407   if (!Merged.isNull())
2408     New->setType(Merged);
2409 
2410   return false;
2411 }
2412 
2413 
2414 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2415                                 ObjCMethodDecl *oldMethod) {
2416 
2417   // Merge the attributes, including deprecated/unavailable
2418   mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
2419 
2420   // Merge attributes from the parameters.
2421   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2422                                        oe = oldMethod->param_end();
2423   for (ObjCMethodDecl::param_iterator
2424          ni = newMethod->param_begin(), ne = newMethod->param_end();
2425        ni != ne && oi != oe; ++ni, ++oi)
2426     mergeParamDeclAttributes(*ni, *oi, Context);
2427 
2428   CheckObjCMethodOverride(newMethod, oldMethod, true);
2429 }
2430 
2431 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2432 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2433 /// emitting diagnostics as appropriate.
2434 ///
2435 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2436 /// to here in AddInitializerToDecl. We can't check them before the initializer
2437 /// is attached.
2438 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2439   if (New->isInvalidDecl() || Old->isInvalidDecl())
2440     return;
2441 
2442   QualType MergedT;
2443   if (getLangOpts().CPlusPlus) {
2444     AutoType *AT = New->getType()->getContainedAutoType();
2445     if (AT && !AT->isDeduced()) {
2446       // We don't know what the new type is until the initializer is attached.
2447       return;
2448     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2449       // These could still be something that needs exception specs checked.
2450       return MergeVarDeclExceptionSpecs(New, Old);
2451     }
2452     // C++ [basic.link]p10:
2453     //   [...] the types specified by all declarations referring to a given
2454     //   object or function shall be identical, except that declarations for an
2455     //   array object can specify array types that differ by the presence or
2456     //   absence of a major array bound (8.3.4).
2457     else if (Old->getType()->isIncompleteArrayType() &&
2458              New->getType()->isArrayType()) {
2459       CanQual<ArrayType> OldArray
2460         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2461       CanQual<ArrayType> NewArray
2462         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2463       if (OldArray->getElementType() == NewArray->getElementType())
2464         MergedT = New->getType();
2465     } else if (Old->getType()->isArrayType() &&
2466              New->getType()->isIncompleteArrayType()) {
2467       CanQual<ArrayType> OldArray
2468         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2469       CanQual<ArrayType> NewArray
2470         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2471       if (OldArray->getElementType() == NewArray->getElementType())
2472         MergedT = Old->getType();
2473     } else if (New->getType()->isObjCObjectPointerType()
2474                && Old->getType()->isObjCObjectPointerType()) {
2475         MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2476                                                         Old->getType());
2477     }
2478   } else {
2479     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2480   }
2481   if (MergedT.isNull()) {
2482     Diag(New->getLocation(), diag::err_redefinition_different_type)
2483       << New->getDeclName() << New->getType() << Old->getType();
2484     Diag(Old->getLocation(), diag::note_previous_definition);
2485     return New->setInvalidDecl();
2486   }
2487   New->setType(MergedT);
2488 }
2489 
2490 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2491 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2492 /// situation, merging decls or emitting diagnostics as appropriate.
2493 ///
2494 /// Tentative definition rules (C99 6.9.2p2) are checked by
2495 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2496 /// definitions here, since the initializer hasn't been attached.
2497 ///
2498 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2499   // If the new decl is already invalid, don't do any other checking.
2500   if (New->isInvalidDecl())
2501     return;
2502 
2503   // Verify the old decl was also a variable.
2504   VarDecl *Old = 0;
2505   if (!Previous.isSingleResult() ||
2506       !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2507     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2508       << New->getDeclName();
2509     Diag(Previous.getRepresentativeDecl()->getLocation(),
2510          diag::note_previous_definition);
2511     return New->setInvalidDecl();
2512   }
2513 
2514   // C++ [class.mem]p1:
2515   //   A member shall not be declared twice in the member-specification [...]
2516   //
2517   // Here, we need only consider static data members.
2518   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2519     Diag(New->getLocation(), diag::err_duplicate_member)
2520       << New->getIdentifier();
2521     Diag(Old->getLocation(), diag::note_previous_declaration);
2522     New->setInvalidDecl();
2523   }
2524 
2525   mergeDeclAttributes(New, Old);
2526   // Warn if an already-declared variable is made a weak_import in a subsequent
2527   // declaration
2528   if (New->getAttr<WeakImportAttr>() &&
2529       Old->getStorageClass() == SC_None &&
2530       !Old->getAttr<WeakImportAttr>()) {
2531     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2532     Diag(Old->getLocation(), diag::note_previous_definition);
2533     // Remove weak_import attribute on new declaration.
2534     New->dropAttr<WeakImportAttr>();
2535   }
2536 
2537   // Merge the types.
2538   MergeVarDeclTypes(New, Old);
2539   if (New->isInvalidDecl())
2540     return;
2541 
2542   // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2543   if (New->getStorageClass() == SC_Static &&
2544       (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2545     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2546     Diag(Old->getLocation(), diag::note_previous_definition);
2547     return New->setInvalidDecl();
2548   }
2549   // C99 6.2.2p4:
2550   //   For an identifier declared with the storage-class specifier
2551   //   extern in a scope in which a prior declaration of that
2552   //   identifier is visible,23) if the prior declaration specifies
2553   //   internal or external linkage, the linkage of the identifier at
2554   //   the later declaration is the same as the linkage specified at
2555   //   the prior declaration. If no prior declaration is visible, or
2556   //   if the prior declaration specifies no linkage, then the
2557   //   identifier has external linkage.
2558   if (New->hasExternalStorage() && Old->hasLinkage())
2559     /* Okay */;
2560   else if (New->getStorageClass() != SC_Static &&
2561            Old->getStorageClass() == SC_Static) {
2562     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2563     Diag(Old->getLocation(), diag::note_previous_definition);
2564     return New->setInvalidDecl();
2565   }
2566 
2567   // Check if extern is followed by non-extern and vice-versa.
2568   if (New->hasExternalStorage() &&
2569       !Old->hasLinkage() && Old->isLocalVarDecl()) {
2570     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2571     Diag(Old->getLocation(), diag::note_previous_definition);
2572     return New->setInvalidDecl();
2573   }
2574   if (Old->hasExternalStorage() &&
2575       !New->hasLinkage() && New->isLocalVarDecl()) {
2576     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2577     Diag(Old->getLocation(), diag::note_previous_definition);
2578     return New->setInvalidDecl();
2579   }
2580 
2581   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2582 
2583   // FIXME: The test for external storage here seems wrong? We still
2584   // need to check for mismatches.
2585   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2586       // Don't complain about out-of-line definitions of static members.
2587       !(Old->getLexicalDeclContext()->isRecord() &&
2588         !New->getLexicalDeclContext()->isRecord())) {
2589     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2590     Diag(Old->getLocation(), diag::note_previous_definition);
2591     return New->setInvalidDecl();
2592   }
2593 
2594   if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2595     Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2596     Diag(Old->getLocation(), diag::note_previous_definition);
2597   } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2598     Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2599     Diag(Old->getLocation(), diag::note_previous_definition);
2600   }
2601 
2602   // C++ doesn't have tentative definitions, so go right ahead and check here.
2603   const VarDecl *Def;
2604   if (getLangOpts().CPlusPlus &&
2605       New->isThisDeclarationADefinition() == VarDecl::Definition &&
2606       (Def = Old->getDefinition())) {
2607     Diag(New->getLocation(), diag::err_redefinition)
2608       << New->getDeclName();
2609     Diag(Def->getLocation(), diag::note_previous_definition);
2610     New->setInvalidDecl();
2611     return;
2612   }
2613   // c99 6.2.2 P4.
2614   // For an identifier declared with the storage-class specifier extern in a
2615   // scope in which a prior declaration of that identifier is visible, if
2616   // the prior declaration specifies internal or external linkage, the linkage
2617   // of the identifier at the later declaration is the same as the linkage
2618   // specified at the prior declaration.
2619   // FIXME. revisit this code.
2620   if (New->hasExternalStorage() &&
2621       Old->getLinkage() == InternalLinkage &&
2622       New->getDeclContext() == Old->getDeclContext())
2623     New->setStorageClass(Old->getStorageClass());
2624 
2625   // Merge "used" flag.
2626   if (Old->isUsed(false))
2627     New->setUsed();
2628 
2629   // Keep a chain of previous declarations.
2630   New->setPreviousDeclaration(Old);
2631 
2632   // Inherit access appropriately.
2633   New->setAccess(Old->getAccess());
2634 }
2635 
2636 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2637 /// no declarator (e.g. "struct foo;") is parsed.
2638 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2639                                        DeclSpec &DS) {
2640   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
2641 }
2642 
2643 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2644 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2645 /// parameters to cope with template friend declarations.
2646 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2647                                        DeclSpec &DS,
2648                                        MultiTemplateParamsArg TemplateParams) {
2649   Decl *TagD = 0;
2650   TagDecl *Tag = 0;
2651   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2652       DS.getTypeSpecType() == DeclSpec::TST_struct ||
2653       DS.getTypeSpecType() == DeclSpec::TST_interface ||
2654       DS.getTypeSpecType() == DeclSpec::TST_union ||
2655       DS.getTypeSpecType() == DeclSpec::TST_enum) {
2656     TagD = DS.getRepAsDecl();
2657 
2658     if (!TagD) // We probably had an error
2659       return 0;
2660 
2661     // Note that the above type specs guarantee that the
2662     // type rep is a Decl, whereas in many of the others
2663     // it's a Type.
2664     if (isa<TagDecl>(TagD))
2665       Tag = cast<TagDecl>(TagD);
2666     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2667       Tag = CTD->getTemplatedDecl();
2668   }
2669 
2670   if (Tag) {
2671     getASTContext().addUnnamedTag(Tag);
2672     Tag->setFreeStanding();
2673     if (Tag->isInvalidDecl())
2674       return Tag;
2675   }
2676 
2677   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2678     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2679     // or incomplete types shall not be restrict-qualified."
2680     if (TypeQuals & DeclSpec::TQ_restrict)
2681       Diag(DS.getRestrictSpecLoc(),
2682            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2683            << DS.getSourceRange();
2684   }
2685 
2686   if (DS.isConstexprSpecified()) {
2687     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2688     // and definitions of functions and variables.
2689     if (Tag)
2690       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2691         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2692             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2693             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
2694             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
2695     else
2696       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2697     // Don't emit warnings after this error.
2698     return TagD;
2699   }
2700 
2701   if (DS.isFriendSpecified()) {
2702     // If we're dealing with a decl but not a TagDecl, assume that
2703     // whatever routines created it handled the friendship aspect.
2704     if (TagD && !Tag)
2705       return 0;
2706     return ActOnFriendTypeDecl(S, DS, TemplateParams);
2707   }
2708 
2709   // Track whether we warned about the fact that there aren't any
2710   // declarators.
2711   bool emittedWarning = false;
2712 
2713   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2714     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2715         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2716       if (getLangOpts().CPlusPlus ||
2717           Record->getDeclContext()->isRecord())
2718         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2719 
2720       Diag(DS.getLocStart(), diag::ext_no_declarators)
2721         << DS.getSourceRange();
2722       emittedWarning = true;
2723     }
2724   }
2725 
2726   // Check for Microsoft C extension: anonymous struct.
2727   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2728       CurContext->isRecord() &&
2729       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2730     // Handle 2 kinds of anonymous struct:
2731     //   struct STRUCT;
2732     // and
2733     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2734     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2735     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2736         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2737          DS.getRepAsType().get()->isStructureType())) {
2738       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2739         << DS.getSourceRange();
2740       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2741     }
2742   }
2743 
2744   if (getLangOpts().CPlusPlus &&
2745       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2746     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2747       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2748           !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2749         Diag(Enum->getLocation(), diag::ext_no_declarators)
2750           << DS.getSourceRange();
2751         emittedWarning = true;
2752       }
2753 
2754   // Skip all the checks below if we have a type error.
2755   if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2756 
2757   if (!DS.isMissingDeclaratorOk()) {
2758     // Warn about typedefs of enums without names, since this is an
2759     // extension in both Microsoft and GNU.
2760     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2761         Tag && isa<EnumDecl>(Tag)) {
2762       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2763         << DS.getSourceRange();
2764       return Tag;
2765     }
2766 
2767     Diag(DS.getLocStart(), diag::ext_no_declarators)
2768       << DS.getSourceRange();
2769     emittedWarning = true;
2770   }
2771 
2772   // We're going to complain about a bunch of spurious specifiers;
2773   // only do this if we're declaring a tag, because otherwise we
2774   // should be getting diag::ext_no_declarators.
2775   if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2776     return TagD;
2777 
2778   // Note that a linkage-specification sets a storage class, but
2779   // 'extern "C" struct foo;' is actually valid and not theoretically
2780   // useless.
2781   if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2782     if (!DS.isExternInLinkageSpec())
2783       Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2784         << DeclSpec::getSpecifierName(scs);
2785 
2786   if (DS.isThreadSpecified())
2787     Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2788   if (DS.getTypeQualifiers()) {
2789     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2790       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2791     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2792       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2793     // Restrict is covered above.
2794   }
2795   if (DS.isInlineSpecified())
2796     Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2797   if (DS.isVirtualSpecified())
2798     Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2799   if (DS.isExplicitSpecified())
2800     Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2801 
2802   if (DS.isModulePrivateSpecified() &&
2803       Tag && Tag->getDeclContext()->isFunctionOrMethod())
2804     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2805       << Tag->getTagKind()
2806       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2807 
2808   // Warn about ignored type attributes, for example:
2809   // __attribute__((aligned)) struct A;
2810   // Attributes should be placed after tag to apply to type declaration.
2811   if (!DS.getAttributes().empty()) {
2812     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2813     if (TypeSpecType == DeclSpec::TST_class ||
2814         TypeSpecType == DeclSpec::TST_struct ||
2815         TypeSpecType == DeclSpec::TST_interface ||
2816         TypeSpecType == DeclSpec::TST_union ||
2817         TypeSpecType == DeclSpec::TST_enum) {
2818       AttributeList* attrs = DS.getAttributes().getList();
2819       while (attrs) {
2820         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
2821         << attrs->getName()
2822         << (TypeSpecType == DeclSpec::TST_class ? 0 :
2823             TypeSpecType == DeclSpec::TST_struct ? 1 :
2824             TypeSpecType == DeclSpec::TST_union ? 2 :
2825             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
2826         attrs = attrs->getNext();
2827       }
2828     }
2829   }
2830 
2831   ActOnDocumentableDecl(TagD);
2832 
2833   return TagD;
2834 }
2835 
2836 /// We are trying to inject an anonymous member into the given scope;
2837 /// check if there's an existing declaration that can't be overloaded.
2838 ///
2839 /// \return true if this is a forbidden redeclaration
2840 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2841                                          Scope *S,
2842                                          DeclContext *Owner,
2843                                          DeclarationName Name,
2844                                          SourceLocation NameLoc,
2845                                          unsigned diagnostic) {
2846   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2847                  Sema::ForRedeclaration);
2848   if (!SemaRef.LookupName(R, S)) return false;
2849 
2850   if (R.getAsSingle<TagDecl>())
2851     return false;
2852 
2853   // Pick a representative declaration.
2854   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2855   assert(PrevDecl && "Expected a non-null Decl");
2856 
2857   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2858     return false;
2859 
2860   SemaRef.Diag(NameLoc, diagnostic) << Name;
2861   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2862 
2863   return true;
2864 }
2865 
2866 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
2867 /// anonymous struct or union AnonRecord into the owning context Owner
2868 /// and scope S. This routine will be invoked just after we realize
2869 /// that an unnamed union or struct is actually an anonymous union or
2870 /// struct, e.g.,
2871 ///
2872 /// @code
2873 /// union {
2874 ///   int i;
2875 ///   float f;
2876 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2877 ///    // f into the surrounding scope.x
2878 /// @endcode
2879 ///
2880 /// This routine is recursive, injecting the names of nested anonymous
2881 /// structs/unions into the owning context and scope as well.
2882 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2883                                                 DeclContext *Owner,
2884                                                 RecordDecl *AnonRecord,
2885                                                 AccessSpecifier AS,
2886                               SmallVector<NamedDecl*, 2> &Chaining,
2887                                                       bool MSAnonStruct) {
2888   unsigned diagKind
2889     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2890                             : diag::err_anonymous_struct_member_redecl;
2891 
2892   bool Invalid = false;
2893 
2894   // Look every FieldDecl and IndirectFieldDecl with a name.
2895   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2896                                DEnd = AnonRecord->decls_end();
2897        D != DEnd; ++D) {
2898     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2899         cast<NamedDecl>(*D)->getDeclName()) {
2900       ValueDecl *VD = cast<ValueDecl>(*D);
2901       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2902                                        VD->getLocation(), diagKind)) {
2903         // C++ [class.union]p2:
2904         //   The names of the members of an anonymous union shall be
2905         //   distinct from the names of any other entity in the
2906         //   scope in which the anonymous union is declared.
2907         Invalid = true;
2908       } else {
2909         // C++ [class.union]p2:
2910         //   For the purpose of name lookup, after the anonymous union
2911         //   definition, the members of the anonymous union are
2912         //   considered to have been defined in the scope in which the
2913         //   anonymous union is declared.
2914         unsigned OldChainingSize = Chaining.size();
2915         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2916           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2917                PE = IF->chain_end(); PI != PE; ++PI)
2918             Chaining.push_back(*PI);
2919         else
2920           Chaining.push_back(VD);
2921 
2922         assert(Chaining.size() >= 2);
2923         NamedDecl **NamedChain =
2924           new (SemaRef.Context)NamedDecl*[Chaining.size()];
2925         for (unsigned i = 0; i < Chaining.size(); i++)
2926           NamedChain[i] = Chaining[i];
2927 
2928         IndirectFieldDecl* IndirectField =
2929           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2930                                     VD->getIdentifier(), VD->getType(),
2931                                     NamedChain, Chaining.size());
2932 
2933         IndirectField->setAccess(AS);
2934         IndirectField->setImplicit();
2935         SemaRef.PushOnScopeChains(IndirectField, S);
2936 
2937         // That includes picking up the appropriate access specifier.
2938         if (AS != AS_none) IndirectField->setAccess(AS);
2939 
2940         Chaining.resize(OldChainingSize);
2941       }
2942     }
2943   }
2944 
2945   return Invalid;
2946 }
2947 
2948 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2949 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
2950 /// illegal input values are mapped to SC_None.
2951 static StorageClass
2952 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2953   switch (StorageClassSpec) {
2954   case DeclSpec::SCS_unspecified:    return SC_None;
2955   case DeclSpec::SCS_extern:         return SC_Extern;
2956   case DeclSpec::SCS_static:         return SC_Static;
2957   case DeclSpec::SCS_auto:           return SC_Auto;
2958   case DeclSpec::SCS_register:       return SC_Register;
2959   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2960     // Illegal SCSs map to None: error reporting is up to the caller.
2961   case DeclSpec::SCS_mutable:        // Fall through.
2962   case DeclSpec::SCS_typedef:        return SC_None;
2963   }
2964   llvm_unreachable("unknown storage class specifier");
2965 }
2966 
2967 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2968 /// a StorageClass. Any error reporting is up to the caller:
2969 /// illegal input values are mapped to SC_None.
2970 static StorageClass
2971 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2972   switch (StorageClassSpec) {
2973   case DeclSpec::SCS_unspecified:    return SC_None;
2974   case DeclSpec::SCS_extern:         return SC_Extern;
2975   case DeclSpec::SCS_static:         return SC_Static;
2976   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2977     // Illegal SCSs map to None: error reporting is up to the caller.
2978   case DeclSpec::SCS_auto:           // Fall through.
2979   case DeclSpec::SCS_mutable:        // Fall through.
2980   case DeclSpec::SCS_register:       // Fall through.
2981   case DeclSpec::SCS_typedef:        return SC_None;
2982   }
2983   llvm_unreachable("unknown storage class specifier");
2984 }
2985 
2986 /// BuildAnonymousStructOrUnion - Handle the declaration of an
2987 /// anonymous structure or union. Anonymous unions are a C++ feature
2988 /// (C++ [class.union]) and a C11 feature; anonymous structures
2989 /// are a C11 feature and GNU C++ extension.
2990 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2991                                              AccessSpecifier AS,
2992                                              RecordDecl *Record) {
2993   DeclContext *Owner = Record->getDeclContext();
2994 
2995   // Diagnose whether this anonymous struct/union is an extension.
2996   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2997     Diag(Record->getLocation(), diag::ext_anonymous_union);
2998   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2999     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3000   else if (!Record->isUnion() && !getLangOpts().C11)
3001     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3002 
3003   // C and C++ require different kinds of checks for anonymous
3004   // structs/unions.
3005   bool Invalid = false;
3006   if (getLangOpts().CPlusPlus) {
3007     const char* PrevSpec = 0;
3008     unsigned DiagID;
3009     if (Record->isUnion()) {
3010       // C++ [class.union]p6:
3011       //   Anonymous unions declared in a named namespace or in the
3012       //   global namespace shall be declared static.
3013       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3014           (isa<TranslationUnitDecl>(Owner) ||
3015            (isa<NamespaceDecl>(Owner) &&
3016             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3017         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3018           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3019 
3020         // Recover by adding 'static'.
3021         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3022                                PrevSpec, DiagID);
3023       }
3024       // C++ [class.union]p6:
3025       //   A storage class is not allowed in a declaration of an
3026       //   anonymous union in a class scope.
3027       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3028                isa<RecordDecl>(Owner)) {
3029         Diag(DS.getStorageClassSpecLoc(),
3030              diag::err_anonymous_union_with_storage_spec)
3031           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3032 
3033         // Recover by removing the storage specifier.
3034         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3035                                SourceLocation(),
3036                                PrevSpec, DiagID);
3037       }
3038     }
3039 
3040     // Ignore const/volatile/restrict qualifiers.
3041     if (DS.getTypeQualifiers()) {
3042       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3043         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3044           << Record->isUnion() << 0
3045           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3046       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3047         Diag(DS.getVolatileSpecLoc(),
3048              diag::ext_anonymous_struct_union_qualified)
3049           << Record->isUnion() << 1
3050           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3051       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3052         Diag(DS.getRestrictSpecLoc(),
3053              diag::ext_anonymous_struct_union_qualified)
3054           << Record->isUnion() << 2
3055           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3056 
3057       DS.ClearTypeQualifiers();
3058     }
3059 
3060     // C++ [class.union]p2:
3061     //   The member-specification of an anonymous union shall only
3062     //   define non-static data members. [Note: nested types and
3063     //   functions cannot be declared within an anonymous union. ]
3064     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3065                                  MemEnd = Record->decls_end();
3066          Mem != MemEnd; ++Mem) {
3067       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3068         // C++ [class.union]p3:
3069         //   An anonymous union shall not have private or protected
3070         //   members (clause 11).
3071         assert(FD->getAccess() != AS_none);
3072         if (FD->getAccess() != AS_public) {
3073           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3074             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3075           Invalid = true;
3076         }
3077 
3078         // C++ [class.union]p1
3079         //   An object of a class with a non-trivial constructor, a non-trivial
3080         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3081         //   assignment operator cannot be a member of a union, nor can an
3082         //   array of such objects.
3083         if (CheckNontrivialField(FD))
3084           Invalid = true;
3085       } else if ((*Mem)->isImplicit()) {
3086         // Any implicit members are fine.
3087       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3088         // This is a type that showed up in an
3089         // elaborated-type-specifier inside the anonymous struct or
3090         // union, but which actually declares a type outside of the
3091         // anonymous struct or union. It's okay.
3092       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3093         if (!MemRecord->isAnonymousStructOrUnion() &&
3094             MemRecord->getDeclName()) {
3095           // Visual C++ allows type definition in anonymous struct or union.
3096           if (getLangOpts().MicrosoftExt)
3097             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3098               << (int)Record->isUnion();
3099           else {
3100             // This is a nested type declaration.
3101             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3102               << (int)Record->isUnion();
3103             Invalid = true;
3104           }
3105         }
3106       } else if (isa<AccessSpecDecl>(*Mem)) {
3107         // Any access specifier is fine.
3108       } else {
3109         // We have something that isn't a non-static data
3110         // member. Complain about it.
3111         unsigned DK = diag::err_anonymous_record_bad_member;
3112         if (isa<TypeDecl>(*Mem))
3113           DK = diag::err_anonymous_record_with_type;
3114         else if (isa<FunctionDecl>(*Mem))
3115           DK = diag::err_anonymous_record_with_function;
3116         else if (isa<VarDecl>(*Mem))
3117           DK = diag::err_anonymous_record_with_static;
3118 
3119         // Visual C++ allows type definition in anonymous struct or union.
3120         if (getLangOpts().MicrosoftExt &&
3121             DK == diag::err_anonymous_record_with_type)
3122           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3123             << (int)Record->isUnion();
3124         else {
3125           Diag((*Mem)->getLocation(), DK)
3126               << (int)Record->isUnion();
3127           Invalid = true;
3128         }
3129       }
3130     }
3131   }
3132 
3133   if (!Record->isUnion() && !Owner->isRecord()) {
3134     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3135       << (int)getLangOpts().CPlusPlus;
3136     Invalid = true;
3137   }
3138 
3139   // Mock up a declarator.
3140   Declarator Dc(DS, Declarator::MemberContext);
3141   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3142   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3143 
3144   // Create a declaration for this anonymous struct/union.
3145   NamedDecl *Anon = 0;
3146   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3147     Anon = FieldDecl::Create(Context, OwningClass,
3148                              DS.getLocStart(),
3149                              Record->getLocation(),
3150                              /*IdentifierInfo=*/0,
3151                              Context.getTypeDeclType(Record),
3152                              TInfo,
3153                              /*BitWidth=*/0, /*Mutable=*/false,
3154                              /*InitStyle=*/ICIS_NoInit);
3155     Anon->setAccess(AS);
3156     if (getLangOpts().CPlusPlus)
3157       FieldCollector->Add(cast<FieldDecl>(Anon));
3158   } else {
3159     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3160     assert(SCSpec != DeclSpec::SCS_typedef &&
3161            "Parser allowed 'typedef' as storage class VarDecl.");
3162     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3163     if (SCSpec == DeclSpec::SCS_mutable) {
3164       // mutable can only appear on non-static class members, so it's always
3165       // an error here
3166       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3167       Invalid = true;
3168       SC = SC_None;
3169     }
3170     SCSpec = DS.getStorageClassSpecAsWritten();
3171     VarDecl::StorageClass SCAsWritten
3172       = StorageClassSpecToVarDeclStorageClass(SCSpec);
3173 
3174     Anon = VarDecl::Create(Context, Owner,
3175                            DS.getLocStart(),
3176                            Record->getLocation(), /*IdentifierInfo=*/0,
3177                            Context.getTypeDeclType(Record),
3178                            TInfo, SC, SCAsWritten);
3179 
3180     // Default-initialize the implicit variable. This initialization will be
3181     // trivial in almost all cases, except if a union member has an in-class
3182     // initializer:
3183     //   union { int n = 0; };
3184     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3185   }
3186   Anon->setImplicit();
3187 
3188   // Add the anonymous struct/union object to the current
3189   // context. We'll be referencing this object when we refer to one of
3190   // its members.
3191   Owner->addDecl(Anon);
3192 
3193   // Inject the members of the anonymous struct/union into the owning
3194   // context and into the identifier resolver chain for name lookup
3195   // purposes.
3196   SmallVector<NamedDecl*, 2> Chain;
3197   Chain.push_back(Anon);
3198 
3199   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3200                                           Chain, false))
3201     Invalid = true;
3202 
3203   // Mark this as an anonymous struct/union type. Note that we do not
3204   // do this until after we have already checked and injected the
3205   // members of this anonymous struct/union type, because otherwise
3206   // the members could be injected twice: once by DeclContext when it
3207   // builds its lookup table, and once by
3208   // InjectAnonymousStructOrUnionMembers.
3209   Record->setAnonymousStructOrUnion(true);
3210 
3211   if (Invalid)
3212     Anon->setInvalidDecl();
3213 
3214   return Anon;
3215 }
3216 
3217 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3218 /// Microsoft C anonymous structure.
3219 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3220 /// Example:
3221 ///
3222 /// struct A { int a; };
3223 /// struct B { struct A; int b; };
3224 ///
3225 /// void foo() {
3226 ///   B var;
3227 ///   var.a = 3;
3228 /// }
3229 ///
3230 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3231                                            RecordDecl *Record) {
3232 
3233   // If there is no Record, get the record via the typedef.
3234   if (!Record)
3235     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3236 
3237   // Mock up a declarator.
3238   Declarator Dc(DS, Declarator::TypeNameContext);
3239   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3240   assert(TInfo && "couldn't build declarator info for anonymous struct");
3241 
3242   // Create a declaration for this anonymous struct.
3243   NamedDecl* Anon = FieldDecl::Create(Context,
3244                              cast<RecordDecl>(CurContext),
3245                              DS.getLocStart(),
3246                              DS.getLocStart(),
3247                              /*IdentifierInfo=*/0,
3248                              Context.getTypeDeclType(Record),
3249                              TInfo,
3250                              /*BitWidth=*/0, /*Mutable=*/false,
3251                              /*InitStyle=*/ICIS_NoInit);
3252   Anon->setImplicit();
3253 
3254   // Add the anonymous struct object to the current context.
3255   CurContext->addDecl(Anon);
3256 
3257   // Inject the members of the anonymous struct into the current
3258   // context and into the identifier resolver chain for name lookup
3259   // purposes.
3260   SmallVector<NamedDecl*, 2> Chain;
3261   Chain.push_back(Anon);
3262 
3263   RecordDecl *RecordDef = Record->getDefinition();
3264   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3265                                                         RecordDef, AS_none,
3266                                                         Chain, true))
3267     Anon->setInvalidDecl();
3268 
3269   return Anon;
3270 }
3271 
3272 /// GetNameForDeclarator - Determine the full declaration name for the
3273 /// given Declarator.
3274 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3275   return GetNameFromUnqualifiedId(D.getName());
3276 }
3277 
3278 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3279 DeclarationNameInfo
3280 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3281   DeclarationNameInfo NameInfo;
3282   NameInfo.setLoc(Name.StartLocation);
3283 
3284   switch (Name.getKind()) {
3285 
3286   case UnqualifiedId::IK_ImplicitSelfParam:
3287   case UnqualifiedId::IK_Identifier:
3288     NameInfo.setName(Name.Identifier);
3289     NameInfo.setLoc(Name.StartLocation);
3290     return NameInfo;
3291 
3292   case UnqualifiedId::IK_OperatorFunctionId:
3293     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3294                                            Name.OperatorFunctionId.Operator));
3295     NameInfo.setLoc(Name.StartLocation);
3296     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3297       = Name.OperatorFunctionId.SymbolLocations[0];
3298     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3299       = Name.EndLocation.getRawEncoding();
3300     return NameInfo;
3301 
3302   case UnqualifiedId::IK_LiteralOperatorId:
3303     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3304                                                            Name.Identifier));
3305     NameInfo.setLoc(Name.StartLocation);
3306     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3307     return NameInfo;
3308 
3309   case UnqualifiedId::IK_ConversionFunctionId: {
3310     TypeSourceInfo *TInfo;
3311     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3312     if (Ty.isNull())
3313       return DeclarationNameInfo();
3314     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3315                                                Context.getCanonicalType(Ty)));
3316     NameInfo.setLoc(Name.StartLocation);
3317     NameInfo.setNamedTypeInfo(TInfo);
3318     return NameInfo;
3319   }
3320 
3321   case UnqualifiedId::IK_ConstructorName: {
3322     TypeSourceInfo *TInfo;
3323     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3324     if (Ty.isNull())
3325       return DeclarationNameInfo();
3326     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3327                                               Context.getCanonicalType(Ty)));
3328     NameInfo.setLoc(Name.StartLocation);
3329     NameInfo.setNamedTypeInfo(TInfo);
3330     return NameInfo;
3331   }
3332 
3333   case UnqualifiedId::IK_ConstructorTemplateId: {
3334     // In well-formed code, we can only have a constructor
3335     // template-id that refers to the current context, so go there
3336     // to find the actual type being constructed.
3337     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3338     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3339       return DeclarationNameInfo();
3340 
3341     // Determine the type of the class being constructed.
3342     QualType CurClassType = Context.getTypeDeclType(CurClass);
3343 
3344     // FIXME: Check two things: that the template-id names the same type as
3345     // CurClassType, and that the template-id does not occur when the name
3346     // was qualified.
3347 
3348     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3349                                     Context.getCanonicalType(CurClassType)));
3350     NameInfo.setLoc(Name.StartLocation);
3351     // FIXME: should we retrieve TypeSourceInfo?
3352     NameInfo.setNamedTypeInfo(0);
3353     return NameInfo;
3354   }
3355 
3356   case UnqualifiedId::IK_DestructorName: {
3357     TypeSourceInfo *TInfo;
3358     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3359     if (Ty.isNull())
3360       return DeclarationNameInfo();
3361     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3362                                               Context.getCanonicalType(Ty)));
3363     NameInfo.setLoc(Name.StartLocation);
3364     NameInfo.setNamedTypeInfo(TInfo);
3365     return NameInfo;
3366   }
3367 
3368   case UnqualifiedId::IK_TemplateId: {
3369     TemplateName TName = Name.TemplateId->Template.get();
3370     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3371     return Context.getNameForTemplate(TName, TNameLoc);
3372   }
3373 
3374   } // switch (Name.getKind())
3375 
3376   llvm_unreachable("Unknown name kind");
3377 }
3378 
3379 static QualType getCoreType(QualType Ty) {
3380   do {
3381     if (Ty->isPointerType() || Ty->isReferenceType())
3382       Ty = Ty->getPointeeType();
3383     else if (Ty->isArrayType())
3384       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3385     else
3386       return Ty.withoutLocalFastQualifiers();
3387   } while (true);
3388 }
3389 
3390 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3391 /// and Definition have "nearly" matching parameters. This heuristic is
3392 /// used to improve diagnostics in the case where an out-of-line function
3393 /// definition doesn't match any declaration within the class or namespace.
3394 /// Also sets Params to the list of indices to the parameters that differ
3395 /// between the declaration and the definition. If hasSimilarParameters
3396 /// returns true and Params is empty, then all of the parameters match.
3397 static bool hasSimilarParameters(ASTContext &Context,
3398                                      FunctionDecl *Declaration,
3399                                      FunctionDecl *Definition,
3400                                      llvm::SmallVectorImpl<unsigned> &Params) {
3401   Params.clear();
3402   if (Declaration->param_size() != Definition->param_size())
3403     return false;
3404   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3405     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3406     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3407 
3408     // The parameter types are identical
3409     if (Context.hasSameType(DefParamTy, DeclParamTy))
3410       continue;
3411 
3412     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3413     QualType DefParamBaseTy = getCoreType(DefParamTy);
3414     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3415     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3416 
3417     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3418         (DeclTyName && DeclTyName == DefTyName))
3419       Params.push_back(Idx);
3420     else  // The two parameters aren't even close
3421       return false;
3422   }
3423 
3424   return true;
3425 }
3426 
3427 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3428 /// declarator needs to be rebuilt in the current instantiation.
3429 /// Any bits of declarator which appear before the name are valid for
3430 /// consideration here.  That's specifically the type in the decl spec
3431 /// and the base type in any member-pointer chunks.
3432 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3433                                                     DeclarationName Name) {
3434   // The types we specifically need to rebuild are:
3435   //   - typenames, typeofs, and decltypes
3436   //   - types which will become injected class names
3437   // Of course, we also need to rebuild any type referencing such a
3438   // type.  It's safest to just say "dependent", but we call out a
3439   // few cases here.
3440 
3441   DeclSpec &DS = D.getMutableDeclSpec();
3442   switch (DS.getTypeSpecType()) {
3443   case DeclSpec::TST_typename:
3444   case DeclSpec::TST_typeofType:
3445   case DeclSpec::TST_underlyingType:
3446   case DeclSpec::TST_atomic: {
3447     // Grab the type from the parser.
3448     TypeSourceInfo *TSI = 0;
3449     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3450     if (T.isNull() || !T->isDependentType()) break;
3451 
3452     // Make sure there's a type source info.  This isn't really much
3453     // of a waste; most dependent types should have type source info
3454     // attached already.
3455     if (!TSI)
3456       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3457 
3458     // Rebuild the type in the current instantiation.
3459     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3460     if (!TSI) return true;
3461 
3462     // Store the new type back in the decl spec.
3463     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3464     DS.UpdateTypeRep(LocType);
3465     break;
3466   }
3467 
3468   case DeclSpec::TST_decltype:
3469   case DeclSpec::TST_typeofExpr: {
3470     Expr *E = DS.getRepAsExpr();
3471     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3472     if (Result.isInvalid()) return true;
3473     DS.UpdateExprRep(Result.get());
3474     break;
3475   }
3476 
3477   default:
3478     // Nothing to do for these decl specs.
3479     break;
3480   }
3481 
3482   // It doesn't matter what order we do this in.
3483   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3484     DeclaratorChunk &Chunk = D.getTypeObject(I);
3485 
3486     // The only type information in the declarator which can come
3487     // before the declaration name is the base type of a member
3488     // pointer.
3489     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3490       continue;
3491 
3492     // Rebuild the scope specifier in-place.
3493     CXXScopeSpec &SS = Chunk.Mem.Scope();
3494     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3495       return true;
3496   }
3497 
3498   return false;
3499 }
3500 
3501 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3502   D.setFunctionDefinitionKind(FDK_Declaration);
3503   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
3504 
3505   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3506       Dcl && Dcl->getDeclContext()->isFileContext())
3507     Dcl->setTopLevelDeclInObjCContainer();
3508 
3509   return Dcl;
3510 }
3511 
3512 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3513 ///   If T is the name of a class, then each of the following shall have a
3514 ///   name different from T:
3515 ///     - every static data member of class T;
3516 ///     - every member function of class T
3517 ///     - every member of class T that is itself a type;
3518 /// \returns true if the declaration name violates these rules.
3519 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3520                                    DeclarationNameInfo NameInfo) {
3521   DeclarationName Name = NameInfo.getName();
3522 
3523   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3524     if (Record->getIdentifier() && Record->getDeclName() == Name) {
3525       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3526       return true;
3527     }
3528 
3529   return false;
3530 }
3531 
3532 /// \brief Diagnose a declaration whose declarator-id has the given
3533 /// nested-name-specifier.
3534 ///
3535 /// \param SS The nested-name-specifier of the declarator-id.
3536 ///
3537 /// \param DC The declaration context to which the nested-name-specifier
3538 /// resolves.
3539 ///
3540 /// \param Name The name of the entity being declared.
3541 ///
3542 /// \param Loc The location of the name of the entity being declared.
3543 ///
3544 /// \returns true if we cannot safely recover from this error, false otherwise.
3545 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3546                                         DeclarationName Name,
3547                                       SourceLocation Loc) {
3548   DeclContext *Cur = CurContext;
3549   while (isa<LinkageSpecDecl>(Cur))
3550     Cur = Cur->getParent();
3551 
3552   // C++ [dcl.meaning]p1:
3553   //   A declarator-id shall not be qualified except for the definition
3554   //   of a member function (9.3) or static data member (9.4) outside of
3555   //   its class, the definition or explicit instantiation of a function
3556   //   or variable member of a namespace outside of its namespace, or the
3557   //   definition of an explicit specialization outside of its namespace,
3558   //   or the declaration of a friend function that is a member of
3559   //   another class or namespace (11.3). [...]
3560 
3561   // The user provided a superfluous scope specifier that refers back to the
3562   // class or namespaces in which the entity is already declared.
3563   //
3564   // class X {
3565   //   void X::f();
3566   // };
3567   if (Cur->Equals(DC)) {
3568     Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3569                                    : diag::err_member_extra_qualification)
3570       << Name << FixItHint::CreateRemoval(SS.getRange());
3571     SS.clear();
3572     return false;
3573   }
3574 
3575   // Check whether the qualifying scope encloses the scope of the original
3576   // declaration.
3577   if (!Cur->Encloses(DC)) {
3578     if (Cur->isRecord())
3579       Diag(Loc, diag::err_member_qualification)
3580         << Name << SS.getRange();
3581     else if (isa<TranslationUnitDecl>(DC))
3582       Diag(Loc, diag::err_invalid_declarator_global_scope)
3583         << Name << SS.getRange();
3584     else if (isa<FunctionDecl>(Cur))
3585       Diag(Loc, diag::err_invalid_declarator_in_function)
3586         << Name << SS.getRange();
3587     else
3588       Diag(Loc, diag::err_invalid_declarator_scope)
3589       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3590 
3591     return true;
3592   }
3593 
3594   if (Cur->isRecord()) {
3595     // Cannot qualify members within a class.
3596     Diag(Loc, diag::err_member_qualification)
3597       << Name << SS.getRange();
3598     SS.clear();
3599 
3600     // C++ constructors and destructors with incorrect scopes can break
3601     // our AST invariants by having the wrong underlying types. If
3602     // that's the case, then drop this declaration entirely.
3603     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3604          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3605         !Context.hasSameType(Name.getCXXNameType(),
3606                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3607       return true;
3608 
3609     return false;
3610   }
3611 
3612   // C++11 [dcl.meaning]p1:
3613   //   [...] "The nested-name-specifier of the qualified declarator-id shall
3614   //   not begin with a decltype-specifer"
3615   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3616   while (SpecLoc.getPrefix())
3617     SpecLoc = SpecLoc.getPrefix();
3618   if (dyn_cast_or_null<DecltypeType>(
3619         SpecLoc.getNestedNameSpecifier()->getAsType()))
3620     Diag(Loc, diag::err_decltype_in_declarator)
3621       << SpecLoc.getTypeLoc().getSourceRange();
3622 
3623   return false;
3624 }
3625 
3626 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3627                              MultiTemplateParamsArg TemplateParamLists) {
3628   // TODO: consider using NameInfo for diagnostic.
3629   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3630   DeclarationName Name = NameInfo.getName();
3631 
3632   // All of these full declarators require an identifier.  If it doesn't have
3633   // one, the ParsedFreeStandingDeclSpec action should be used.
3634   if (!Name) {
3635     if (!D.isInvalidType())  // Reject this if we think it is valid.
3636       Diag(D.getDeclSpec().getLocStart(),
3637            diag::err_declarator_need_ident)
3638         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3639     return 0;
3640   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3641     return 0;
3642 
3643   // The scope passed in may not be a decl scope.  Zip up the scope tree until
3644   // we find one that is.
3645   while ((S->getFlags() & Scope::DeclScope) == 0 ||
3646          (S->getFlags() & Scope::TemplateParamScope) != 0)
3647     S = S->getParent();
3648 
3649   DeclContext *DC = CurContext;
3650   if (D.getCXXScopeSpec().isInvalid())
3651     D.setInvalidType();
3652   else if (D.getCXXScopeSpec().isSet()) {
3653     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3654                                         UPPC_DeclarationQualifier))
3655       return 0;
3656 
3657     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3658     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3659     if (!DC) {
3660       // If we could not compute the declaration context, it's because the
3661       // declaration context is dependent but does not refer to a class,
3662       // class template, or class template partial specialization. Complain
3663       // and return early, to avoid the coming semantic disaster.
3664       Diag(D.getIdentifierLoc(),
3665            diag::err_template_qualified_declarator_no_match)
3666         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3667         << D.getCXXScopeSpec().getRange();
3668       return 0;
3669     }
3670     bool IsDependentContext = DC->isDependentContext();
3671 
3672     if (!IsDependentContext &&
3673         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3674       return 0;
3675 
3676     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3677       Diag(D.getIdentifierLoc(),
3678            diag::err_member_def_undefined_record)
3679         << Name << DC << D.getCXXScopeSpec().getRange();
3680       D.setInvalidType();
3681     } else if (!D.getDeclSpec().isFriendSpecified()) {
3682       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3683                                       Name, D.getIdentifierLoc())) {
3684         if (DC->isRecord())
3685           return 0;
3686 
3687         D.setInvalidType();
3688       }
3689     }
3690 
3691     // Check whether we need to rebuild the type of the given
3692     // declaration in the current instantiation.
3693     if (EnteringContext && IsDependentContext &&
3694         TemplateParamLists.size() != 0) {
3695       ContextRAII SavedContext(*this, DC);
3696       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3697         D.setInvalidType();
3698     }
3699   }
3700 
3701   if (DiagnoseClassNameShadow(DC, NameInfo))
3702     // If this is a typedef, we'll end up spewing multiple diagnostics.
3703     // Just return early; it's safer.
3704     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3705       return 0;
3706 
3707   NamedDecl *New;
3708 
3709   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3710   QualType R = TInfo->getType();
3711 
3712   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3713                                       UPPC_DeclarationType))
3714     D.setInvalidType();
3715 
3716   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3717                         ForRedeclaration);
3718 
3719   // See if this is a redefinition of a variable in the same scope.
3720   if (!D.getCXXScopeSpec().isSet()) {
3721     bool IsLinkageLookup = false;
3722 
3723     // If the declaration we're planning to build will be a function
3724     // or object with linkage, then look for another declaration with
3725     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3726     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3727       /* Do nothing*/;
3728     else if (R->isFunctionType()) {
3729       if (CurContext->isFunctionOrMethod() ||
3730           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3731         IsLinkageLookup = true;
3732     } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3733       IsLinkageLookup = true;
3734     else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3735              D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3736       IsLinkageLookup = true;
3737 
3738     if (IsLinkageLookup)
3739       Previous.clear(LookupRedeclarationWithLinkage);
3740 
3741     LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3742   } else { // Something like "int foo::x;"
3743     LookupQualifiedName(Previous, DC);
3744 
3745     // C++ [dcl.meaning]p1:
3746     //   When the declarator-id is qualified, the declaration shall refer to a
3747     //  previously declared member of the class or namespace to which the
3748     //  qualifier refers (or, in the case of a namespace, of an element of the
3749     //  inline namespace set of that namespace (7.3.1)) or to a specialization
3750     //  thereof; [...]
3751     //
3752     // Note that we already checked the context above, and that we do not have
3753     // enough information to make sure that Previous contains the declaration
3754     // we want to match. For example, given:
3755     //
3756     //   class X {
3757     //     void f();
3758     //     void f(float);
3759     //   };
3760     //
3761     //   void X::f(int) { } // ill-formed
3762     //
3763     // In this case, Previous will point to the overload set
3764     // containing the two f's declared in X, but neither of them
3765     // matches.
3766 
3767     // C++ [dcl.meaning]p1:
3768     //   [...] the member shall not merely have been introduced by a
3769     //   using-declaration in the scope of the class or namespace nominated by
3770     //   the nested-name-specifier of the declarator-id.
3771     RemoveUsingDecls(Previous);
3772   }
3773 
3774   if (Previous.isSingleResult() &&
3775       Previous.getFoundDecl()->isTemplateParameter()) {
3776     // Maybe we will complain about the shadowed template parameter.
3777     if (!D.isInvalidType())
3778       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3779                                       Previous.getFoundDecl());
3780 
3781     // Just pretend that we didn't see the previous declaration.
3782     Previous.clear();
3783   }
3784 
3785   // In C++, the previous declaration we find might be a tag type
3786   // (class or enum). In this case, the new declaration will hide the
3787   // tag type. Note that this does does not apply if we're declaring a
3788   // typedef (C++ [dcl.typedef]p4).
3789   if (Previous.isSingleTagDecl() &&
3790       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3791     Previous.clear();
3792 
3793   bool AddToScope = true;
3794   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3795     if (TemplateParamLists.size()) {
3796       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3797       return 0;
3798     }
3799 
3800     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3801   } else if (R->isFunctionType()) {
3802     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3803                                   TemplateParamLists,
3804                                   AddToScope);
3805   } else {
3806     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3807                                   TemplateParamLists);
3808   }
3809 
3810   if (New == 0)
3811     return 0;
3812 
3813   // If this has an identifier and is not an invalid redeclaration or
3814   // function template specialization, add it to the scope stack.
3815   if (New->getDeclName() && AddToScope &&
3816        !(D.isRedeclaration() && New->isInvalidDecl()))
3817     PushOnScopeChains(New, S);
3818 
3819   return New;
3820 }
3821 
3822 /// Helper method to turn variable array types into constant array
3823 /// types in certain situations which would otherwise be errors (for
3824 /// GCC compatibility).
3825 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3826                                                     ASTContext &Context,
3827                                                     bool &SizeIsNegative,
3828                                                     llvm::APSInt &Oversized) {
3829   // This method tries to turn a variable array into a constant
3830   // array even when the size isn't an ICE.  This is necessary
3831   // for compatibility with code that depends on gcc's buggy
3832   // constant expression folding, like struct {char x[(int)(char*)2];}
3833   SizeIsNegative = false;
3834   Oversized = 0;
3835 
3836   if (T->isDependentType())
3837     return QualType();
3838 
3839   QualifierCollector Qs;
3840   const Type *Ty = Qs.strip(T);
3841 
3842   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3843     QualType Pointee = PTy->getPointeeType();
3844     QualType FixedType =
3845         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3846                                             Oversized);
3847     if (FixedType.isNull()) return FixedType;
3848     FixedType = Context.getPointerType(FixedType);
3849     return Qs.apply(Context, FixedType);
3850   }
3851   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3852     QualType Inner = PTy->getInnerType();
3853     QualType FixedType =
3854         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3855                                             Oversized);
3856     if (FixedType.isNull()) return FixedType;
3857     FixedType = Context.getParenType(FixedType);
3858     return Qs.apply(Context, FixedType);
3859   }
3860 
3861   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3862   if (!VLATy)
3863     return QualType();
3864   // FIXME: We should probably handle this case
3865   if (VLATy->getElementType()->isVariablyModifiedType())
3866     return QualType();
3867 
3868   llvm::APSInt Res;
3869   if (!VLATy->getSizeExpr() ||
3870       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3871     return QualType();
3872 
3873   // Check whether the array size is negative.
3874   if (Res.isSigned() && Res.isNegative()) {
3875     SizeIsNegative = true;
3876     return QualType();
3877   }
3878 
3879   // Check whether the array is too large to be addressed.
3880   unsigned ActiveSizeBits
3881     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3882                                               Res);
3883   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3884     Oversized = Res;
3885     return QualType();
3886   }
3887 
3888   return Context.getConstantArrayType(VLATy->getElementType(),
3889                                       Res, ArrayType::Normal, 0);
3890 }
3891 
3892 static void
3893 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
3894   if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
3895     PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
3896     FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
3897                                       DstPTL->getPointeeLoc());
3898     DstPTL->setStarLoc(SrcPTL->getStarLoc());
3899     return;
3900   }
3901   if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
3902     ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
3903     FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
3904                                       DstPTL->getInnerLoc());
3905     DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
3906     DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
3907     return;
3908   }
3909   ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
3910   ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
3911   TypeLoc SrcElemTL = SrcATL->getElementLoc();
3912   TypeLoc DstElemTL = DstATL->getElementLoc();
3913   DstElemTL.initializeFullCopy(SrcElemTL);
3914   DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
3915   DstATL->setSizeExpr(SrcATL->getSizeExpr());
3916   DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
3917 }
3918 
3919 /// Helper method to turn variable array types into constant array
3920 /// types in certain situations which would otherwise be errors (for
3921 /// GCC compatibility).
3922 static TypeSourceInfo*
3923 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
3924                                               ASTContext &Context,
3925                                               bool &SizeIsNegative,
3926                                               llvm::APSInt &Oversized) {
3927   QualType FixedTy
3928     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
3929                                           SizeIsNegative, Oversized);
3930   if (FixedTy.isNull())
3931     return 0;
3932   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
3933   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
3934                                     FixedTInfo->getTypeLoc());
3935   return FixedTInfo;
3936 }
3937 
3938 /// \brief Register the given locally-scoped external C declaration so
3939 /// that it can be found later for redeclarations
3940 void
3941 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3942                                        const LookupResult &Previous,
3943                                        Scope *S) {
3944   assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3945          "Decl is not a locally-scoped decl!");
3946   // Note that we have a locally-scoped external with this name.
3947   LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3948 
3949   if (!Previous.isSingleResult())
3950     return;
3951 
3952   NamedDecl *PrevDecl = Previous.getFoundDecl();
3953 
3954   // If there was a previous declaration of this variable, it may be
3955   // in our identifier chain. Update the identifier chain with the new
3956   // declaration.
3957   if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3958     // The previous declaration was found on the identifer resolver
3959     // chain, so remove it from its scope.
3960 
3961     if (S->isDeclScope(PrevDecl)) {
3962       // Special case for redeclarations in the SAME scope.
3963       // Because this declaration is going to be added to the identifier chain
3964       // later, we should temporarily take it OFF the chain.
3965       IdResolver.RemoveDecl(ND);
3966 
3967     } else {
3968       // Find the scope for the original declaration.
3969       while (S && !S->isDeclScope(PrevDecl))
3970         S = S->getParent();
3971     }
3972 
3973     if (S)
3974       S->RemoveDecl(PrevDecl);
3975   }
3976 }
3977 
3978 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3979 Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3980   if (ExternalSource) {
3981     // Load locally-scoped external decls from the external source.
3982     SmallVector<NamedDecl *, 4> Decls;
3983     ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3984     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3985       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3986         = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3987       if (Pos == LocallyScopedExternalDecls.end())
3988         LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3989     }
3990   }
3991 
3992   return LocallyScopedExternalDecls.find(Name);
3993 }
3994 
3995 /// \brief Diagnose function specifiers on a declaration of an identifier that
3996 /// does not identify a function.
3997 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3998   // FIXME: We should probably indicate the identifier in question to avoid
3999   // confusion for constructs like "inline int a(), b;"
4000   if (D.getDeclSpec().isInlineSpecified())
4001     Diag(D.getDeclSpec().getInlineSpecLoc(),
4002          diag::err_inline_non_function);
4003 
4004   if (D.getDeclSpec().isVirtualSpecified())
4005     Diag(D.getDeclSpec().getVirtualSpecLoc(),
4006          diag::err_virtual_non_function);
4007 
4008   if (D.getDeclSpec().isExplicitSpecified())
4009     Diag(D.getDeclSpec().getExplicitSpecLoc(),
4010          diag::err_explicit_non_function);
4011 }
4012 
4013 NamedDecl*
4014 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4015                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4016   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4017   if (D.getCXXScopeSpec().isSet()) {
4018     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4019       << D.getCXXScopeSpec().getRange();
4020     D.setInvalidType();
4021     // Pretend we didn't see the scope specifier.
4022     DC = CurContext;
4023     Previous.clear();
4024   }
4025 
4026   if (getLangOpts().CPlusPlus) {
4027     // Check that there are no default arguments (C++ only).
4028     CheckExtraCXXDefaultArguments(D);
4029   }
4030 
4031   DiagnoseFunctionSpecifiers(D);
4032 
4033   if (D.getDeclSpec().isThreadSpecified())
4034     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4035   if (D.getDeclSpec().isConstexprSpecified())
4036     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4037       << 1;
4038 
4039   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4040     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4041       << D.getName().getSourceRange();
4042     return 0;
4043   }
4044 
4045   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4046   if (!NewTD) return 0;
4047 
4048   // Handle attributes prior to checking for duplicates in MergeVarDecl
4049   ProcessDeclAttributes(S, NewTD, D);
4050 
4051   CheckTypedefForVariablyModifiedType(S, NewTD);
4052 
4053   bool Redeclaration = D.isRedeclaration();
4054   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4055   D.setRedeclaration(Redeclaration);
4056   return ND;
4057 }
4058 
4059 void
4060 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4061   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4062   // then it shall have block scope.
4063   // Note that variably modified types must be fixed before merging the decl so
4064   // that redeclarations will match.
4065   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4066   QualType T = TInfo->getType();
4067   if (T->isVariablyModifiedType()) {
4068     getCurFunction()->setHasBranchProtectedScope();
4069 
4070     if (S->getFnParent() == 0) {
4071       bool SizeIsNegative;
4072       llvm::APSInt Oversized;
4073       TypeSourceInfo *FixedTInfo =
4074         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4075                                                       SizeIsNegative,
4076                                                       Oversized);
4077       if (FixedTInfo) {
4078         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4079         NewTD->setTypeSourceInfo(FixedTInfo);
4080       } else {
4081         if (SizeIsNegative)
4082           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4083         else if (T->isVariableArrayType())
4084           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4085         else if (Oversized.getBoolValue())
4086           Diag(NewTD->getLocation(), diag::err_array_too_large)
4087             << Oversized.toString(10);
4088         else
4089           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4090         NewTD->setInvalidDecl();
4091       }
4092     }
4093   }
4094 }
4095 
4096 
4097 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4098 /// declares a typedef-name, either using the 'typedef' type specifier or via
4099 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4100 NamedDecl*
4101 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4102                            LookupResult &Previous, bool &Redeclaration) {
4103   // Merge the decl with the existing one if appropriate. If the decl is
4104   // in an outer scope, it isn't the same thing.
4105   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4106                        /*ExplicitInstantiationOrSpecialization=*/false);
4107   if (!Previous.empty()) {
4108     Redeclaration = true;
4109     MergeTypedefNameDecl(NewTD, Previous);
4110   }
4111 
4112   // If this is the C FILE type, notify the AST context.
4113   if (IdentifierInfo *II = NewTD->getIdentifier())
4114     if (!NewTD->isInvalidDecl() &&
4115         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4116       if (II->isStr("FILE"))
4117         Context.setFILEDecl(NewTD);
4118       else if (II->isStr("jmp_buf"))
4119         Context.setjmp_bufDecl(NewTD);
4120       else if (II->isStr("sigjmp_buf"))
4121         Context.setsigjmp_bufDecl(NewTD);
4122       else if (II->isStr("ucontext_t"))
4123         Context.setucontext_tDecl(NewTD);
4124     }
4125 
4126   return NewTD;
4127 }
4128 
4129 /// \brief Determines whether the given declaration is an out-of-scope
4130 /// previous declaration.
4131 ///
4132 /// This routine should be invoked when name lookup has found a
4133 /// previous declaration (PrevDecl) that is not in the scope where a
4134 /// new declaration by the same name is being introduced. If the new
4135 /// declaration occurs in a local scope, previous declarations with
4136 /// linkage may still be considered previous declarations (C99
4137 /// 6.2.2p4-5, C++ [basic.link]p6).
4138 ///
4139 /// \param PrevDecl the previous declaration found by name
4140 /// lookup
4141 ///
4142 /// \param DC the context in which the new declaration is being
4143 /// declared.
4144 ///
4145 /// \returns true if PrevDecl is an out-of-scope previous declaration
4146 /// for a new delcaration with the same name.
4147 static bool
4148 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4149                                 ASTContext &Context) {
4150   if (!PrevDecl)
4151     return false;
4152 
4153   if (!PrevDecl->hasLinkage())
4154     return false;
4155 
4156   if (Context.getLangOpts().CPlusPlus) {
4157     // C++ [basic.link]p6:
4158     //   If there is a visible declaration of an entity with linkage
4159     //   having the same name and type, ignoring entities declared
4160     //   outside the innermost enclosing namespace scope, the block
4161     //   scope declaration declares that same entity and receives the
4162     //   linkage of the previous declaration.
4163     DeclContext *OuterContext = DC->getRedeclContext();
4164     if (!OuterContext->isFunctionOrMethod())
4165       // This rule only applies to block-scope declarations.
4166       return false;
4167 
4168     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4169     if (PrevOuterContext->isRecord())
4170       // We found a member function: ignore it.
4171       return false;
4172 
4173     // Find the innermost enclosing namespace for the new and
4174     // previous declarations.
4175     OuterContext = OuterContext->getEnclosingNamespaceContext();
4176     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4177 
4178     // The previous declaration is in a different namespace, so it
4179     // isn't the same function.
4180     if (!OuterContext->Equals(PrevOuterContext))
4181       return false;
4182   }
4183 
4184   return true;
4185 }
4186 
4187 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4188   CXXScopeSpec &SS = D.getCXXScopeSpec();
4189   if (!SS.isSet()) return;
4190   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4191 }
4192 
4193 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4194   QualType type = decl->getType();
4195   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4196   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4197     // Various kinds of declaration aren't allowed to be __autoreleasing.
4198     unsigned kind = -1U;
4199     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4200       if (var->hasAttr<BlocksAttr>())
4201         kind = 0; // __block
4202       else if (!var->hasLocalStorage())
4203         kind = 1; // global
4204     } else if (isa<ObjCIvarDecl>(decl)) {
4205       kind = 3; // ivar
4206     } else if (isa<FieldDecl>(decl)) {
4207       kind = 2; // field
4208     }
4209 
4210     if (kind != -1U) {
4211       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4212         << kind;
4213     }
4214   } else if (lifetime == Qualifiers::OCL_None) {
4215     // Try to infer lifetime.
4216     if (!type->isObjCLifetimeType())
4217       return false;
4218 
4219     lifetime = type->getObjCARCImplicitLifetime();
4220     type = Context.getLifetimeQualifiedType(type, lifetime);
4221     decl->setType(type);
4222   }
4223 
4224   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4225     // Thread-local variables cannot have lifetime.
4226     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4227         var->isThreadSpecified()) {
4228       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4229         << var->getType();
4230       return true;
4231     }
4232   }
4233 
4234   return false;
4235 }
4236 
4237 NamedDecl*
4238 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4239                               TypeSourceInfo *TInfo, LookupResult &Previous,
4240                               MultiTemplateParamsArg TemplateParamLists) {
4241   QualType R = TInfo->getType();
4242   DeclarationName Name = GetNameForDeclarator(D).getName();
4243 
4244   // Check that there are no default arguments (C++ only).
4245   if (getLangOpts().CPlusPlus)
4246     CheckExtraCXXDefaultArguments(D);
4247 
4248   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4249   assert(SCSpec != DeclSpec::SCS_typedef &&
4250          "Parser allowed 'typedef' as storage class VarDecl.");
4251   VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
4252   if (SCSpec == DeclSpec::SCS_mutable) {
4253     // mutable can only appear on non-static class members, so it's always
4254     // an error here
4255     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4256     D.setInvalidType();
4257     SC = SC_None;
4258   }
4259   SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4260   VarDecl::StorageClass SCAsWritten
4261     = StorageClassSpecToVarDeclStorageClass(SCSpec);
4262 
4263   IdentifierInfo *II = Name.getAsIdentifierInfo();
4264   if (!II) {
4265     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4266       << Name;
4267     return 0;
4268   }
4269 
4270   DiagnoseFunctionSpecifiers(D);
4271 
4272   if (!DC->isRecord() && S->getFnParent() == 0) {
4273     // C99 6.9p2: The storage-class specifiers auto and register shall not
4274     // appear in the declaration specifiers in an external declaration.
4275     if (SC == SC_Auto || SC == SC_Register) {
4276 
4277       // If this is a register variable with an asm label specified, then this
4278       // is a GNU extension.
4279       if (SC == SC_Register && D.getAsmLabel())
4280         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4281       else
4282         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4283       D.setInvalidType();
4284     }
4285   }
4286 
4287   if (getLangOpts().OpenCL) {
4288     // Set up the special work-group-local storage class for variables in the
4289     // OpenCL __local address space.
4290     if (R.getAddressSpace() == LangAS::opencl_local)
4291       SC = SC_OpenCLWorkGroupLocal;
4292   }
4293 
4294   bool isExplicitSpecialization = false;
4295   VarDecl *NewVD;
4296   if (!getLangOpts().CPlusPlus) {
4297     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4298                             D.getIdentifierLoc(), II,
4299                             R, TInfo, SC, SCAsWritten);
4300 
4301     if (D.isInvalidType())
4302       NewVD->setInvalidDecl();
4303   } else {
4304     if (DC->isRecord() && !CurContext->isRecord()) {
4305       // This is an out-of-line definition of a static data member.
4306       if (SC == SC_Static) {
4307         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4308              diag::err_static_out_of_line)
4309           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4310       } else if (SC == SC_None)
4311         SC = SC_Static;
4312     }
4313     if (SC == SC_Static && CurContext->isRecord()) {
4314       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4315         if (RD->isLocalClass())
4316           Diag(D.getIdentifierLoc(),
4317                diag::err_static_data_member_not_allowed_in_local_class)
4318             << Name << RD->getDeclName();
4319 
4320         // C++98 [class.union]p1: If a union contains a static data member,
4321         // the program is ill-formed. C++11 drops this restriction.
4322         if (RD->isUnion())
4323           Diag(D.getIdentifierLoc(),
4324                getLangOpts().CPlusPlus0x
4325                  ? diag::warn_cxx98_compat_static_data_member_in_union
4326                  : diag::ext_static_data_member_in_union) << Name;
4327         // We conservatively disallow static data members in anonymous structs.
4328         else if (!RD->getDeclName())
4329           Diag(D.getIdentifierLoc(),
4330                diag::err_static_data_member_not_allowed_in_anon_struct)
4331             << Name << RD->isUnion();
4332       }
4333     }
4334 
4335     // Match up the template parameter lists with the scope specifier, then
4336     // determine whether we have a template or a template specialization.
4337     isExplicitSpecialization = false;
4338     bool Invalid = false;
4339     if (TemplateParameterList *TemplateParams
4340         = MatchTemplateParametersToScopeSpecifier(
4341                                   D.getDeclSpec().getLocStart(),
4342                                                   D.getIdentifierLoc(),
4343                                                   D.getCXXScopeSpec(),
4344                                                   TemplateParamLists.data(),
4345                                                   TemplateParamLists.size(),
4346                                                   /*never a friend*/ false,
4347                                                   isExplicitSpecialization,
4348                                                   Invalid)) {
4349       if (TemplateParams->size() > 0) {
4350         // There is no such thing as a variable template.
4351         Diag(D.getIdentifierLoc(), diag::err_template_variable)
4352           << II
4353           << SourceRange(TemplateParams->getTemplateLoc(),
4354                          TemplateParams->getRAngleLoc());
4355         return 0;
4356       } else {
4357         // There is an extraneous 'template<>' for this variable. Complain
4358         // about it, but allow the declaration of the variable.
4359         Diag(TemplateParams->getTemplateLoc(),
4360              diag::err_template_variable_noparams)
4361           << II
4362           << SourceRange(TemplateParams->getTemplateLoc(),
4363                          TemplateParams->getRAngleLoc());
4364       }
4365     }
4366 
4367     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4368                             D.getIdentifierLoc(), II,
4369                             R, TInfo, SC, SCAsWritten);
4370 
4371     // If this decl has an auto type in need of deduction, make a note of the
4372     // Decl so we can diagnose uses of it in its own initializer.
4373     if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4374         R->getContainedAutoType())
4375       ParsingInitForAutoVars.insert(NewVD);
4376 
4377     if (D.isInvalidType() || Invalid)
4378       NewVD->setInvalidDecl();
4379 
4380     SetNestedNameSpecifier(NewVD, D);
4381 
4382     if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4383       NewVD->setTemplateParameterListsInfo(Context,
4384                                            TemplateParamLists.size(),
4385                                            TemplateParamLists.data());
4386     }
4387 
4388     if (D.getDeclSpec().isConstexprSpecified())
4389       NewVD->setConstexpr(true);
4390   }
4391 
4392   // Set the lexical context. If the declarator has a C++ scope specifier, the
4393   // lexical context will be different from the semantic context.
4394   NewVD->setLexicalDeclContext(CurContext);
4395 
4396   if (D.getDeclSpec().isThreadSpecified()) {
4397     if (NewVD->hasLocalStorage())
4398       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4399     else if (!Context.getTargetInfo().isTLSSupported())
4400       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4401     else
4402       NewVD->setThreadSpecified(true);
4403   }
4404 
4405   if (D.getDeclSpec().isModulePrivateSpecified()) {
4406     if (isExplicitSpecialization)
4407       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4408         << 2
4409         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4410     else if (NewVD->hasLocalStorage())
4411       Diag(NewVD->getLocation(), diag::err_module_private_local)
4412         << 0 << NewVD->getDeclName()
4413         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4414         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4415     else
4416       NewVD->setModulePrivate();
4417   }
4418 
4419   // Handle attributes prior to checking for duplicates in MergeVarDecl
4420   ProcessDeclAttributes(S, NewVD, D);
4421 
4422   if (getLangOpts().CUDA) {
4423     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4424     // storage [duration]."
4425     if (SC == SC_None && S->getFnParent() != 0 &&
4426        (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>()))
4427       NewVD->setStorageClass(SC_Static);
4428   }
4429 
4430   // In auto-retain/release, infer strong retension for variables of
4431   // retainable type.
4432   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4433     NewVD->setInvalidDecl();
4434 
4435   // Handle GNU asm-label extension (encoded as an attribute).
4436   if (Expr *E = (Expr*)D.getAsmLabel()) {
4437     // The parser guarantees this is a string.
4438     StringLiteral *SE = cast<StringLiteral>(E);
4439     StringRef Label = SE->getString();
4440     if (S->getFnParent() != 0) {
4441       switch (SC) {
4442       case SC_None:
4443       case SC_Auto:
4444         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4445         break;
4446       case SC_Register:
4447         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4448           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4449         break;
4450       case SC_Static:
4451       case SC_Extern:
4452       case SC_PrivateExtern:
4453       case SC_OpenCLWorkGroupLocal:
4454         break;
4455       }
4456     }
4457 
4458     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4459                                                 Context, Label));
4460   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4461     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4462       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4463     if (I != ExtnameUndeclaredIdentifiers.end()) {
4464       NewVD->addAttr(I->second);
4465       ExtnameUndeclaredIdentifiers.erase(I);
4466     }
4467   }
4468 
4469   // Diagnose shadowed variables before filtering for scope.
4470   if (!D.getCXXScopeSpec().isSet())
4471     CheckShadow(S, NewVD, Previous);
4472 
4473   // Don't consider existing declarations that are in a different
4474   // scope and are out-of-semantic-context declarations (if the new
4475   // declaration has linkage).
4476   FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4477                        isExplicitSpecialization);
4478 
4479   if (!getLangOpts().CPlusPlus) {
4480     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4481   } else {
4482     // Merge the decl with the existing one if appropriate.
4483     if (!Previous.empty()) {
4484       if (Previous.isSingleResult() &&
4485           isa<FieldDecl>(Previous.getFoundDecl()) &&
4486           D.getCXXScopeSpec().isSet()) {
4487         // The user tried to define a non-static data member
4488         // out-of-line (C++ [dcl.meaning]p1).
4489         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4490           << D.getCXXScopeSpec().getRange();
4491         Previous.clear();
4492         NewVD->setInvalidDecl();
4493       }
4494     } else if (D.getCXXScopeSpec().isSet()) {
4495       // No previous declaration in the qualifying scope.
4496       Diag(D.getIdentifierLoc(), diag::err_no_member)
4497         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4498         << D.getCXXScopeSpec().getRange();
4499       NewVD->setInvalidDecl();
4500     }
4501 
4502     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4503 
4504     // This is an explicit specialization of a static data member. Check it.
4505     if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4506         CheckMemberSpecialization(NewVD, Previous))
4507       NewVD->setInvalidDecl();
4508   }
4509 
4510   // If this is a locally-scoped extern C variable, update the map of
4511   // such variables.
4512   if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4513       !NewVD->isInvalidDecl())
4514     RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4515 
4516   // If there's a #pragma GCC visibility in scope, and this isn't a class
4517   // member, set the visibility of this variable.
4518   if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4519     AddPushedVisibilityAttribute(NewVD);
4520 
4521   MarkUnusedFileScopedDecl(NewVD);
4522 
4523   return NewVD;
4524 }
4525 
4526 /// \brief Diagnose variable or built-in function shadowing.  Implements
4527 /// -Wshadow.
4528 ///
4529 /// This method is called whenever a VarDecl is added to a "useful"
4530 /// scope.
4531 ///
4532 /// \param S the scope in which the shadowing name is being declared
4533 /// \param R the lookup of the name
4534 ///
4535 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4536   // Return if warning is ignored.
4537   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4538         DiagnosticsEngine::Ignored)
4539     return;
4540 
4541   // Don't diagnose declarations at file scope.
4542   if (D->hasGlobalStorage())
4543     return;
4544 
4545   DeclContext *NewDC = D->getDeclContext();
4546 
4547   // Only diagnose if we're shadowing an unambiguous field or variable.
4548   if (R.getResultKind() != LookupResult::Found)
4549     return;
4550 
4551   NamedDecl* ShadowedDecl = R.getFoundDecl();
4552   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4553     return;
4554 
4555   // Fields are not shadowed by variables in C++ static methods.
4556   if (isa<FieldDecl>(ShadowedDecl))
4557     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4558       if (MD->isStatic())
4559         return;
4560 
4561   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4562     if (shadowedVar->isExternC()) {
4563       // For shadowing external vars, make sure that we point to the global
4564       // declaration, not a locally scoped extern declaration.
4565       for (VarDecl::redecl_iterator
4566              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4567            I != E; ++I)
4568         if (I->isFileVarDecl()) {
4569           ShadowedDecl = *I;
4570           break;
4571         }
4572     }
4573 
4574   DeclContext *OldDC = ShadowedDecl->getDeclContext();
4575 
4576   // Only warn about certain kinds of shadowing for class members.
4577   if (NewDC && NewDC->isRecord()) {
4578     // In particular, don't warn about shadowing non-class members.
4579     if (!OldDC->isRecord())
4580       return;
4581 
4582     // TODO: should we warn about static data members shadowing
4583     // static data members from base classes?
4584 
4585     // TODO: don't diagnose for inaccessible shadowed members.
4586     // This is hard to do perfectly because we might friend the
4587     // shadowing context, but that's just a false negative.
4588   }
4589 
4590   // Determine what kind of declaration we're shadowing.
4591   unsigned Kind;
4592   if (isa<RecordDecl>(OldDC)) {
4593     if (isa<FieldDecl>(ShadowedDecl))
4594       Kind = 3; // field
4595     else
4596       Kind = 2; // static data member
4597   } else if (OldDC->isFileContext())
4598     Kind = 1; // global
4599   else
4600     Kind = 0; // local
4601 
4602   DeclarationName Name = R.getLookupName();
4603 
4604   // Emit warning and note.
4605   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4606   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4607 }
4608 
4609 /// \brief Check -Wshadow without the advantage of a previous lookup.
4610 void Sema::CheckShadow(Scope *S, VarDecl *D) {
4611   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4612         DiagnosticsEngine::Ignored)
4613     return;
4614 
4615   LookupResult R(*this, D->getDeclName(), D->getLocation(),
4616                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4617   LookupName(R, S);
4618   CheckShadow(S, D, R);
4619 }
4620 
4621 /// \brief Perform semantic checking on a newly-created variable
4622 /// declaration.
4623 ///
4624 /// This routine performs all of the type-checking required for a
4625 /// variable declaration once it has been built. It is used both to
4626 /// check variables after they have been parsed and their declarators
4627 /// have been translated into a declaration, and to check variables
4628 /// that have been instantiated from a template.
4629 ///
4630 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4631 ///
4632 /// Returns true if the variable declaration is a redeclaration.
4633 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4634                                     LookupResult &Previous) {
4635   // If the decl is already known invalid, don't check it.
4636   if (NewVD->isInvalidDecl())
4637     return false;
4638 
4639   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
4640   QualType T = TInfo->getType();
4641 
4642   if (T->isObjCObjectType()) {
4643     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4644       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4645     T = Context.getObjCObjectPointerType(T);
4646     NewVD->setType(T);
4647   }
4648 
4649   // Emit an error if an address space was applied to decl with local storage.
4650   // This includes arrays of objects with address space qualifiers, but not
4651   // automatic variables that point to other address spaces.
4652   // ISO/IEC TR 18037 S5.1.2
4653   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4654     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4655     NewVD->setInvalidDecl();
4656     return false;
4657   }
4658 
4659   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4660   // scope.
4661   if ((getLangOpts().OpenCLVersion >= 120)
4662       && NewVD->isStaticLocal()) {
4663     Diag(NewVD->getLocation(), diag::err_static_function_scope);
4664     NewVD->setInvalidDecl();
4665     return false;
4666   }
4667 
4668   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4669       && !NewVD->hasAttr<BlocksAttr>()) {
4670     if (getLangOpts().getGC() != LangOptions::NonGC)
4671       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4672     else {
4673       assert(!getLangOpts().ObjCAutoRefCount);
4674       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4675     }
4676   }
4677 
4678   bool isVM = T->isVariablyModifiedType();
4679   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4680       NewVD->hasAttr<BlocksAttr>())
4681     getCurFunction()->setHasBranchProtectedScope();
4682 
4683   if ((isVM && NewVD->hasLinkage()) ||
4684       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4685     bool SizeIsNegative;
4686     llvm::APSInt Oversized;
4687     TypeSourceInfo *FixedTInfo =
4688       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4689                                                     SizeIsNegative, Oversized);
4690     if (FixedTInfo == 0 && T->isVariableArrayType()) {
4691       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4692       // FIXME: This won't give the correct result for
4693       // int a[10][n];
4694       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4695 
4696       if (NewVD->isFileVarDecl())
4697         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4698         << SizeRange;
4699       else if (NewVD->getStorageClass() == SC_Static)
4700         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4701         << SizeRange;
4702       else
4703         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4704         << SizeRange;
4705       NewVD->setInvalidDecl();
4706       return false;
4707     }
4708 
4709     if (FixedTInfo == 0) {
4710       if (NewVD->isFileVarDecl())
4711         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4712       else
4713         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4714       NewVD->setInvalidDecl();
4715       return false;
4716     }
4717 
4718     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4719     NewVD->setType(FixedTInfo->getType());
4720     NewVD->setTypeSourceInfo(FixedTInfo);
4721   }
4722 
4723   if (Previous.empty() && NewVD->isExternC()) {
4724     // Since we did not find anything by this name and we're declaring
4725     // an extern "C" variable, look for a non-visible extern "C"
4726     // declaration with the same name.
4727     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4728       = findLocallyScopedExternalDecl(NewVD->getDeclName());
4729     if (Pos != LocallyScopedExternalDecls.end())
4730       Previous.addDecl(Pos->second);
4731   }
4732 
4733   if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4734     Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4735       << T;
4736     NewVD->setInvalidDecl();
4737     return false;
4738   }
4739 
4740   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4741     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4742     NewVD->setInvalidDecl();
4743     return false;
4744   }
4745 
4746   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4747     Diag(NewVD->getLocation(), diag::err_block_on_vm);
4748     NewVD->setInvalidDecl();
4749     return false;
4750   }
4751 
4752   if (NewVD->isConstexpr() && !T->isDependentType() &&
4753       RequireLiteralType(NewVD->getLocation(), T,
4754                          diag::err_constexpr_var_non_literal)) {
4755     NewVD->setInvalidDecl();
4756     return false;
4757   }
4758 
4759   if (!Previous.empty()) {
4760     MergeVarDecl(NewVD, Previous);
4761     return true;
4762   }
4763   return false;
4764 }
4765 
4766 /// \brief Data used with FindOverriddenMethod
4767 struct FindOverriddenMethodData {
4768   Sema *S;
4769   CXXMethodDecl *Method;
4770 };
4771 
4772 /// \brief Member lookup function that determines whether a given C++
4773 /// method overrides a method in a base class, to be used with
4774 /// CXXRecordDecl::lookupInBases().
4775 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4776                                  CXXBasePath &Path,
4777                                  void *UserData) {
4778   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4779 
4780   FindOverriddenMethodData *Data
4781     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4782 
4783   DeclarationName Name = Data->Method->getDeclName();
4784 
4785   // FIXME: Do we care about other names here too?
4786   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4787     // We really want to find the base class destructor here.
4788     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4789     CanQualType CT = Data->S->Context.getCanonicalType(T);
4790 
4791     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4792   }
4793 
4794   for (Path.Decls = BaseRecord->lookup(Name);
4795        Path.Decls.first != Path.Decls.second;
4796        ++Path.Decls.first) {
4797     NamedDecl *D = *Path.Decls.first;
4798     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4799       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4800         return true;
4801     }
4802   }
4803 
4804   return false;
4805 }
4806 
4807 namespace {
4808   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
4809 }
4810 /// \brief Report an error regarding overriding, along with any relevant
4811 /// overriden methods.
4812 ///
4813 /// \param DiagID the primary error to report.
4814 /// \param MD the overriding method.
4815 /// \param OEK which overrides to include as notes.
4816 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
4817                             OverrideErrorKind OEK = OEK_All) {
4818   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
4819   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4820                                       E = MD->end_overridden_methods();
4821        I != E; ++I) {
4822     // This check (& the OEK parameter) could be replaced by a predicate, but
4823     // without lambdas that would be overkill. This is still nicer than writing
4824     // out the diag loop 3 times.
4825     if ((OEK == OEK_All) ||
4826         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
4827         (OEK == OEK_Deleted && (*I)->isDeleted()))
4828       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
4829   }
4830 }
4831 
4832 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4833 /// and if so, check that it's a valid override and remember it.
4834 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4835   // Look for virtual methods in base classes that this method might override.
4836   CXXBasePaths Paths;
4837   FindOverriddenMethodData Data;
4838   Data.Method = MD;
4839   Data.S = this;
4840   bool hasDeletedOverridenMethods = false;
4841   bool hasNonDeletedOverridenMethods = false;
4842   bool AddedAny = false;
4843   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4844     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4845          E = Paths.found_decls_end(); I != E; ++I) {
4846       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4847         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4848         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4849             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4850             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4851           hasDeletedOverridenMethods |= OldMD->isDeleted();
4852           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
4853           AddedAny = true;
4854         }
4855       }
4856     }
4857   }
4858 
4859   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
4860     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
4861   }
4862   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
4863     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
4864   }
4865 
4866   return AddedAny;
4867 }
4868 
4869 namespace {
4870   // Struct for holding all of the extra arguments needed by
4871   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4872   struct ActOnFDArgs {
4873     Scope *S;
4874     Declarator &D;
4875     MultiTemplateParamsArg TemplateParamLists;
4876     bool AddToScope;
4877   };
4878 }
4879 
4880 namespace {
4881 
4882 // Callback to only accept typo corrections that have a non-zero edit distance.
4883 // Also only accept corrections that have the same parent decl.
4884 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4885  public:
4886   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4887                             CXXRecordDecl *Parent)
4888       : Context(Context), OriginalFD(TypoFD),
4889         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4890 
4891   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4892     if (candidate.getEditDistance() == 0)
4893       return false;
4894 
4895     llvm::SmallVector<unsigned, 1> MismatchedParams;
4896     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4897                                           CDeclEnd = candidate.end();
4898          CDecl != CDeclEnd; ++CDecl) {
4899       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4900 
4901       if (FD && !FD->hasBody() &&
4902           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4903         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4904           CXXRecordDecl *Parent = MD->getParent();
4905           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4906             return true;
4907         } else if (!ExpectedParent) {
4908           return true;
4909         }
4910       }
4911     }
4912 
4913     return false;
4914   }
4915 
4916  private:
4917   ASTContext &Context;
4918   FunctionDecl *OriginalFD;
4919   CXXRecordDecl *ExpectedParent;
4920 };
4921 
4922 }
4923 
4924 /// \brief Generate diagnostics for an invalid function redeclaration.
4925 ///
4926 /// This routine handles generating the diagnostic messages for an invalid
4927 /// function redeclaration, including finding possible similar declarations
4928 /// or performing typo correction if there are no previous declarations with
4929 /// the same name.
4930 ///
4931 /// Returns a NamedDecl iff typo correction was performed and substituting in
4932 /// the new declaration name does not cause new errors.
4933 static NamedDecl* DiagnoseInvalidRedeclaration(
4934     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4935     ActOnFDArgs &ExtraArgs) {
4936   NamedDecl *Result = NULL;
4937   DeclarationName Name = NewFD->getDeclName();
4938   DeclContext *NewDC = NewFD->getDeclContext();
4939   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4940                     Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4941   llvm::SmallVector<unsigned, 1> MismatchedParams;
4942   llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4943   TypoCorrection Correction;
4944   bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4945                        ExtraArgs.D.getDeclSpec().isFriendSpecified());
4946   unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4947                                   : diag::err_member_def_does_not_match;
4948 
4949   NewFD->setInvalidDecl();
4950   SemaRef.LookupQualifiedName(Prev, NewDC);
4951   assert(!Prev.isAmbiguous() &&
4952          "Cannot have an ambiguity in previous-declaration lookup");
4953   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4954   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
4955                                       MD ? MD->getParent() : 0);
4956   if (!Prev.empty()) {
4957     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4958          Func != FuncEnd; ++Func) {
4959       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4960       if (FD &&
4961           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4962         // Add 1 to the index so that 0 can mean the mismatch didn't
4963         // involve a parameter
4964         unsigned ParamNum =
4965             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4966         NearMatches.push_back(std::make_pair(FD, ParamNum));
4967       }
4968     }
4969   // If the qualified name lookup yielded nothing, try typo correction
4970   } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4971                                          Prev.getLookupKind(), 0, 0,
4972                                          Validator, NewDC))) {
4973     // Trap errors.
4974     Sema::SFINAETrap Trap(SemaRef);
4975 
4976     // Set up everything for the call to ActOnFunctionDeclarator
4977     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4978                               ExtraArgs.D.getIdentifierLoc());
4979     Previous.clear();
4980     Previous.setLookupName(Correction.getCorrection());
4981     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4982                                     CDeclEnd = Correction.end();
4983          CDecl != CDeclEnd; ++CDecl) {
4984       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4985       if (FD && !FD->hasBody() &&
4986           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4987         Previous.addDecl(FD);
4988       }
4989     }
4990     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4991     // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4992     // pieces need to verify the typo-corrected C++ declaraction and hopefully
4993     // eliminate the need for the parameter pack ExtraArgs.
4994     Result = SemaRef.ActOnFunctionDeclarator(
4995         ExtraArgs.S, ExtraArgs.D,
4996         Correction.getCorrectionDecl()->getDeclContext(),
4997         NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4998         ExtraArgs.AddToScope);
4999     if (Trap.hasErrorOccurred()) {
5000       // Pretend the typo correction never occurred
5001       ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
5002                                 ExtraArgs.D.getIdentifierLoc());
5003       ExtraArgs.D.setRedeclaration(wasRedeclaration);
5004       Previous.clear();
5005       Previous.setLookupName(Name);
5006       Result = NULL;
5007     } else {
5008       for (LookupResult::iterator Func = Previous.begin(),
5009                                FuncEnd = Previous.end();
5010            Func != FuncEnd; ++Func) {
5011         if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
5012           NearMatches.push_back(std::make_pair(FD, 0));
5013       }
5014     }
5015     if (NearMatches.empty()) {
5016       // Ignore the correction if it didn't yield any close FunctionDecl matches
5017       Correction = TypoCorrection();
5018     } else {
5019       DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5020                              : diag::err_member_def_does_not_match_suggest;
5021     }
5022   }
5023 
5024   if (Correction) {
5025     // FIXME: use Correction.getCorrectionRange() instead of computing the range
5026     // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5027     // turn causes the correction to fully qualify the name. If we fix
5028     // CorrectTypo to minimally qualify then this change should be good.
5029     SourceRange FixItLoc(NewFD->getLocation());
5030     CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5031     if (Correction.getCorrectionSpecifier() && SS.isValid())
5032       FixItLoc.setBegin(SS.getBeginLoc());
5033     SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
5034         << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
5035         << FixItHint::CreateReplacement(
5036             FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5037   } else {
5038     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5039         << Name << NewDC << NewFD->getLocation();
5040   }
5041 
5042   bool NewFDisConst = false;
5043   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
5044     NewFDisConst = NewMD->isConst();
5045 
5046   for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
5047        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5048        NearMatch != NearMatchEnd; ++NearMatch) {
5049     FunctionDecl *FD = NearMatch->first;
5050     bool FDisConst = false;
5051     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
5052       FDisConst = MD->isConst();
5053 
5054     if (unsigned Idx = NearMatch->second) {
5055       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
5056       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5057       if (Loc.isInvalid()) Loc = FD->getLocation();
5058       SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
5059           << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5060     } else if (Correction) {
5061       SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
5062           << Correction.getQuoted(SemaRef.getLangOpts());
5063     } else if (FDisConst != NewFDisConst) {
5064       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
5065           << NewFDisConst << FD->getSourceRange().getEnd();
5066     } else
5067       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
5068   }
5069   return Result;
5070 }
5071 
5072 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5073                                                           Declarator &D) {
5074   switch (D.getDeclSpec().getStorageClassSpec()) {
5075   default: llvm_unreachable("Unknown storage class!");
5076   case DeclSpec::SCS_auto:
5077   case DeclSpec::SCS_register:
5078   case DeclSpec::SCS_mutable:
5079     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5080                  diag::err_typecheck_sclass_func);
5081     D.setInvalidType();
5082     break;
5083   case DeclSpec::SCS_unspecified: break;
5084   case DeclSpec::SCS_extern: return SC_Extern;
5085   case DeclSpec::SCS_static: {
5086     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5087       // C99 6.7.1p5:
5088       //   The declaration of an identifier for a function that has
5089       //   block scope shall have no explicit storage-class specifier
5090       //   other than extern
5091       // See also (C++ [dcl.stc]p4).
5092       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5093                    diag::err_static_block_func);
5094       break;
5095     } else
5096       return SC_Static;
5097   }
5098   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5099   }
5100 
5101   // No explicit storage class has already been returned
5102   return SC_None;
5103 }
5104 
5105 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5106                                            DeclContext *DC, QualType &R,
5107                                            TypeSourceInfo *TInfo,
5108                                            FunctionDecl::StorageClass SC,
5109                                            bool &IsVirtualOkay) {
5110   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5111   DeclarationName Name = NameInfo.getName();
5112 
5113   FunctionDecl *NewFD = 0;
5114   bool isInline = D.getDeclSpec().isInlineSpecified();
5115   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5116   FunctionDecl::StorageClass SCAsWritten
5117     = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5118 
5119   if (!SemaRef.getLangOpts().CPlusPlus) {
5120     // Determine whether the function was written with a
5121     // prototype. This true when:
5122     //   - there is a prototype in the declarator, or
5123     //   - the type R of the function is some kind of typedef or other reference
5124     //     to a type name (which eventually refers to a function type).
5125     bool HasPrototype =
5126       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5127       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5128 
5129     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
5130                                  D.getLocStart(), NameInfo, R,
5131                                  TInfo, SC, SCAsWritten, isInline,
5132                                  HasPrototype);
5133     if (D.isInvalidType())
5134       NewFD->setInvalidDecl();
5135 
5136     // Set the lexical context.
5137     NewFD->setLexicalDeclContext(SemaRef.CurContext);
5138 
5139     return NewFD;
5140   }
5141 
5142   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5143   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5144 
5145   // Check that the return type is not an abstract class type.
5146   // For record types, this is done by the AbstractClassUsageDiagnoser once
5147   // the class has been completely parsed.
5148   if (!DC->isRecord() &&
5149       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5150                                      R->getAs<FunctionType>()->getResultType(),
5151                                      diag::err_abstract_type_in_decl,
5152                                      SemaRef.AbstractReturnType))
5153     D.setInvalidType();
5154 
5155   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5156     // This is a C++ constructor declaration.
5157     assert(DC->isRecord() &&
5158            "Constructors can only be declared in a member context");
5159 
5160     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5161     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5162                                       D.getLocStart(), NameInfo,
5163                                       R, TInfo, isExplicit, isInline,
5164                                       /*isImplicitlyDeclared=*/false,
5165                                       isConstexpr);
5166 
5167   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5168     // This is a C++ destructor declaration.
5169     if (DC->isRecord()) {
5170       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5171       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5172       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5173                                         SemaRef.Context, Record,
5174                                         D.getLocStart(),
5175                                         NameInfo, R, TInfo, isInline,
5176                                         /*isImplicitlyDeclared=*/false);
5177 
5178       // If the class is complete, then we now create the implicit exception
5179       // specification. If the class is incomplete or dependent, we can't do
5180       // it yet.
5181       if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
5182           Record->getDefinition() && !Record->isBeingDefined() &&
5183           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5184         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5185       }
5186 
5187       IsVirtualOkay = true;
5188       return NewDD;
5189 
5190     } else {
5191       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5192       D.setInvalidType();
5193 
5194       // Create a FunctionDecl to satisfy the function definition parsing
5195       // code path.
5196       return FunctionDecl::Create(SemaRef.Context, DC,
5197                                   D.getLocStart(),
5198                                   D.getIdentifierLoc(), Name, R, TInfo,
5199                                   SC, SCAsWritten, isInline,
5200                                   /*hasPrototype=*/true, isConstexpr);
5201     }
5202 
5203   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5204     if (!DC->isRecord()) {
5205       SemaRef.Diag(D.getIdentifierLoc(),
5206            diag::err_conv_function_not_member);
5207       return 0;
5208     }
5209 
5210     SemaRef.CheckConversionDeclarator(D, R, SC);
5211     IsVirtualOkay = true;
5212     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5213                                      D.getLocStart(), NameInfo,
5214                                      R, TInfo, isInline, isExplicit,
5215                                      isConstexpr, SourceLocation());
5216 
5217   } else if (DC->isRecord()) {
5218     // If the name of the function is the same as the name of the record,
5219     // then this must be an invalid constructor that has a return type.
5220     // (The parser checks for a return type and makes the declarator a
5221     // constructor if it has no return type).
5222     if (Name.getAsIdentifierInfo() &&
5223         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5224       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5225         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5226         << SourceRange(D.getIdentifierLoc());
5227       return 0;
5228     }
5229 
5230     bool isStatic = SC == SC_Static;
5231 
5232     // [class.free]p1:
5233     // Any allocation function for a class T is a static member
5234     // (even if not explicitly declared static).
5235     if (Name.getCXXOverloadedOperator() == OO_New ||
5236         Name.getCXXOverloadedOperator() == OO_Array_New)
5237       isStatic = true;
5238 
5239     // [class.free]p6 Any deallocation function for a class X is a static member
5240     // (even if not explicitly declared static).
5241     if (Name.getCXXOverloadedOperator() == OO_Delete ||
5242         Name.getCXXOverloadedOperator() == OO_Array_Delete)
5243       isStatic = true;
5244 
5245     IsVirtualOkay = !isStatic;
5246 
5247     // This is a C++ method declaration.
5248     return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5249                                  D.getLocStart(), NameInfo, R,
5250                                  TInfo, isStatic, SCAsWritten, isInline,
5251                                  isConstexpr, SourceLocation());
5252 
5253   } else {
5254     // Determine whether the function was written with a
5255     // prototype. This true when:
5256     //   - we're in C++ (where every function has a prototype),
5257     return FunctionDecl::Create(SemaRef.Context, DC,
5258                                 D.getLocStart(),
5259                                 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5260                                 true/*HasPrototype*/, isConstexpr);
5261   }
5262 }
5263 
5264 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5265   // In C++, the empty parameter-type-list must be spelled "void"; a
5266   // typedef of void is not permitted.
5267   if (getLangOpts().CPlusPlus &&
5268       Param->getType().getUnqualifiedType() != Context.VoidTy) {
5269     bool IsTypeAlias = false;
5270     if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5271       IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5272     else if (const TemplateSpecializationType *TST =
5273                Param->getType()->getAs<TemplateSpecializationType>())
5274       IsTypeAlias = TST->isTypeAlias();
5275     Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5276       << IsTypeAlias;
5277   }
5278 }
5279 
5280 NamedDecl*
5281 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5282                               TypeSourceInfo *TInfo, LookupResult &Previous,
5283                               MultiTemplateParamsArg TemplateParamLists,
5284                               bool &AddToScope) {
5285   QualType R = TInfo->getType();
5286 
5287   assert(R.getTypePtr()->isFunctionType());
5288 
5289   // TODO: consider using NameInfo for diagnostic.
5290   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5291   DeclarationName Name = NameInfo.getName();
5292   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
5293 
5294   if (D.getDeclSpec().isThreadSpecified())
5295     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5296 
5297   // Do not allow returning a objc interface by-value.
5298   if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
5299     Diag(D.getIdentifierLoc(),
5300          diag::err_object_cannot_be_passed_returned_by_value) << 0
5301     << R->getAs<FunctionType>()->getResultType()
5302     << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
5303 
5304     QualType T = R->getAs<FunctionType>()->getResultType();
5305     T = Context.getObjCObjectPointerType(T);
5306     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5307       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5308       R = Context.getFunctionType(T, FPT->arg_type_begin(),
5309                                   FPT->getNumArgs(), EPI);
5310     }
5311     else if (isa<FunctionNoProtoType>(R))
5312       R = Context.getFunctionNoProtoType(T);
5313   }
5314 
5315   bool isFriend = false;
5316   FunctionTemplateDecl *FunctionTemplate = 0;
5317   bool isExplicitSpecialization = false;
5318   bool isFunctionTemplateSpecialization = false;
5319 
5320   bool isDependentClassScopeExplicitSpecialization = false;
5321   bool HasExplicitTemplateArgs = false;
5322   TemplateArgumentListInfo TemplateArgs;
5323 
5324   bool isVirtualOkay = false;
5325 
5326   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5327                                               isVirtualOkay);
5328   if (!NewFD) return 0;
5329 
5330   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5331     NewFD->setTopLevelDeclInObjCContainer();
5332 
5333   if (getLangOpts().CPlusPlus) {
5334     bool isInline = D.getDeclSpec().isInlineSpecified();
5335     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5336     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5337     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5338     isFriend = D.getDeclSpec().isFriendSpecified();
5339     if (isFriend && !isInline && D.isFunctionDefinition()) {
5340       // C++ [class.friend]p5
5341       //   A function can be defined in a friend declaration of a
5342       //   class . . . . Such a function is implicitly inline.
5343       NewFD->setImplicitlyInline();
5344     }
5345 
5346     // If this is a method defined in an __interface, and is not a constructor
5347     // or an overloaded operator, then set the pure flag (isVirtual will already
5348     // return true).
5349     if (const CXXRecordDecl *Parent =
5350           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5351       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
5352         NewFD->setPure(true);
5353     }
5354 
5355     SetNestedNameSpecifier(NewFD, D);
5356     isExplicitSpecialization = false;
5357     isFunctionTemplateSpecialization = false;
5358     if (D.isInvalidType())
5359       NewFD->setInvalidDecl();
5360 
5361     // Set the lexical context. If the declarator has a C++
5362     // scope specifier, or is the object of a friend declaration, the
5363     // lexical context will be different from the semantic context.
5364     NewFD->setLexicalDeclContext(CurContext);
5365 
5366     // Match up the template parameter lists with the scope specifier, then
5367     // determine whether we have a template or a template specialization.
5368     bool Invalid = false;
5369     if (TemplateParameterList *TemplateParams
5370           = MatchTemplateParametersToScopeSpecifier(
5371                                   D.getDeclSpec().getLocStart(),
5372                                   D.getIdentifierLoc(),
5373                                   D.getCXXScopeSpec(),
5374                                   TemplateParamLists.data(),
5375                                   TemplateParamLists.size(),
5376                                   isFriend,
5377                                   isExplicitSpecialization,
5378                                   Invalid)) {
5379       if (TemplateParams->size() > 0) {
5380         // This is a function template
5381 
5382         // Check that we can declare a template here.
5383         if (CheckTemplateDeclScope(S, TemplateParams))
5384           return 0;
5385 
5386         // A destructor cannot be a template.
5387         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5388           Diag(NewFD->getLocation(), diag::err_destructor_template);
5389           return 0;
5390         }
5391 
5392         // If we're adding a template to a dependent context, we may need to
5393         // rebuilding some of the types used within the template parameter list,
5394         // now that we know what the current instantiation is.
5395         if (DC->isDependentContext()) {
5396           ContextRAII SavedContext(*this, DC);
5397           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5398             Invalid = true;
5399         }
5400 
5401 
5402         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5403                                                         NewFD->getLocation(),
5404                                                         Name, TemplateParams,
5405                                                         NewFD);
5406         FunctionTemplate->setLexicalDeclContext(CurContext);
5407         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5408 
5409         // For source fidelity, store the other template param lists.
5410         if (TemplateParamLists.size() > 1) {
5411           NewFD->setTemplateParameterListsInfo(Context,
5412                                                TemplateParamLists.size() - 1,
5413                                                TemplateParamLists.data());
5414         }
5415       } else {
5416         // This is a function template specialization.
5417         isFunctionTemplateSpecialization = true;
5418         // For source fidelity, store all the template param lists.
5419         NewFD->setTemplateParameterListsInfo(Context,
5420                                              TemplateParamLists.size(),
5421                                              TemplateParamLists.data());
5422 
5423         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5424         if (isFriend) {
5425           // We want to remove the "template<>", found here.
5426           SourceRange RemoveRange = TemplateParams->getSourceRange();
5427 
5428           // If we remove the template<> and the name is not a
5429           // template-id, we're actually silently creating a problem:
5430           // the friend declaration will refer to an untemplated decl,
5431           // and clearly the user wants a template specialization.  So
5432           // we need to insert '<>' after the name.
5433           SourceLocation InsertLoc;
5434           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5435             InsertLoc = D.getName().getSourceRange().getEnd();
5436             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5437           }
5438 
5439           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5440             << Name << RemoveRange
5441             << FixItHint::CreateRemoval(RemoveRange)
5442             << FixItHint::CreateInsertion(InsertLoc, "<>");
5443         }
5444       }
5445     }
5446     else {
5447       // All template param lists were matched against the scope specifier:
5448       // this is NOT (an explicit specialization of) a template.
5449       if (TemplateParamLists.size() > 0)
5450         // For source fidelity, store all the template param lists.
5451         NewFD->setTemplateParameterListsInfo(Context,
5452                                              TemplateParamLists.size(),
5453                                              TemplateParamLists.data());
5454     }
5455 
5456     if (Invalid) {
5457       NewFD->setInvalidDecl();
5458       if (FunctionTemplate)
5459         FunctionTemplate->setInvalidDecl();
5460     }
5461 
5462     // C++ [dcl.fct.spec]p5:
5463     //   The virtual specifier shall only be used in declarations of
5464     //   nonstatic class member functions that appear within a
5465     //   member-specification of a class declaration; see 10.3.
5466     //
5467     if (isVirtual && !NewFD->isInvalidDecl()) {
5468       if (!isVirtualOkay) {
5469         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5470              diag::err_virtual_non_function);
5471       } else if (!CurContext->isRecord()) {
5472         // 'virtual' was specified outside of the class.
5473         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5474              diag::err_virtual_out_of_class)
5475           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5476       } else if (NewFD->getDescribedFunctionTemplate()) {
5477         // C++ [temp.mem]p3:
5478         //  A member function template shall not be virtual.
5479         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5480              diag::err_virtual_member_function_template)
5481           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5482       } else {
5483         // Okay: Add virtual to the method.
5484         NewFD->setVirtualAsWritten(true);
5485       }
5486     }
5487 
5488     // C++ [dcl.fct.spec]p3:
5489     //  The inline specifier shall not appear on a block scope function
5490     //  declaration.
5491     if (isInline && !NewFD->isInvalidDecl()) {
5492       if (CurContext->isFunctionOrMethod()) {
5493         // 'inline' is not allowed on block scope function declaration.
5494         Diag(D.getDeclSpec().getInlineSpecLoc(),
5495              diag::err_inline_declaration_block_scope) << Name
5496           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5497       }
5498     }
5499 
5500     // C++ [dcl.fct.spec]p6:
5501     //  The explicit specifier shall be used only in the declaration of a
5502     //  constructor or conversion function within its class definition;
5503     //  see 12.3.1 and 12.3.2.
5504     if (isExplicit && !NewFD->isInvalidDecl()) {
5505       if (!CurContext->isRecord()) {
5506         // 'explicit' was specified outside of the class.
5507         Diag(D.getDeclSpec().getExplicitSpecLoc(),
5508              diag::err_explicit_out_of_class)
5509           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5510       } else if (!isa<CXXConstructorDecl>(NewFD) &&
5511                  !isa<CXXConversionDecl>(NewFD)) {
5512         // 'explicit' was specified on a function that wasn't a constructor
5513         // or conversion function.
5514         Diag(D.getDeclSpec().getExplicitSpecLoc(),
5515              diag::err_explicit_non_ctor_or_conv_function)
5516           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5517       }
5518     }
5519 
5520     if (isConstexpr) {
5521       // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5522       // are implicitly inline.
5523       NewFD->setImplicitlyInline();
5524 
5525       // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5526       // be either constructors or to return a literal type. Therefore,
5527       // destructors cannot be declared constexpr.
5528       if (isa<CXXDestructorDecl>(NewFD))
5529         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5530     }
5531 
5532     // If __module_private__ was specified, mark the function accordingly.
5533     if (D.getDeclSpec().isModulePrivateSpecified()) {
5534       if (isFunctionTemplateSpecialization) {
5535         SourceLocation ModulePrivateLoc
5536           = D.getDeclSpec().getModulePrivateSpecLoc();
5537         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5538           << 0
5539           << FixItHint::CreateRemoval(ModulePrivateLoc);
5540       } else {
5541         NewFD->setModulePrivate();
5542         if (FunctionTemplate)
5543           FunctionTemplate->setModulePrivate();
5544       }
5545     }
5546 
5547     if (isFriend) {
5548       // For now, claim that the objects have no previous declaration.
5549       if (FunctionTemplate) {
5550         FunctionTemplate->setObjectOfFriendDecl(false);
5551         FunctionTemplate->setAccess(AS_public);
5552       }
5553       NewFD->setObjectOfFriendDecl(false);
5554       NewFD->setAccess(AS_public);
5555     }
5556 
5557     // If a function is defined as defaulted or deleted, mark it as such now.
5558     switch (D.getFunctionDefinitionKind()) {
5559       case FDK_Declaration:
5560       case FDK_Definition:
5561         break;
5562 
5563       case FDK_Defaulted:
5564         NewFD->setDefaulted();
5565         break;
5566 
5567       case FDK_Deleted:
5568         NewFD->setDeletedAsWritten();
5569         break;
5570     }
5571 
5572     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5573         D.isFunctionDefinition()) {
5574       // C++ [class.mfct]p2:
5575       //   A member function may be defined (8.4) in its class definition, in
5576       //   which case it is an inline member function (7.1.2)
5577       NewFD->setImplicitlyInline();
5578     }
5579 
5580     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5581         !CurContext->isRecord()) {
5582       // C++ [class.static]p1:
5583       //   A data or function member of a class may be declared static
5584       //   in a class definition, in which case it is a static member of
5585       //   the class.
5586 
5587       // Complain about the 'static' specifier if it's on an out-of-line
5588       // member function definition.
5589       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5590            diag::err_static_out_of_line)
5591         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5592     }
5593 
5594     // C++11 [except.spec]p15:
5595     //   A deallocation function with no exception-specification is treated
5596     //   as if it were specified with noexcept(true).
5597     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
5598     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
5599          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
5600         getLangOpts().CPlusPlus0x && FPT && !FPT->hasExceptionSpec()) {
5601       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5602       EPI.ExceptionSpecType = EST_BasicNoexcept;
5603       NewFD->setType(Context.getFunctionType(FPT->getResultType(),
5604                                              FPT->arg_type_begin(),
5605                                              FPT->getNumArgs(), EPI));
5606     }
5607   }
5608 
5609   // Filter out previous declarations that don't match the scope.
5610   FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5611                        isExplicitSpecialization ||
5612                        isFunctionTemplateSpecialization);
5613 
5614   // Handle GNU asm-label extension (encoded as an attribute).
5615   if (Expr *E = (Expr*) D.getAsmLabel()) {
5616     // The parser guarantees this is a string.
5617     StringLiteral *SE = cast<StringLiteral>(E);
5618     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5619                                                 SE->getString()));
5620   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5621     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5622       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5623     if (I != ExtnameUndeclaredIdentifiers.end()) {
5624       NewFD->addAttr(I->second);
5625       ExtnameUndeclaredIdentifiers.erase(I);
5626     }
5627   }
5628 
5629   // Copy the parameter declarations from the declarator D to the function
5630   // declaration NewFD, if they are available.  First scavenge them into Params.
5631   SmallVector<ParmVarDecl*, 16> Params;
5632   if (D.isFunctionDeclarator()) {
5633     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5634 
5635     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5636     // function that takes no arguments, not a function that takes a
5637     // single void argument.
5638     // We let through "const void" here because Sema::GetTypeForDeclarator
5639     // already checks for that case.
5640     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5641         FTI.ArgInfo[0].Param &&
5642         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5643       // Empty arg list, don't push any params.
5644       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
5645     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5646       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5647         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5648         assert(Param->getDeclContext() != NewFD && "Was set before ?");
5649         Param->setDeclContext(NewFD);
5650         Params.push_back(Param);
5651 
5652         if (Param->isInvalidDecl())
5653           NewFD->setInvalidDecl();
5654       }
5655     }
5656 
5657   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5658     // When we're declaring a function with a typedef, typeof, etc as in the
5659     // following example, we'll need to synthesize (unnamed)
5660     // parameters for use in the declaration.
5661     //
5662     // @code
5663     // typedef void fn(int);
5664     // fn f;
5665     // @endcode
5666 
5667     // Synthesize a parameter for each argument type.
5668     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5669          AE = FT->arg_type_end(); AI != AE; ++AI) {
5670       ParmVarDecl *Param =
5671         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5672       Param->setScopeInfo(0, Params.size());
5673       Params.push_back(Param);
5674     }
5675   } else {
5676     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5677            "Should not need args for typedef of non-prototype fn");
5678   }
5679 
5680   // Finally, we know we have the right number of parameters, install them.
5681   NewFD->setParams(Params);
5682 
5683   // Find all anonymous symbols defined during the declaration of this function
5684   // and add to NewFD. This lets us track decls such 'enum Y' in:
5685   //
5686   //   void f(enum Y {AA} x) {}
5687   //
5688   // which would otherwise incorrectly end up in the translation unit scope.
5689   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5690   DeclsInPrototypeScope.clear();
5691 
5692   // Process the non-inheritable attributes on this declaration.
5693   ProcessDeclAttributes(S, NewFD, D,
5694                         /*NonInheritable=*/true, /*Inheritable=*/false);
5695 
5696   // Functions returning a variably modified type violate C99 6.7.5.2p2
5697   // because all functions have linkage.
5698   if (!NewFD->isInvalidDecl() &&
5699       NewFD->getResultType()->isVariablyModifiedType()) {
5700     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5701     NewFD->setInvalidDecl();
5702   }
5703 
5704   // Handle attributes.
5705   ProcessDeclAttributes(S, NewFD, D,
5706                         /*NonInheritable=*/false, /*Inheritable=*/true);
5707 
5708   QualType RetType = NewFD->getResultType();
5709   const CXXRecordDecl *Ret = RetType->isRecordType() ?
5710       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
5711   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
5712       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
5713     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5714     if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
5715       NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
5716                                                         Context));
5717     }
5718   }
5719 
5720   if (!getLangOpts().CPlusPlus) {
5721     // Perform semantic checking on the function declaration.
5722     bool isExplicitSpecialization=false;
5723     if (!NewFD->isInvalidDecl()) {
5724       if (NewFD->isMain())
5725         CheckMain(NewFD, D.getDeclSpec());
5726       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5727                                                   isExplicitSpecialization));
5728     }
5729     // Make graceful recovery from an invalid redeclaration.
5730     else if (!Previous.empty())
5731            D.setRedeclaration(true);
5732     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5733             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5734            "previous declaration set still overloaded");
5735   } else {
5736     // If the declarator is a template-id, translate the parser's template
5737     // argument list into our AST format.
5738     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5739       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5740       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5741       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5742       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5743                                          TemplateId->NumArgs);
5744       translateTemplateArguments(TemplateArgsPtr,
5745                                  TemplateArgs);
5746 
5747       HasExplicitTemplateArgs = true;
5748 
5749       if (NewFD->isInvalidDecl()) {
5750         HasExplicitTemplateArgs = false;
5751       } else if (FunctionTemplate) {
5752         // Function template with explicit template arguments.
5753         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5754           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5755 
5756         HasExplicitTemplateArgs = false;
5757       } else if (!isFunctionTemplateSpecialization &&
5758                  !D.getDeclSpec().isFriendSpecified()) {
5759         // We have encountered something that the user meant to be a
5760         // specialization (because it has explicitly-specified template
5761         // arguments) but that was not introduced with a "template<>" (or had
5762         // too few of them).
5763         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5764           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5765           << FixItHint::CreateInsertion(
5766                                     D.getDeclSpec().getLocStart(),
5767                                         "template<> ");
5768         isFunctionTemplateSpecialization = true;
5769       } else {
5770         // "friend void foo<>(int);" is an implicit specialization decl.
5771         isFunctionTemplateSpecialization = true;
5772       }
5773     } else if (isFriend && isFunctionTemplateSpecialization) {
5774       // This combination is only possible in a recovery case;  the user
5775       // wrote something like:
5776       //   template <> friend void foo(int);
5777       // which we're recovering from as if the user had written:
5778       //   friend void foo<>(int);
5779       // Go ahead and fake up a template id.
5780       HasExplicitTemplateArgs = true;
5781         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5782       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5783     }
5784 
5785     // If it's a friend (and only if it's a friend), it's possible
5786     // that either the specialized function type or the specialized
5787     // template is dependent, and therefore matching will fail.  In
5788     // this case, don't check the specialization yet.
5789     bool InstantiationDependent = false;
5790     if (isFunctionTemplateSpecialization && isFriend &&
5791         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5792          TemplateSpecializationType::anyDependentTemplateArguments(
5793             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5794             InstantiationDependent))) {
5795       assert(HasExplicitTemplateArgs &&
5796              "friend function specialization without template args");
5797       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5798                                                        Previous))
5799         NewFD->setInvalidDecl();
5800     } else if (isFunctionTemplateSpecialization) {
5801       if (CurContext->isDependentContext() && CurContext->isRecord()
5802           && !isFriend) {
5803         isDependentClassScopeExplicitSpecialization = true;
5804         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5805           diag::ext_function_specialization_in_class :
5806           diag::err_function_specialization_in_class)
5807           << NewFD->getDeclName();
5808       } else if (CheckFunctionTemplateSpecialization(NewFD,
5809                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5810                                                      Previous))
5811         NewFD->setInvalidDecl();
5812 
5813       // C++ [dcl.stc]p1:
5814       //   A storage-class-specifier shall not be specified in an explicit
5815       //   specialization (14.7.3)
5816       if (SC != SC_None) {
5817         if (SC != NewFD->getStorageClass())
5818           Diag(NewFD->getLocation(),
5819                diag::err_explicit_specialization_inconsistent_storage_class)
5820             << SC
5821             << FixItHint::CreateRemoval(
5822                                       D.getDeclSpec().getStorageClassSpecLoc());
5823 
5824         else
5825           Diag(NewFD->getLocation(),
5826                diag::ext_explicit_specialization_storage_class)
5827             << FixItHint::CreateRemoval(
5828                                       D.getDeclSpec().getStorageClassSpecLoc());
5829       }
5830 
5831     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5832       if (CheckMemberSpecialization(NewFD, Previous))
5833           NewFD->setInvalidDecl();
5834     }
5835 
5836     // Perform semantic checking on the function declaration.
5837     if (!isDependentClassScopeExplicitSpecialization) {
5838       if (NewFD->isInvalidDecl()) {
5839         // If this is a class member, mark the class invalid immediately.
5840         // This avoids some consistency errors later.
5841         if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5842           methodDecl->getParent()->setInvalidDecl();
5843       } else {
5844         if (NewFD->isMain())
5845           CheckMain(NewFD, D.getDeclSpec());
5846         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5847                                                     isExplicitSpecialization));
5848       }
5849     }
5850 
5851     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5852             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5853            "previous declaration set still overloaded");
5854 
5855     NamedDecl *PrincipalDecl = (FunctionTemplate
5856                                 ? cast<NamedDecl>(FunctionTemplate)
5857                                 : NewFD);
5858 
5859     if (isFriend && D.isRedeclaration()) {
5860       AccessSpecifier Access = AS_public;
5861       if (!NewFD->isInvalidDecl())
5862         Access = NewFD->getPreviousDecl()->getAccess();
5863 
5864       NewFD->setAccess(Access);
5865       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5866 
5867       PrincipalDecl->setObjectOfFriendDecl(true);
5868     }
5869 
5870     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5871         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5872       PrincipalDecl->setNonMemberOperator();
5873 
5874     // If we have a function template, check the template parameter
5875     // list. This will check and merge default template arguments.
5876     if (FunctionTemplate) {
5877       FunctionTemplateDecl *PrevTemplate =
5878                                      FunctionTemplate->getPreviousDecl();
5879       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5880                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5881                             D.getDeclSpec().isFriendSpecified()
5882                               ? (D.isFunctionDefinition()
5883                                    ? TPC_FriendFunctionTemplateDefinition
5884                                    : TPC_FriendFunctionTemplate)
5885                               : (D.getCXXScopeSpec().isSet() &&
5886                                  DC && DC->isRecord() &&
5887                                  DC->isDependentContext())
5888                                   ? TPC_ClassTemplateMember
5889                                   : TPC_FunctionTemplate);
5890     }
5891 
5892     if (NewFD->isInvalidDecl()) {
5893       // Ignore all the rest of this.
5894     } else if (!D.isRedeclaration()) {
5895       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5896                                        AddToScope };
5897       // Fake up an access specifier if it's supposed to be a class member.
5898       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5899         NewFD->setAccess(AS_public);
5900 
5901       // Qualified decls generally require a previous declaration.
5902       if (D.getCXXScopeSpec().isSet()) {
5903         // ...with the major exception of templated-scope or
5904         // dependent-scope friend declarations.
5905 
5906         // TODO: we currently also suppress this check in dependent
5907         // contexts because (1) the parameter depth will be off when
5908         // matching friend templates and (2) we might actually be
5909         // selecting a friend based on a dependent factor.  But there
5910         // are situations where these conditions don't apply and we
5911         // can actually do this check immediately.
5912         if (isFriend &&
5913             (TemplateParamLists.size() ||
5914              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5915              CurContext->isDependentContext())) {
5916           // ignore these
5917         } else {
5918           // The user tried to provide an out-of-line definition for a
5919           // function that is a member of a class or namespace, but there
5920           // was no such member function declared (C++ [class.mfct]p2,
5921           // C++ [namespace.memdef]p2). For example:
5922           //
5923           // class X {
5924           //   void f() const;
5925           // };
5926           //
5927           // void X::f() { } // ill-formed
5928           //
5929           // Complain about this problem, and attempt to suggest close
5930           // matches (e.g., those that differ only in cv-qualifiers and
5931           // whether the parameter types are references).
5932 
5933           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5934                                                                NewFD,
5935                                                                ExtraArgs)) {
5936             AddToScope = ExtraArgs.AddToScope;
5937             return Result;
5938           }
5939         }
5940 
5941         // Unqualified local friend declarations are required to resolve
5942         // to something.
5943       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5944         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5945                                                              NewFD,
5946                                                              ExtraArgs)) {
5947           AddToScope = ExtraArgs.AddToScope;
5948           return Result;
5949         }
5950       }
5951 
5952     } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5953                !isFriend && !isFunctionTemplateSpecialization &&
5954                !isExplicitSpecialization) {
5955       // An out-of-line member function declaration must also be a
5956       // definition (C++ [dcl.meaning]p1).
5957       // Note that this is not the case for explicit specializations of
5958       // function templates or member functions of class templates, per
5959       // C++ [temp.expl.spec]p2. We also allow these declarations as an
5960       // extension for compatibility with old SWIG code which likes to
5961       // generate them.
5962       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5963         << D.getCXXScopeSpec().getRange();
5964     }
5965   }
5966 
5967   AddKnownFunctionAttributes(NewFD);
5968 
5969   if (NewFD->hasAttr<OverloadableAttr>() &&
5970       !NewFD->getType()->getAs<FunctionProtoType>()) {
5971     Diag(NewFD->getLocation(),
5972          diag::err_attribute_overloadable_no_prototype)
5973       << NewFD;
5974 
5975     // Turn this into a variadic function with no parameters.
5976     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5977     FunctionProtoType::ExtProtoInfo EPI;
5978     EPI.Variadic = true;
5979     EPI.ExtInfo = FT->getExtInfo();
5980 
5981     QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5982     NewFD->setType(R);
5983   }
5984 
5985   // If there's a #pragma GCC visibility in scope, and this isn't a class
5986   // member, set the visibility of this function.
5987   if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5988     AddPushedVisibilityAttribute(NewFD);
5989 
5990   // If there's a #pragma clang arc_cf_code_audited in scope, consider
5991   // marking the function.
5992   AddCFAuditedAttribute(NewFD);
5993 
5994   // If this is a locally-scoped extern C function, update the
5995   // map of such names.
5996   if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5997       && !NewFD->isInvalidDecl())
5998     RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5999 
6000   // Set this FunctionDecl's range up to the right paren.
6001   NewFD->setRangeEnd(D.getSourceRange().getEnd());
6002 
6003   if (getLangOpts().CPlusPlus) {
6004     if (FunctionTemplate) {
6005       if (NewFD->isInvalidDecl())
6006         FunctionTemplate->setInvalidDecl();
6007       return FunctionTemplate;
6008     }
6009   }
6010 
6011   // OpenCL v1.2 s6.8 static is invalid for kernel functions.
6012   if ((getLangOpts().OpenCLVersion >= 120)
6013       && NewFD->hasAttr<OpenCLKernelAttr>()
6014       && (SC == SC_Static)) {
6015     Diag(D.getIdentifierLoc(), diag::err_static_kernel);
6016     D.setInvalidType();
6017   }
6018 
6019   MarkUnusedFileScopedDecl(NewFD);
6020 
6021   if (getLangOpts().CUDA)
6022     if (IdentifierInfo *II = NewFD->getIdentifier())
6023       if (!NewFD->isInvalidDecl() &&
6024           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6025         if (II->isStr("cudaConfigureCall")) {
6026           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6027             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6028 
6029           Context.setcudaConfigureCallDecl(NewFD);
6030         }
6031       }
6032 
6033   // Here we have an function template explicit specialization at class scope.
6034   // The actually specialization will be postponed to template instatiation
6035   // time via the ClassScopeFunctionSpecializationDecl node.
6036   if (isDependentClassScopeExplicitSpecialization) {
6037     ClassScopeFunctionSpecializationDecl *NewSpec =
6038                          ClassScopeFunctionSpecializationDecl::Create(
6039                                 Context, CurContext, SourceLocation(),
6040                                 cast<CXXMethodDecl>(NewFD),
6041                                 HasExplicitTemplateArgs, TemplateArgs);
6042     CurContext->addDecl(NewSpec);
6043     AddToScope = false;
6044   }
6045 
6046   return NewFD;
6047 }
6048 
6049 /// \brief Perform semantic checking of a new function declaration.
6050 ///
6051 /// Performs semantic analysis of the new function declaration
6052 /// NewFD. This routine performs all semantic checking that does not
6053 /// require the actual declarator involved in the declaration, and is
6054 /// used both for the declaration of functions as they are parsed
6055 /// (called via ActOnDeclarator) and for the declaration of functions
6056 /// that have been instantiated via C++ template instantiation (called
6057 /// via InstantiateDecl).
6058 ///
6059 /// \param IsExplicitSpecialization whether this new function declaration is
6060 /// an explicit specialization of the previous declaration.
6061 ///
6062 /// This sets NewFD->isInvalidDecl() to true if there was an error.
6063 ///
6064 /// \returns true if the function declaration is a redeclaration.
6065 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
6066                                     LookupResult &Previous,
6067                                     bool IsExplicitSpecialization) {
6068   assert(!NewFD->getResultType()->isVariablyModifiedType()
6069          && "Variably modified return types are not handled here");
6070 
6071   // Check for a previous declaration of this name.
6072   if (Previous.empty() && NewFD->isExternC()) {
6073     // Since we did not find anything by this name and we're declaring
6074     // an extern "C" function, look for a non-visible extern "C"
6075     // declaration with the same name.
6076     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6077       = findLocallyScopedExternalDecl(NewFD->getDeclName());
6078     if (Pos != LocallyScopedExternalDecls.end())
6079       Previous.addDecl(Pos->second);
6080   }
6081 
6082   bool Redeclaration = false;
6083 
6084   // Merge or overload the declaration with an existing declaration of
6085   // the same name, if appropriate.
6086   if (!Previous.empty()) {
6087     // Determine whether NewFD is an overload of PrevDecl or
6088     // a declaration that requires merging. If it's an overload,
6089     // there's no more work to do here; we'll just add the new
6090     // function to the scope.
6091 
6092     NamedDecl *OldDecl = 0;
6093     if (!AllowOverloadingOfFunction(Previous, Context)) {
6094       Redeclaration = true;
6095       OldDecl = Previous.getFoundDecl();
6096     } else {
6097       switch (CheckOverload(S, NewFD, Previous, OldDecl,
6098                             /*NewIsUsingDecl*/ false)) {
6099       case Ovl_Match:
6100         Redeclaration = true;
6101         break;
6102 
6103       case Ovl_NonFunction:
6104         Redeclaration = true;
6105         break;
6106 
6107       case Ovl_Overload:
6108         Redeclaration = false;
6109         break;
6110       }
6111 
6112       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
6113         // If a function name is overloadable in C, then every function
6114         // with that name must be marked "overloadable".
6115         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6116           << Redeclaration << NewFD;
6117         NamedDecl *OverloadedDecl = 0;
6118         if (Redeclaration)
6119           OverloadedDecl = OldDecl;
6120         else if (!Previous.empty())
6121           OverloadedDecl = Previous.getRepresentativeDecl();
6122         if (OverloadedDecl)
6123           Diag(OverloadedDecl->getLocation(),
6124                diag::note_attribute_overloadable_prev_overload);
6125         NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6126                                                         Context));
6127       }
6128     }
6129 
6130     if (Redeclaration) {
6131       // NewFD and OldDecl represent declarations that need to be
6132       // merged.
6133       if (MergeFunctionDecl(NewFD, OldDecl, S)) {
6134         NewFD->setInvalidDecl();
6135         return Redeclaration;
6136       }
6137 
6138       Previous.clear();
6139       Previous.addDecl(OldDecl);
6140 
6141       if (FunctionTemplateDecl *OldTemplateDecl
6142                                     = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
6143         NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
6144         FunctionTemplateDecl *NewTemplateDecl
6145           = NewFD->getDescribedFunctionTemplate();
6146         assert(NewTemplateDecl && "Template/non-template mismatch");
6147         if (CXXMethodDecl *Method
6148               = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6149           Method->setAccess(OldTemplateDecl->getAccess());
6150           NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6151         }
6152 
6153         // If this is an explicit specialization of a member that is a function
6154         // template, mark it as a member specialization.
6155         if (IsExplicitSpecialization &&
6156             NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6157           NewTemplateDecl->setMemberSpecialization();
6158           assert(OldTemplateDecl->isMemberSpecialization());
6159         }
6160 
6161       } else {
6162         if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
6163           NewFD->setAccess(OldDecl->getAccess());
6164         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
6165       }
6166     }
6167   }
6168 
6169   // Semantic checking for this function declaration (in isolation).
6170   if (getLangOpts().CPlusPlus) {
6171     // C++-specific checks.
6172     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6173       CheckConstructor(Constructor);
6174     } else if (CXXDestructorDecl *Destructor =
6175                 dyn_cast<CXXDestructorDecl>(NewFD)) {
6176       CXXRecordDecl *Record = Destructor->getParent();
6177       QualType ClassType = Context.getTypeDeclType(Record);
6178 
6179       // FIXME: Shouldn't we be able to perform this check even when the class
6180       // type is dependent? Both gcc and edg can handle that.
6181       if (!ClassType->isDependentType()) {
6182         DeclarationName Name
6183           = Context.DeclarationNames.getCXXDestructorName(
6184                                         Context.getCanonicalType(ClassType));
6185         if (NewFD->getDeclName() != Name) {
6186           Diag(NewFD->getLocation(), diag::err_destructor_name);
6187           NewFD->setInvalidDecl();
6188           return Redeclaration;
6189         }
6190       }
6191     } else if (CXXConversionDecl *Conversion
6192                = dyn_cast<CXXConversionDecl>(NewFD)) {
6193       ActOnConversionDeclarator(Conversion);
6194     }
6195 
6196     // Find any virtual functions that this function overrides.
6197     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6198       if (!Method->isFunctionTemplateSpecialization() &&
6199           !Method->getDescribedFunctionTemplate() &&
6200           Method->isCanonicalDecl()) {
6201         if (AddOverriddenMethods(Method->getParent(), Method)) {
6202           // If the function was marked as "static", we have a problem.
6203           if (NewFD->getStorageClass() == SC_Static) {
6204             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
6205           }
6206         }
6207       }
6208 
6209       if (Method->isStatic())
6210         checkThisInStaticMemberFunctionType(Method);
6211     }
6212 
6213     // Extra checking for C++ overloaded operators (C++ [over.oper]).
6214     if (NewFD->isOverloadedOperator() &&
6215         CheckOverloadedOperatorDeclaration(NewFD)) {
6216       NewFD->setInvalidDecl();
6217       return Redeclaration;
6218     }
6219 
6220     // Extra checking for C++0x literal operators (C++0x [over.literal]).
6221     if (NewFD->getLiteralIdentifier() &&
6222         CheckLiteralOperatorDeclaration(NewFD)) {
6223       NewFD->setInvalidDecl();
6224       return Redeclaration;
6225     }
6226 
6227     // In C++, check default arguments now that we have merged decls. Unless
6228     // the lexical context is the class, because in this case this is done
6229     // during delayed parsing anyway.
6230     if (!CurContext->isRecord())
6231       CheckCXXDefaultArguments(NewFD);
6232 
6233     // If this function declares a builtin function, check the type of this
6234     // declaration against the expected type for the builtin.
6235     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6236       ASTContext::GetBuiltinTypeError Error;
6237       QualType T = Context.GetBuiltinType(BuiltinID, Error);
6238       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6239         // The type of this function differs from the type of the builtin,
6240         // so forget about the builtin entirely.
6241         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6242       }
6243     }
6244 
6245     // If this function is declared as being extern "C", then check to see if
6246     // the function returns a UDT (class, struct, or union type) that is not C
6247     // compatible, and if it does, warn the user.
6248     if (NewFD->isExternC()) {
6249       QualType R = NewFD->getResultType();
6250       if (R->isIncompleteType() && !R->isVoidType())
6251         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6252             << NewFD << R;
6253       else if (!R.isPODType(Context) && !R->isVoidType() &&
6254                !R->isObjCObjectPointerType())
6255         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
6256     }
6257   }
6258   return Redeclaration;
6259 }
6260 
6261 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
6262   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
6263   //   static or constexpr is ill-formed.
6264   // C99 6.7.4p4:  In a hosted environment, the inline function specifier
6265   //   shall not appear in a declaration of main.
6266   // static main is not an error under C99, but we should warn about it.
6267   if (FD->getStorageClass() == SC_Static)
6268     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
6269          ? diag::err_static_main : diag::warn_static_main)
6270       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6271   if (FD->isInlineSpecified())
6272     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6273       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
6274   if (FD->isConstexpr()) {
6275     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6276       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6277     FD->setConstexpr(false);
6278   }
6279 
6280   QualType T = FD->getType();
6281   assert(T->isFunctionType() && "function decl is not of function type");
6282   const FunctionType* FT = T->castAs<FunctionType>();
6283 
6284   // All the standards say that main() should should return 'int'.
6285   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6286     // In C and C++, main magically returns 0 if you fall off the end;
6287     // set the flag which tells us that.
6288     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6289     FD->setHasImplicitReturnZero(true);
6290 
6291   // In C with GNU extensions we allow main() to have non-integer return
6292   // type, but we should warn about the extension, and we disable the
6293   // implicit-return-zero rule.
6294   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
6295     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6296 
6297   // Otherwise, this is just a flat-out error.
6298   } else {
6299     Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
6300     FD->setInvalidDecl(true);
6301   }
6302 
6303   // Treat protoless main() as nullary.
6304   if (isa<FunctionNoProtoType>(FT)) return;
6305 
6306   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6307   unsigned nparams = FTP->getNumArgs();
6308   assert(FD->getNumParams() == nparams);
6309 
6310   bool HasExtraParameters = (nparams > 3);
6311 
6312   // Darwin passes an undocumented fourth argument of type char**.  If
6313   // other platforms start sprouting these, the logic below will start
6314   // getting shifty.
6315   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
6316     HasExtraParameters = false;
6317 
6318   if (HasExtraParameters) {
6319     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6320     FD->setInvalidDecl(true);
6321     nparams = 3;
6322   }
6323 
6324   // FIXME: a lot of the following diagnostics would be improved
6325   // if we had some location information about types.
6326 
6327   QualType CharPP =
6328     Context.getPointerType(Context.getPointerType(Context.CharTy));
6329   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
6330 
6331   for (unsigned i = 0; i < nparams; ++i) {
6332     QualType AT = FTP->getArgType(i);
6333 
6334     bool mismatch = true;
6335 
6336     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6337       mismatch = false;
6338     else if (Expected[i] == CharPP) {
6339       // As an extension, the following forms are okay:
6340       //   char const **
6341       //   char const * const *
6342       //   char * const *
6343 
6344       QualifierCollector qs;
6345       const PointerType* PT;
6346       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6347           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
6348           (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6349         qs.removeConst();
6350         mismatch = !qs.empty();
6351       }
6352     }
6353 
6354     if (mismatch) {
6355       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6356       // TODO: suggest replacing given type with expected type
6357       FD->setInvalidDecl(true);
6358     }
6359   }
6360 
6361   if (nparams == 1 && !FD->isInvalidDecl()) {
6362     Diag(FD->getLocation(), diag::warn_main_one_arg);
6363   }
6364 
6365   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6366     Diag(FD->getLocation(), diag::err_main_template_decl);
6367     FD->setInvalidDecl();
6368   }
6369 }
6370 
6371 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6372   // FIXME: Need strict checking.  In C89, we need to check for
6373   // any assignment, increment, decrement, function-calls, or
6374   // commas outside of a sizeof.  In C99, it's the same list,
6375   // except that the aforementioned are allowed in unevaluated
6376   // expressions.  Everything else falls under the
6377   // "may accept other forms of constant expressions" exception.
6378   // (We never end up here for C++, so the constant expression
6379   // rules there don't matter.)
6380   if (Init->isConstantInitializer(Context, false))
6381     return false;
6382   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6383     << Init->getSourceRange();
6384   return true;
6385 }
6386 
6387 namespace {
6388   // Visits an initialization expression to see if OrigDecl is evaluated in
6389   // its own initialization and throws a warning if it does.
6390   class SelfReferenceChecker
6391       : public EvaluatedExprVisitor<SelfReferenceChecker> {
6392     Sema &S;
6393     Decl *OrigDecl;
6394     bool isRecordType;
6395     bool isPODType;
6396     bool isReferenceType;
6397 
6398   public:
6399     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6400 
6401     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6402                                                     S(S), OrigDecl(OrigDecl) {
6403       isPODType = false;
6404       isRecordType = false;
6405       isReferenceType = false;
6406       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6407         isPODType = VD->getType().isPODType(S.Context);
6408         isRecordType = VD->getType()->isRecordType();
6409         isReferenceType = VD->getType()->isReferenceType();
6410       }
6411     }
6412 
6413     // For most expressions, the cast is directly above the DeclRefExpr.
6414     // For conditional operators, the cast can be outside the conditional
6415     // operator if both expressions are DeclRefExpr's.
6416     void HandleValue(Expr *E) {
6417       if (isReferenceType)
6418         return;
6419       E = E->IgnoreParenImpCasts();
6420       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6421         HandleDeclRefExpr(DRE);
6422         return;
6423       }
6424 
6425       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6426         HandleValue(CO->getTrueExpr());
6427         HandleValue(CO->getFalseExpr());
6428         return;
6429       }
6430 
6431       if (isa<MemberExpr>(E)) {
6432         Expr *Base = E->IgnoreParenImpCasts();
6433         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6434           // Check for static member variables and don't warn on them.
6435           if (!isa<FieldDecl>(ME->getMemberDecl()))
6436             return;
6437           Base = ME->getBase()->IgnoreParenImpCasts();
6438         }
6439         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
6440           HandleDeclRefExpr(DRE);
6441         return;
6442       }
6443     }
6444 
6445     // Reference types are handled here since all uses of references are
6446     // bad, not just r-value uses.
6447     void VisitDeclRefExpr(DeclRefExpr *E) {
6448       if (isReferenceType)
6449         HandleDeclRefExpr(E);
6450     }
6451 
6452     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6453       if (E->getCastKind() == CK_LValueToRValue ||
6454           (isRecordType && E->getCastKind() == CK_NoOp))
6455         HandleValue(E->getSubExpr());
6456 
6457       Inherited::VisitImplicitCastExpr(E);
6458     }
6459 
6460     void VisitMemberExpr(MemberExpr *E) {
6461       // Don't warn on arrays since they can be treated as pointers.
6462       if (E->getType()->canDecayToPointerType()) return;
6463 
6464       // Warn when a non-static method call is followed by non-static member
6465       // field accesses, which is followed by a DeclRefExpr.
6466       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
6467       bool Warn = (MD && !MD->isStatic());
6468       Expr *Base = E->getBase()->IgnoreParenImpCasts();
6469       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6470         if (!isa<FieldDecl>(ME->getMemberDecl()))
6471           Warn = false;
6472         Base = ME->getBase()->IgnoreParenImpCasts();
6473       }
6474 
6475       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
6476         if (Warn)
6477           HandleDeclRefExpr(DRE);
6478         return;
6479       }
6480 
6481       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
6482       // Visit that expression.
6483       Visit(Base);
6484     }
6485 
6486     void VisitUnaryOperator(UnaryOperator *E) {
6487       // For POD record types, addresses of its own members are well-defined.
6488       if (E->getOpcode() == UO_AddrOf && isRecordType &&
6489           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
6490         if (!isPODType)
6491           HandleValue(E->getSubExpr());
6492         return;
6493       }
6494       Inherited::VisitUnaryOperator(E);
6495     }
6496 
6497     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6498 
6499     void HandleDeclRefExpr(DeclRefExpr *DRE) {
6500       Decl* ReferenceDecl = DRE->getDecl();
6501       if (OrigDecl != ReferenceDecl) return;
6502       unsigned diag = isReferenceType
6503           ? diag::warn_uninit_self_reference_in_reference_init
6504           : diag::warn_uninit_self_reference_in_init;
6505       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6506                             S.PDiag(diag)
6507                               << DRE->getNameInfo().getName()
6508                               << OrigDecl->getLocation()
6509                               << DRE->getSourceRange());
6510     }
6511   };
6512 
6513   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6514   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
6515                                  bool DirectInit) {
6516     // Parameters arguments are occassionially constructed with itself,
6517     // for instance, in recursive functions.  Skip them.
6518     if (isa<ParmVarDecl>(OrigDecl))
6519       return;
6520 
6521     E = E->IgnoreParens();
6522 
6523     // Skip checking T a = a where T is not a record or reference type.
6524     // Doing so is a way to silence uninitialized warnings.
6525     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
6526       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
6527         if (ICE->getCastKind() == CK_LValueToRValue)
6528           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
6529             if (DRE->getDecl() == OrigDecl)
6530               return;
6531 
6532     SelfReferenceChecker(S, OrigDecl).Visit(E);
6533   }
6534 }
6535 
6536 /// AddInitializerToDecl - Adds the initializer Init to the
6537 /// declaration dcl. If DirectInit is true, this is C++ direct
6538 /// initialization rather than copy initialization.
6539 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6540                                 bool DirectInit, bool TypeMayContainAuto) {
6541   // If there is no declaration, there was an error parsing it.  Just ignore
6542   // the initializer.
6543   if (RealDecl == 0 || RealDecl->isInvalidDecl())
6544     return;
6545 
6546   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6547     // With declarators parsed the way they are, the parser cannot
6548     // distinguish between a normal initializer and a pure-specifier.
6549     // Thus this grotesque test.
6550     IntegerLiteral *IL;
6551     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6552         Context.getCanonicalType(IL->getType()) == Context.IntTy)
6553       CheckPureMethod(Method, Init->getSourceRange());
6554     else {
6555       Diag(Method->getLocation(), diag::err_member_function_initialization)
6556         << Method->getDeclName() << Init->getSourceRange();
6557       Method->setInvalidDecl();
6558     }
6559     return;
6560   }
6561 
6562   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6563   if (!VDecl) {
6564     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6565     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6566     RealDecl->setInvalidDecl();
6567     return;
6568   }
6569 
6570   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6571 
6572   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6573   AutoType *Auto = 0;
6574   if (TypeMayContainAuto &&
6575       (Auto = VDecl->getType()->getContainedAutoType()) &&
6576       !Auto->isDeduced()) {
6577     Expr *DeduceInit = Init;
6578     // Initializer could be a C++ direct-initializer. Deduction only works if it
6579     // contains exactly one expression.
6580     if (CXXDirectInit) {
6581       if (CXXDirectInit->getNumExprs() == 0) {
6582         // It isn't possible to write this directly, but it is possible to
6583         // end up in this situation with "auto x(some_pack...);"
6584         Diag(CXXDirectInit->getLocStart(),
6585              diag::err_auto_var_init_no_expression)
6586           << VDecl->getDeclName() << VDecl->getType()
6587           << VDecl->getSourceRange();
6588         RealDecl->setInvalidDecl();
6589         return;
6590       } else if (CXXDirectInit->getNumExprs() > 1) {
6591         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6592              diag::err_auto_var_init_multiple_expressions)
6593           << VDecl->getDeclName() << VDecl->getType()
6594           << VDecl->getSourceRange();
6595         RealDecl->setInvalidDecl();
6596         return;
6597       } else {
6598         DeduceInit = CXXDirectInit->getExpr(0);
6599       }
6600     }
6601     TypeSourceInfo *DeducedType = 0;
6602     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6603             DAR_Failed)
6604       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6605     if (!DeducedType) {
6606       RealDecl->setInvalidDecl();
6607       return;
6608     }
6609     VDecl->setTypeSourceInfo(DeducedType);
6610     VDecl->setType(DeducedType->getType());
6611     VDecl->ClearLinkageCache();
6612 
6613     // In ARC, infer lifetime.
6614     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6615       VDecl->setInvalidDecl();
6616 
6617     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6618     // 'id' instead of a specific object type prevents most of our usual checks.
6619     // We only want to warn outside of template instantiations, though:
6620     // inside a template, the 'id' could have come from a parameter.
6621     if (ActiveTemplateInstantiations.empty() &&
6622         DeducedType->getType()->isObjCIdType()) {
6623       SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6624       Diag(Loc, diag::warn_auto_var_is_id)
6625         << VDecl->getDeclName() << DeduceInit->getSourceRange();
6626     }
6627 
6628     // If this is a redeclaration, check that the type we just deduced matches
6629     // the previously declared type.
6630     if (VarDecl *Old = VDecl->getPreviousDecl())
6631       MergeVarDeclTypes(VDecl, Old);
6632   }
6633 
6634   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6635     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6636     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6637     VDecl->setInvalidDecl();
6638     return;
6639   }
6640 
6641   if (!VDecl->getType()->isDependentType()) {
6642     // A definition must end up with a complete type, which means it must be
6643     // complete with the restriction that an array type might be completed by
6644     // the initializer; note that later code assumes this restriction.
6645     QualType BaseDeclType = VDecl->getType();
6646     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6647       BaseDeclType = Array->getElementType();
6648     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6649                             diag::err_typecheck_decl_incomplete_type)) {
6650       RealDecl->setInvalidDecl();
6651       return;
6652     }
6653 
6654     // The variable can not have an abstract class type.
6655     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6656                                diag::err_abstract_type_in_decl,
6657                                AbstractVariableType))
6658       VDecl->setInvalidDecl();
6659   }
6660 
6661   const VarDecl *Def;
6662   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6663     Diag(VDecl->getLocation(), diag::err_redefinition)
6664       << VDecl->getDeclName();
6665     Diag(Def->getLocation(), diag::note_previous_definition);
6666     VDecl->setInvalidDecl();
6667     return;
6668   }
6669 
6670   const VarDecl* PrevInit = 0;
6671   if (getLangOpts().CPlusPlus) {
6672     // C++ [class.static.data]p4
6673     //   If a static data member is of const integral or const
6674     //   enumeration type, its declaration in the class definition can
6675     //   specify a constant-initializer which shall be an integral
6676     //   constant expression (5.19). In that case, the member can appear
6677     //   in integral constant expressions. The member shall still be
6678     //   defined in a namespace scope if it is used in the program and the
6679     //   namespace scope definition shall not contain an initializer.
6680     //
6681     // We already performed a redefinition check above, but for static
6682     // data members we also need to check whether there was an in-class
6683     // declaration with an initializer.
6684     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6685       Diag(VDecl->getLocation(), diag::err_redefinition)
6686         << VDecl->getDeclName();
6687       Diag(PrevInit->getLocation(), diag::note_previous_definition);
6688       return;
6689     }
6690 
6691     if (VDecl->hasLocalStorage())
6692       getCurFunction()->setHasBranchProtectedScope();
6693 
6694     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6695       VDecl->setInvalidDecl();
6696       return;
6697     }
6698   }
6699 
6700   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6701   // a kernel function cannot be initialized."
6702   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6703     Diag(VDecl->getLocation(), diag::err_local_cant_init);
6704     VDecl->setInvalidDecl();
6705     return;
6706   }
6707 
6708   // Get the decls type and save a reference for later, since
6709   // CheckInitializerTypes may change it.
6710   QualType DclT = VDecl->getType(), SavT = DclT;
6711 
6712   // Top-level message sends default to 'id' when we're in a debugger
6713   // and we are assigning it to a variable of 'id' type.
6714   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6715     if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6716       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6717       if (Result.isInvalid()) {
6718         VDecl->setInvalidDecl();
6719         return;
6720       }
6721       Init = Result.take();
6722     }
6723 
6724   // Perform the initialization.
6725   if (!VDecl->isInvalidDecl()) {
6726     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6727     InitializationKind Kind
6728       = DirectInit ?
6729           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6730                                                            Init->getLocStart(),
6731                                                            Init->getLocEnd())
6732                         : InitializationKind::CreateDirectList(
6733                                                           VDecl->getLocation())
6734                    : InitializationKind::CreateCopy(VDecl->getLocation(),
6735                                                     Init->getLocStart());
6736 
6737     Expr **Args = &Init;
6738     unsigned NumArgs = 1;
6739     if (CXXDirectInit) {
6740       Args = CXXDirectInit->getExprs();
6741       NumArgs = CXXDirectInit->getNumExprs();
6742     }
6743     InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6744     ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6745                                         MultiExprArg(Args, NumArgs), &DclT);
6746     if (Result.isInvalid()) {
6747       VDecl->setInvalidDecl();
6748       return;
6749     }
6750 
6751     Init = Result.takeAs<Expr>();
6752   }
6753 
6754   // Check for self-references within variable initializers.
6755   // Variables declared within a function/method body (except for references)
6756   // are handled by a dataflow analysis.
6757   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
6758       VDecl->getType()->isReferenceType()) {
6759     CheckSelfReference(*this, RealDecl, Init, DirectInit);
6760   }
6761 
6762   // If the type changed, it means we had an incomplete type that was
6763   // completed by the initializer. For example:
6764   //   int ary[] = { 1, 3, 5 };
6765   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6766   if (!VDecl->isInvalidDecl() && (DclT != SavT))
6767     VDecl->setType(DclT);
6768 
6769   // Check any implicit conversions within the expression.
6770   CheckImplicitConversions(Init, VDecl->getLocation());
6771 
6772   if (!VDecl->isInvalidDecl()) {
6773     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6774 
6775     if (VDecl->hasAttr<BlocksAttr>())
6776       checkRetainCycles(VDecl, Init);
6777 
6778     // It is safe to assign a weak reference into a strong variable.
6779     // Although this code can still have problems:
6780     //   id x = self.weakProp;
6781     //   id y = self.weakProp;
6782     // we do not warn to warn spuriously when 'x' and 'y' are on separate
6783     // paths through the function. This should be revisited if
6784     // -Wrepeated-use-of-weak is made flow-sensitive.
6785     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
6786       DiagnosticsEngine::Level Level =
6787         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
6788                                  Init->getLocStart());
6789       if (Level != DiagnosticsEngine::Ignored)
6790         getCurFunction()->markSafeWeakUse(Init);
6791     }
6792   }
6793 
6794   Init = MaybeCreateExprWithCleanups(Init);
6795   // Attach the initializer to the decl.
6796   VDecl->setInit(Init);
6797 
6798   if (VDecl->isLocalVarDecl()) {
6799     // C99 6.7.8p4: All the expressions in an initializer for an object that has
6800     // static storage duration shall be constant expressions or string literals.
6801     // C++ does not have this restriction.
6802     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6803         VDecl->getStorageClass() == SC_Static)
6804       CheckForConstantInitializer(Init, DclT);
6805   } else if (VDecl->isStaticDataMember() &&
6806              VDecl->getLexicalDeclContext()->isRecord()) {
6807     // This is an in-class initialization for a static data member, e.g.,
6808     //
6809     // struct S {
6810     //   static const int value = 17;
6811     // };
6812 
6813     // C++ [class.mem]p4:
6814     //   A member-declarator can contain a constant-initializer only
6815     //   if it declares a static member (9.4) of const integral or
6816     //   const enumeration type, see 9.4.2.
6817     //
6818     // C++11 [class.static.data]p3:
6819     //   If a non-volatile const static data member is of integral or
6820     //   enumeration type, its declaration in the class definition can
6821     //   specify a brace-or-equal-initializer in which every initalizer-clause
6822     //   that is an assignment-expression is a constant expression. A static
6823     //   data member of literal type can be declared in the class definition
6824     //   with the constexpr specifier; if so, its declaration shall specify a
6825     //   brace-or-equal-initializer in which every initializer-clause that is
6826     //   an assignment-expression is a constant expression.
6827 
6828     // Do nothing on dependent types.
6829     if (DclT->isDependentType()) {
6830 
6831     // Allow any 'static constexpr' members, whether or not they are of literal
6832     // type. We separately check that every constexpr variable is of literal
6833     // type.
6834     } else if (VDecl->isConstexpr()) {
6835 
6836     // Require constness.
6837     } else if (!DclT.isConstQualified()) {
6838       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6839         << Init->getSourceRange();
6840       VDecl->setInvalidDecl();
6841 
6842     // We allow integer constant expressions in all cases.
6843     } else if (DclT->isIntegralOrEnumerationType()) {
6844       // Check whether the expression is a constant expression.
6845       SourceLocation Loc;
6846       if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6847         // In C++11, a non-constexpr const static data member with an
6848         // in-class initializer cannot be volatile.
6849         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6850       else if (Init->isValueDependent())
6851         ; // Nothing to check.
6852       else if (Init->isIntegerConstantExpr(Context, &Loc))
6853         ; // Ok, it's an ICE!
6854       else if (Init->isEvaluatable(Context)) {
6855         // If we can constant fold the initializer through heroics, accept it,
6856         // but report this as a use of an extension for -pedantic.
6857         Diag(Loc, diag::ext_in_class_initializer_non_constant)
6858           << Init->getSourceRange();
6859       } else {
6860         // Otherwise, this is some crazy unknown case.  Report the issue at the
6861         // location provided by the isIntegerConstantExpr failed check.
6862         Diag(Loc, diag::err_in_class_initializer_non_constant)
6863           << Init->getSourceRange();
6864         VDecl->setInvalidDecl();
6865       }
6866 
6867     // We allow foldable floating-point constants as an extension.
6868     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6869       Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6870         << DclT << Init->getSourceRange();
6871       if (getLangOpts().CPlusPlus0x)
6872         Diag(VDecl->getLocation(),
6873              diag::note_in_class_initializer_float_type_constexpr)
6874           << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6875 
6876       if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6877         Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6878           << Init->getSourceRange();
6879         VDecl->setInvalidDecl();
6880       }
6881 
6882     // Suggest adding 'constexpr' in C++11 for literal types.
6883     } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6884       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6885         << DclT << Init->getSourceRange()
6886         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6887       VDecl->setConstexpr(true);
6888 
6889     } else {
6890       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6891         << DclT << Init->getSourceRange();
6892       VDecl->setInvalidDecl();
6893     }
6894   } else if (VDecl->isFileVarDecl()) {
6895     if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6896         (!getLangOpts().CPlusPlus ||
6897          !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6898       Diag(VDecl->getLocation(), diag::warn_extern_init);
6899 
6900     // C99 6.7.8p4. All file scoped initializers need to be constant.
6901     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6902       CheckForConstantInitializer(Init, DclT);
6903   }
6904 
6905   // We will represent direct-initialization similarly to copy-initialization:
6906   //    int x(1);  -as-> int x = 1;
6907   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6908   //
6909   // Clients that want to distinguish between the two forms, can check for
6910   // direct initializer using VarDecl::getInitStyle().
6911   // A major benefit is that clients that don't particularly care about which
6912   // exactly form was it (like the CodeGen) can handle both cases without
6913   // special case code.
6914 
6915   // C++ 8.5p11:
6916   // The form of initialization (using parentheses or '=') is generally
6917   // insignificant, but does matter when the entity being initialized has a
6918   // class type.
6919   if (CXXDirectInit) {
6920     assert(DirectInit && "Call-style initializer must be direct init.");
6921     VDecl->setInitStyle(VarDecl::CallInit);
6922   } else if (DirectInit) {
6923     // This must be list-initialization. No other way is direct-initialization.
6924     VDecl->setInitStyle(VarDecl::ListInit);
6925   }
6926 
6927   CheckCompleteVariableDeclaration(VDecl);
6928 }
6929 
6930 /// ActOnInitializerError - Given that there was an error parsing an
6931 /// initializer for the given declaration, try to return to some form
6932 /// of sanity.
6933 void Sema::ActOnInitializerError(Decl *D) {
6934   // Our main concern here is re-establishing invariants like "a
6935   // variable's type is either dependent or complete".
6936   if (!D || D->isInvalidDecl()) return;
6937 
6938   VarDecl *VD = dyn_cast<VarDecl>(D);
6939   if (!VD) return;
6940 
6941   // Auto types are meaningless if we can't make sense of the initializer.
6942   if (ParsingInitForAutoVars.count(D)) {
6943     D->setInvalidDecl();
6944     return;
6945   }
6946 
6947   QualType Ty = VD->getType();
6948   if (Ty->isDependentType()) return;
6949 
6950   // Require a complete type.
6951   if (RequireCompleteType(VD->getLocation(),
6952                           Context.getBaseElementType(Ty),
6953                           diag::err_typecheck_decl_incomplete_type)) {
6954     VD->setInvalidDecl();
6955     return;
6956   }
6957 
6958   // Require an abstract type.
6959   if (RequireNonAbstractType(VD->getLocation(), Ty,
6960                              diag::err_abstract_type_in_decl,
6961                              AbstractVariableType)) {
6962     VD->setInvalidDecl();
6963     return;
6964   }
6965 
6966   // Don't bother complaining about constructors or destructors,
6967   // though.
6968 }
6969 
6970 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6971                                   bool TypeMayContainAuto) {
6972   // If there is no declaration, there was an error parsing it. Just ignore it.
6973   if (RealDecl == 0)
6974     return;
6975 
6976   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6977     QualType Type = Var->getType();
6978 
6979     // C++11 [dcl.spec.auto]p3
6980     if (TypeMayContainAuto && Type->getContainedAutoType()) {
6981       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6982         << Var->getDeclName() << Type;
6983       Var->setInvalidDecl();
6984       return;
6985     }
6986 
6987     // C++11 [class.static.data]p3: A static data member can be declared with
6988     // the constexpr specifier; if so, its declaration shall specify
6989     // a brace-or-equal-initializer.
6990     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6991     // the definition of a variable [...] or the declaration of a static data
6992     // member.
6993     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6994       if (Var->isStaticDataMember())
6995         Diag(Var->getLocation(),
6996              diag::err_constexpr_static_mem_var_requires_init)
6997           << Var->getDeclName();
6998       else
6999         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
7000       Var->setInvalidDecl();
7001       return;
7002     }
7003 
7004     switch (Var->isThisDeclarationADefinition()) {
7005     case VarDecl::Definition:
7006       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
7007         break;
7008 
7009       // We have an out-of-line definition of a static data member
7010       // that has an in-class initializer, so we type-check this like
7011       // a declaration.
7012       //
7013       // Fall through
7014 
7015     case VarDecl::DeclarationOnly:
7016       // It's only a declaration.
7017 
7018       // Block scope. C99 6.7p7: If an identifier for an object is
7019       // declared with no linkage (C99 6.2.2p6), the type for the
7020       // object shall be complete.
7021       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
7022           !Var->getLinkage() && !Var->isInvalidDecl() &&
7023           RequireCompleteType(Var->getLocation(), Type,
7024                               diag::err_typecheck_decl_incomplete_type))
7025         Var->setInvalidDecl();
7026 
7027       // Make sure that the type is not abstract.
7028       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7029           RequireNonAbstractType(Var->getLocation(), Type,
7030                                  diag::err_abstract_type_in_decl,
7031                                  AbstractVariableType))
7032         Var->setInvalidDecl();
7033       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7034           Var->getStorageClass() == SC_PrivateExtern) {
7035         Diag(Var->getLocation(), diag::warn_private_extern);
7036         Diag(Var->getLocation(), diag::note_private_extern);
7037       }
7038 
7039       return;
7040 
7041     case VarDecl::TentativeDefinition:
7042       // File scope. C99 6.9.2p2: A declaration of an identifier for an
7043       // object that has file scope without an initializer, and without a
7044       // storage-class specifier or with the storage-class specifier "static",
7045       // constitutes a tentative definition. Note: A tentative definition with
7046       // external linkage is valid (C99 6.2.2p5).
7047       if (!Var->isInvalidDecl()) {
7048         if (const IncompleteArrayType *ArrayT
7049                                     = Context.getAsIncompleteArrayType(Type)) {
7050           if (RequireCompleteType(Var->getLocation(),
7051                                   ArrayT->getElementType(),
7052                                   diag::err_illegal_decl_array_incomplete_type))
7053             Var->setInvalidDecl();
7054         } else if (Var->getStorageClass() == SC_Static) {
7055           // C99 6.9.2p3: If the declaration of an identifier for an object is
7056           // a tentative definition and has internal linkage (C99 6.2.2p3), the
7057           // declared type shall not be an incomplete type.
7058           // NOTE: code such as the following
7059           //     static struct s;
7060           //     struct s { int a; };
7061           // is accepted by gcc. Hence here we issue a warning instead of
7062           // an error and we do not invalidate the static declaration.
7063           // NOTE: to avoid multiple warnings, only check the first declaration.
7064           if (Var->getPreviousDecl() == 0)
7065             RequireCompleteType(Var->getLocation(), Type,
7066                                 diag::ext_typecheck_decl_incomplete_type);
7067         }
7068       }
7069 
7070       // Record the tentative definition; we're done.
7071       if (!Var->isInvalidDecl())
7072         TentativeDefinitions.push_back(Var);
7073       return;
7074     }
7075 
7076     // Provide a specific diagnostic for uninitialized variable
7077     // definitions with incomplete array type.
7078     if (Type->isIncompleteArrayType()) {
7079       Diag(Var->getLocation(),
7080            diag::err_typecheck_incomplete_array_needs_initializer);
7081       Var->setInvalidDecl();
7082       return;
7083     }
7084 
7085     // Provide a specific diagnostic for uninitialized variable
7086     // definitions with reference type.
7087     if (Type->isReferenceType()) {
7088       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7089         << Var->getDeclName()
7090         << SourceRange(Var->getLocation(), Var->getLocation());
7091       Var->setInvalidDecl();
7092       return;
7093     }
7094 
7095     // Do not attempt to type-check the default initializer for a
7096     // variable with dependent type.
7097     if (Type->isDependentType())
7098       return;
7099 
7100     if (Var->isInvalidDecl())
7101       return;
7102 
7103     if (RequireCompleteType(Var->getLocation(),
7104                             Context.getBaseElementType(Type),
7105                             diag::err_typecheck_decl_incomplete_type)) {
7106       Var->setInvalidDecl();
7107       return;
7108     }
7109 
7110     // The variable can not have an abstract class type.
7111     if (RequireNonAbstractType(Var->getLocation(), Type,
7112                                diag::err_abstract_type_in_decl,
7113                                AbstractVariableType)) {
7114       Var->setInvalidDecl();
7115       return;
7116     }
7117 
7118     // Check for jumps past the implicit initializer.  C++0x
7119     // clarifies that this applies to a "variable with automatic
7120     // storage duration", not a "local variable".
7121     // C++11 [stmt.dcl]p3
7122     //   A program that jumps from a point where a variable with automatic
7123     //   storage duration is not in scope to a point where it is in scope is
7124     //   ill-formed unless the variable has scalar type, class type with a
7125     //   trivial default constructor and a trivial destructor, a cv-qualified
7126     //   version of one of these types, or an array of one of the preceding
7127     //   types and is declared without an initializer.
7128     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
7129       if (const RecordType *Record
7130             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
7131         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
7132         // Mark the function for further checking even if the looser rules of
7133         // C++11 do not require such checks, so that we can diagnose
7134         // incompatibilities with C++98.
7135         if (!CXXRecord->isPOD())
7136           getCurFunction()->setHasBranchProtectedScope();
7137       }
7138     }
7139 
7140     // C++03 [dcl.init]p9:
7141     //   If no initializer is specified for an object, and the
7142     //   object is of (possibly cv-qualified) non-POD class type (or
7143     //   array thereof), the object shall be default-initialized; if
7144     //   the object is of const-qualified type, the underlying class
7145     //   type shall have a user-declared default
7146     //   constructor. Otherwise, if no initializer is specified for
7147     //   a non- static object, the object and its subobjects, if
7148     //   any, have an indeterminate initial value); if the object
7149     //   or any of its subobjects are of const-qualified type, the
7150     //   program is ill-formed.
7151     // C++0x [dcl.init]p11:
7152     //   If no initializer is specified for an object, the object is
7153     //   default-initialized; [...].
7154     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7155     InitializationKind Kind
7156       = InitializationKind::CreateDefault(Var->getLocation());
7157 
7158     InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
7159     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
7160     if (Init.isInvalid())
7161       Var->setInvalidDecl();
7162     else if (Init.get()) {
7163       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
7164       // This is important for template substitution.
7165       Var->setInitStyle(VarDecl::CallInit);
7166     }
7167 
7168     CheckCompleteVariableDeclaration(Var);
7169   }
7170 }
7171 
7172 void Sema::ActOnCXXForRangeDecl(Decl *D) {
7173   VarDecl *VD = dyn_cast<VarDecl>(D);
7174   if (!VD) {
7175     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7176     D->setInvalidDecl();
7177     return;
7178   }
7179 
7180   VD->setCXXForRangeDecl(true);
7181 
7182   // for-range-declaration cannot be given a storage class specifier.
7183   int Error = -1;
7184   switch (VD->getStorageClassAsWritten()) {
7185   case SC_None:
7186     break;
7187   case SC_Extern:
7188     Error = 0;
7189     break;
7190   case SC_Static:
7191     Error = 1;
7192     break;
7193   case SC_PrivateExtern:
7194     Error = 2;
7195     break;
7196   case SC_Auto:
7197     Error = 3;
7198     break;
7199   case SC_Register:
7200     Error = 4;
7201     break;
7202   case SC_OpenCLWorkGroupLocal:
7203     llvm_unreachable("Unexpected storage class");
7204   }
7205   if (VD->isConstexpr())
7206     Error = 5;
7207   if (Error != -1) {
7208     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7209       << VD->getDeclName() << Error;
7210     D->setInvalidDecl();
7211   }
7212 }
7213 
7214 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7215   if (var->isInvalidDecl()) return;
7216 
7217   // In ARC, don't allow jumps past the implicit initialization of a
7218   // local retaining variable.
7219   if (getLangOpts().ObjCAutoRefCount &&
7220       var->hasLocalStorage()) {
7221     switch (var->getType().getObjCLifetime()) {
7222     case Qualifiers::OCL_None:
7223     case Qualifiers::OCL_ExplicitNone:
7224     case Qualifiers::OCL_Autoreleasing:
7225       break;
7226 
7227     case Qualifiers::OCL_Weak:
7228     case Qualifiers::OCL_Strong:
7229       getCurFunction()->setHasBranchProtectedScope();
7230       break;
7231     }
7232   }
7233 
7234   if (var->isThisDeclarationADefinition() &&
7235       var->getLinkage() == ExternalLinkage) {
7236     // Find a previous declaration that's not a definition.
7237     VarDecl *prev = var->getPreviousDecl();
7238     while (prev && prev->isThisDeclarationADefinition())
7239       prev = prev->getPreviousDecl();
7240 
7241     if (!prev)
7242       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7243   }
7244 
7245   // All the following checks are C++ only.
7246   if (!getLangOpts().CPlusPlus) return;
7247 
7248   QualType type = var->getType();
7249   if (type->isDependentType()) return;
7250 
7251   // __block variables might require us to capture a copy-initializer.
7252   if (var->hasAttr<BlocksAttr>()) {
7253     // It's currently invalid to ever have a __block variable with an
7254     // array type; should we diagnose that here?
7255 
7256     // Regardless, we don't want to ignore array nesting when
7257     // constructing this copy.
7258     if (type->isStructureOrClassType()) {
7259       SourceLocation poi = var->getLocation();
7260       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
7261       ExprResult result =
7262         PerformCopyInitialization(
7263                         InitializedEntity::InitializeBlock(poi, type, false),
7264                                   poi, Owned(varRef));
7265       if (!result.isInvalid()) {
7266         result = MaybeCreateExprWithCleanups(result);
7267         Expr *init = result.takeAs<Expr>();
7268         Context.setBlockVarCopyInits(var, init);
7269       }
7270     }
7271   }
7272 
7273   Expr *Init = var->getInit();
7274   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7275   QualType baseType = Context.getBaseElementType(type);
7276 
7277   if (!var->getDeclContext()->isDependentContext() &&
7278       Init && !Init->isValueDependent()) {
7279     if (IsGlobal && !var->isConstexpr() &&
7280         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7281                                             var->getLocation())
7282           != DiagnosticsEngine::Ignored &&
7283         !Init->isConstantInitializer(Context, baseType->isReferenceType()))
7284       Diag(var->getLocation(), diag::warn_global_constructor)
7285         << Init->getSourceRange();
7286 
7287     if (var->isConstexpr()) {
7288       llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7289       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7290         SourceLocation DiagLoc = var->getLocation();
7291         // If the note doesn't add any useful information other than a source
7292         // location, fold it into the primary diagnostic.
7293         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7294               diag::note_invalid_subexpr_in_const_expr) {
7295           DiagLoc = Notes[0].first;
7296           Notes.clear();
7297         }
7298         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7299           << var << Init->getSourceRange();
7300         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7301           Diag(Notes[I].first, Notes[I].second);
7302       }
7303     } else if (var->isUsableInConstantExpressions(Context)) {
7304       // Check whether the initializer of a const variable of integral or
7305       // enumeration type is an ICE now, since we can't tell whether it was
7306       // initialized by a constant expression if we check later.
7307       var->checkInitIsICE();
7308     }
7309   }
7310 
7311   // Require the destructor.
7312   if (const RecordType *recordType = baseType->getAs<RecordType>())
7313     FinalizeVarWithDestructor(var, recordType);
7314 }
7315 
7316 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7317 /// any semantic actions necessary after any initializer has been attached.
7318 void
7319 Sema::FinalizeDeclaration(Decl *ThisDecl) {
7320   // Note that we are no longer parsing the initializer for this declaration.
7321   ParsingInitForAutoVars.erase(ThisDecl);
7322 
7323   // Now we have parsed the initializer and can update the table of magic
7324   // tag values.
7325   if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
7326     const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
7327     if (VD && VD->getType()->isIntegralOrEnumerationType()) {
7328       for (specific_attr_iterator<TypeTagForDatatypeAttr>
7329                I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
7330                E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
7331            I != E; ++I) {
7332         const Expr *MagicValueExpr = VD->getInit();
7333         if (!MagicValueExpr) {
7334           continue;
7335         }
7336         llvm::APSInt MagicValueInt;
7337         if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
7338           Diag(I->getRange().getBegin(),
7339                diag::err_type_tag_for_datatype_not_ice)
7340             << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7341           continue;
7342         }
7343         if (MagicValueInt.getActiveBits() > 64) {
7344           Diag(I->getRange().getBegin(),
7345                diag::err_type_tag_for_datatype_too_large)
7346             << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7347           continue;
7348         }
7349         uint64_t MagicValue = MagicValueInt.getZExtValue();
7350         RegisterTypeTagForDatatype(I->getArgumentKind(),
7351                                    MagicValue,
7352                                    I->getMatchingCType(),
7353                                    I->getLayoutCompatible(),
7354                                    I->getMustBeNull());
7355       }
7356     }
7357   }
7358 }
7359 
7360 Sema::DeclGroupPtrTy
7361 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7362                               Decl **Group, unsigned NumDecls) {
7363   SmallVector<Decl*, 8> Decls;
7364 
7365   if (DS.isTypeSpecOwned())
7366     Decls.push_back(DS.getRepAsDecl());
7367 
7368   for (unsigned i = 0; i != NumDecls; ++i)
7369     if (Decl *D = Group[i])
7370       Decls.push_back(D);
7371 
7372   if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
7373     if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
7374       getASTContext().addUnnamedTag(Tag);
7375 
7376   return BuildDeclaratorGroup(Decls.data(), Decls.size(),
7377                               DS.getTypeSpecType() == DeclSpec::TST_auto);
7378 }
7379 
7380 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
7381 /// group, performing any necessary semantic checking.
7382 Sema::DeclGroupPtrTy
7383 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7384                            bool TypeMayContainAuto) {
7385   // C++0x [dcl.spec.auto]p7:
7386   //   If the type deduced for the template parameter U is not the same in each
7387   //   deduction, the program is ill-formed.
7388   // FIXME: When initializer-list support is added, a distinction is needed
7389   // between the deduced type U and the deduced type which 'auto' stands for.
7390   //   auto a = 0, b = { 1, 2, 3 };
7391   // is legal because the deduced type U is 'int' in both cases.
7392   if (TypeMayContainAuto && NumDecls > 1) {
7393     QualType Deduced;
7394     CanQualType DeducedCanon;
7395     VarDecl *DeducedDecl = 0;
7396     for (unsigned i = 0; i != NumDecls; ++i) {
7397       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7398         AutoType *AT = D->getType()->getContainedAutoType();
7399         // Don't reissue diagnostics when instantiating a template.
7400         if (AT && D->isInvalidDecl())
7401           break;
7402         if (AT && AT->isDeduced()) {
7403           QualType U = AT->getDeducedType();
7404           CanQualType UCanon = Context.getCanonicalType(U);
7405           if (Deduced.isNull()) {
7406             Deduced = U;
7407             DeducedCanon = UCanon;
7408             DeducedDecl = D;
7409           } else if (DeducedCanon != UCanon) {
7410             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7411                  diag::err_auto_different_deductions)
7412               << Deduced << DeducedDecl->getDeclName()
7413               << U << D->getDeclName()
7414               << DeducedDecl->getInit()->getSourceRange()
7415               << D->getInit()->getSourceRange();
7416             D->setInvalidDecl();
7417             break;
7418           }
7419         }
7420       }
7421     }
7422   }
7423 
7424   ActOnDocumentableDecls(Group, NumDecls);
7425 
7426   return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
7427 }
7428 
7429 void Sema::ActOnDocumentableDecl(Decl *D) {
7430   ActOnDocumentableDecls(&D, 1);
7431 }
7432 
7433 void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7434   // Don't parse the comment if Doxygen diagnostics are ignored.
7435   if (NumDecls == 0 || !Group[0])
7436    return;
7437 
7438   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7439                                Group[0]->getLocation())
7440         == DiagnosticsEngine::Ignored)
7441     return;
7442 
7443   if (NumDecls >= 2) {
7444     // This is a decl group.  Normally it will contain only declarations
7445     // procuded from declarator list.  But in case we have any definitions or
7446     // additional declaration references:
7447     //   'typedef struct S {} S;'
7448     //   'typedef struct S *S;'
7449     //   'struct S *pS;'
7450     // FinalizeDeclaratorGroup adds these as separate declarations.
7451     Decl *MaybeTagDecl = Group[0];
7452     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7453       Group++;
7454       NumDecls--;
7455     }
7456   }
7457 
7458   // See if there are any new comments that are not attached to a decl.
7459   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7460   if (!Comments.empty() &&
7461       !Comments.back()->isAttached()) {
7462     // There is at least one comment that not attached to a decl.
7463     // Maybe it should be attached to one of these decls?
7464     //
7465     // Note that this way we pick up not only comments that precede the
7466     // declaration, but also comments that *follow* the declaration -- thanks to
7467     // the lookahead in the lexer: we've consumed the semicolon and looked
7468     // ahead through comments.
7469     for (unsigned i = 0; i != NumDecls; ++i)
7470       Context.getCommentForDecl(Group[i], &PP);
7471   }
7472 }
7473 
7474 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7475 /// to introduce parameters into function prototype scope.
7476 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
7477   const DeclSpec &DS = D.getDeclSpec();
7478 
7479   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
7480   // C++03 [dcl.stc]p2 also permits 'auto'.
7481   VarDecl::StorageClass StorageClass = SC_None;
7482   VarDecl::StorageClass StorageClassAsWritten = SC_None;
7483   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
7484     StorageClass = SC_Register;
7485     StorageClassAsWritten = SC_Register;
7486   } else if (getLangOpts().CPlusPlus &&
7487              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7488     StorageClass = SC_Auto;
7489     StorageClassAsWritten = SC_Auto;
7490   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
7491     Diag(DS.getStorageClassSpecLoc(),
7492          diag::err_invalid_storage_class_in_func_decl);
7493     D.getMutableDeclSpec().ClearStorageClassSpecs();
7494   }
7495 
7496   if (D.getDeclSpec().isThreadSpecified())
7497     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
7498   if (D.getDeclSpec().isConstexprSpecified())
7499     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7500       << 0;
7501 
7502   DiagnoseFunctionSpecifiers(D);
7503 
7504   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7505   QualType parmDeclType = TInfo->getType();
7506 
7507   if (getLangOpts().CPlusPlus) {
7508     // Check that there are no default arguments inside the type of this
7509     // parameter.
7510     CheckExtraCXXDefaultArguments(D);
7511 
7512     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7513     if (D.getCXXScopeSpec().isSet()) {
7514       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7515         << D.getCXXScopeSpec().getRange();
7516       D.getCXXScopeSpec().clear();
7517     }
7518   }
7519 
7520   // Ensure we have a valid name
7521   IdentifierInfo *II = 0;
7522   if (D.hasName()) {
7523     II = D.getIdentifier();
7524     if (!II) {
7525       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7526         << GetNameForDeclarator(D).getName().getAsString();
7527       D.setInvalidType(true);
7528     }
7529   }
7530 
7531   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
7532   if (II) {
7533     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7534                    ForRedeclaration);
7535     LookupName(R, S);
7536     if (R.isSingleResult()) {
7537       NamedDecl *PrevDecl = R.getFoundDecl();
7538       if (PrevDecl->isTemplateParameter()) {
7539         // Maybe we will complain about the shadowed template parameter.
7540         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7541         // Just pretend that we didn't see the previous declaration.
7542         PrevDecl = 0;
7543       } else if (S->isDeclScope(PrevDecl)) {
7544         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
7545         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7546 
7547         // Recover by removing the name
7548         II = 0;
7549         D.SetIdentifier(0, D.getIdentifierLoc());
7550         D.setInvalidType(true);
7551       }
7552     }
7553   }
7554 
7555   // Temporarily put parameter variables in the translation unit, not
7556   // the enclosing context.  This prevents them from accidentally
7557   // looking like class members in C++.
7558   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
7559                                     D.getLocStart(),
7560                                     D.getIdentifierLoc(), II,
7561                                     parmDeclType, TInfo,
7562                                     StorageClass, StorageClassAsWritten);
7563 
7564   if (D.isInvalidType())
7565     New->setInvalidDecl();
7566 
7567   assert(S->isFunctionPrototypeScope());
7568   assert(S->getFunctionPrototypeDepth() >= 1);
7569   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7570                     S->getNextFunctionPrototypeIndex());
7571 
7572   // Add the parameter declaration into this scope.
7573   S->AddDecl(New);
7574   if (II)
7575     IdResolver.AddDecl(New);
7576 
7577   ProcessDeclAttributes(S, New, D);
7578 
7579   if (D.getDeclSpec().isModulePrivateSpecified())
7580     Diag(New->getLocation(), diag::err_module_private_local)
7581       << 1 << New->getDeclName()
7582       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7583       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7584 
7585   if (New->hasAttr<BlocksAttr>()) {
7586     Diag(New->getLocation(), diag::err_block_on_nonlocal);
7587   }
7588   return New;
7589 }
7590 
7591 /// \brief Synthesizes a variable for a parameter arising from a
7592 /// typedef.
7593 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7594                                               SourceLocation Loc,
7595                                               QualType T) {
7596   /* FIXME: setting StartLoc == Loc.
7597      Would it be worth to modify callers so as to provide proper source
7598      location for the unnamed parameters, embedding the parameter's type? */
7599   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7600                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
7601                                            SC_None, SC_None, 0);
7602   Param->setImplicit();
7603   return Param;
7604 }
7605 
7606 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7607                                     ParmVarDecl * const *ParamEnd) {
7608   // Don't diagnose unused-parameter errors in template instantiations; we
7609   // will already have done so in the template itself.
7610   if (!ActiveTemplateInstantiations.empty())
7611     return;
7612 
7613   for (; Param != ParamEnd; ++Param) {
7614     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7615         !(*Param)->hasAttr<UnusedAttr>()) {
7616       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7617         << (*Param)->getDeclName();
7618     }
7619   }
7620 }
7621 
7622 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7623                                                   ParmVarDecl * const *ParamEnd,
7624                                                   QualType ReturnTy,
7625                                                   NamedDecl *D) {
7626   if (LangOpts.NumLargeByValueCopy == 0) // No check.
7627     return;
7628 
7629   // Warn if the return value is pass-by-value and larger than the specified
7630   // threshold.
7631   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7632     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7633     if (Size > LangOpts.NumLargeByValueCopy)
7634       Diag(D->getLocation(), diag::warn_return_value_size)
7635           << D->getDeclName() << Size;
7636   }
7637 
7638   // Warn if any parameter is pass-by-value and larger than the specified
7639   // threshold.
7640   for (; Param != ParamEnd; ++Param) {
7641     QualType T = (*Param)->getType();
7642     if (T->isDependentType() || !T.isPODType(Context))
7643       continue;
7644     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7645     if (Size > LangOpts.NumLargeByValueCopy)
7646       Diag((*Param)->getLocation(), diag::warn_parameter_size)
7647           << (*Param)->getDeclName() << Size;
7648   }
7649 }
7650 
7651 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7652                                   SourceLocation NameLoc, IdentifierInfo *Name,
7653                                   QualType T, TypeSourceInfo *TSInfo,
7654                                   VarDecl::StorageClass StorageClass,
7655                                   VarDecl::StorageClass StorageClassAsWritten) {
7656   // In ARC, infer a lifetime qualifier for appropriate parameter types.
7657   if (getLangOpts().ObjCAutoRefCount &&
7658       T.getObjCLifetime() == Qualifiers::OCL_None &&
7659       T->isObjCLifetimeType()) {
7660 
7661     Qualifiers::ObjCLifetime lifetime;
7662 
7663     // Special cases for arrays:
7664     //   - if it's const, use __unsafe_unretained
7665     //   - otherwise, it's an error
7666     if (T->isArrayType()) {
7667       if (!T.isConstQualified()) {
7668         DelayedDiagnostics.add(
7669             sema::DelayedDiagnostic::makeForbiddenType(
7670             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7671       }
7672       lifetime = Qualifiers::OCL_ExplicitNone;
7673     } else {
7674       lifetime = T->getObjCARCImplicitLifetime();
7675     }
7676     T = Context.getLifetimeQualifiedType(T, lifetime);
7677   }
7678 
7679   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7680                                          Context.getAdjustedParameterType(T),
7681                                          TSInfo,
7682                                          StorageClass, StorageClassAsWritten,
7683                                          0);
7684 
7685   // Parameters can not be abstract class types.
7686   // For record types, this is done by the AbstractClassUsageDiagnoser once
7687   // the class has been completely parsed.
7688   if (!CurContext->isRecord() &&
7689       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7690                              AbstractParamType))
7691     New->setInvalidDecl();
7692 
7693   // Parameter declarators cannot be interface types. All ObjC objects are
7694   // passed by reference.
7695   if (T->isObjCObjectType()) {
7696     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
7697     Diag(NameLoc,
7698          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7699       << FixItHint::CreateInsertion(TypeEndLoc, "*");
7700     T = Context.getObjCObjectPointerType(T);
7701     New->setType(T);
7702   }
7703 
7704   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7705   // duration shall not be qualified by an address-space qualifier."
7706   // Since all parameters have automatic store duration, they can not have
7707   // an address space.
7708   if (T.getAddressSpace() != 0) {
7709     Diag(NameLoc, diag::err_arg_with_address_space);
7710     New->setInvalidDecl();
7711   }
7712 
7713   return New;
7714 }
7715 
7716 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7717                                            SourceLocation LocAfterDecls) {
7718   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7719 
7720   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7721   // for a K&R function.
7722   if (!FTI.hasPrototype) {
7723     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7724       --i;
7725       if (FTI.ArgInfo[i].Param == 0) {
7726         SmallString<256> Code;
7727         llvm::raw_svector_ostream(Code) << "  int "
7728                                         << FTI.ArgInfo[i].Ident->getName()
7729                                         << ";\n";
7730         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7731           << FTI.ArgInfo[i].Ident
7732           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7733 
7734         // Implicitly declare the argument as type 'int' for lack of a better
7735         // type.
7736         AttributeFactory attrs;
7737         DeclSpec DS(attrs);
7738         const char* PrevSpec; // unused
7739         unsigned DiagID; // unused
7740         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7741                            PrevSpec, DiagID);
7742         // Use the identifier location for the type source range.
7743         DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
7744         DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
7745         Declarator ParamD(DS, Declarator::KNRTypeListContext);
7746         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7747         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7748       }
7749     }
7750   }
7751 }
7752 
7753 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
7754   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7755   assert(D.isFunctionDeclarator() && "Not a function declarator!");
7756   Scope *ParentScope = FnBodyScope->getParent();
7757 
7758   D.setFunctionDefinitionKind(FDK_Definition);
7759   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
7760   return ActOnStartOfFunctionDef(FnBodyScope, DP);
7761 }
7762 
7763 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7764   // Don't warn about invalid declarations.
7765   if (FD->isInvalidDecl())
7766     return false;
7767 
7768   // Or declarations that aren't global.
7769   if (!FD->isGlobal())
7770     return false;
7771 
7772   // Don't warn about C++ member functions.
7773   if (isa<CXXMethodDecl>(FD))
7774     return false;
7775 
7776   // Don't warn about 'main'.
7777   if (FD->isMain())
7778     return false;
7779 
7780   // Don't warn about inline functions.
7781   if (FD->isInlined())
7782     return false;
7783 
7784   // Don't warn about function templates.
7785   if (FD->getDescribedFunctionTemplate())
7786     return false;
7787 
7788   // Don't warn about function template specializations.
7789   if (FD->isFunctionTemplateSpecialization())
7790     return false;
7791 
7792   // Don't warn for OpenCL kernels.
7793   if (FD->hasAttr<OpenCLKernelAttr>())
7794     return false;
7795 
7796   bool MissingPrototype = true;
7797   for (const FunctionDecl *Prev = FD->getPreviousDecl();
7798        Prev; Prev = Prev->getPreviousDecl()) {
7799     // Ignore any declarations that occur in function or method
7800     // scope, because they aren't visible from the header.
7801     if (Prev->getDeclContext()->isFunctionOrMethod())
7802       continue;
7803 
7804     MissingPrototype = !Prev->getType()->isFunctionProtoType();
7805     break;
7806   }
7807 
7808   return MissingPrototype;
7809 }
7810 
7811 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7812   // Don't complain if we're in GNU89 mode and the previous definition
7813   // was an extern inline function.
7814   const FunctionDecl *Definition;
7815   if (FD->isDefined(Definition) &&
7816       !canRedefineFunction(Definition, getLangOpts())) {
7817     if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7818         Definition->getStorageClass() == SC_Extern)
7819       Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7820         << FD->getDeclName() << getLangOpts().CPlusPlus;
7821     else
7822       Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7823     Diag(Definition->getLocation(), diag::note_previous_definition);
7824     FD->setInvalidDecl();
7825   }
7826 }
7827 
7828 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7829   // Clear the last template instantiation error context.
7830   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7831 
7832   if (!D)
7833     return D;
7834   FunctionDecl *FD = 0;
7835 
7836   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7837     FD = FunTmpl->getTemplatedDecl();
7838   else
7839     FD = cast<FunctionDecl>(D);
7840 
7841   // Enter a new function scope
7842   PushFunctionScope();
7843 
7844   // See if this is a redefinition.
7845   if (!FD->isLateTemplateParsed())
7846     CheckForFunctionRedefinition(FD);
7847 
7848   // Builtin functions cannot be defined.
7849   if (unsigned BuiltinID = FD->getBuiltinID()) {
7850     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7851       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7852       FD->setInvalidDecl();
7853     }
7854   }
7855 
7856   // The return type of a function definition must be complete
7857   // (C99 6.9.1p3, C++ [dcl.fct]p6).
7858   QualType ResultType = FD->getResultType();
7859   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7860       !FD->isInvalidDecl() &&
7861       RequireCompleteType(FD->getLocation(), ResultType,
7862                           diag::err_func_def_incomplete_result))
7863     FD->setInvalidDecl();
7864 
7865   // GNU warning -Wmissing-prototypes:
7866   //   Warn if a global function is defined without a previous
7867   //   prototype declaration. This warning is issued even if the
7868   //   definition itself provides a prototype. The aim is to detect
7869   //   global functions that fail to be declared in header files.
7870   if (ShouldWarnAboutMissingPrototype(FD))
7871     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7872 
7873   if (FnBodyScope)
7874     PushDeclContext(FnBodyScope, FD);
7875 
7876   // Check the validity of our function parameters
7877   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7878                            /*CheckParameterNames=*/true);
7879 
7880   // Introduce our parameters into the function scope
7881   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7882     ParmVarDecl *Param = FD->getParamDecl(p);
7883     Param->setOwningFunction(FD);
7884 
7885     // If this has an identifier, add it to the scope stack.
7886     if (Param->getIdentifier() && FnBodyScope) {
7887       CheckShadow(FnBodyScope, Param);
7888 
7889       PushOnScopeChains(Param, FnBodyScope);
7890     }
7891   }
7892 
7893   // If we had any tags defined in the function prototype,
7894   // introduce them into the function scope.
7895   if (FnBodyScope) {
7896     for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7897            E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7898       NamedDecl *D = *I;
7899 
7900       // Some of these decls (like enums) may have been pinned to the translation unit
7901       // for lack of a real context earlier. If so, remove from the translation unit
7902       // and reattach to the current context.
7903       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7904         // Is the decl actually in the context?
7905         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7906                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7907           if (*DI == D) {
7908             Context.getTranslationUnitDecl()->removeDecl(D);
7909             break;
7910           }
7911         }
7912         // Either way, reassign the lexical decl context to our FunctionDecl.
7913         D->setLexicalDeclContext(CurContext);
7914       }
7915 
7916       // If the decl has a non-null name, make accessible in the current scope.
7917       if (!D->getName().empty())
7918         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7919 
7920       // Similarly, dive into enums and fish their constants out, making them
7921       // accessible in this scope.
7922       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7923         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7924                EE = ED->enumerator_end(); EI != EE; ++EI)
7925           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7926       }
7927     }
7928   }
7929 
7930   // Ensure that the function's exception specification is instantiated.
7931   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7932     ResolveExceptionSpec(D->getLocation(), FPT);
7933 
7934   // Checking attributes of current function definition
7935   // dllimport attribute.
7936   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7937   if (DA && (!FD->getAttr<DLLExportAttr>())) {
7938     // dllimport attribute cannot be directly applied to definition.
7939     // Microsoft accepts dllimport for functions defined within class scope.
7940     if (!DA->isInherited() &&
7941         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7942       Diag(FD->getLocation(),
7943            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7944         << "dllimport";
7945       FD->setInvalidDecl();
7946       return FD;
7947     }
7948 
7949     // Visual C++ appears to not think this is an issue, so only issue
7950     // a warning when Microsoft extensions are disabled.
7951     if (!LangOpts.MicrosoftExt) {
7952       // If a symbol previously declared dllimport is later defined, the
7953       // attribute is ignored in subsequent references, and a warning is
7954       // emitted.
7955       Diag(FD->getLocation(),
7956            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7957         << FD->getName() << "dllimport";
7958     }
7959   }
7960   // We want to attach documentation to original Decl (which might be
7961   // a function template).
7962   ActOnDocumentableDecl(D);
7963   return FD;
7964 }
7965 
7966 /// \brief Given the set of return statements within a function body,
7967 /// compute the variables that are subject to the named return value
7968 /// optimization.
7969 ///
7970 /// Each of the variables that is subject to the named return value
7971 /// optimization will be marked as NRVO variables in the AST, and any
7972 /// return statement that has a marked NRVO variable as its NRVO candidate can
7973 /// use the named return value optimization.
7974 ///
7975 /// This function applies a very simplistic algorithm for NRVO: if every return
7976 /// statement in the function has the same NRVO candidate, that candidate is
7977 /// the NRVO variable.
7978 ///
7979 /// FIXME: Employ a smarter algorithm that accounts for multiple return
7980 /// statements and the lifetimes of the NRVO candidates. We should be able to
7981 /// find a maximal set of NRVO variables.
7982 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7983   ReturnStmt **Returns = Scope->Returns.data();
7984 
7985   const VarDecl *NRVOCandidate = 0;
7986   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7987     if (!Returns[I]->getNRVOCandidate())
7988       return;
7989 
7990     if (!NRVOCandidate)
7991       NRVOCandidate = Returns[I]->getNRVOCandidate();
7992     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7993       return;
7994   }
7995 
7996   if (NRVOCandidate)
7997     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7998 }
7999 
8000 bool Sema::canSkipFunctionBody(Decl *D) {
8001   if (!Consumer.shouldSkipFunctionBody(D))
8002     return false;
8003 
8004   if (isa<ObjCMethodDecl>(D))
8005     return true;
8006 
8007   FunctionDecl *FD = 0;
8008   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
8009     FD = FTD->getTemplatedDecl();
8010   else
8011     FD = cast<FunctionDecl>(D);
8012 
8013   // We cannot skip the body of a function (or function template) which is
8014   // constexpr, since we may need to evaluate its body in order to parse the
8015   // rest of the file.
8016   return !FD->isConstexpr();
8017 }
8018 
8019 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
8020   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
8021     FD->setHasSkippedBody();
8022   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
8023     MD->setHasSkippedBody();
8024   return ActOnFinishFunctionBody(Decl, 0);
8025 }
8026 
8027 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
8028   return ActOnFinishFunctionBody(D, BodyArg, false);
8029 }
8030 
8031 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
8032                                     bool IsInstantiation) {
8033   FunctionDecl *FD = 0;
8034   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
8035   if (FunTmpl)
8036     FD = FunTmpl->getTemplatedDecl();
8037   else
8038     FD = dyn_cast_or_null<FunctionDecl>(dcl);
8039 
8040   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
8041   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
8042 
8043   if (FD) {
8044     FD->setBody(Body);
8045 
8046     // If the function implicitly returns zero (like 'main') or is naked,
8047     // don't complain about missing return statements.
8048     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
8049       WP.disableCheckFallThrough();
8050 
8051     // MSVC permits the use of pure specifier (=0) on function definition,
8052     // defined at class scope, warn about this non standard construct.
8053     if (getLangOpts().MicrosoftExt && FD->isPure())
8054       Diag(FD->getLocation(), diag::warn_pure_function_definition);
8055 
8056     if (!FD->isInvalidDecl()) {
8057       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
8058       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8059                                              FD->getResultType(), FD);
8060 
8061       // If this is a constructor, we need a vtable.
8062       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8063         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
8064 
8065       // Try to apply the named return value optimization. We have to check
8066       // if we can do this here because lambdas keep return statements around
8067       // to deduce an implicit return type.
8068       if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8069           !FD->isDependentContext())
8070         computeNRVO(Body, getCurFunction());
8071     }
8072 
8073     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8074            "Function parsing confused");
8075   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
8076     assert(MD == getCurMethodDecl() && "Method parsing confused");
8077     MD->setBody(Body);
8078     if (!MD->isInvalidDecl()) {
8079       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
8080       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8081                                              MD->getResultType(), MD);
8082 
8083       if (Body)
8084         computeNRVO(Body, getCurFunction());
8085     }
8086     if (getCurFunction()->ObjCShouldCallSuper) {
8087       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8088         << MD->getSelector().getAsString();
8089       getCurFunction()->ObjCShouldCallSuper = false;
8090     }
8091   } else {
8092     return 0;
8093   }
8094 
8095   assert(!getCurFunction()->ObjCShouldCallSuper &&
8096          "This should only be set for ObjC methods, which should have been "
8097          "handled in the block above.");
8098 
8099   // Verify and clean out per-function state.
8100   if (Body) {
8101     // C++ constructors that have function-try-blocks can't have return
8102     // statements in the handlers of that block. (C++ [except.handle]p14)
8103     // Verify this.
8104     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8105       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8106 
8107     // Verify that gotos and switch cases don't jump into scopes illegally.
8108     if (getCurFunction()->NeedsScopeChecking() &&
8109         !dcl->isInvalidDecl() &&
8110         !hasAnyUnrecoverableErrorsInThisFunction() &&
8111         !PP.isCodeCompletionEnabled())
8112       DiagnoseInvalidJumps(Body);
8113 
8114     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8115       if (!Destructor->getParent()->isDependentType())
8116         CheckDestructor(Destructor);
8117 
8118       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8119                                              Destructor->getParent());
8120     }
8121 
8122     // If any errors have occurred, clear out any temporaries that may have
8123     // been leftover. This ensures that these temporaries won't be picked up for
8124     // deletion in some later function.
8125     if (PP.getDiagnostics().hasErrorOccurred() ||
8126         PP.getDiagnostics().getSuppressAllDiagnostics()) {
8127       DiscardCleanupsInEvaluationContext();
8128     } else if (!isa<FunctionTemplateDecl>(dcl)) {
8129       // Since the body is valid, issue any analysis-based warnings that are
8130       // enabled.
8131       ActivePolicy = &WP;
8132     }
8133 
8134     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8135         (!CheckConstexprFunctionDecl(FD) ||
8136          !CheckConstexprFunctionBody(FD, Body)))
8137       FD->setInvalidDecl();
8138 
8139     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
8140     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
8141     assert(MaybeODRUseExprs.empty() &&
8142            "Leftover expressions for odr-use checking");
8143   }
8144 
8145   if (!IsInstantiation)
8146     PopDeclContext();
8147 
8148   PopFunctionScopeInfo(ActivePolicy, dcl);
8149 
8150   // If any errors have occurred, clear out any temporaries that may have
8151   // been leftover. This ensures that these temporaries won't be picked up for
8152   // deletion in some later function.
8153   if (getDiagnostics().hasErrorOccurred()) {
8154     DiscardCleanupsInEvaluationContext();
8155   }
8156 
8157   return dcl;
8158 }
8159 
8160 
8161 /// When we finish delayed parsing of an attribute, we must attach it to the
8162 /// relevant Decl.
8163 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8164                                        ParsedAttributes &Attrs) {
8165   // Always attach attributes to the underlying decl.
8166   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8167     D = TD->getTemplatedDecl();
8168   ProcessDeclAttributeList(S, D, Attrs.getList());
8169 
8170   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8171     if (Method->isStatic())
8172       checkThisInStaticMemberFunctionAttributes(Method);
8173 }
8174 
8175 
8176 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8177 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
8178 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
8179                                           IdentifierInfo &II, Scope *S) {
8180   // Before we produce a declaration for an implicitly defined
8181   // function, see whether there was a locally-scoped declaration of
8182   // this name as a function or variable. If so, use that
8183   // (non-visible) declaration, and complain about it.
8184   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
8185     = findLocallyScopedExternalDecl(&II);
8186   if (Pos != LocallyScopedExternalDecls.end()) {
8187     Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8188     Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8189     return Pos->second;
8190   }
8191 
8192   // Extension in C99.  Legal in C90, but warn about it.
8193   unsigned diag_id;
8194   if (II.getName().startswith("__builtin_"))
8195     diag_id = diag::warn_builtin_unknown;
8196   else if (getLangOpts().C99)
8197     diag_id = diag::ext_implicit_function_decl;
8198   else
8199     diag_id = diag::warn_implicit_function_decl;
8200   Diag(Loc, diag_id) << &II;
8201 
8202   // Because typo correction is expensive, only do it if the implicit
8203   // function declaration is going to be treated as an error.
8204   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8205     TypoCorrection Corrected;
8206     DeclFilterCCC<FunctionDecl> Validator;
8207     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
8208                                       LookupOrdinaryName, S, 0, Validator))) {
8209       std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8210       std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
8211       FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
8212 
8213       Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8214           << FixItHint::CreateReplacement(Loc, CorrectedStr);
8215 
8216       if (Func->getLocation().isValid()
8217           && !II.getName().startswith("__builtin_"))
8218         Diag(Func->getLocation(), diag::note_previous_decl)
8219             << CorrectedQuotedStr;
8220     }
8221   }
8222 
8223   // Set a Declarator for the implicit definition: int foo();
8224   const char *Dummy;
8225   AttributeFactory attrFactory;
8226   DeclSpec DS(attrFactory);
8227   unsigned DiagID;
8228   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
8229   (void)Error; // Silence warning.
8230   assert(!Error && "Error setting up implicit decl!");
8231   SourceLocation NoLoc;
8232   Declarator D(DS, Declarator::BlockContext);
8233   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8234                                              /*IsAmbiguous=*/false,
8235                                              /*RParenLoc=*/NoLoc,
8236                                              /*ArgInfo=*/0,
8237                                              /*NumArgs=*/0,
8238                                              /*EllipsisLoc=*/NoLoc,
8239                                              /*RParenLoc=*/NoLoc,
8240                                              /*TypeQuals=*/0,
8241                                              /*RefQualifierIsLvalueRef=*/true,
8242                                              /*RefQualifierLoc=*/NoLoc,
8243                                              /*ConstQualifierLoc=*/NoLoc,
8244                                              /*VolatileQualifierLoc=*/NoLoc,
8245                                              /*MutableLoc=*/NoLoc,
8246                                              EST_None,
8247                                              /*ESpecLoc=*/NoLoc,
8248                                              /*Exceptions=*/0,
8249                                              /*ExceptionRanges=*/0,
8250                                              /*NumExceptions=*/0,
8251                                              /*NoexceptExpr=*/0,
8252                                              Loc, Loc, D),
8253                 DS.getAttributes(),
8254                 SourceLocation());
8255   D.SetIdentifier(&II, Loc);
8256 
8257   // Insert this function into translation-unit scope.
8258 
8259   DeclContext *PrevDC = CurContext;
8260   CurContext = Context.getTranslationUnitDecl();
8261 
8262   FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
8263   FD->setImplicit();
8264 
8265   CurContext = PrevDC;
8266 
8267   AddKnownFunctionAttributes(FD);
8268 
8269   return FD;
8270 }
8271 
8272 /// \brief Adds any function attributes that we know a priori based on
8273 /// the declaration of this function.
8274 ///
8275 /// These attributes can apply both to implicitly-declared builtins
8276 /// (like __builtin___printf_chk) or to library-declared functions
8277 /// like NSLog or printf.
8278 ///
8279 /// We need to check for duplicate attributes both here and where user-written
8280 /// attributes are applied to declarations.
8281 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8282   if (FD->isInvalidDecl())
8283     return;
8284 
8285   // If this is a built-in function, map its builtin attributes to
8286   // actual attributes.
8287   if (unsigned BuiltinID = FD->getBuiltinID()) {
8288     // Handle printf-formatting attributes.
8289     unsigned FormatIdx;
8290     bool HasVAListArg;
8291     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
8292       if (!FD->getAttr<FormatAttr>()) {
8293         const char *fmt = "printf";
8294         unsigned int NumParams = FD->getNumParams();
8295         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8296             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
8297           fmt = "NSString";
8298         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8299                                                fmt, FormatIdx+1,
8300                                                HasVAListArg ? 0 : FormatIdx+2));
8301       }
8302     }
8303     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
8304                                              HasVAListArg)) {
8305      if (!FD->getAttr<FormatAttr>())
8306        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8307                                               "scanf", FormatIdx+1,
8308                                               HasVAListArg ? 0 : FormatIdx+2));
8309     }
8310 
8311     // Mark const if we don't care about errno and that is the only
8312     // thing preventing the function from being const. This allows
8313     // IRgen to use LLVM intrinsics for such functions.
8314     if (!getLangOpts().MathErrno &&
8315         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
8316       if (!FD->getAttr<ConstAttr>())
8317         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8318     }
8319 
8320     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
8321         !FD->getAttr<ReturnsTwiceAttr>())
8322       FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
8323     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
8324       FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
8325     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
8326       FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8327   }
8328 
8329   IdentifierInfo *Name = FD->getIdentifier();
8330   if (!Name)
8331     return;
8332   if ((!getLangOpts().CPlusPlus &&
8333        FD->getDeclContext()->isTranslationUnit()) ||
8334       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
8335        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
8336        LinkageSpecDecl::lang_c)) {
8337     // Okay: this could be a libc/libm/Objective-C function we know
8338     // about.
8339   } else
8340     return;
8341 
8342   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
8343     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
8344     // target-specific builtins, perhaps?
8345     if (!FD->getAttr<FormatAttr>())
8346       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8347                                              "printf", 2,
8348                                              Name->isStr("vasprintf") ? 0 : 3));
8349   }
8350 
8351   if (Name->isStr("__CFStringMakeConstantString")) {
8352     // We already have a __builtin___CFStringMakeConstantString,
8353     // but builds that use -fno-constant-cfstrings don't go through that.
8354     if (!FD->getAttr<FormatArgAttr>())
8355       FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
8356   }
8357 }
8358 
8359 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
8360                                     TypeSourceInfo *TInfo) {
8361   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
8362   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
8363 
8364   if (!TInfo) {
8365     assert(D.isInvalidType() && "no declarator info for valid type");
8366     TInfo = Context.getTrivialTypeSourceInfo(T);
8367   }
8368 
8369   // Scope manipulation handled by caller.
8370   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
8371                                            D.getLocStart(),
8372                                            D.getIdentifierLoc(),
8373                                            D.getIdentifier(),
8374                                            TInfo);
8375 
8376   // Bail out immediately if we have an invalid declaration.
8377   if (D.isInvalidType()) {
8378     NewTD->setInvalidDecl();
8379     return NewTD;
8380   }
8381 
8382   if (D.getDeclSpec().isModulePrivateSpecified()) {
8383     if (CurContext->isFunctionOrMethod())
8384       Diag(NewTD->getLocation(), diag::err_module_private_local)
8385         << 2 << NewTD->getDeclName()
8386         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8387         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8388     else
8389       NewTD->setModulePrivate();
8390   }
8391 
8392   // C++ [dcl.typedef]p8:
8393   //   If the typedef declaration defines an unnamed class (or
8394   //   enum), the first typedef-name declared by the declaration
8395   //   to be that class type (or enum type) is used to denote the
8396   //   class type (or enum type) for linkage purposes only.
8397   // We need to check whether the type was declared in the declaration.
8398   switch (D.getDeclSpec().getTypeSpecType()) {
8399   case TST_enum:
8400   case TST_struct:
8401   case TST_interface:
8402   case TST_union:
8403   case TST_class: {
8404     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8405 
8406     // Do nothing if the tag is not anonymous or already has an
8407     // associated typedef (from an earlier typedef in this decl group).
8408     if (tagFromDeclSpec->getIdentifier()) break;
8409     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
8410 
8411     // A well-formed anonymous tag must always be a TUK_Definition.
8412     assert(tagFromDeclSpec->isThisDeclarationADefinition());
8413 
8414     // The type must match the tag exactly;  no qualifiers allowed.
8415     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8416       break;
8417 
8418     // Otherwise, set this is the anon-decl typedef for the tag.
8419     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
8420     break;
8421   }
8422 
8423   default:
8424     break;
8425   }
8426 
8427   return NewTD;
8428 }
8429 
8430 
8431 /// \brief Check that this is a valid underlying type for an enum declaration.
8432 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8433   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8434   QualType T = TI->getType();
8435 
8436   if (T->isDependentType() || T->isIntegralType(Context))
8437     return false;
8438 
8439   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8440   return true;
8441 }
8442 
8443 /// Check whether this is a valid redeclaration of a previous enumeration.
8444 /// \return true if the redeclaration was invalid.
8445 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8446                                   QualType EnumUnderlyingTy,
8447                                   const EnumDecl *Prev) {
8448   bool IsFixed = !EnumUnderlyingTy.isNull();
8449 
8450   if (IsScoped != Prev->isScoped()) {
8451     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8452       << Prev->isScoped();
8453     Diag(Prev->getLocation(), diag::note_previous_use);
8454     return true;
8455   }
8456 
8457   if (IsFixed && Prev->isFixed()) {
8458     if (!EnumUnderlyingTy->isDependentType() &&
8459         !Prev->getIntegerType()->isDependentType() &&
8460         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
8461                                         Prev->getIntegerType())) {
8462       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8463         << EnumUnderlyingTy << Prev->getIntegerType();
8464       Diag(Prev->getLocation(), diag::note_previous_use);
8465       return true;
8466     }
8467   } else if (IsFixed != Prev->isFixed()) {
8468     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8469       << Prev->isFixed();
8470     Diag(Prev->getLocation(), diag::note_previous_use);
8471     return true;
8472   }
8473 
8474   return false;
8475 }
8476 
8477 /// \brief Get diagnostic %select index for tag kind for
8478 /// redeclaration diagnostic message.
8479 /// WARNING: Indexes apply to particular diagnostics only!
8480 ///
8481 /// \returns diagnostic %select index.
8482 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
8483   switch (Tag) {
8484   case TTK_Struct: return 0;
8485   case TTK_Interface: return 1;
8486   case TTK_Class:  return 2;
8487   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
8488   }
8489 }
8490 
8491 /// \brief Determine if tag kind is a class-key compatible with
8492 /// class for redeclaration (class, struct, or __interface).
8493 ///
8494 /// \returns true iff the tag kind is compatible.
8495 static bool isClassCompatTagKind(TagTypeKind Tag)
8496 {
8497   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
8498 }
8499 
8500 /// \brief Determine whether a tag with a given kind is acceptable
8501 /// as a redeclaration of the given tag declaration.
8502 ///
8503 /// \returns true if the new tag kind is acceptable, false otherwise.
8504 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
8505                                         TagTypeKind NewTag, bool isDefinition,
8506                                         SourceLocation NewTagLoc,
8507                                         const IdentifierInfo &Name) {
8508   // C++ [dcl.type.elab]p3:
8509   //   The class-key or enum keyword present in the
8510   //   elaborated-type-specifier shall agree in kind with the
8511   //   declaration to which the name in the elaborated-type-specifier
8512   //   refers. This rule also applies to the form of
8513   //   elaborated-type-specifier that declares a class-name or
8514   //   friend class since it can be construed as referring to the
8515   //   definition of the class. Thus, in any
8516   //   elaborated-type-specifier, the enum keyword shall be used to
8517   //   refer to an enumeration (7.2), the union class-key shall be
8518   //   used to refer to a union (clause 9), and either the class or
8519   //   struct class-key shall be used to refer to a class (clause 9)
8520   //   declared using the class or struct class-key.
8521   TagTypeKind OldTag = Previous->getTagKind();
8522   if (!isDefinition || !isClassCompatTagKind(NewTag))
8523     if (OldTag == NewTag)
8524       return true;
8525 
8526   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
8527     // Warn about the struct/class tag mismatch.
8528     bool isTemplate = false;
8529     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8530       isTemplate = Record->getDescribedClassTemplate();
8531 
8532     if (!ActiveTemplateInstantiations.empty()) {
8533       // In a template instantiation, do not offer fix-its for tag mismatches
8534       // since they usually mess up the template instead of fixing the problem.
8535       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8536         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8537         << getRedeclDiagFromTagKind(OldTag);
8538       return true;
8539     }
8540 
8541     if (isDefinition) {
8542       // On definitions, check previous tags and issue a fix-it for each
8543       // one that doesn't match the current tag.
8544       if (Previous->getDefinition()) {
8545         // Don't suggest fix-its for redefinitions.
8546         return true;
8547       }
8548 
8549       bool previousMismatch = false;
8550       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8551            E(Previous->redecls_end()); I != E; ++I) {
8552         if (I->getTagKind() != NewTag) {
8553           if (!previousMismatch) {
8554             previousMismatch = true;
8555             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
8556               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8557               << getRedeclDiagFromTagKind(I->getTagKind());
8558           }
8559           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
8560             << getRedeclDiagFromTagKind(NewTag)
8561             << FixItHint::CreateReplacement(I->getInnerLocStart(),
8562                  TypeWithKeyword::getTagTypeKindName(NewTag));
8563         }
8564       }
8565       return true;
8566     }
8567 
8568     // Check for a previous definition.  If current tag and definition
8569     // are same type, do nothing.  If no definition, but disagree with
8570     // with previous tag type, give a warning, but no fix-it.
8571     const TagDecl *Redecl = Previous->getDefinition() ?
8572                             Previous->getDefinition() : Previous;
8573     if (Redecl->getTagKind() == NewTag) {
8574       return true;
8575     }
8576 
8577     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8578       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8579       << getRedeclDiagFromTagKind(OldTag);
8580     Diag(Redecl->getLocation(), diag::note_previous_use);
8581 
8582     // If there is a previous defintion, suggest a fix-it.
8583     if (Previous->getDefinition()) {
8584         Diag(NewTagLoc, diag::note_struct_class_suggestion)
8585           << getRedeclDiagFromTagKind(Redecl->getTagKind())
8586           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
8587                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
8588     }
8589 
8590     return true;
8591   }
8592   return false;
8593 }
8594 
8595 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
8596 /// former case, Name will be non-null.  In the later case, Name will be null.
8597 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
8598 /// reference/declaration/definition of a tag.
8599 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8600                      SourceLocation KWLoc, CXXScopeSpec &SS,
8601                      IdentifierInfo *Name, SourceLocation NameLoc,
8602                      AttributeList *Attr, AccessSpecifier AS,
8603                      SourceLocation ModulePrivateLoc,
8604                      MultiTemplateParamsArg TemplateParameterLists,
8605                      bool &OwnedDecl, bool &IsDependent,
8606                      SourceLocation ScopedEnumKWLoc,
8607                      bool ScopedEnumUsesClassTag,
8608                      TypeResult UnderlyingType) {
8609   // If this is not a definition, it must have a name.
8610   IdentifierInfo *OrigName = Name;
8611   assert((Name != 0 || TUK == TUK_Definition) &&
8612          "Nameless record must be a definition!");
8613   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
8614 
8615   OwnedDecl = false;
8616   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8617   bool ScopedEnum = ScopedEnumKWLoc.isValid();
8618 
8619   // FIXME: Check explicit specializations more carefully.
8620   bool isExplicitSpecialization = false;
8621   bool Invalid = false;
8622 
8623   // We only need to do this matching if we have template parameters
8624   // or a scope specifier, which also conveniently avoids this work
8625   // for non-C++ cases.
8626   if (TemplateParameterLists.size() > 0 ||
8627       (SS.isNotEmpty() && TUK != TUK_Reference)) {
8628     if (TemplateParameterList *TemplateParams
8629           = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
8630                                                 TemplateParameterLists.data(),
8631                                                 TemplateParameterLists.size(),
8632                                                     TUK == TUK_Friend,
8633                                                     isExplicitSpecialization,
8634                                                     Invalid)) {
8635       if (TemplateParams->size() > 0) {
8636         // This is a declaration or definition of a class template (which may
8637         // be a member of another template).
8638 
8639         if (Invalid)
8640           return 0;
8641 
8642         OwnedDecl = false;
8643         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
8644                                                SS, Name, NameLoc, Attr,
8645                                                TemplateParams, AS,
8646                                                ModulePrivateLoc,
8647                                                TemplateParameterLists.size()-1,
8648                                                TemplateParameterLists.data());
8649         return Result.get();
8650       } else {
8651         // The "template<>" header is extraneous.
8652         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8653           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8654         isExplicitSpecialization = true;
8655       }
8656     }
8657   }
8658 
8659   // Figure out the underlying type if this a enum declaration. We need to do
8660   // this early, because it's needed to detect if this is an incompatible
8661   // redeclaration.
8662   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8663 
8664   if (Kind == TTK_Enum) {
8665     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8666       // No underlying type explicitly specified, or we failed to parse the
8667       // type, default to int.
8668       EnumUnderlying = Context.IntTy.getTypePtr();
8669     else if (UnderlyingType.get()) {
8670       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8671       // integral type; any cv-qualification is ignored.
8672       TypeSourceInfo *TI = 0;
8673       GetTypeFromParser(UnderlyingType.get(), &TI);
8674       EnumUnderlying = TI;
8675 
8676       if (CheckEnumUnderlyingType(TI))
8677         // Recover by falling back to int.
8678         EnumUnderlying = Context.IntTy.getTypePtr();
8679 
8680       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8681                                           UPPC_FixedUnderlyingType))
8682         EnumUnderlying = Context.IntTy.getTypePtr();
8683 
8684     } else if (getLangOpts().MicrosoftMode)
8685       // Microsoft enums are always of int type.
8686       EnumUnderlying = Context.IntTy.getTypePtr();
8687   }
8688 
8689   DeclContext *SearchDC = CurContext;
8690   DeclContext *DC = CurContext;
8691   bool isStdBadAlloc = false;
8692 
8693   RedeclarationKind Redecl = ForRedeclaration;
8694   if (TUK == TUK_Friend || TUK == TUK_Reference)
8695     Redecl = NotForRedeclaration;
8696 
8697   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8698 
8699   if (Name && SS.isNotEmpty()) {
8700     // We have a nested-name tag ('struct foo::bar').
8701 
8702     // Check for invalid 'foo::'.
8703     if (SS.isInvalid()) {
8704       Name = 0;
8705       goto CreateNewDecl;
8706     }
8707 
8708     // If this is a friend or a reference to a class in a dependent
8709     // context, don't try to make a decl for it.
8710     if (TUK == TUK_Friend || TUK == TUK_Reference) {
8711       DC = computeDeclContext(SS, false);
8712       if (!DC) {
8713         IsDependent = true;
8714         return 0;
8715       }
8716     } else {
8717       DC = computeDeclContext(SS, true);
8718       if (!DC) {
8719         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8720           << SS.getRange();
8721         return 0;
8722       }
8723     }
8724 
8725     if (RequireCompleteDeclContext(SS, DC))
8726       return 0;
8727 
8728     SearchDC = DC;
8729     // Look-up name inside 'foo::'.
8730     LookupQualifiedName(Previous, DC);
8731 
8732     if (Previous.isAmbiguous())
8733       return 0;
8734 
8735     if (Previous.empty()) {
8736       // Name lookup did not find anything. However, if the
8737       // nested-name-specifier refers to the current instantiation,
8738       // and that current instantiation has any dependent base
8739       // classes, we might find something at instantiation time: treat
8740       // this as a dependent elaborated-type-specifier.
8741       // But this only makes any sense for reference-like lookups.
8742       if (Previous.wasNotFoundInCurrentInstantiation() &&
8743           (TUK == TUK_Reference || TUK == TUK_Friend)) {
8744         IsDependent = true;
8745         return 0;
8746       }
8747 
8748       // A tag 'foo::bar' must already exist.
8749       Diag(NameLoc, diag::err_not_tag_in_scope)
8750         << Kind << Name << DC << SS.getRange();
8751       Name = 0;
8752       Invalid = true;
8753       goto CreateNewDecl;
8754     }
8755   } else if (Name) {
8756     // If this is a named struct, check to see if there was a previous forward
8757     // declaration or definition.
8758     // FIXME: We're looking into outer scopes here, even when we
8759     // shouldn't be. Doing so can result in ambiguities that we
8760     // shouldn't be diagnosing.
8761     LookupName(Previous, S);
8762 
8763     if (Previous.isAmbiguous() &&
8764         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8765       LookupResult::Filter F = Previous.makeFilter();
8766       while (F.hasNext()) {
8767         NamedDecl *ND = F.next();
8768         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8769           F.erase();
8770       }
8771       F.done();
8772     }
8773 
8774     // Note:  there used to be some attempt at recovery here.
8775     if (Previous.isAmbiguous())
8776       return 0;
8777 
8778     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8779       // FIXME: This makes sure that we ignore the contexts associated
8780       // with C structs, unions, and enums when looking for a matching
8781       // tag declaration or definition. See the similar lookup tweak
8782       // in Sema::LookupName; is there a better way to deal with this?
8783       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8784         SearchDC = SearchDC->getParent();
8785     }
8786   } else if (S->isFunctionPrototypeScope()) {
8787     // If this is an enum declaration in function prototype scope, set its
8788     // initial context to the translation unit.
8789     // FIXME: [citation needed]
8790     SearchDC = Context.getTranslationUnitDecl();
8791   }
8792 
8793   if (Previous.isSingleResult() &&
8794       Previous.getFoundDecl()->isTemplateParameter()) {
8795     // Maybe we will complain about the shadowed template parameter.
8796     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8797     // Just pretend that we didn't see the previous declaration.
8798     Previous.clear();
8799   }
8800 
8801   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8802       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8803     // This is a declaration of or a reference to "std::bad_alloc".
8804     isStdBadAlloc = true;
8805 
8806     if (Previous.empty() && StdBadAlloc) {
8807       // std::bad_alloc has been implicitly declared (but made invisible to
8808       // name lookup). Fill in this implicit declaration as the previous
8809       // declaration, so that the declarations get chained appropriately.
8810       Previous.addDecl(getStdBadAlloc());
8811     }
8812   }
8813 
8814   // If we didn't find a previous declaration, and this is a reference
8815   // (or friend reference), move to the correct scope.  In C++, we
8816   // also need to do a redeclaration lookup there, just in case
8817   // there's a shadow friend decl.
8818   if (Name && Previous.empty() &&
8819       (TUK == TUK_Reference || TUK == TUK_Friend)) {
8820     if (Invalid) goto CreateNewDecl;
8821     assert(SS.isEmpty());
8822 
8823     if (TUK == TUK_Reference) {
8824       // C++ [basic.scope.pdecl]p5:
8825       //   -- for an elaborated-type-specifier of the form
8826       //
8827       //          class-key identifier
8828       //
8829       //      if the elaborated-type-specifier is used in the
8830       //      decl-specifier-seq or parameter-declaration-clause of a
8831       //      function defined in namespace scope, the identifier is
8832       //      declared as a class-name in the namespace that contains
8833       //      the declaration; otherwise, except as a friend
8834       //      declaration, the identifier is declared in the smallest
8835       //      non-class, non-function-prototype scope that contains the
8836       //      declaration.
8837       //
8838       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8839       // C structs and unions.
8840       //
8841       // It is an error in C++ to declare (rather than define) an enum
8842       // type, including via an elaborated type specifier.  We'll
8843       // diagnose that later; for now, declare the enum in the same
8844       // scope as we would have picked for any other tag type.
8845       //
8846       // GNU C also supports this behavior as part of its incomplete
8847       // enum types extension, while GNU C++ does not.
8848       //
8849       // Find the context where we'll be declaring the tag.
8850       // FIXME: We would like to maintain the current DeclContext as the
8851       // lexical context,
8852       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8853         SearchDC = SearchDC->getParent();
8854 
8855       // Find the scope where we'll be declaring the tag.
8856       while (S->isClassScope() ||
8857              (getLangOpts().CPlusPlus &&
8858               S->isFunctionPrototypeScope()) ||
8859              ((S->getFlags() & Scope::DeclScope) == 0) ||
8860              (S->getEntity() &&
8861               ((DeclContext *)S->getEntity())->isTransparentContext()))
8862         S = S->getParent();
8863     } else {
8864       assert(TUK == TUK_Friend);
8865       // C++ [namespace.memdef]p3:
8866       //   If a friend declaration in a non-local class first declares a
8867       //   class or function, the friend class or function is a member of
8868       //   the innermost enclosing namespace.
8869       SearchDC = SearchDC->getEnclosingNamespaceContext();
8870     }
8871 
8872     // In C++, we need to do a redeclaration lookup to properly
8873     // diagnose some problems.
8874     if (getLangOpts().CPlusPlus) {
8875       Previous.setRedeclarationKind(ForRedeclaration);
8876       LookupQualifiedName(Previous, SearchDC);
8877     }
8878   }
8879 
8880   if (!Previous.empty()) {
8881     NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8882 
8883     // It's okay to have a tag decl in the same scope as a typedef
8884     // which hides a tag decl in the same scope.  Finding this
8885     // insanity with a redeclaration lookup can only actually happen
8886     // in C++.
8887     //
8888     // This is also okay for elaborated-type-specifiers, which is
8889     // technically forbidden by the current standard but which is
8890     // okay according to the likely resolution of an open issue;
8891     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8892     if (getLangOpts().CPlusPlus) {
8893       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8894         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8895           TagDecl *Tag = TT->getDecl();
8896           if (Tag->getDeclName() == Name &&
8897               Tag->getDeclContext()->getRedeclContext()
8898                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
8899             PrevDecl = Tag;
8900             Previous.clear();
8901             Previous.addDecl(Tag);
8902             Previous.resolveKind();
8903           }
8904         }
8905       }
8906     }
8907 
8908     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8909       // If this is a use of a previous tag, or if the tag is already declared
8910       // in the same scope (so that the definition/declaration completes or
8911       // rementions the tag), reuse the decl.
8912       if (TUK == TUK_Reference || TUK == TUK_Friend ||
8913           isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8914         // Make sure that this wasn't declared as an enum and now used as a
8915         // struct or something similar.
8916         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8917                                           TUK == TUK_Definition, KWLoc,
8918                                           *Name)) {
8919           bool SafeToContinue
8920             = (PrevTagDecl->getTagKind() != TTK_Enum &&
8921                Kind != TTK_Enum);
8922           if (SafeToContinue)
8923             Diag(KWLoc, diag::err_use_with_wrong_tag)
8924               << Name
8925               << FixItHint::CreateReplacement(SourceRange(KWLoc),
8926                                               PrevTagDecl->getKindName());
8927           else
8928             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8929           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8930 
8931           if (SafeToContinue)
8932             Kind = PrevTagDecl->getTagKind();
8933           else {
8934             // Recover by making this an anonymous redefinition.
8935             Name = 0;
8936             Previous.clear();
8937             Invalid = true;
8938           }
8939         }
8940 
8941         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8942           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8943 
8944           // If this is an elaborated-type-specifier for a scoped enumeration,
8945           // the 'class' keyword is not necessary and not permitted.
8946           if (TUK == TUK_Reference || TUK == TUK_Friend) {
8947             if (ScopedEnum)
8948               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8949                 << PrevEnum->isScoped()
8950                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8951             return PrevTagDecl;
8952           }
8953 
8954           QualType EnumUnderlyingTy;
8955           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8956             EnumUnderlyingTy = TI->getType();
8957           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8958             EnumUnderlyingTy = QualType(T, 0);
8959 
8960           // All conflicts with previous declarations are recovered by
8961           // returning the previous declaration, unless this is a definition,
8962           // in which case we want the caller to bail out.
8963           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8964                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
8965             return TUK == TUK_Declaration ? PrevTagDecl : 0;
8966         }
8967 
8968         if (!Invalid) {
8969           // If this is a use, just return the declaration we found.
8970 
8971           // FIXME: In the future, return a variant or some other clue
8972           // for the consumer of this Decl to know it doesn't own it.
8973           // For our current ASTs this shouldn't be a problem, but will
8974           // need to be changed with DeclGroups.
8975           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8976                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8977             return PrevTagDecl;
8978 
8979           // Diagnose attempts to redefine a tag.
8980           if (TUK == TUK_Definition) {
8981             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8982               // If we're defining a specialization and the previous definition
8983               // is from an implicit instantiation, don't emit an error
8984               // here; we'll catch this in the general case below.
8985               bool IsExplicitSpecializationAfterInstantiation = false;
8986               if (isExplicitSpecialization) {
8987                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8988                   IsExplicitSpecializationAfterInstantiation =
8989                     RD->getTemplateSpecializationKind() !=
8990                     TSK_ExplicitSpecialization;
8991                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8992                   IsExplicitSpecializationAfterInstantiation =
8993                     ED->getTemplateSpecializationKind() !=
8994                     TSK_ExplicitSpecialization;
8995               }
8996 
8997               if (!IsExplicitSpecializationAfterInstantiation) {
8998                 // A redeclaration in function prototype scope in C isn't
8999                 // visible elsewhere, so merely issue a warning.
9000                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
9001                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
9002                 else
9003                   Diag(NameLoc, diag::err_redefinition) << Name;
9004                 Diag(Def->getLocation(), diag::note_previous_definition);
9005                 // If this is a redefinition, recover by making this
9006                 // struct be anonymous, which will make any later
9007                 // references get the previous definition.
9008                 Name = 0;
9009                 Previous.clear();
9010                 Invalid = true;
9011               }
9012             } else {
9013               // If the type is currently being defined, complain
9014               // about a nested redefinition.
9015               const TagType *Tag
9016                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
9017               if (Tag->isBeingDefined()) {
9018                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
9019                 Diag(PrevTagDecl->getLocation(),
9020                      diag::note_previous_definition);
9021                 Name = 0;
9022                 Previous.clear();
9023                 Invalid = true;
9024               }
9025             }
9026 
9027             // Okay, this is definition of a previously declared or referenced
9028             // tag PrevDecl. We're going to create a new Decl for it.
9029           }
9030         }
9031         // If we get here we have (another) forward declaration or we
9032         // have a definition.  Just create a new decl.
9033 
9034       } else {
9035         // If we get here, this is a definition of a new tag type in a nested
9036         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
9037         // new decl/type.  We set PrevDecl to NULL so that the entities
9038         // have distinct types.
9039         Previous.clear();
9040       }
9041       // If we get here, we're going to create a new Decl. If PrevDecl
9042       // is non-NULL, it's a definition of the tag declared by
9043       // PrevDecl. If it's NULL, we have a new definition.
9044 
9045 
9046     // Otherwise, PrevDecl is not a tag, but was found with tag
9047     // lookup.  This is only actually possible in C++, where a few
9048     // things like templates still live in the tag namespace.
9049     } else {
9050       // Use a better diagnostic if an elaborated-type-specifier
9051       // found the wrong kind of type on the first
9052       // (non-redeclaration) lookup.
9053       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
9054           !Previous.isForRedeclaration()) {
9055         unsigned Kind = 0;
9056         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9057         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9058         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9059         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9060         Diag(PrevDecl->getLocation(), diag::note_declared_at);
9061         Invalid = true;
9062 
9063       // Otherwise, only diagnose if the declaration is in scope.
9064       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9065                                 isExplicitSpecialization)) {
9066         // do nothing
9067 
9068       // Diagnose implicit declarations introduced by elaborated types.
9069       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9070         unsigned Kind = 0;
9071         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9072         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9073         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9074         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9075         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9076         Invalid = true;
9077 
9078       // Otherwise it's a declaration.  Call out a particularly common
9079       // case here.
9080       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9081         unsigned Kind = 0;
9082         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
9083         Diag(NameLoc, diag::err_tag_definition_of_typedef)
9084           << Name << Kind << TND->getUnderlyingType();
9085         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9086         Invalid = true;
9087 
9088       // Otherwise, diagnose.
9089       } else {
9090         // The tag name clashes with something else in the target scope,
9091         // issue an error and recover by making this tag be anonymous.
9092         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
9093         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9094         Name = 0;
9095         Invalid = true;
9096       }
9097 
9098       // The existing declaration isn't relevant to us; we're in a
9099       // new scope, so clear out the previous declaration.
9100       Previous.clear();
9101     }
9102   }
9103 
9104 CreateNewDecl:
9105 
9106   TagDecl *PrevDecl = 0;
9107   if (Previous.isSingleResult())
9108     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9109 
9110   // If there is an identifier, use the location of the identifier as the
9111   // location of the decl, otherwise use the location of the struct/union
9112   // keyword.
9113   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
9114 
9115   // Otherwise, create a new declaration. If there is a previous
9116   // declaration of the same entity, the two will be linked via
9117   // PrevDecl.
9118   TagDecl *New;
9119 
9120   bool IsForwardReference = false;
9121   if (Kind == TTK_Enum) {
9122     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9123     // enum X { A, B, C } D;    D should chain to X.
9124     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
9125                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
9126                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
9127     // If this is an undefined enum, warn.
9128     if (TUK != TUK_Definition && !Invalid) {
9129       TagDecl *Def;
9130       if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
9131         // C++0x: 7.2p2: opaque-enum-declaration.
9132         // Conflicts are diagnosed above. Do nothing.
9133       }
9134       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
9135         Diag(Loc, diag::ext_forward_ref_enum_def)
9136           << New;
9137         Diag(Def->getLocation(), diag::note_previous_definition);
9138       } else {
9139         unsigned DiagID = diag::ext_forward_ref_enum;
9140         if (getLangOpts().MicrosoftMode)
9141           DiagID = diag::ext_ms_forward_ref_enum;
9142         else if (getLangOpts().CPlusPlus)
9143           DiagID = diag::err_forward_ref_enum;
9144         Diag(Loc, DiagID);
9145 
9146         // If this is a forward-declared reference to an enumeration, make a
9147         // note of it; we won't actually be introducing the declaration into
9148         // the declaration context.
9149         if (TUK == TUK_Reference)
9150           IsForwardReference = true;
9151       }
9152     }
9153 
9154     if (EnumUnderlying) {
9155       EnumDecl *ED = cast<EnumDecl>(New);
9156       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9157         ED->setIntegerTypeSourceInfo(TI);
9158       else
9159         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9160       ED->setPromotionType(ED->getIntegerType());
9161     }
9162 
9163   } else {
9164     // struct/union/class
9165 
9166     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9167     // struct X { int A; } D;    D should chain to X.
9168     if (getLangOpts().CPlusPlus) {
9169       // FIXME: Look for a way to use RecordDecl for simple structs.
9170       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9171                                   cast_or_null<CXXRecordDecl>(PrevDecl));
9172 
9173       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
9174         StdBadAlloc = cast<CXXRecordDecl>(New);
9175     } else
9176       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9177                                cast_or_null<RecordDecl>(PrevDecl));
9178   }
9179 
9180   // Maybe add qualifier info.
9181   if (SS.isNotEmpty()) {
9182     if (SS.isSet()) {
9183       // If this is either a declaration or a definition, check the
9184       // nested-name-specifier against the current context. We don't do this
9185       // for explicit specializations, because they have similar checking
9186       // (with more specific diagnostics) in the call to
9187       // CheckMemberSpecialization, below.
9188       if (!isExplicitSpecialization &&
9189           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9190           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9191         Invalid = true;
9192 
9193       New->setQualifierInfo(SS.getWithLocInContext(Context));
9194       if (TemplateParameterLists.size() > 0) {
9195         New->setTemplateParameterListsInfo(Context,
9196                                            TemplateParameterLists.size(),
9197                                            TemplateParameterLists.data());
9198       }
9199     }
9200     else
9201       Invalid = true;
9202   }
9203 
9204   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9205     // Add alignment attributes if necessary; these attributes are checked when
9206     // the ASTContext lays out the structure.
9207     //
9208     // It is important for implementing the correct semantics that this
9209     // happen here (in act on tag decl). The #pragma pack stack is
9210     // maintained as a result of parser callbacks which can occur at
9211     // many points during the parsing of a struct declaration (because
9212     // the #pragma tokens are effectively skipped over during the
9213     // parsing of the struct).
9214     if (TUK == TUK_Definition) {
9215       AddAlignmentAttributesForRecord(RD);
9216       AddMsStructLayoutForRecord(RD);
9217     }
9218   }
9219 
9220   if (ModulePrivateLoc.isValid()) {
9221     if (isExplicitSpecialization)
9222       Diag(New->getLocation(), diag::err_module_private_specialization)
9223         << 2
9224         << FixItHint::CreateRemoval(ModulePrivateLoc);
9225     // __module_private__ does not apply to local classes. However, we only
9226     // diagnose this as an error when the declaration specifiers are
9227     // freestanding. Here, we just ignore the __module_private__.
9228     else if (!SearchDC->isFunctionOrMethod())
9229       New->setModulePrivate();
9230   }
9231 
9232   // If this is a specialization of a member class (of a class template),
9233   // check the specialization.
9234   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
9235     Invalid = true;
9236 
9237   if (Invalid)
9238     New->setInvalidDecl();
9239 
9240   if (Attr)
9241     ProcessDeclAttributeList(S, New, Attr);
9242 
9243   // If we're declaring or defining a tag in function prototype scope
9244   // in C, note that this type can only be used within the function.
9245   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
9246     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9247 
9248   // Set the lexical context. If the tag has a C++ scope specifier, the
9249   // lexical context will be different from the semantic context.
9250   New->setLexicalDeclContext(CurContext);
9251 
9252   // Mark this as a friend decl if applicable.
9253   // In Microsoft mode, a friend declaration also acts as a forward
9254   // declaration so we always pass true to setObjectOfFriendDecl to make
9255   // the tag name visible.
9256   if (TUK == TUK_Friend)
9257     New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
9258                                getLangOpts().MicrosoftExt);
9259 
9260   // Set the access specifier.
9261   if (!Invalid && SearchDC->isRecord())
9262     SetMemberAccessSpecifier(New, PrevDecl, AS);
9263 
9264   if (TUK == TUK_Definition)
9265     New->startDefinition();
9266 
9267   // If this has an identifier, add it to the scope stack.
9268   if (TUK == TUK_Friend) {
9269     // We might be replacing an existing declaration in the lookup tables;
9270     // if so, borrow its access specifier.
9271     if (PrevDecl)
9272       New->setAccess(PrevDecl->getAccess());
9273 
9274     DeclContext *DC = New->getDeclContext()->getRedeclContext();
9275     DC->makeDeclVisibleInContext(New);
9276     if (Name) // can be null along some error paths
9277       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9278         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
9279   } else if (Name) {
9280     S = getNonFieldDeclScope(S);
9281     PushOnScopeChains(New, S, !IsForwardReference);
9282     if (IsForwardReference)
9283       SearchDC->makeDeclVisibleInContext(New);
9284 
9285   } else {
9286     CurContext->addDecl(New);
9287   }
9288 
9289   // If this is the C FILE type, notify the AST context.
9290   if (IdentifierInfo *II = New->getIdentifier())
9291     if (!New->isInvalidDecl() &&
9292         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
9293         II->isStr("FILE"))
9294       Context.setFILEDecl(New);
9295 
9296   // If we were in function prototype scope (and not in C++ mode), add this
9297   // tag to the list of decls to inject into the function definition scope.
9298   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
9299       InFunctionDeclarator && Name)
9300     DeclsInPrototypeScope.push_back(New);
9301 
9302   if (PrevDecl)
9303     mergeDeclAttributes(New, PrevDecl);
9304 
9305   // If there's a #pragma GCC visibility in scope, set the visibility of this
9306   // record.
9307   AddPushedVisibilityAttribute(New);
9308 
9309   OwnedDecl = true;
9310   // In C++, don't return an invalid declaration. We can't recover well from
9311   // the cases where we make the type anonymous.
9312   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
9313 }
9314 
9315 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
9316   AdjustDeclIfTemplate(TagD);
9317   TagDecl *Tag = cast<TagDecl>(TagD);
9318 
9319   // Enter the tag context.
9320   PushDeclContext(S, Tag);
9321 
9322   ActOnDocumentableDecl(TagD);
9323 
9324   // If there's a #pragma GCC visibility in scope, set the visibility of this
9325   // record.
9326   AddPushedVisibilityAttribute(Tag);
9327 }
9328 
9329 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
9330   assert(isa<ObjCContainerDecl>(IDecl) &&
9331          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
9332   DeclContext *OCD = cast<DeclContext>(IDecl);
9333   assert(getContainingDC(OCD) == CurContext &&
9334       "The next DeclContext should be lexically contained in the current one.");
9335   CurContext = OCD;
9336   return IDecl;
9337 }
9338 
9339 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
9340                                            SourceLocation FinalLoc,
9341                                            SourceLocation LBraceLoc) {
9342   AdjustDeclIfTemplate(TagD);
9343   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
9344 
9345   FieldCollector->StartClass();
9346 
9347   if (!Record->getIdentifier())
9348     return;
9349 
9350   if (FinalLoc.isValid())
9351     Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
9352 
9353   // C++ [class]p2:
9354   //   [...] The class-name is also inserted into the scope of the
9355   //   class itself; this is known as the injected-class-name. For
9356   //   purposes of access checking, the injected-class-name is treated
9357   //   as if it were a public member name.
9358   CXXRecordDecl *InjectedClassName
9359     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
9360                             Record->getLocStart(), Record->getLocation(),
9361                             Record->getIdentifier(),
9362                             /*PrevDecl=*/0,
9363                             /*DelayTypeCreation=*/true);
9364   Context.getTypeDeclType(InjectedClassName, Record);
9365   InjectedClassName->setImplicit();
9366   InjectedClassName->setAccess(AS_public);
9367   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
9368       InjectedClassName->setDescribedClassTemplate(Template);
9369   PushOnScopeChains(InjectedClassName, S);
9370   assert(InjectedClassName->isInjectedClassName() &&
9371          "Broken injected-class-name");
9372 }
9373 
9374 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
9375                                     SourceLocation RBraceLoc) {
9376   AdjustDeclIfTemplate(TagD);
9377   TagDecl *Tag = cast<TagDecl>(TagD);
9378   Tag->setRBraceLoc(RBraceLoc);
9379 
9380   // Make sure we "complete" the definition even it is invalid.
9381   if (Tag->isBeingDefined()) {
9382     assert(Tag->isInvalidDecl() && "We should already have completed it");
9383     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9384       RD->completeDefinition();
9385   }
9386 
9387   if (isa<CXXRecordDecl>(Tag))
9388     FieldCollector->FinishClass();
9389 
9390   // Exit this scope of this tag's definition.
9391   PopDeclContext();
9392 
9393   // Notify the consumer that we've defined a tag.
9394   Consumer.HandleTagDeclDefinition(Tag);
9395 }
9396 
9397 void Sema::ActOnObjCContainerFinishDefinition() {
9398   // Exit this scope of this interface definition.
9399   PopDeclContext();
9400 }
9401 
9402 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
9403   assert(DC == CurContext && "Mismatch of container contexts");
9404   OriginalLexicalContext = DC;
9405   ActOnObjCContainerFinishDefinition();
9406 }
9407 
9408 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9409   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
9410   OriginalLexicalContext = 0;
9411 }
9412 
9413 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
9414   AdjustDeclIfTemplate(TagD);
9415   TagDecl *Tag = cast<TagDecl>(TagD);
9416   Tag->setInvalidDecl();
9417 
9418   // Make sure we "complete" the definition even it is invalid.
9419   if (Tag->isBeingDefined()) {
9420     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9421       RD->completeDefinition();
9422   }
9423 
9424   // We're undoing ActOnTagStartDefinition here, not
9425   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9426   // the FieldCollector.
9427 
9428   PopDeclContext();
9429 }
9430 
9431 // Note that FieldName may be null for anonymous bitfields.
9432 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9433                                 IdentifierInfo *FieldName,
9434                                 QualType FieldTy, Expr *BitWidth,
9435                                 bool *ZeroWidth) {
9436   // Default to true; that shouldn't confuse checks for emptiness
9437   if (ZeroWidth)
9438     *ZeroWidth = true;
9439 
9440   // C99 6.7.2.1p4 - verify the field type.
9441   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
9442   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
9443     // Handle incomplete types with specific error.
9444     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
9445       return ExprError();
9446     if (FieldName)
9447       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9448         << FieldName << FieldTy << BitWidth->getSourceRange();
9449     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9450       << FieldTy << BitWidth->getSourceRange();
9451   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9452                                              UPPC_BitFieldWidth))
9453     return ExprError();
9454 
9455   // If the bit-width is type- or value-dependent, don't try to check
9456   // it now.
9457   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
9458     return Owned(BitWidth);
9459 
9460   llvm::APSInt Value;
9461   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9462   if (ICE.isInvalid())
9463     return ICE;
9464   BitWidth = ICE.take();
9465 
9466   if (Value != 0 && ZeroWidth)
9467     *ZeroWidth = false;
9468 
9469   // Zero-width bitfield is ok for anonymous field.
9470   if (Value == 0 && FieldName)
9471     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
9472 
9473   if (Value.isSigned() && Value.isNegative()) {
9474     if (FieldName)
9475       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
9476                << FieldName << Value.toString(10);
9477     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9478       << Value.toString(10);
9479   }
9480 
9481   if (!FieldTy->isDependentType()) {
9482     uint64_t TypeSize = Context.getTypeSize(FieldTy);
9483     if (Value.getZExtValue() > TypeSize) {
9484       if (!getLangOpts().CPlusPlus) {
9485         if (FieldName)
9486           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9487             << FieldName << (unsigned)Value.getZExtValue()
9488             << (unsigned)TypeSize;
9489 
9490         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9491           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9492       }
9493 
9494       if (FieldName)
9495         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9496           << FieldName << (unsigned)Value.getZExtValue()
9497           << (unsigned)TypeSize;
9498       else
9499         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9500           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9501     }
9502   }
9503 
9504   return Owned(BitWidth);
9505 }
9506 
9507 /// ActOnField - Each field of a C struct/union is passed into this in order
9508 /// to create a FieldDecl object for it.
9509 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
9510                        Declarator &D, Expr *BitfieldWidth) {
9511   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
9512                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
9513                                /*InitStyle=*/ICIS_NoInit, AS_public);
9514   return Res;
9515 }
9516 
9517 /// HandleField - Analyze a field of a C struct or a C++ data member.
9518 ///
9519 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9520                              SourceLocation DeclStart,
9521                              Declarator &D, Expr *BitWidth,
9522                              InClassInitStyle InitStyle,
9523                              AccessSpecifier AS) {
9524   IdentifierInfo *II = D.getIdentifier();
9525   SourceLocation Loc = DeclStart;
9526   if (II) Loc = D.getIdentifierLoc();
9527 
9528   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9529   QualType T = TInfo->getType();
9530   if (getLangOpts().CPlusPlus) {
9531     CheckExtraCXXDefaultArguments(D);
9532 
9533     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9534                                         UPPC_DataMemberType)) {
9535       D.setInvalidType();
9536       T = Context.IntTy;
9537       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9538     }
9539   }
9540 
9541   DiagnoseFunctionSpecifiers(D);
9542 
9543   if (D.getDeclSpec().isThreadSpecified())
9544     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
9545   if (D.getDeclSpec().isConstexprSpecified())
9546     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9547       << 2;
9548 
9549   // Check to see if this name was declared as a member previously
9550   NamedDecl *PrevDecl = 0;
9551   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9552   LookupName(Previous, S);
9553   switch (Previous.getResultKind()) {
9554     case LookupResult::Found:
9555     case LookupResult::FoundUnresolvedValue:
9556       PrevDecl = Previous.getAsSingle<NamedDecl>();
9557       break;
9558 
9559     case LookupResult::FoundOverloaded:
9560       PrevDecl = Previous.getRepresentativeDecl();
9561       break;
9562 
9563     case LookupResult::NotFound:
9564     case LookupResult::NotFoundInCurrentInstantiation:
9565     case LookupResult::Ambiguous:
9566       break;
9567   }
9568   Previous.suppressDiagnostics();
9569 
9570   if (PrevDecl && PrevDecl->isTemplateParameter()) {
9571     // Maybe we will complain about the shadowed template parameter.
9572     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9573     // Just pretend that we didn't see the previous declaration.
9574     PrevDecl = 0;
9575   }
9576 
9577   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9578     PrevDecl = 0;
9579 
9580   bool Mutable
9581     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
9582   SourceLocation TSSL = D.getLocStart();
9583   FieldDecl *NewFD
9584     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
9585                      TSSL, AS, PrevDecl, &D);
9586 
9587   if (NewFD->isInvalidDecl())
9588     Record->setInvalidDecl();
9589 
9590   if (D.getDeclSpec().isModulePrivateSpecified())
9591     NewFD->setModulePrivate();
9592 
9593   if (NewFD->isInvalidDecl() && PrevDecl) {
9594     // Don't introduce NewFD into scope; there's already something
9595     // with the same name in the same scope.
9596   } else if (II) {
9597     PushOnScopeChains(NewFD, S);
9598   } else
9599     Record->addDecl(NewFD);
9600 
9601   return NewFD;
9602 }
9603 
9604 /// \brief Build a new FieldDecl and check its well-formedness.
9605 ///
9606 /// This routine builds a new FieldDecl given the fields name, type,
9607 /// record, etc. \p PrevDecl should refer to any previous declaration
9608 /// with the same name and in the same scope as the field to be
9609 /// created.
9610 ///
9611 /// \returns a new FieldDecl.
9612 ///
9613 /// \todo The Declarator argument is a hack. It will be removed once
9614 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
9615                                 TypeSourceInfo *TInfo,
9616                                 RecordDecl *Record, SourceLocation Loc,
9617                                 bool Mutable, Expr *BitWidth,
9618                                 InClassInitStyle InitStyle,
9619                                 SourceLocation TSSL,
9620                                 AccessSpecifier AS, NamedDecl *PrevDecl,
9621                                 Declarator *D) {
9622   IdentifierInfo *II = Name.getAsIdentifierInfo();
9623   bool InvalidDecl = false;
9624   if (D) InvalidDecl = D->isInvalidType();
9625 
9626   // If we receive a broken type, recover by assuming 'int' and
9627   // marking this declaration as invalid.
9628   if (T.isNull()) {
9629     InvalidDecl = true;
9630     T = Context.IntTy;
9631   }
9632 
9633   QualType EltTy = Context.getBaseElementType(T);
9634   if (!EltTy->isDependentType()) {
9635     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9636       // Fields of incomplete type force their record to be invalid.
9637       Record->setInvalidDecl();
9638       InvalidDecl = true;
9639     } else {
9640       NamedDecl *Def;
9641       EltTy->isIncompleteType(&Def);
9642       if (Def && Def->isInvalidDecl()) {
9643         Record->setInvalidDecl();
9644         InvalidDecl = true;
9645       }
9646     }
9647   }
9648 
9649   // C99 6.7.2.1p8: A member of a structure or union may have any type other
9650   // than a variably modified type.
9651   if (!InvalidDecl && T->isVariablyModifiedType()) {
9652     bool SizeIsNegative;
9653     llvm::APSInt Oversized;
9654 
9655     TypeSourceInfo *FixedTInfo =
9656       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
9657                                                     SizeIsNegative,
9658                                                     Oversized);
9659     if (FixedTInfo) {
9660       Diag(Loc, diag::warn_illegal_constant_array_size);
9661       TInfo = FixedTInfo;
9662       T = FixedTInfo->getType();
9663     } else {
9664       if (SizeIsNegative)
9665         Diag(Loc, diag::err_typecheck_negative_array_size);
9666       else if (Oversized.getBoolValue())
9667         Diag(Loc, diag::err_array_too_large)
9668           << Oversized.toString(10);
9669       else
9670         Diag(Loc, diag::err_typecheck_field_variable_size);
9671       InvalidDecl = true;
9672     }
9673   }
9674 
9675   // Fields can not have abstract class types
9676   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9677                                              diag::err_abstract_type_in_decl,
9678                                              AbstractFieldType))
9679     InvalidDecl = true;
9680 
9681   bool ZeroWidth = false;
9682   // If this is declared as a bit-field, check the bit-field.
9683   if (!InvalidDecl && BitWidth) {
9684     BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9685     if (!BitWidth) {
9686       InvalidDecl = true;
9687       BitWidth = 0;
9688       ZeroWidth = false;
9689     }
9690   }
9691 
9692   // Check that 'mutable' is consistent with the type of the declaration.
9693   if (!InvalidDecl && Mutable) {
9694     unsigned DiagID = 0;
9695     if (T->isReferenceType())
9696       DiagID = diag::err_mutable_reference;
9697     else if (T.isConstQualified())
9698       DiagID = diag::err_mutable_const;
9699 
9700     if (DiagID) {
9701       SourceLocation ErrLoc = Loc;
9702       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9703         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9704       Diag(ErrLoc, DiagID);
9705       Mutable = false;
9706       InvalidDecl = true;
9707     }
9708   }
9709 
9710   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9711                                        BitWidth, Mutable, InitStyle);
9712   if (InvalidDecl)
9713     NewFD->setInvalidDecl();
9714 
9715   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9716     Diag(Loc, diag::err_duplicate_member) << II;
9717     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9718     NewFD->setInvalidDecl();
9719   }
9720 
9721   if (!InvalidDecl && getLangOpts().CPlusPlus) {
9722     if (Record->isUnion()) {
9723       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9724         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9725         if (RDecl->getDefinition()) {
9726           // C++ [class.union]p1: An object of a class with a non-trivial
9727           // constructor, a non-trivial copy constructor, a non-trivial
9728           // destructor, or a non-trivial copy assignment operator
9729           // cannot be a member of a union, nor can an array of such
9730           // objects.
9731           if (CheckNontrivialField(NewFD))
9732             NewFD->setInvalidDecl();
9733         }
9734       }
9735 
9736       // C++ [class.union]p1: If a union contains a member of reference type,
9737       // the program is ill-formed.
9738       if (EltTy->isReferenceType()) {
9739         Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9740           << NewFD->getDeclName() << EltTy;
9741         NewFD->setInvalidDecl();
9742       }
9743     }
9744   }
9745 
9746   // FIXME: We need to pass in the attributes given an AST
9747   // representation, not a parser representation.
9748   if (D)
9749     // FIXME: What to pass instead of TUScope?
9750     ProcessDeclAttributes(TUScope, NewFD, *D);
9751 
9752   // In auto-retain/release, infer strong retension for fields of
9753   // retainable type.
9754   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9755     NewFD->setInvalidDecl();
9756 
9757   if (T.isObjCGCWeak())
9758     Diag(Loc, diag::warn_attribute_weak_on_field);
9759 
9760   NewFD->setAccess(AS);
9761   return NewFD;
9762 }
9763 
9764 bool Sema::CheckNontrivialField(FieldDecl *FD) {
9765   assert(FD);
9766   assert(getLangOpts().CPlusPlus && "valid check only for C++");
9767 
9768   if (FD->isInvalidDecl())
9769     return true;
9770 
9771   QualType EltTy = Context.getBaseElementType(FD->getType());
9772   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9773     CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9774     if (RDecl->getDefinition()) {
9775       // We check for copy constructors before constructors
9776       // because otherwise we'll never get complaints about
9777       // copy constructors.
9778 
9779       CXXSpecialMember member = CXXInvalid;
9780       // We're required to check for any non-trivial constructors. Since the
9781       // implicit default constructor is suppressed if there are any
9782       // user-declared constructors, we just need to check that there is a
9783       // trivial default constructor and a trivial copy constructor. (We don't
9784       // worry about move constructors here, since this is a C++98 check.)
9785       if (RDecl->hasNonTrivialCopyConstructor())
9786         member = CXXCopyConstructor;
9787       else if (!RDecl->hasTrivialDefaultConstructor())
9788         member = CXXDefaultConstructor;
9789       else if (RDecl->hasNonTrivialCopyAssignment())
9790         member = CXXCopyAssignment;
9791       else if (RDecl->hasNonTrivialDestructor())
9792         member = CXXDestructor;
9793 
9794       if (member != CXXInvalid) {
9795         if (!getLangOpts().CPlusPlus0x &&
9796             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9797           // Objective-C++ ARC: it is an error to have a non-trivial field of
9798           // a union. However, system headers in Objective-C programs
9799           // occasionally have Objective-C lifetime objects within unions,
9800           // and rather than cause the program to fail, we make those
9801           // members unavailable.
9802           SourceLocation Loc = FD->getLocation();
9803           if (getSourceManager().isInSystemHeader(Loc)) {
9804             if (!FD->hasAttr<UnavailableAttr>())
9805               FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9806                                   "this system field has retaining ownership"));
9807             return false;
9808           }
9809         }
9810 
9811         Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9812                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9813                diag::err_illegal_union_or_anon_struct_member)
9814           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9815         DiagnoseNontrivial(RT, member);
9816         return !getLangOpts().CPlusPlus0x;
9817       }
9818     }
9819   }
9820 
9821   return false;
9822 }
9823 
9824 /// If the given constructor is user-declared, produce a diagnostic explaining
9825 /// that it makes the class non-trivial.
9826 static bool diagnoseNonTrivialUserDeclaredCtor(Sema &S, QualType QT,
9827                                                CXXConstructorDecl *CD,
9828                                                Sema::CXXSpecialMember CSM) {
9829   if (CD->isImplicit())
9830     return false;
9831 
9832   SourceLocation CtorLoc = CD->getLocation();
9833   S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9834   return true;
9835 }
9836 
9837 /// DiagnoseNontrivial - Given that a class has a non-trivial
9838 /// special member, figure out why.
9839 /// FIXME: These checks are not correct in C++11 mode. Currently, this is OK
9840 /// since we only use this in C++11 for a -Wc++98-compat warning.
9841 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9842   QualType QT(T, 0U);
9843   CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9844 
9845   // Check whether the member was user-declared.
9846   switch (member) {
9847   case CXXInvalid:
9848     break;
9849 
9850   case CXXDefaultConstructor:
9851     if (RD->hasUserDeclaredConstructor()) {
9852       typedef CXXRecordDecl::ctor_iterator ctor_iter;
9853       for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9854         if (diagnoseNonTrivialUserDeclaredCtor(*this, QT, *CI, member))
9855           return;
9856 
9857       // No user-delcared constructors; look for constructor templates.
9858       typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9859           tmpl_iter;
9860       for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9861            TI != TE; ++TI) {
9862         CXXConstructorDecl *CD =
9863             dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9864         if (CD && diagnoseNonTrivialUserDeclaredCtor(*this, QT, CD, member))
9865           return;
9866       }
9867     }
9868     break;
9869 
9870   case CXXCopyConstructor:
9871     if (RD->hasUserDeclaredCopyConstructor()) {
9872       SourceLocation CtorLoc =
9873         RD->getCopyConstructor(0)->getLocation();
9874       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9875       return;
9876     }
9877     break;
9878 
9879   case CXXMoveConstructor:
9880     if (RD->hasUserDeclaredMoveConstructor()) {
9881       SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9882       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9883       return;
9884     }
9885     break;
9886 
9887   case CXXCopyAssignment:
9888     if (RD->hasUserDeclaredCopyAssignment()) {
9889       SourceLocation AssignLoc =
9890         RD->getCopyAssignmentOperator(0)->getLocation();
9891       Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9892       return;
9893     }
9894     break;
9895 
9896   case CXXMoveAssignment:
9897     if (RD->hasUserDeclaredMoveAssignment()) {
9898       SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9899       Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9900       return;
9901     }
9902     break;
9903 
9904   case CXXDestructor:
9905     if (RD->hasUserDeclaredDestructor()) {
9906       SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9907       Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9908       return;
9909     }
9910     break;
9911   }
9912 
9913   typedef CXXRecordDecl::base_class_iterator base_iter;
9914 
9915   // Virtual bases and members inhibit trivial copying/construction,
9916   // but not trivial destruction.
9917   if (member != CXXDestructor) {
9918     // Check for virtual bases.  vbases includes indirect virtual bases,
9919     // so we just iterate through the direct bases.
9920     for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9921       if (bi->isVirtual()) {
9922         SourceLocation BaseLoc = bi->getLocStart();
9923         Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9924         return;
9925       }
9926 
9927     // Check for virtual methods.
9928     typedef CXXRecordDecl::method_iterator meth_iter;
9929     for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9930          ++mi) {
9931       if (mi->isVirtual()) {
9932         SourceLocation MLoc = mi->getLocStart();
9933         Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9934         return;
9935       }
9936     }
9937   }
9938 
9939   bool (CXXRecordDecl::*hasNonTrivial)() const;
9940   switch (member) {
9941   case CXXDefaultConstructor:
9942     hasNonTrivial = &CXXRecordDecl::hasNonTrivialDefaultConstructor; break;
9943   case CXXCopyConstructor:
9944     hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyConstructor; break;
9945   case CXXCopyAssignment:
9946     hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyAssignment; break;
9947   case CXXMoveConstructor:
9948     hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveConstructor; break;
9949   case CXXMoveAssignment:
9950     hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveAssignment; break;
9951   case CXXDestructor:
9952     hasNonTrivial = &CXXRecordDecl::hasNonTrivialDestructor; break;
9953   case CXXInvalid:
9954     llvm_unreachable("unexpected special member");
9955   }
9956 
9957   // Check for nontrivial bases (and recurse).
9958   for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9959     const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9960     assert(BaseRT && "Don't know how to handle dependent bases");
9961     CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9962     if ((BaseRecTy->*hasNonTrivial)()) {
9963       SourceLocation BaseLoc = bi->getLocStart();
9964       Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9965       DiagnoseNontrivial(BaseRT, member);
9966       return;
9967     }
9968   }
9969 
9970   // Check for nontrivial members (and recurse).
9971   typedef RecordDecl::field_iterator field_iter;
9972   for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9973        ++fi) {
9974     QualType EltTy = Context.getBaseElementType(fi->getType());
9975     if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9976       CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9977 
9978       if ((EltRD->*hasNonTrivial)()) {
9979         SourceLocation FLoc = fi->getLocation();
9980         Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9981         DiagnoseNontrivial(EltRT, member);
9982         return;
9983       }
9984     }
9985 
9986     if (EltTy->isObjCLifetimeType()) {
9987       switch (EltTy.getObjCLifetime()) {
9988       case Qualifiers::OCL_None:
9989       case Qualifiers::OCL_ExplicitNone:
9990         break;
9991 
9992       case Qualifiers::OCL_Autoreleasing:
9993       case Qualifiers::OCL_Weak:
9994       case Qualifiers::OCL_Strong:
9995         Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
9996           << QT << EltTy.getObjCLifetime();
9997         return;
9998       }
9999     }
10000   }
10001 }
10002 
10003 /// TranslateIvarVisibility - Translate visibility from a token ID to an
10004 ///  AST enum value.
10005 static ObjCIvarDecl::AccessControl
10006 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
10007   switch (ivarVisibility) {
10008   default: llvm_unreachable("Unknown visitibility kind");
10009   case tok::objc_private: return ObjCIvarDecl::Private;
10010   case tok::objc_public: return ObjCIvarDecl::Public;
10011   case tok::objc_protected: return ObjCIvarDecl::Protected;
10012   case tok::objc_package: return ObjCIvarDecl::Package;
10013   }
10014 }
10015 
10016 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
10017 /// in order to create an IvarDecl object for it.
10018 Decl *Sema::ActOnIvar(Scope *S,
10019                                 SourceLocation DeclStart,
10020                                 Declarator &D, Expr *BitfieldWidth,
10021                                 tok::ObjCKeywordKind Visibility) {
10022 
10023   IdentifierInfo *II = D.getIdentifier();
10024   Expr *BitWidth = (Expr*)BitfieldWidth;
10025   SourceLocation Loc = DeclStart;
10026   if (II) Loc = D.getIdentifierLoc();
10027 
10028   // FIXME: Unnamed fields can be handled in various different ways, for
10029   // example, unnamed unions inject all members into the struct namespace!
10030 
10031   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10032   QualType T = TInfo->getType();
10033 
10034   if (BitWidth) {
10035     // 6.7.2.1p3, 6.7.2.1p4
10036     BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
10037     if (!BitWidth)
10038       D.setInvalidType();
10039   } else {
10040     // Not a bitfield.
10041 
10042     // validate II.
10043 
10044   }
10045   if (T->isReferenceType()) {
10046     Diag(Loc, diag::err_ivar_reference_type);
10047     D.setInvalidType();
10048   }
10049   // C99 6.7.2.1p8: A member of a structure or union may have any type other
10050   // than a variably modified type.
10051   else if (T->isVariablyModifiedType()) {
10052     Diag(Loc, diag::err_typecheck_ivar_variable_size);
10053     D.setInvalidType();
10054   }
10055 
10056   // Get the visibility (access control) for this ivar.
10057   ObjCIvarDecl::AccessControl ac =
10058     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
10059                                         : ObjCIvarDecl::None;
10060   // Must set ivar's DeclContext to its enclosing interface.
10061   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
10062   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
10063     return 0;
10064   ObjCContainerDecl *EnclosingContext;
10065   if (ObjCImplementationDecl *IMPDecl =
10066       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10067     if (LangOpts.ObjCRuntime.isFragile()) {
10068     // Case of ivar declared in an implementation. Context is that of its class.
10069       EnclosingContext = IMPDecl->getClassInterface();
10070       assert(EnclosingContext && "Implementation has no class interface!");
10071     }
10072     else
10073       EnclosingContext = EnclosingDecl;
10074   } else {
10075     if (ObjCCategoryDecl *CDecl =
10076         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10077       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
10078         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
10079         return 0;
10080       }
10081     }
10082     EnclosingContext = EnclosingDecl;
10083   }
10084 
10085   // Construct the decl.
10086   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
10087                                              DeclStart, Loc, II, T,
10088                                              TInfo, ac, (Expr *)BitfieldWidth);
10089 
10090   if (II) {
10091     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
10092                                            ForRedeclaration);
10093     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
10094         && !isa<TagDecl>(PrevDecl)) {
10095       Diag(Loc, diag::err_duplicate_member) << II;
10096       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10097       NewID->setInvalidDecl();
10098     }
10099   }
10100 
10101   // Process attributes attached to the ivar.
10102   ProcessDeclAttributes(S, NewID, D);
10103 
10104   if (D.isInvalidType())
10105     NewID->setInvalidDecl();
10106 
10107   // In ARC, infer 'retaining' for ivars of retainable type.
10108   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
10109     NewID->setInvalidDecl();
10110 
10111   if (D.getDeclSpec().isModulePrivateSpecified())
10112     NewID->setModulePrivate();
10113 
10114   if (II) {
10115     // FIXME: When interfaces are DeclContexts, we'll need to add
10116     // these to the interface.
10117     S->AddDecl(NewID);
10118     IdResolver.AddDecl(NewID);
10119   }
10120 
10121   if (LangOpts.ObjCRuntime.isNonFragile() &&
10122       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
10123     Diag(Loc, diag::warn_ivars_in_interface);
10124 
10125   return NewID;
10126 }
10127 
10128 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
10129 /// class and class extensions. For every class @interface and class
10130 /// extension @interface, if the last ivar is a bitfield of any type,
10131 /// then add an implicit `char :0` ivar to the end of that interface.
10132 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
10133                              SmallVectorImpl<Decl *> &AllIvarDecls) {
10134   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
10135     return;
10136 
10137   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
10138   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
10139 
10140   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
10141     return;
10142   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
10143   if (!ID) {
10144     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
10145       if (!CD->IsClassExtension())
10146         return;
10147     }
10148     // No need to add this to end of @implementation.
10149     else
10150       return;
10151   }
10152   // All conditions are met. Add a new bitfield to the tail end of ivars.
10153   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
10154   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
10155 
10156   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
10157                               DeclLoc, DeclLoc, 0,
10158                               Context.CharTy,
10159                               Context.getTrivialTypeSourceInfo(Context.CharTy,
10160                                                                DeclLoc),
10161                               ObjCIvarDecl::Private, BW,
10162                               true);
10163   AllIvarDecls.push_back(Ivar);
10164 }
10165 
10166 void Sema::ActOnFields(Scope* S,
10167                        SourceLocation RecLoc, Decl *EnclosingDecl,
10168                        llvm::ArrayRef<Decl *> Fields,
10169                        SourceLocation LBrac, SourceLocation RBrac,
10170                        AttributeList *Attr) {
10171   assert(EnclosingDecl && "missing record or interface decl");
10172 
10173   // If this is an Objective-C @implementation or category and we have
10174   // new fields here we should reset the layout of the interface since
10175   // it will now change.
10176   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10177     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10178     switch (DC->getKind()) {
10179     default: break;
10180     case Decl::ObjCCategory:
10181       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10182       break;
10183     case Decl::ObjCImplementation:
10184       Context.
10185         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10186       break;
10187     }
10188   }
10189 
10190   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10191 
10192   // Start counting up the number of named members; make sure to include
10193   // members of anonymous structs and unions in the total.
10194   unsigned NumNamedMembers = 0;
10195   if (Record) {
10196     for (RecordDecl::decl_iterator i = Record->decls_begin(),
10197                                    e = Record->decls_end(); i != e; i++) {
10198       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10199         if (IFD->getDeclName())
10200           ++NumNamedMembers;
10201     }
10202   }
10203 
10204   // Verify that all the fields are okay.
10205   SmallVector<FieldDecl*, 32> RecFields;
10206 
10207   bool ARCErrReported = false;
10208   for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10209        i != end; ++i) {
10210     FieldDecl *FD = cast<FieldDecl>(*i);
10211 
10212     // Get the type for the field.
10213     const Type *FDTy = FD->getType().getTypePtr();
10214 
10215     if (!FD->isAnonymousStructOrUnion()) {
10216       // Remember all fields written by the user.
10217       RecFields.push_back(FD);
10218     }
10219 
10220     // If the field is already invalid for some reason, don't emit more
10221     // diagnostics about it.
10222     if (FD->isInvalidDecl()) {
10223       EnclosingDecl->setInvalidDecl();
10224       continue;
10225     }
10226 
10227     // C99 6.7.2.1p2:
10228     //   A structure or union shall not contain a member with
10229     //   incomplete or function type (hence, a structure shall not
10230     //   contain an instance of itself, but may contain a pointer to
10231     //   an instance of itself), except that the last member of a
10232     //   structure with more than one named member may have incomplete
10233     //   array type; such a structure (and any union containing,
10234     //   possibly recursively, a member that is such a structure)
10235     //   shall not be a member of a structure or an element of an
10236     //   array.
10237     if (FDTy->isFunctionType()) {
10238       // Field declared as a function.
10239       Diag(FD->getLocation(), diag::err_field_declared_as_function)
10240         << FD->getDeclName();
10241       FD->setInvalidDecl();
10242       EnclosingDecl->setInvalidDecl();
10243       continue;
10244     } else if (FDTy->isIncompleteArrayType() && Record &&
10245                ((i + 1 == Fields.end() && !Record->isUnion()) ||
10246                 ((getLangOpts().MicrosoftExt ||
10247                   getLangOpts().CPlusPlus) &&
10248                  (i + 1 == Fields.end() || Record->isUnion())))) {
10249       // Flexible array member.
10250       // Microsoft and g++ is more permissive regarding flexible array.
10251       // It will accept flexible array in union and also
10252       // as the sole element of a struct/class.
10253       if (getLangOpts().MicrosoftExt) {
10254         if (Record->isUnion())
10255           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
10256             << FD->getDeclName();
10257         else if (Fields.size() == 1)
10258           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
10259             << FD->getDeclName() << Record->getTagKind();
10260       } else if (getLangOpts().CPlusPlus) {
10261         if (Record->isUnion())
10262           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10263             << FD->getDeclName();
10264         else if (Fields.size() == 1)
10265           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10266             << FD->getDeclName() << Record->getTagKind();
10267       } else if (!getLangOpts().C99) {
10268       if (Record->isUnion())
10269         Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10270           << FD->getDeclName();
10271       else
10272         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10273           << FD->getDeclName() << Record->getTagKind();
10274       } else if (NumNamedMembers < 1) {
10275         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
10276           << FD->getDeclName();
10277         FD->setInvalidDecl();
10278         EnclosingDecl->setInvalidDecl();
10279         continue;
10280       }
10281       if (!FD->getType()->isDependentType() &&
10282           !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
10283         Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
10284           << FD->getDeclName() << FD->getType();
10285         FD->setInvalidDecl();
10286         EnclosingDecl->setInvalidDecl();
10287         continue;
10288       }
10289       // Okay, we have a legal flexible array member at the end of the struct.
10290       if (Record)
10291         Record->setHasFlexibleArrayMember(true);
10292     } else if (!FDTy->isDependentType() &&
10293                RequireCompleteType(FD->getLocation(), FD->getType(),
10294                                    diag::err_field_incomplete)) {
10295       // Incomplete type
10296       FD->setInvalidDecl();
10297       EnclosingDecl->setInvalidDecl();
10298       continue;
10299     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
10300       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10301         // If this is a member of a union, then entire union becomes "flexible".
10302         if (Record && Record->isUnion()) {
10303           Record->setHasFlexibleArrayMember(true);
10304         } else {
10305           // If this is a struct/class and this is not the last element, reject
10306           // it.  Note that GCC supports variable sized arrays in the middle of
10307           // structures.
10308           if (i + 1 != Fields.end())
10309             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
10310               << FD->getDeclName() << FD->getType();
10311           else {
10312             // We support flexible arrays at the end of structs in
10313             // other structs as an extension.
10314             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10315               << FD->getDeclName();
10316             if (Record)
10317               Record->setHasFlexibleArrayMember(true);
10318           }
10319         }
10320       }
10321       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10322           RequireNonAbstractType(FD->getLocation(), FD->getType(),
10323                                  diag::err_abstract_type_in_decl,
10324                                  AbstractIvarType)) {
10325         // Ivars can not have abstract class types
10326         FD->setInvalidDecl();
10327       }
10328       if (Record && FDTTy->getDecl()->hasObjectMember())
10329         Record->setHasObjectMember(true);
10330     } else if (FDTy->isObjCObjectType()) {
10331       /// A field cannot be an Objective-c object
10332       Diag(FD->getLocation(), diag::err_statically_allocated_object)
10333         << FixItHint::CreateInsertion(FD->getLocation(), "*");
10334       QualType T = Context.getObjCObjectPointerType(FD->getType());
10335       FD->setType(T);
10336     } else if (!getLangOpts().CPlusPlus) {
10337       if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
10338         // It's an error in ARC if a field has lifetime.
10339         // We don't want to report this in a system header, though,
10340         // so we just make the field unavailable.
10341         // FIXME: that's really not sufficient; we need to make the type
10342         // itself invalid to, say, initialize or copy.
10343         QualType T = FD->getType();
10344         Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10345         if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10346           SourceLocation loc = FD->getLocation();
10347           if (getSourceManager().isInSystemHeader(loc)) {
10348             if (!FD->hasAttr<UnavailableAttr>()) {
10349               FD->addAttr(new (Context) UnavailableAttr(loc, Context,
10350                                 "this system field has retaining ownership"));
10351             }
10352           } else {
10353             Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
10354               << T->isBlockPointerType();
10355           }
10356           ARCErrReported = true;
10357         }
10358       }
10359       else if (getLangOpts().ObjC1 &&
10360                getLangOpts().getGC() != LangOptions::NonGC &&
10361                Record && !Record->hasObjectMember()) {
10362         if (FD->getType()->isObjCObjectPointerType() ||
10363             FD->getType().isObjCGCStrong())
10364           Record->setHasObjectMember(true);
10365         else if (Context.getAsArrayType(FD->getType())) {
10366           QualType BaseType = Context.getBaseElementType(FD->getType());
10367           if (BaseType->isRecordType() &&
10368               BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10369             Record->setHasObjectMember(true);
10370           else if (BaseType->isObjCObjectPointerType() ||
10371                    BaseType.isObjCGCStrong())
10372                  Record->setHasObjectMember(true);
10373         }
10374       }
10375     }
10376     // Keep track of the number of named members.
10377     if (FD->getIdentifier())
10378       ++NumNamedMembers;
10379   }
10380 
10381   // Okay, we successfully defined 'Record'.
10382   if (Record) {
10383     bool Completed = false;
10384     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10385       if (!CXXRecord->isInvalidDecl()) {
10386         // Set access bits correctly on the directly-declared conversions.
10387         for (CXXRecordDecl::conversion_iterator
10388                I = CXXRecord->conversion_begin(),
10389                E = CXXRecord->conversion_end(); I != E; ++I)
10390           I.setAccess((*I)->getAccess());
10391 
10392         if (!CXXRecord->isDependentType()) {
10393           // Adjust user-defined destructor exception spec.
10394           if (getLangOpts().CPlusPlus0x &&
10395               CXXRecord->hasUserDeclaredDestructor())
10396             AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10397 
10398           // Add any implicitly-declared members to this class.
10399           AddImplicitlyDeclaredMembersToClass(CXXRecord);
10400 
10401           // If we have virtual base classes, we may end up finding multiple
10402           // final overriders for a given virtual function. Check for this
10403           // problem now.
10404           if (CXXRecord->getNumVBases()) {
10405             CXXFinalOverriderMap FinalOverriders;
10406             CXXRecord->getFinalOverriders(FinalOverriders);
10407 
10408             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10409                                              MEnd = FinalOverriders.end();
10410                  M != MEnd; ++M) {
10411               for (OverridingMethods::iterator SO = M->second.begin(),
10412                                             SOEnd = M->second.end();
10413                    SO != SOEnd; ++SO) {
10414                 assert(SO->second.size() > 0 &&
10415                        "Virtual function without overridding functions?");
10416                 if (SO->second.size() == 1)
10417                   continue;
10418 
10419                 // C++ [class.virtual]p2:
10420                 //   In a derived class, if a virtual member function of a base
10421                 //   class subobject has more than one final overrider the
10422                 //   program is ill-formed.
10423                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10424                   << (const NamedDecl *)M->first << Record;
10425                 Diag(M->first->getLocation(),
10426                      diag::note_overridden_virtual_function);
10427                 for (OverridingMethods::overriding_iterator
10428                           OM = SO->second.begin(),
10429                        OMEnd = SO->second.end();
10430                      OM != OMEnd; ++OM)
10431                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
10432                     << (const NamedDecl *)M->first << OM->Method->getParent();
10433 
10434                 Record->setInvalidDecl();
10435               }
10436             }
10437             CXXRecord->completeDefinition(&FinalOverriders);
10438             Completed = true;
10439           }
10440         }
10441       }
10442     }
10443 
10444     if (!Completed)
10445       Record->completeDefinition();
10446 
10447   } else {
10448     ObjCIvarDecl **ClsFields =
10449       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
10450     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
10451       ID->setEndOfDefinitionLoc(RBrac);
10452       // Add ivar's to class's DeclContext.
10453       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10454         ClsFields[i]->setLexicalDeclContext(ID);
10455         ID->addDecl(ClsFields[i]);
10456       }
10457       // Must enforce the rule that ivars in the base classes may not be
10458       // duplicates.
10459       if (ID->getSuperClass())
10460         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
10461     } else if (ObjCImplementationDecl *IMPDecl =
10462                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10463       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
10464       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10465         // Ivar declared in @implementation never belongs to the implementation.
10466         // Only it is in implementation's lexical context.
10467         ClsFields[I]->setLexicalDeclContext(IMPDecl);
10468       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
10469       IMPDecl->setIvarLBraceLoc(LBrac);
10470       IMPDecl->setIvarRBraceLoc(RBrac);
10471     } else if (ObjCCategoryDecl *CDecl =
10472                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10473       // case of ivars in class extension; all other cases have been
10474       // reported as errors elsewhere.
10475       // FIXME. Class extension does not have a LocEnd field.
10476       // CDecl->setLocEnd(RBrac);
10477       // Add ivar's to class extension's DeclContext.
10478       // Diagnose redeclaration of private ivars.
10479       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
10480       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10481         if (IDecl) {
10482           if (const ObjCIvarDecl *ClsIvar =
10483               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10484             Diag(ClsFields[i]->getLocation(),
10485                  diag::err_duplicate_ivar_declaration);
10486             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10487             continue;
10488           }
10489           for (const ObjCCategoryDecl *ClsExtDecl =
10490                 IDecl->getFirstClassExtension();
10491                ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10492             if (const ObjCIvarDecl *ClsExtIvar =
10493                 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10494               Diag(ClsFields[i]->getLocation(),
10495                    diag::err_duplicate_ivar_declaration);
10496               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10497               continue;
10498             }
10499           }
10500         }
10501         ClsFields[i]->setLexicalDeclContext(CDecl);
10502         CDecl->addDecl(ClsFields[i]);
10503       }
10504       CDecl->setIvarLBraceLoc(LBrac);
10505       CDecl->setIvarRBraceLoc(RBrac);
10506     }
10507   }
10508 
10509   if (Attr)
10510     ProcessDeclAttributeList(S, Record, Attr);
10511 }
10512 
10513 /// \brief Determine whether the given integral value is representable within
10514 /// the given type T.
10515 static bool isRepresentableIntegerValue(ASTContext &Context,
10516                                         llvm::APSInt &Value,
10517                                         QualType T) {
10518   assert(T->isIntegralType(Context) && "Integral type required!");
10519   unsigned BitWidth = Context.getIntWidth(T);
10520 
10521   if (Value.isUnsigned() || Value.isNonNegative()) {
10522     if (T->isSignedIntegerOrEnumerationType())
10523       --BitWidth;
10524     return Value.getActiveBits() <= BitWidth;
10525   }
10526   return Value.getMinSignedBits() <= BitWidth;
10527 }
10528 
10529 // \brief Given an integral type, return the next larger integral type
10530 // (or a NULL type of no such type exists).
10531 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10532   // FIXME: Int128/UInt128 support, which also needs to be introduced into
10533   // enum checking below.
10534   assert(T->isIntegralType(Context) && "Integral type required!");
10535   const unsigned NumTypes = 4;
10536   QualType SignedIntegralTypes[NumTypes] = {
10537     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10538   };
10539   QualType UnsignedIntegralTypes[NumTypes] = {
10540     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10541     Context.UnsignedLongLongTy
10542   };
10543 
10544   unsigned BitWidth = Context.getTypeSize(T);
10545   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10546                                                         : UnsignedIntegralTypes;
10547   for (unsigned I = 0; I != NumTypes; ++I)
10548     if (Context.getTypeSize(Types[I]) > BitWidth)
10549       return Types[I];
10550 
10551   return QualType();
10552 }
10553 
10554 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10555                                           EnumConstantDecl *LastEnumConst,
10556                                           SourceLocation IdLoc,
10557                                           IdentifierInfo *Id,
10558                                           Expr *Val) {
10559   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10560   llvm::APSInt EnumVal(IntWidth);
10561   QualType EltTy;
10562 
10563   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10564     Val = 0;
10565 
10566   if (Val)
10567     Val = DefaultLvalueConversion(Val).take();
10568 
10569   if (Val) {
10570     if (Enum->isDependentType() || Val->isTypeDependent())
10571       EltTy = Context.DependentTy;
10572     else {
10573       SourceLocation ExpLoc;
10574       if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
10575           !getLangOpts().MicrosoftMode) {
10576         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10577         // constant-expression in the enumerator-definition shall be a converted
10578         // constant expression of the underlying type.
10579         EltTy = Enum->getIntegerType();
10580         ExprResult Converted =
10581           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10582                                            CCEK_Enumerator);
10583         if (Converted.isInvalid())
10584           Val = 0;
10585         else
10586           Val = Converted.take();
10587       } else if (!Val->isValueDependent() &&
10588                  !(Val = VerifyIntegerConstantExpression(Val,
10589                                                          &EnumVal).take())) {
10590         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
10591       } else {
10592         if (Enum->isFixed()) {
10593           EltTy = Enum->getIntegerType();
10594 
10595           // In Obj-C and Microsoft mode, require the enumeration value to be
10596           // representable in the underlying type of the enumeration. In C++11,
10597           // we perform a non-narrowing conversion as part of converted constant
10598           // expression checking.
10599           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10600             if (getLangOpts().MicrosoftMode) {
10601               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
10602               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10603             } else
10604               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
10605           } else
10606             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10607         } else if (getLangOpts().CPlusPlus) {
10608           // C++11 [dcl.enum]p5:
10609           //   If the underlying type is not fixed, the type of each enumerator
10610           //   is the type of its initializing value:
10611           //     - If an initializer is specified for an enumerator, the
10612           //       initializing value has the same type as the expression.
10613           EltTy = Val->getType();
10614         } else {
10615           // C99 6.7.2.2p2:
10616           //   The expression that defines the value of an enumeration constant
10617           //   shall be an integer constant expression that has a value
10618           //   representable as an int.
10619 
10620           // Complain if the value is not representable in an int.
10621           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10622             Diag(IdLoc, diag::ext_enum_value_not_int)
10623               << EnumVal.toString(10) << Val->getSourceRange()
10624               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10625           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10626             // Force the type of the expression to 'int'.
10627             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10628           }
10629           EltTy = Val->getType();
10630         }
10631       }
10632     }
10633   }
10634 
10635   if (!Val) {
10636     if (Enum->isDependentType())
10637       EltTy = Context.DependentTy;
10638     else if (!LastEnumConst) {
10639       // C++0x [dcl.enum]p5:
10640       //   If the underlying type is not fixed, the type of each enumerator
10641       //   is the type of its initializing value:
10642       //     - If no initializer is specified for the first enumerator, the
10643       //       initializing value has an unspecified integral type.
10644       //
10645       // GCC uses 'int' for its unspecified integral type, as does
10646       // C99 6.7.2.2p3.
10647       if (Enum->isFixed()) {
10648         EltTy = Enum->getIntegerType();
10649       }
10650       else {
10651         EltTy = Context.IntTy;
10652       }
10653     } else {
10654       // Assign the last value + 1.
10655       EnumVal = LastEnumConst->getInitVal();
10656       ++EnumVal;
10657       EltTy = LastEnumConst->getType();
10658 
10659       // Check for overflow on increment.
10660       if (EnumVal < LastEnumConst->getInitVal()) {
10661         // C++0x [dcl.enum]p5:
10662         //   If the underlying type is not fixed, the type of each enumerator
10663         //   is the type of its initializing value:
10664         //
10665         //     - Otherwise the type of the initializing value is the same as
10666         //       the type of the initializing value of the preceding enumerator
10667         //       unless the incremented value is not representable in that type,
10668         //       in which case the type is an unspecified integral type
10669         //       sufficient to contain the incremented value. If no such type
10670         //       exists, the program is ill-formed.
10671         QualType T = getNextLargerIntegralType(Context, EltTy);
10672         if (T.isNull() || Enum->isFixed()) {
10673           // There is no integral type larger enough to represent this
10674           // value. Complain, then allow the value to wrap around.
10675           EnumVal = LastEnumConst->getInitVal();
10676           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10677           ++EnumVal;
10678           if (Enum->isFixed())
10679             // When the underlying type is fixed, this is ill-formed.
10680             Diag(IdLoc, diag::err_enumerator_wrapped)
10681               << EnumVal.toString(10)
10682               << EltTy;
10683           else
10684             Diag(IdLoc, diag::warn_enumerator_too_large)
10685               << EnumVal.toString(10);
10686         } else {
10687           EltTy = T;
10688         }
10689 
10690         // Retrieve the last enumerator's value, extent that type to the
10691         // type that is supposed to be large enough to represent the incremented
10692         // value, then increment.
10693         EnumVal = LastEnumConst->getInitVal();
10694         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10695         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10696         ++EnumVal;
10697 
10698         // If we're not in C++, diagnose the overflow of enumerator values,
10699         // which in C99 means that the enumerator value is not representable in
10700         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10701         // permits enumerator values that are representable in some larger
10702         // integral type.
10703         if (!getLangOpts().CPlusPlus && !T.isNull())
10704           Diag(IdLoc, diag::warn_enum_value_overflow);
10705       } else if (!getLangOpts().CPlusPlus &&
10706                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10707         // Enforce C99 6.7.2.2p2 even when we compute the next value.
10708         Diag(IdLoc, diag::ext_enum_value_not_int)
10709           << EnumVal.toString(10) << 1;
10710       }
10711     }
10712   }
10713 
10714   if (!EltTy->isDependentType()) {
10715     // Make the enumerator value match the signedness and size of the
10716     // enumerator's type.
10717     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10718     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10719   }
10720 
10721   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10722                                   Val, EnumVal);
10723 }
10724 
10725 
10726 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10727                               SourceLocation IdLoc, IdentifierInfo *Id,
10728                               AttributeList *Attr,
10729                               SourceLocation EqualLoc, Expr *Val) {
10730   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10731   EnumConstantDecl *LastEnumConst =
10732     cast_or_null<EnumConstantDecl>(lastEnumConst);
10733 
10734   // The scope passed in may not be a decl scope.  Zip up the scope tree until
10735   // we find one that is.
10736   S = getNonFieldDeclScope(S);
10737 
10738   // Verify that there isn't already something declared with this name in this
10739   // scope.
10740   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10741                                          ForRedeclaration);
10742   if (PrevDecl && PrevDecl->isTemplateParameter()) {
10743     // Maybe we will complain about the shadowed template parameter.
10744     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10745     // Just pretend that we didn't see the previous declaration.
10746     PrevDecl = 0;
10747   }
10748 
10749   if (PrevDecl) {
10750     // When in C++, we may get a TagDecl with the same name; in this case the
10751     // enum constant will 'hide' the tag.
10752     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10753            "Received TagDecl when not in C++!");
10754     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10755       if (isa<EnumConstantDecl>(PrevDecl))
10756         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10757       else
10758         Diag(IdLoc, diag::err_redefinition) << Id;
10759       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10760       return 0;
10761     }
10762   }
10763 
10764   // C++ [class.mem]p15:
10765   // If T is the name of a class, then each of the following shall have a name
10766   // different from T:
10767   // - every enumerator of every member of class T that is an unscoped
10768   // enumerated type
10769   if (CXXRecordDecl *Record
10770                       = dyn_cast<CXXRecordDecl>(
10771                              TheEnumDecl->getDeclContext()->getRedeclContext()))
10772     if (!TheEnumDecl->isScoped() &&
10773         Record->getIdentifier() && Record->getIdentifier() == Id)
10774       Diag(IdLoc, diag::err_member_name_of_class) << Id;
10775 
10776   EnumConstantDecl *New =
10777     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10778 
10779   if (New) {
10780     // Process attributes.
10781     if (Attr) ProcessDeclAttributeList(S, New, Attr);
10782 
10783     // Register this decl in the current scope stack.
10784     New->setAccess(TheEnumDecl->getAccess());
10785     PushOnScopeChains(New, S);
10786   }
10787 
10788   ActOnDocumentableDecl(New);
10789 
10790   return New;
10791 }
10792 
10793 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10794                          SourceLocation RBraceLoc, Decl *EnumDeclX,
10795                          Decl **Elements, unsigned NumElements,
10796                          Scope *S, AttributeList *Attr) {
10797   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10798   QualType EnumType = Context.getTypeDeclType(Enum);
10799 
10800   if (Attr)
10801     ProcessDeclAttributeList(S, Enum, Attr);
10802 
10803   if (Enum->isDependentType()) {
10804     for (unsigned i = 0; i != NumElements; ++i) {
10805       EnumConstantDecl *ECD =
10806         cast_or_null<EnumConstantDecl>(Elements[i]);
10807       if (!ECD) continue;
10808 
10809       ECD->setType(EnumType);
10810     }
10811 
10812     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10813     return;
10814   }
10815 
10816   // TODO: If the result value doesn't fit in an int, it must be a long or long
10817   // long value.  ISO C does not support this, but GCC does as an extension,
10818   // emit a warning.
10819   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10820   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10821   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10822 
10823   // Verify that all the values are okay, compute the size of the values, and
10824   // reverse the list.
10825   unsigned NumNegativeBits = 0;
10826   unsigned NumPositiveBits = 0;
10827 
10828   // Keep track of whether all elements have type int.
10829   bool AllElementsInt = true;
10830 
10831   for (unsigned i = 0; i != NumElements; ++i) {
10832     EnumConstantDecl *ECD =
10833       cast_or_null<EnumConstantDecl>(Elements[i]);
10834     if (!ECD) continue;  // Already issued a diagnostic.
10835 
10836     const llvm::APSInt &InitVal = ECD->getInitVal();
10837 
10838     // Keep track of the size of positive and negative values.
10839     if (InitVal.isUnsigned() || InitVal.isNonNegative())
10840       NumPositiveBits = std::max(NumPositiveBits,
10841                                  (unsigned)InitVal.getActiveBits());
10842     else
10843       NumNegativeBits = std::max(NumNegativeBits,
10844                                  (unsigned)InitVal.getMinSignedBits());
10845 
10846     // Keep track of whether every enum element has type int (very commmon).
10847     if (AllElementsInt)
10848       AllElementsInt = ECD->getType() == Context.IntTy;
10849   }
10850 
10851   // Figure out the type that should be used for this enum.
10852   QualType BestType;
10853   unsigned BestWidth;
10854 
10855   // C++0x N3000 [conv.prom]p3:
10856   //   An rvalue of an unscoped enumeration type whose underlying
10857   //   type is not fixed can be converted to an rvalue of the first
10858   //   of the following types that can represent all the values of
10859   //   the enumeration: int, unsigned int, long int, unsigned long
10860   //   int, long long int, or unsigned long long int.
10861   // C99 6.4.4.3p2:
10862   //   An identifier declared as an enumeration constant has type int.
10863   // The C99 rule is modified by a gcc extension
10864   QualType BestPromotionType;
10865 
10866   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10867   // -fshort-enums is the equivalent to specifying the packed attribute on all
10868   // enum definitions.
10869   if (LangOpts.ShortEnums)
10870     Packed = true;
10871 
10872   if (Enum->isFixed()) {
10873     BestType = Enum->getIntegerType();
10874     if (BestType->isPromotableIntegerType())
10875       BestPromotionType = Context.getPromotedIntegerType(BestType);
10876     else
10877       BestPromotionType = BestType;
10878     // We don't need to set BestWidth, because BestType is going to be the type
10879     // of the enumerators, but we do anyway because otherwise some compilers
10880     // warn that it might be used uninitialized.
10881     BestWidth = CharWidth;
10882   }
10883   else if (NumNegativeBits) {
10884     // If there is a negative value, figure out the smallest integer type (of
10885     // int/long/longlong) that fits.
10886     // If it's packed, check also if it fits a char or a short.
10887     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10888       BestType = Context.SignedCharTy;
10889       BestWidth = CharWidth;
10890     } else if (Packed && NumNegativeBits <= ShortWidth &&
10891                NumPositiveBits < ShortWidth) {
10892       BestType = Context.ShortTy;
10893       BestWidth = ShortWidth;
10894     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10895       BestType = Context.IntTy;
10896       BestWidth = IntWidth;
10897     } else {
10898       BestWidth = Context.getTargetInfo().getLongWidth();
10899 
10900       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10901         BestType = Context.LongTy;
10902       } else {
10903         BestWidth = Context.getTargetInfo().getLongLongWidth();
10904 
10905         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10906           Diag(Enum->getLocation(), diag::warn_enum_too_large);
10907         BestType = Context.LongLongTy;
10908       }
10909     }
10910     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10911   } else {
10912     // If there is no negative value, figure out the smallest type that fits
10913     // all of the enumerator values.
10914     // If it's packed, check also if it fits a char or a short.
10915     if (Packed && NumPositiveBits <= CharWidth) {
10916       BestType = Context.UnsignedCharTy;
10917       BestPromotionType = Context.IntTy;
10918       BestWidth = CharWidth;
10919     } else if (Packed && NumPositiveBits <= ShortWidth) {
10920       BestType = Context.UnsignedShortTy;
10921       BestPromotionType = Context.IntTy;
10922       BestWidth = ShortWidth;
10923     } else if (NumPositiveBits <= IntWidth) {
10924       BestType = Context.UnsignedIntTy;
10925       BestWidth = IntWidth;
10926       BestPromotionType
10927         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10928                            ? Context.UnsignedIntTy : Context.IntTy;
10929     } else if (NumPositiveBits <=
10930                (BestWidth = Context.getTargetInfo().getLongWidth())) {
10931       BestType = Context.UnsignedLongTy;
10932       BestPromotionType
10933         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10934                            ? Context.UnsignedLongTy : Context.LongTy;
10935     } else {
10936       BestWidth = Context.getTargetInfo().getLongLongWidth();
10937       assert(NumPositiveBits <= BestWidth &&
10938              "How could an initializer get larger than ULL?");
10939       BestType = Context.UnsignedLongLongTy;
10940       BestPromotionType
10941         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10942                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
10943     }
10944   }
10945 
10946   // Loop over all of the enumerator constants, changing their types to match
10947   // the type of the enum if needed.
10948   for (unsigned i = 0; i != NumElements; ++i) {
10949     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10950     if (!ECD) continue;  // Already issued a diagnostic.
10951 
10952     // Standard C says the enumerators have int type, but we allow, as an
10953     // extension, the enumerators to be larger than int size.  If each
10954     // enumerator value fits in an int, type it as an int, otherwise type it the
10955     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
10956     // that X has type 'int', not 'unsigned'.
10957 
10958     // Determine whether the value fits into an int.
10959     llvm::APSInt InitVal = ECD->getInitVal();
10960 
10961     // If it fits into an integer type, force it.  Otherwise force it to match
10962     // the enum decl type.
10963     QualType NewTy;
10964     unsigned NewWidth;
10965     bool NewSign;
10966     if (!getLangOpts().CPlusPlus &&
10967         !Enum->isFixed() &&
10968         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10969       NewTy = Context.IntTy;
10970       NewWidth = IntWidth;
10971       NewSign = true;
10972     } else if (ECD->getType() == BestType) {
10973       // Already the right type!
10974       if (getLangOpts().CPlusPlus)
10975         // C++ [dcl.enum]p4: Following the closing brace of an
10976         // enum-specifier, each enumerator has the type of its
10977         // enumeration.
10978         ECD->setType(EnumType);
10979       continue;
10980     } else {
10981       NewTy = BestType;
10982       NewWidth = BestWidth;
10983       NewSign = BestType->isSignedIntegerOrEnumerationType();
10984     }
10985 
10986     // Adjust the APSInt value.
10987     InitVal = InitVal.extOrTrunc(NewWidth);
10988     InitVal.setIsSigned(NewSign);
10989     ECD->setInitVal(InitVal);
10990 
10991     // Adjust the Expr initializer and type.
10992     if (ECD->getInitExpr() &&
10993         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10994       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10995                                                 CK_IntegralCast,
10996                                                 ECD->getInitExpr(),
10997                                                 /*base paths*/ 0,
10998                                                 VK_RValue));
10999     if (getLangOpts().CPlusPlus)
11000       // C++ [dcl.enum]p4: Following the closing brace of an
11001       // enum-specifier, each enumerator has the type of its
11002       // enumeration.
11003       ECD->setType(EnumType);
11004     else
11005       ECD->setType(NewTy);
11006   }
11007 
11008   Enum->completeDefinition(BestType, BestPromotionType,
11009                            NumPositiveBits, NumNegativeBits);
11010 
11011   // If we're declaring a function, ensure this decl isn't forgotten about -
11012   // it needs to go into the function scope.
11013   if (InFunctionDeclarator)
11014     DeclsInPrototypeScope.push_back(Enum);
11015 }
11016 
11017 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
11018                                   SourceLocation StartLoc,
11019                                   SourceLocation EndLoc) {
11020   StringLiteral *AsmString = cast<StringLiteral>(expr);
11021 
11022   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
11023                                                    AsmString, StartLoc,
11024                                                    EndLoc);
11025   CurContext->addDecl(New);
11026   return New;
11027 }
11028 
11029 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
11030                                    SourceLocation ImportLoc,
11031                                    ModuleIdPath Path) {
11032   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
11033                                                 Module::AllVisible,
11034                                                 /*IsIncludeDirective=*/false);
11035   if (!Mod)
11036     return true;
11037 
11038   llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
11039   Module *ModCheck = Mod;
11040   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
11041     // If we've run out of module parents, just drop the remaining identifiers.
11042     // We need the length to be consistent.
11043     if (!ModCheck)
11044       break;
11045     ModCheck = ModCheck->Parent;
11046 
11047     IdentifierLocs.push_back(Path[I].second);
11048   }
11049 
11050   ImportDecl *Import = ImportDecl::Create(Context,
11051                                           Context.getTranslationUnitDecl(),
11052                                           AtLoc.isValid()? AtLoc : ImportLoc,
11053                                           Mod, IdentifierLocs);
11054   Context.getTranslationUnitDecl()->addDecl(Import);
11055   return Import;
11056 }
11057 
11058 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
11059                                       IdentifierInfo* AliasName,
11060                                       SourceLocation PragmaLoc,
11061                                       SourceLocation NameLoc,
11062                                       SourceLocation AliasNameLoc) {
11063   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
11064                                     LookupOrdinaryName);
11065   AsmLabelAttr *Attr =
11066      ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
11067 
11068   if (PrevDecl)
11069     PrevDecl->addAttr(Attr);
11070   else
11071     (void)ExtnameUndeclaredIdentifiers.insert(
11072       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
11073 }
11074 
11075 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
11076                              SourceLocation PragmaLoc,
11077                              SourceLocation NameLoc) {
11078   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
11079 
11080   if (PrevDecl) {
11081     PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
11082   } else {
11083     (void)WeakUndeclaredIdentifiers.insert(
11084       std::pair<IdentifierInfo*,WeakInfo>
11085         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
11086   }
11087 }
11088 
11089 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
11090                                 IdentifierInfo* AliasName,
11091                                 SourceLocation PragmaLoc,
11092                                 SourceLocation NameLoc,
11093                                 SourceLocation AliasNameLoc) {
11094   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
11095                                     LookupOrdinaryName);
11096   WeakInfo W = WeakInfo(Name, NameLoc);
11097 
11098   if (PrevDecl) {
11099     if (!PrevDecl->hasAttr<AliasAttr>())
11100       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
11101         DeclApplyPragmaWeak(TUScope, ND, W);
11102   } else {
11103     (void)WeakUndeclaredIdentifiers.insert(
11104       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
11105   }
11106 }
11107 
11108 Decl *Sema::getObjCDeclContext() const {
11109   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
11110 }
11111 
11112 AvailabilityResult Sema::getCurContextAvailability() const {
11113   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
11114   return D->getAvailability();
11115 }
11116