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/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34 #include "clang/Parse/ParseDiagnostic.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 using namespace clang;
50 using namespace sema;
51 
52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53   if (OwnedType) {
54     Decl *Group[2] = { OwnedType, Ptr };
55     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56   }
57 
58   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
59 }
60 
61 namespace {
62 
63 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64  public:
65   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66                        bool AllowTemplates=false)
67       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68         AllowClassTemplates(AllowTemplates) {
69     WantExpressionKeywords = false;
70     WantCXXNamedCasts = false;
71     WantRemainingKeywords = false;
72   }
73 
74   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
75     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78       return (IsType || AllowedTemplate) &&
79              (AllowInvalidDecl || !ND->isInvalidDecl());
80     }
81     return !WantClassName && candidate.isKeyword();
82   }
83 
84  private:
85   bool AllowInvalidDecl;
86   bool WantClassName;
87   bool AllowClassTemplates;
88 };
89 
90 }
91 
92 /// \brief Determine whether the token kind starts a simple-type-specifier.
93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94   switch (Kind) {
95   // FIXME: Take into account the current language when deciding whether a
96   // token kind is a valid type specifier
97   case tok::kw_short:
98   case tok::kw_long:
99   case tok::kw___int64:
100   case tok::kw___int128:
101   case tok::kw_signed:
102   case tok::kw_unsigned:
103   case tok::kw_void:
104   case tok::kw_char:
105   case tok::kw_int:
106   case tok::kw_half:
107   case tok::kw_float:
108   case tok::kw_double:
109   case tok::kw_wchar_t:
110   case tok::kw_bool:
111   case tok::kw___underlying_type:
112     return true;
113 
114   case tok::annot_typename:
115   case tok::kw_char16_t:
116   case tok::kw_char32_t:
117   case tok::kw_typeof:
118   case tok::annot_decltype:
119   case tok::kw_decltype:
120     return getLangOpts().CPlusPlus;
121 
122   default:
123     break;
124   }
125 
126   return false;
127 }
128 
129 /// \brief If the identifier refers to a type name within this scope,
130 /// return the declaration of that type.
131 ///
132 /// This routine performs ordinary name lookup of the identifier II
133 /// within the given scope, with optional C++ scope specifier SS, to
134 /// determine whether the name refers to a type. If so, returns an
135 /// opaque pointer (actually a QualType) corresponding to that
136 /// type. Otherwise, returns NULL.
137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
138                              Scope *S, CXXScopeSpec *SS,
139                              bool isClassName, bool HasTrailingDot,
140                              ParsedType ObjectTypePtr,
141                              bool IsCtorOrDtorName,
142                              bool WantNontrivialTypeSourceInfo,
143                              IdentifierInfo **CorrectedII) {
144   // Determine where we will perform name lookup.
145   DeclContext *LookupCtx = 0;
146   if (ObjectTypePtr) {
147     QualType ObjectType = ObjectTypePtr.get();
148     if (ObjectType->isRecordType())
149       LookupCtx = computeDeclContext(ObjectType);
150   } else if (SS && SS->isNotEmpty()) {
151     LookupCtx = computeDeclContext(*SS, false);
152 
153     if (!LookupCtx) {
154       if (isDependentScopeSpecifier(*SS)) {
155         // C++ [temp.res]p3:
156         //   A qualified-id that refers to a type and in which the
157         //   nested-name-specifier depends on a template-parameter (14.6.2)
158         //   shall be prefixed by the keyword typename to indicate that the
159         //   qualified-id denotes a type, forming an
160         //   elaborated-type-specifier (7.1.5.3).
161         //
162         // We therefore do not perform any name lookup if the result would
163         // refer to a member of an unknown specialization.
164         if (!isClassName && !IsCtorOrDtorName)
165           return ParsedType();
166 
167         // We know from the grammar that this name refers to a type,
168         // so build a dependent node to describe the type.
169         if (WantNontrivialTypeSourceInfo)
170           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171 
172         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
173         QualType T =
174           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
175                             II, NameLoc);
176 
177           return ParsedType::make(T);
178       }
179 
180       return ParsedType();
181     }
182 
183     if (!LookupCtx->isDependentContext() &&
184         RequireCompleteDeclContext(*SS, LookupCtx))
185       return ParsedType();
186   }
187 
188   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189   // lookup for class-names.
190   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191                                       LookupOrdinaryName;
192   LookupResult Result(*this, &II, NameLoc, Kind);
193   if (LookupCtx) {
194     // Perform "qualified" name lookup into the declaration context we
195     // computed, which is either the type of the base of a member access
196     // expression or the declaration context associated with a prior
197     // nested-name-specifier.
198     LookupQualifiedName(Result, LookupCtx);
199 
200     if (ObjectTypePtr && Result.empty()) {
201       // C++ [basic.lookup.classref]p3:
202       //   If the unqualified-id is ~type-name, the type-name is looked up
203       //   in the context of the entire postfix-expression. If the type T of
204       //   the object expression is of a class type C, the type-name is also
205       //   looked up in the scope of class C. At least one of the lookups shall
206       //   find a name that refers to (possibly cv-qualified) T.
207       LookupName(Result, S);
208     }
209   } else {
210     // Perform unqualified name lookup.
211     LookupName(Result, S);
212   }
213 
214   NamedDecl *IIDecl = 0;
215   switch (Result.getResultKind()) {
216   case LookupResult::NotFound:
217   case LookupResult::NotFoundInCurrentInstantiation:
218     if (CorrectedII) {
219       TypeNameValidatorCCC Validator(true, isClassName);
220       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
221                                               Kind, S, SS, Validator);
222       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
223       TemplateTy Template;
224       bool MemberOfUnknownSpecialization;
225       UnqualifiedId TemplateName;
226       TemplateName.setIdentifier(NewII, NameLoc);
227       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
228       CXXScopeSpec NewSS, *NewSSPtr = SS;
229       if (SS && NNS) {
230         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
231         NewSSPtr = &NewSS;
232       }
233       if (Correction && (NNS || NewII != &II) &&
234           // Ignore a correction to a template type as the to-be-corrected
235           // identifier is not a template (typo correction for template names
236           // is handled elsewhere).
237           !(getLangOpts().CPlusPlus && NewSSPtr &&
238             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
239                            false, Template, MemberOfUnknownSpecialization))) {
240         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
241                                     isClassName, HasTrailingDot, ObjectTypePtr,
242                                     IsCtorOrDtorName,
243                                     WantNontrivialTypeSourceInfo);
244         if (Ty) {
245           diagnoseTypo(Correction,
246                        PDiag(diag::err_unknown_type_or_class_name_suggest)
247                          << Result.getLookupName() << isClassName);
248           if (SS && NNS)
249             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
250           *CorrectedII = NewII;
251           return Ty;
252         }
253       }
254     }
255     // If typo correction failed or was not performed, fall through
256   case LookupResult::FoundOverloaded:
257   case LookupResult::FoundUnresolvedValue:
258     Result.suppressDiagnostics();
259     return ParsedType();
260 
261   case LookupResult::Ambiguous:
262     // Recover from type-hiding ambiguities by hiding the type.  We'll
263     // do the lookup again when looking for an object, and we can
264     // diagnose the error then.  If we don't do this, then the error
265     // about hiding the type will be immediately followed by an error
266     // that only makes sense if the identifier was treated like a type.
267     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
268       Result.suppressDiagnostics();
269       return ParsedType();
270     }
271 
272     // Look to see if we have a type anywhere in the list of results.
273     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
274          Res != ResEnd; ++Res) {
275       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
276         if (!IIDecl ||
277             (*Res)->getLocation().getRawEncoding() <
278               IIDecl->getLocation().getRawEncoding())
279           IIDecl = *Res;
280       }
281     }
282 
283     if (!IIDecl) {
284       // None of the entities we found is a type, so there is no way
285       // to even assume that the result is a type. In this case, don't
286       // complain about the ambiguity. The parser will either try to
287       // perform this lookup again (e.g., as an object name), which
288       // will produce the ambiguity, or will complain that it expected
289       // a type name.
290       Result.suppressDiagnostics();
291       return ParsedType();
292     }
293 
294     // We found a type within the ambiguous lookup; diagnose the
295     // ambiguity and then return that type. This might be the right
296     // answer, or it might not be, but it suppresses any attempt to
297     // perform the name lookup again.
298     break;
299 
300   case LookupResult::Found:
301     IIDecl = Result.getFoundDecl();
302     break;
303   }
304 
305   assert(IIDecl && "Didn't find decl");
306 
307   QualType T;
308   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
309     DiagnoseUseOfDecl(IIDecl, NameLoc);
310 
311     if (T.isNull())
312       T = Context.getTypeDeclType(TD);
313 
314     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315     // constructor or destructor name (in such a case, the scope specifier
316     // will be attached to the enclosing Expr or Decl node).
317     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
318       if (WantNontrivialTypeSourceInfo) {
319         // Construct a type with type-source information.
320         TypeLocBuilder Builder;
321         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322 
323         T = getElaboratedType(ETK_None, *SS, T);
324         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
325         ElabTL.setElaboratedKeywordLoc(SourceLocation());
326         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328       } else {
329         T = getElaboratedType(ETK_None, *SS, T);
330       }
331     }
332   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
333     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
334     if (!HasTrailingDot)
335       T = Context.getObjCInterfaceType(IDecl);
336   }
337 
338   if (T.isNull()) {
339     // If it's not plausibly a type, suppress diagnostics.
340     Result.suppressDiagnostics();
341     return ParsedType();
342   }
343   return ParsedType::make(T);
344 }
345 
346 /// isTagName() - This method is called *for error recovery purposes only*
347 /// to determine if the specified name is a valid tag name ("struct foo").  If
348 /// so, this returns the TST for the tag corresponding to it (TST_enum,
349 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
350 /// cases in C where the user forgot to specify the tag.
351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
352   // Do a tag name lookup in this scope.
353   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
354   LookupName(R, S, false);
355   R.suppressDiagnostics();
356   if (R.getResultKind() == LookupResult::Found)
357     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
358       switch (TD->getTagKind()) {
359       case TTK_Struct: return DeclSpec::TST_struct;
360       case TTK_Interface: return DeclSpec::TST_interface;
361       case TTK_Union:  return DeclSpec::TST_union;
362       case TTK_Class:  return DeclSpec::TST_class;
363       case TTK_Enum:   return DeclSpec::TST_enum;
364       }
365     }
366 
367   return DeclSpec::TST_unspecified;
368 }
369 
370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
372 /// then downgrade the missing typename error to a warning.
373 /// This is needed for MSVC compatibility; Example:
374 /// @code
375 /// template<class T> class A {
376 /// public:
377 ///   typedef int TYPE;
378 /// };
379 /// template<class T> class B : public A<T> {
380 /// public:
381 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
382 /// };
383 /// @endcode
384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
385   if (CurContext->isRecord()) {
386     const Type *Ty = SS->getScopeRep()->getAsType();
387 
388     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
389     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
390           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
391       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
392         return true;
393     return S->isFunctionPrototypeScope();
394   }
395   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
396 }
397 
398 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
399                                    SourceLocation IILoc,
400                                    Scope *S,
401                                    CXXScopeSpec *SS,
402                                    ParsedType &SuggestedType,
403                                    bool AllowClassTemplates) {
404   // We don't have anything to suggest (yet).
405   SuggestedType = ParsedType();
406 
407   // There may have been a typo in the name of the type. Look up typo
408   // results, in case we have something that we can suggest.
409   TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
410   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
411                                              LookupOrdinaryName, S, SS,
412                                              Validator)) {
413     if (Corrected.isKeyword()) {
414       // We corrected to a keyword.
415       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
416       II = Corrected.getCorrectionAsIdentifierInfo();
417     } else {
418       // We found a similarly-named type or interface; suggest that.
419       if (!SS || !SS->isSet()) {
420         diagnoseTypo(Corrected,
421                      PDiag(diag::err_unknown_typename_suggest) << II);
422       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
423         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
424         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
425                                 II->getName().equals(CorrectedStr);
426         diagnoseTypo(Corrected,
427                      PDiag(diag::err_unknown_nested_typename_suggest)
428                        << II << DC << DroppedSpecifier << SS->getRange());
429       } else {
430         llvm_unreachable("could not have corrected a typo here");
431       }
432 
433       CXXScopeSpec tmpSS;
434       if (Corrected.getCorrectionSpecifier())
435         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
436                           SourceRange(IILoc));
437       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
438                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
439                                   false, ParsedType(),
440                                   /*IsCtorOrDtorName=*/false,
441                                   /*NonTrivialTypeSourceInfo=*/true);
442     }
443     return true;
444   }
445 
446   if (getLangOpts().CPlusPlus) {
447     // See if II is a class template that the user forgot to pass arguments to.
448     UnqualifiedId Name;
449     Name.setIdentifier(II, IILoc);
450     CXXScopeSpec EmptySS;
451     TemplateTy TemplateResult;
452     bool MemberOfUnknownSpecialization;
453     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
454                        Name, ParsedType(), true, TemplateResult,
455                        MemberOfUnknownSpecialization) == TNK_Type_template) {
456       TemplateName TplName = TemplateResult.get();
457       Diag(IILoc, diag::err_template_missing_args) << TplName;
458       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
459         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
460           << TplDecl->getTemplateParameters()->getSourceRange();
461       }
462       return true;
463     }
464   }
465 
466   // FIXME: Should we move the logic that tries to recover from a missing tag
467   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
468 
469   if (!SS || (!SS->isSet() && !SS->isInvalid()))
470     Diag(IILoc, diag::err_unknown_typename) << II;
471   else if (DeclContext *DC = computeDeclContext(*SS, false))
472     Diag(IILoc, diag::err_typename_nested_not_found)
473       << II << DC << SS->getRange();
474   else if (isDependentScopeSpecifier(*SS)) {
475     unsigned DiagID = diag::err_typename_missing;
476     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
477       DiagID = diag::warn_typename_missing;
478 
479     Diag(SS->getRange().getBegin(), DiagID)
480       << SS->getScopeRep() << II->getName()
481       << SourceRange(SS->getRange().getBegin(), IILoc)
482       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
483     SuggestedType = ActOnTypenameType(S, SourceLocation(),
484                                       *SS, *II, IILoc).get();
485   } else {
486     assert(SS && SS->isInvalid() &&
487            "Invalid scope specifier has already been diagnosed");
488   }
489 
490   return true;
491 }
492 
493 /// \brief Determine whether the given result set contains either a type name
494 /// or
495 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
496   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
497                        NextToken.is(tok::less);
498 
499   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
500     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
501       return true;
502 
503     if (CheckTemplate && isa<TemplateDecl>(*I))
504       return true;
505   }
506 
507   return false;
508 }
509 
510 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
511                                     Scope *S, CXXScopeSpec &SS,
512                                     IdentifierInfo *&Name,
513                                     SourceLocation NameLoc) {
514   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
515   SemaRef.LookupParsedName(R, S, &SS);
516   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
517     const char *TagName = 0;
518     const char *FixItTagName = 0;
519     switch (Tag->getTagKind()) {
520       case TTK_Class:
521         TagName = "class";
522         FixItTagName = "class ";
523         break;
524 
525       case TTK_Enum:
526         TagName = "enum";
527         FixItTagName = "enum ";
528         break;
529 
530       case TTK_Struct:
531         TagName = "struct";
532         FixItTagName = "struct ";
533         break;
534 
535       case TTK_Interface:
536         TagName = "__interface";
537         FixItTagName = "__interface ";
538         break;
539 
540       case TTK_Union:
541         TagName = "union";
542         FixItTagName = "union ";
543         break;
544     }
545 
546     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
547       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
548       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
549 
550     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
551          I != IEnd; ++I)
552       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
553         << Name << TagName;
554 
555     // Replace lookup results with just the tag decl.
556     Result.clear(Sema::LookupTagName);
557     SemaRef.LookupParsedName(Result, S, &SS);
558     return true;
559   }
560 
561   return false;
562 }
563 
564 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
565 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
566                                   QualType T, SourceLocation NameLoc) {
567   ASTContext &Context = S.Context;
568 
569   TypeLocBuilder Builder;
570   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
571 
572   T = S.getElaboratedType(ETK_None, SS, T);
573   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
574   ElabTL.setElaboratedKeywordLoc(SourceLocation());
575   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
576   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
577 }
578 
579 Sema::NameClassification Sema::ClassifyName(Scope *S,
580                                             CXXScopeSpec &SS,
581                                             IdentifierInfo *&Name,
582                                             SourceLocation NameLoc,
583                                             const Token &NextToken,
584                                             bool IsAddressOfOperand,
585                                             CorrectionCandidateCallback *CCC) {
586   DeclarationNameInfo NameInfo(Name, NameLoc);
587   ObjCMethodDecl *CurMethod = getCurMethodDecl();
588 
589   if (NextToken.is(tok::coloncolon)) {
590     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
591                                 QualType(), false, SS, 0, false);
592 
593   }
594 
595   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
596   LookupParsedName(Result, S, &SS, !CurMethod);
597 
598   // Perform lookup for Objective-C instance variables (including automatically
599   // synthesized instance variables), if we're in an Objective-C method.
600   // FIXME: This lookup really, really needs to be folded in to the normal
601   // unqualified lookup mechanism.
602   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
603     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
604     if (E.get() || E.isInvalid())
605       return E;
606   }
607 
608   bool SecondTry = false;
609   bool IsFilteredTemplateName = false;
610 
611 Corrected:
612   switch (Result.getResultKind()) {
613   case LookupResult::NotFound:
614     // If an unqualified-id is followed by a '(', then we have a function
615     // call.
616     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
617       // In C++, this is an ADL-only call.
618       // FIXME: Reference?
619       if (getLangOpts().CPlusPlus)
620         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
621 
622       // C90 6.3.2.2:
623       //   If the expression that precedes the parenthesized argument list in a
624       //   function call consists solely of an identifier, and if no
625       //   declaration is visible for this identifier, the identifier is
626       //   implicitly declared exactly as if, in the innermost block containing
627       //   the function call, the declaration
628       //
629       //     extern int identifier ();
630       //
631       //   appeared.
632       //
633       // We also allow this in C99 as an extension.
634       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
635         Result.addDecl(D);
636         Result.resolveKind();
637         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
638       }
639     }
640 
641     // In C, we first see whether there is a tag type by the same name, in
642     // which case it's likely that the user just forget to write "enum",
643     // "struct", or "union".
644     if (!getLangOpts().CPlusPlus && !SecondTry &&
645         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
646       break;
647     }
648 
649     // Perform typo correction to determine if there is another name that is
650     // close to this name.
651     if (!SecondTry && CCC) {
652       SecondTry = true;
653       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
654                                                  Result.getLookupKind(), S,
655                                                  &SS, *CCC)) {
656         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
657         unsigned QualifiedDiag = diag::err_no_member_suggest;
658 
659         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
660         NamedDecl *UnderlyingFirstDecl
661           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
662         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
663             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
664           UnqualifiedDiag = diag::err_no_template_suggest;
665           QualifiedDiag = diag::err_no_member_template_suggest;
666         } else if (UnderlyingFirstDecl &&
667                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
668                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
669                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
670           UnqualifiedDiag = diag::err_unknown_typename_suggest;
671           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
672         }
673 
674         if (SS.isEmpty()) {
675           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
676         } else {// FIXME: is this even reachable? Test it.
677           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
678           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
679                                   Name->getName().equals(CorrectedStr);
680           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
681                                     << Name << computeDeclContext(SS, false)
682                                     << DroppedSpecifier << SS.getRange());
683         }
684 
685         // Update the name, so that the caller has the new name.
686         Name = Corrected.getCorrectionAsIdentifierInfo();
687 
688         // Typo correction corrected to a keyword.
689         if (Corrected.isKeyword())
690           return Name;
691 
692         // Also update the LookupResult...
693         // FIXME: This should probably go away at some point
694         Result.clear();
695         Result.setLookupName(Corrected.getCorrection());
696         if (FirstDecl)
697           Result.addDecl(FirstDecl);
698 
699         // If we found an Objective-C instance variable, let
700         // LookupInObjCMethod build the appropriate expression to
701         // reference the ivar.
702         // FIXME: This is a gross hack.
703         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
704           Result.clear();
705           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
706           return E;
707         }
708 
709         goto Corrected;
710       }
711     }
712 
713     // We failed to correct; just fall through and let the parser deal with it.
714     Result.suppressDiagnostics();
715     return NameClassification::Unknown();
716 
717   case LookupResult::NotFoundInCurrentInstantiation: {
718     // We performed name lookup into the current instantiation, and there were
719     // dependent bases, so we treat this result the same way as any other
720     // dependent nested-name-specifier.
721 
722     // C++ [temp.res]p2:
723     //   A name used in a template declaration or definition and that is
724     //   dependent on a template-parameter is assumed not to name a type
725     //   unless the applicable name lookup finds a type name or the name is
726     //   qualified by the keyword typename.
727     //
728     // FIXME: If the next token is '<', we might want to ask the parser to
729     // perform some heroics to see if we actually have a
730     // template-argument-list, which would indicate a missing 'template'
731     // keyword here.
732     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
733                                       NameInfo, IsAddressOfOperand,
734                                       /*TemplateArgs=*/0);
735   }
736 
737   case LookupResult::Found:
738   case LookupResult::FoundOverloaded:
739   case LookupResult::FoundUnresolvedValue:
740     break;
741 
742   case LookupResult::Ambiguous:
743     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
744         hasAnyAcceptableTemplateNames(Result)) {
745       // C++ [temp.local]p3:
746       //   A lookup that finds an injected-class-name (10.2) can result in an
747       //   ambiguity in certain cases (for example, if it is found in more than
748       //   one base class). If all of the injected-class-names that are found
749       //   refer to specializations of the same class template, and if the name
750       //   is followed by a template-argument-list, the reference refers to the
751       //   class template itself and not a specialization thereof, and is not
752       //   ambiguous.
753       //
754       // This filtering can make an ambiguous result into an unambiguous one,
755       // so try again after filtering out template names.
756       FilterAcceptableTemplateNames(Result);
757       if (!Result.isAmbiguous()) {
758         IsFilteredTemplateName = true;
759         break;
760       }
761     }
762 
763     // Diagnose the ambiguity and return an error.
764     return NameClassification::Error();
765   }
766 
767   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
768       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
769     // C++ [temp.names]p3:
770     //   After name lookup (3.4) finds that a name is a template-name or that
771     //   an operator-function-id or a literal- operator-id refers to a set of
772     //   overloaded functions any member of which is a function template if
773     //   this is followed by a <, the < is always taken as the delimiter of a
774     //   template-argument-list and never as the less-than operator.
775     if (!IsFilteredTemplateName)
776       FilterAcceptableTemplateNames(Result);
777 
778     if (!Result.empty()) {
779       bool IsFunctionTemplate;
780       bool IsVarTemplate;
781       TemplateName Template;
782       if (Result.end() - Result.begin() > 1) {
783         IsFunctionTemplate = true;
784         Template = Context.getOverloadedTemplateName(Result.begin(),
785                                                      Result.end());
786       } else {
787         TemplateDecl *TD
788           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
789         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
790         IsVarTemplate = isa<VarTemplateDecl>(TD);
791 
792         if (SS.isSet() && !SS.isInvalid())
793           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
794                                                     /*TemplateKeyword=*/false,
795                                                       TD);
796         else
797           Template = TemplateName(TD);
798       }
799 
800       if (IsFunctionTemplate) {
801         // Function templates always go through overload resolution, at which
802         // point we'll perform the various checks (e.g., accessibility) we need
803         // to based on which function we selected.
804         Result.suppressDiagnostics();
805 
806         return NameClassification::FunctionTemplate(Template);
807       }
808 
809       return IsVarTemplate ? NameClassification::VarTemplate(Template)
810                            : NameClassification::TypeTemplate(Template);
811     }
812   }
813 
814   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
815   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
816     DiagnoseUseOfDecl(Type, NameLoc);
817     QualType T = Context.getTypeDeclType(Type);
818     if (SS.isNotEmpty())
819       return buildNestedType(*this, SS, T, NameLoc);
820     return ParsedType::make(T);
821   }
822 
823   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
824   if (!Class) {
825     // FIXME: It's unfortunate that we don't have a Type node for handling this.
826     if (ObjCCompatibleAliasDecl *Alias
827                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
828       Class = Alias->getClassInterface();
829   }
830 
831   if (Class) {
832     DiagnoseUseOfDecl(Class, NameLoc);
833 
834     if (NextToken.is(tok::period)) {
835       // Interface. <something> is parsed as a property reference expression.
836       // Just return "unknown" as a fall-through for now.
837       Result.suppressDiagnostics();
838       return NameClassification::Unknown();
839     }
840 
841     QualType T = Context.getObjCInterfaceType(Class);
842     return ParsedType::make(T);
843   }
844 
845   // We can have a type template here if we're classifying a template argument.
846   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
847     return NameClassification::TypeTemplate(
848         TemplateName(cast<TemplateDecl>(FirstDecl)));
849 
850   // Check for a tag type hidden by a non-type decl in a few cases where it
851   // seems likely a type is wanted instead of the non-type that was found.
852   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
853   if ((NextToken.is(tok::identifier) ||
854        (NextIsOp &&
855         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
856       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
857     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
858     DiagnoseUseOfDecl(Type, NameLoc);
859     QualType T = Context.getTypeDeclType(Type);
860     if (SS.isNotEmpty())
861       return buildNestedType(*this, SS, T, NameLoc);
862     return ParsedType::make(T);
863   }
864 
865   if (FirstDecl->isCXXClassMember())
866     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
867 
868   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
869   return BuildDeclarationNameExpr(SS, Result, ADL);
870 }
871 
872 // Determines the context to return to after temporarily entering a
873 // context.  This depends in an unnecessarily complicated way on the
874 // exact ordering of callbacks from the parser.
875 DeclContext *Sema::getContainingDC(DeclContext *DC) {
876 
877   // Functions defined inline within classes aren't parsed until we've
878   // finished parsing the top-level class, so the top-level class is
879   // the context we'll need to return to.
880   // A Lambda call operator whose parent is a class must not be treated
881   // as an inline member function.  A Lambda can be used legally
882   // either as an in-class member initializer or a default argument.  These
883   // are parsed once the class has been marked complete and so the containing
884   // context would be the nested class (when the lambda is defined in one);
885   // If the class is not complete, then the lambda is being used in an
886   // ill-formed fashion (such as to specify the width of a bit-field, or
887   // in an array-bound) - in which case we still want to return the
888   // lexically containing DC (which could be a nested class).
889   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
890     DC = DC->getLexicalParent();
891 
892     // A function not defined within a class will always return to its
893     // lexical context.
894     if (!isa<CXXRecordDecl>(DC))
895       return DC;
896 
897     // A C++ inline method/friend is parsed *after* the topmost class
898     // it was declared in is fully parsed ("complete");  the topmost
899     // class is the context we need to return to.
900     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
901       DC = RD;
902 
903     // Return the declaration context of the topmost class the inline method is
904     // declared in.
905     return DC;
906   }
907 
908   return DC->getLexicalParent();
909 }
910 
911 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
912   assert(getContainingDC(DC) == CurContext &&
913       "The next DeclContext should be lexically contained in the current one.");
914   CurContext = DC;
915   S->setEntity(DC);
916 }
917 
918 void Sema::PopDeclContext() {
919   assert(CurContext && "DeclContext imbalance!");
920 
921   CurContext = getContainingDC(CurContext);
922   assert(CurContext && "Popped translation unit!");
923 }
924 
925 /// EnterDeclaratorContext - Used when we must lookup names in the context
926 /// of a declarator's nested name specifier.
927 ///
928 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
929   // C++0x [basic.lookup.unqual]p13:
930   //   A name used in the definition of a static data member of class
931   //   X (after the qualified-id of the static member) is looked up as
932   //   if the name was used in a member function of X.
933   // C++0x [basic.lookup.unqual]p14:
934   //   If a variable member of a namespace is defined outside of the
935   //   scope of its namespace then any name used in the definition of
936   //   the variable member (after the declarator-id) is looked up as
937   //   if the definition of the variable member occurred in its
938   //   namespace.
939   // Both of these imply that we should push a scope whose context
940   // is the semantic context of the declaration.  We can't use
941   // PushDeclContext here because that context is not necessarily
942   // lexically contained in the current context.  Fortunately,
943   // the containing scope should have the appropriate information.
944 
945   assert(!S->getEntity() && "scope already has entity");
946 
947 #ifndef NDEBUG
948   Scope *Ancestor = S->getParent();
949   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
950   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
951 #endif
952 
953   CurContext = DC;
954   S->setEntity(DC);
955 }
956 
957 void Sema::ExitDeclaratorContext(Scope *S) {
958   assert(S->getEntity() == CurContext && "Context imbalance!");
959 
960   // Switch back to the lexical context.  The safety of this is
961   // enforced by an assert in EnterDeclaratorContext.
962   Scope *Ancestor = S->getParent();
963   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
964   CurContext = Ancestor->getEntity();
965 
966   // We don't need to do anything with the scope, which is going to
967   // disappear.
968 }
969 
970 
971 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
972   // We assume that the caller has already called
973   // ActOnReenterTemplateScope so getTemplatedDecl() works.
974   FunctionDecl *FD = D->getAsFunction();
975   if (!FD)
976     return;
977 
978   // Same implementation as PushDeclContext, but enters the context
979   // from the lexical parent, rather than the top-level class.
980   assert(CurContext == FD->getLexicalParent() &&
981     "The next DeclContext should be lexically contained in the current one.");
982   CurContext = FD;
983   S->setEntity(CurContext);
984 
985   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
986     ParmVarDecl *Param = FD->getParamDecl(P);
987     // If the parameter has an identifier, then add it to the scope
988     if (Param->getIdentifier()) {
989       S->AddDecl(Param);
990       IdResolver.AddDecl(Param);
991     }
992   }
993 }
994 
995 
996 void Sema::ActOnExitFunctionContext() {
997   // Same implementation as PopDeclContext, but returns to the lexical parent,
998   // rather than the top-level class.
999   assert(CurContext && "DeclContext imbalance!");
1000   CurContext = CurContext->getLexicalParent();
1001   assert(CurContext && "Popped translation unit!");
1002 }
1003 
1004 
1005 /// \brief Determine whether we allow overloading of the function
1006 /// PrevDecl with another declaration.
1007 ///
1008 /// This routine determines whether overloading is possible, not
1009 /// whether some new function is actually an overload. It will return
1010 /// true in C++ (where we can always provide overloads) or, as an
1011 /// extension, in C when the previous function is already an
1012 /// overloaded function declaration or has the "overloadable"
1013 /// attribute.
1014 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1015                                        ASTContext &Context) {
1016   if (Context.getLangOpts().CPlusPlus)
1017     return true;
1018 
1019   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1020     return true;
1021 
1022   return (Previous.getResultKind() == LookupResult::Found
1023           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1024 }
1025 
1026 /// Add this decl to the scope shadowed decl chains.
1027 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1028   // Move up the scope chain until we find the nearest enclosing
1029   // non-transparent context. The declaration will be introduced into this
1030   // scope.
1031   while (S->getEntity() && S->getEntity()->isTransparentContext())
1032     S = S->getParent();
1033 
1034   // Add scoped declarations into their context, so that they can be
1035   // found later. Declarations without a context won't be inserted
1036   // into any context.
1037   if (AddToContext)
1038     CurContext->addDecl(D);
1039 
1040   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1041   // are function-local declarations.
1042   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1043       !D->getDeclContext()->getRedeclContext()->Equals(
1044         D->getLexicalDeclContext()->getRedeclContext()) &&
1045       !D->getLexicalDeclContext()->isFunctionOrMethod())
1046     return;
1047 
1048   // Template instantiations should also not be pushed into scope.
1049   if (isa<FunctionDecl>(D) &&
1050       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1051     return;
1052 
1053   // If this replaces anything in the current scope,
1054   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1055                                IEnd = IdResolver.end();
1056   for (; I != IEnd; ++I) {
1057     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1058       S->RemoveDecl(*I);
1059       IdResolver.RemoveDecl(*I);
1060 
1061       // Should only need to replace one decl.
1062       break;
1063     }
1064   }
1065 
1066   S->AddDecl(D);
1067 
1068   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1069     // Implicitly-generated labels may end up getting generated in an order that
1070     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1071     // the label at the appropriate place in the identifier chain.
1072     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1073       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1074       if (IDC == CurContext) {
1075         if (!S->isDeclScope(*I))
1076           continue;
1077       } else if (IDC->Encloses(CurContext))
1078         break;
1079     }
1080 
1081     IdResolver.InsertDeclAfter(I, D);
1082   } else {
1083     IdResolver.AddDecl(D);
1084   }
1085 }
1086 
1087 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1088   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1089     TUScope->AddDecl(D);
1090 }
1091 
1092 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1093                          bool AllowInlineNamespace) {
1094   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1095 }
1096 
1097 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1098   DeclContext *TargetDC = DC->getPrimaryContext();
1099   do {
1100     if (DeclContext *ScopeDC = S->getEntity())
1101       if (ScopeDC->getPrimaryContext() == TargetDC)
1102         return S;
1103   } while ((S = S->getParent()));
1104 
1105   return 0;
1106 }
1107 
1108 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1109                                             DeclContext*,
1110                                             ASTContext&);
1111 
1112 /// Filters out lookup results that don't fall within the given scope
1113 /// as determined by isDeclInScope.
1114 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1115                                 bool ConsiderLinkage,
1116                                 bool AllowInlineNamespace) {
1117   LookupResult::Filter F = R.makeFilter();
1118   while (F.hasNext()) {
1119     NamedDecl *D = F.next();
1120 
1121     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1122       continue;
1123 
1124     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1125       continue;
1126 
1127     F.erase();
1128   }
1129 
1130   F.done();
1131 }
1132 
1133 static bool isUsingDecl(NamedDecl *D) {
1134   return isa<UsingShadowDecl>(D) ||
1135          isa<UnresolvedUsingTypenameDecl>(D) ||
1136          isa<UnresolvedUsingValueDecl>(D);
1137 }
1138 
1139 /// Removes using shadow declarations from the lookup results.
1140 static void RemoveUsingDecls(LookupResult &R) {
1141   LookupResult::Filter F = R.makeFilter();
1142   while (F.hasNext())
1143     if (isUsingDecl(F.next()))
1144       F.erase();
1145 
1146   F.done();
1147 }
1148 
1149 /// \brief Check for this common pattern:
1150 /// @code
1151 /// class S {
1152 ///   S(const S&); // DO NOT IMPLEMENT
1153 ///   void operator=(const S&); // DO NOT IMPLEMENT
1154 /// };
1155 /// @endcode
1156 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1157   // FIXME: Should check for private access too but access is set after we get
1158   // the decl here.
1159   if (D->doesThisDeclarationHaveABody())
1160     return false;
1161 
1162   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1163     return CD->isCopyConstructor();
1164   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1165     return Method->isCopyAssignmentOperator();
1166   return false;
1167 }
1168 
1169 // We need this to handle
1170 //
1171 // typedef struct {
1172 //   void *foo() { return 0; }
1173 // } A;
1174 //
1175 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1176 // for example. If 'A', foo will have external linkage. If we have '*A',
1177 // foo will have no linkage. Since we can't know until we get to the end
1178 // of the typedef, this function finds out if D might have non-external linkage.
1179 // Callers should verify at the end of the TU if it D has external linkage or
1180 // not.
1181 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1182   const DeclContext *DC = D->getDeclContext();
1183   while (!DC->isTranslationUnit()) {
1184     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1185       if (!RD->hasNameForLinkage())
1186         return true;
1187     }
1188     DC = DC->getParent();
1189   }
1190 
1191   return !D->isExternallyVisible();
1192 }
1193 
1194 // FIXME: This needs to be refactored; some other isInMainFile users want
1195 // these semantics.
1196 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1197   if (S.TUKind != TU_Complete)
1198     return false;
1199   return S.SourceMgr.isInMainFile(Loc);
1200 }
1201 
1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1203   assert(D);
1204 
1205   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1206     return false;
1207 
1208   // Ignore class templates.
1209   if (D->getDeclContext()->isDependentContext() ||
1210       D->getLexicalDeclContext()->isDependentContext())
1211     return false;
1212 
1213   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1214     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1215       return false;
1216 
1217     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1218       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1219         return false;
1220     } else {
1221       // 'static inline' functions are defined in headers; don't warn.
1222       if (FD->isInlineSpecified() &&
1223           !isMainFileLoc(*this, FD->getLocation()))
1224         return false;
1225     }
1226 
1227     if (FD->doesThisDeclarationHaveABody() &&
1228         Context.DeclMustBeEmitted(FD))
1229       return false;
1230   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1231     // Constants and utility variables are defined in headers with internal
1232     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1233     // like "inline".)
1234     if (!isMainFileLoc(*this, VD->getLocation()))
1235       return false;
1236 
1237     if (Context.DeclMustBeEmitted(VD))
1238       return false;
1239 
1240     if (VD->isStaticDataMember() &&
1241         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1242       return false;
1243   } else {
1244     return false;
1245   }
1246 
1247   // Only warn for unused decls internal to the translation unit.
1248   return mightHaveNonExternalLinkage(D);
1249 }
1250 
1251 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1252   if (!D)
1253     return;
1254 
1255   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1256     const FunctionDecl *First = FD->getFirstDecl();
1257     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1258       return; // First should already be in the vector.
1259   }
1260 
1261   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1262     const VarDecl *First = VD->getFirstDecl();
1263     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1264       return; // First should already be in the vector.
1265   }
1266 
1267   if (ShouldWarnIfUnusedFileScopedDecl(D))
1268     UnusedFileScopedDecls.push_back(D);
1269 }
1270 
1271 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1272   if (D->isInvalidDecl())
1273     return false;
1274 
1275   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1276       D->hasAttr<ObjCPreciseLifetimeAttr>())
1277     return false;
1278 
1279   if (isa<LabelDecl>(D))
1280     return true;
1281 
1282   // White-list anything that isn't a local variable.
1283   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1284       !D->getDeclContext()->isFunctionOrMethod())
1285     return false;
1286 
1287   // Types of valid local variables should be complete, so this should succeed.
1288   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1289 
1290     // White-list anything with an __attribute__((unused)) type.
1291     QualType Ty = VD->getType();
1292 
1293     // Only look at the outermost level of typedef.
1294     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1295       if (TT->getDecl()->hasAttr<UnusedAttr>())
1296         return false;
1297     }
1298 
1299     // If we failed to complete the type for some reason, or if the type is
1300     // dependent, don't diagnose the variable.
1301     if (Ty->isIncompleteType() || Ty->isDependentType())
1302       return false;
1303 
1304     if (const TagType *TT = Ty->getAs<TagType>()) {
1305       const TagDecl *Tag = TT->getDecl();
1306       if (Tag->hasAttr<UnusedAttr>())
1307         return false;
1308 
1309       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1310         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1311           return false;
1312 
1313         if (const Expr *Init = VD->getInit()) {
1314           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1315             Init = Cleanups->getSubExpr();
1316           const CXXConstructExpr *Construct =
1317             dyn_cast<CXXConstructExpr>(Init);
1318           if (Construct && !Construct->isElidable()) {
1319             CXXConstructorDecl *CD = Construct->getConstructor();
1320             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1321               return false;
1322           }
1323         }
1324       }
1325     }
1326 
1327     // TODO: __attribute__((unused)) templates?
1328   }
1329 
1330   return true;
1331 }
1332 
1333 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1334                                      FixItHint &Hint) {
1335   if (isa<LabelDecl>(D)) {
1336     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1337                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1338     if (AfterColon.isInvalid())
1339       return;
1340     Hint = FixItHint::CreateRemoval(CharSourceRange::
1341                                     getCharRange(D->getLocStart(), AfterColon));
1342   }
1343   return;
1344 }
1345 
1346 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1347 /// unless they are marked attr(unused).
1348 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1349   FixItHint Hint;
1350   if (!ShouldDiagnoseUnusedDecl(D))
1351     return;
1352 
1353   GenerateFixForUnusedDecl(D, Context, Hint);
1354 
1355   unsigned DiagID;
1356   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1357     DiagID = diag::warn_unused_exception_param;
1358   else if (isa<LabelDecl>(D))
1359     DiagID = diag::warn_unused_label;
1360   else
1361     DiagID = diag::warn_unused_variable;
1362 
1363   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1364 }
1365 
1366 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1367   // Verify that we have no forward references left.  If so, there was a goto
1368   // or address of a label taken, but no definition of it.  Label fwd
1369   // definitions are indicated with a null substmt.
1370   if (L->getStmt() == 0)
1371     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1372 }
1373 
1374 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1375   if (S->decl_empty()) return;
1376   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1377          "Scope shouldn't contain decls!");
1378 
1379   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1380        I != E; ++I) {
1381     Decl *TmpD = (*I);
1382     assert(TmpD && "This decl didn't get pushed??");
1383 
1384     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1385     NamedDecl *D = cast<NamedDecl>(TmpD);
1386 
1387     if (!D->getDeclName()) continue;
1388 
1389     // Diagnose unused variables in this scope.
1390     if (!S->hasUnrecoverableErrorOccurred())
1391       DiagnoseUnusedDecl(D);
1392 
1393     // If this was a forward reference to a label, verify it was defined.
1394     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1395       CheckPoppedLabel(LD, *this);
1396 
1397     // Remove this name from our lexical scope.
1398     IdResolver.RemoveDecl(D);
1399   }
1400 }
1401 
1402 /// \brief Look for an Objective-C class in the translation unit.
1403 ///
1404 /// \param Id The name of the Objective-C class we're looking for. If
1405 /// typo-correction fixes this name, the Id will be updated
1406 /// to the fixed name.
1407 ///
1408 /// \param IdLoc The location of the name in the translation unit.
1409 ///
1410 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1411 /// if there is no class with the given name.
1412 ///
1413 /// \returns The declaration of the named Objective-C class, or NULL if the
1414 /// class could not be found.
1415 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1416                                               SourceLocation IdLoc,
1417                                               bool DoTypoCorrection) {
1418   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1419   // creation from this context.
1420   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1421 
1422   if (!IDecl && DoTypoCorrection) {
1423     // Perform typo correction at the given location, but only if we
1424     // find an Objective-C class name.
1425     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1426     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1427                                        LookupOrdinaryName, TUScope, NULL,
1428                                        Validator)) {
1429       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1430       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1431       Id = IDecl->getIdentifier();
1432     }
1433   }
1434   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1435   // This routine must always return a class definition, if any.
1436   if (Def && Def->getDefinition())
1437       Def = Def->getDefinition();
1438   return Def;
1439 }
1440 
1441 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1442 /// from S, where a non-field would be declared. This routine copes
1443 /// with the difference between C and C++ scoping rules in structs and
1444 /// unions. For example, the following code is well-formed in C but
1445 /// ill-formed in C++:
1446 /// @code
1447 /// struct S6 {
1448 ///   enum { BAR } e;
1449 /// };
1450 ///
1451 /// void test_S6() {
1452 ///   struct S6 a;
1453 ///   a.e = BAR;
1454 /// }
1455 /// @endcode
1456 /// For the declaration of BAR, this routine will return a different
1457 /// scope. The scope S will be the scope of the unnamed enumeration
1458 /// within S6. In C++, this routine will return the scope associated
1459 /// with S6, because the enumeration's scope is a transparent
1460 /// context but structures can contain non-field names. In C, this
1461 /// routine will return the translation unit scope, since the
1462 /// enumeration's scope is a transparent context and structures cannot
1463 /// contain non-field names.
1464 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1465   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1466          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1467          (S->isClassScope() && !getLangOpts().CPlusPlus))
1468     S = S->getParent();
1469   return S;
1470 }
1471 
1472 /// \brief Looks up the declaration of "struct objc_super" and
1473 /// saves it for later use in building builtin declaration of
1474 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1475 /// pre-existing declaration exists no action takes place.
1476 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1477                                         IdentifierInfo *II) {
1478   if (!II->isStr("objc_msgSendSuper"))
1479     return;
1480   ASTContext &Context = ThisSema.Context;
1481 
1482   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1483                       SourceLocation(), Sema::LookupTagName);
1484   ThisSema.LookupName(Result, S);
1485   if (Result.getResultKind() == LookupResult::Found)
1486     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1487       Context.setObjCSuperType(Context.getTagDeclType(TD));
1488 }
1489 
1490 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1491 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1492 /// if we're creating this built-in in anticipation of redeclaring the
1493 /// built-in.
1494 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1495                                      Scope *S, bool ForRedeclaration,
1496                                      SourceLocation Loc) {
1497   LookupPredefedObjCSuperType(*this, S, II);
1498 
1499   Builtin::ID BID = (Builtin::ID)bid;
1500 
1501   ASTContext::GetBuiltinTypeError Error;
1502   QualType R = Context.GetBuiltinType(BID, Error);
1503   switch (Error) {
1504   case ASTContext::GE_None:
1505     // Okay
1506     break;
1507 
1508   case ASTContext::GE_Missing_stdio:
1509     if (ForRedeclaration)
1510       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1511         << Context.BuiltinInfo.GetName(BID);
1512     return 0;
1513 
1514   case ASTContext::GE_Missing_setjmp:
1515     if (ForRedeclaration)
1516       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1517         << Context.BuiltinInfo.GetName(BID);
1518     return 0;
1519 
1520   case ASTContext::GE_Missing_ucontext:
1521     if (ForRedeclaration)
1522       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1523         << Context.BuiltinInfo.GetName(BID);
1524     return 0;
1525   }
1526 
1527   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1528     Diag(Loc, diag::ext_implicit_lib_function_decl)
1529       << Context.BuiltinInfo.GetName(BID)
1530       << R;
1531     if (Context.BuiltinInfo.getHeaderName(BID) &&
1532         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1533           != DiagnosticsEngine::Ignored)
1534       Diag(Loc, diag::note_please_include_header)
1535         << Context.BuiltinInfo.getHeaderName(BID)
1536         << Context.BuiltinInfo.GetName(BID);
1537   }
1538 
1539   DeclContext *Parent = Context.getTranslationUnitDecl();
1540   if (getLangOpts().CPlusPlus) {
1541     LinkageSpecDecl *CLinkageDecl =
1542         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1543                                 LinkageSpecDecl::lang_c, false);
1544     CLinkageDecl->setImplicit();
1545     Parent->addDecl(CLinkageDecl);
1546     Parent = CLinkageDecl;
1547   }
1548 
1549   FunctionDecl *New = FunctionDecl::Create(Context,
1550                                            Parent,
1551                                            Loc, Loc, II, R, /*TInfo=*/0,
1552                                            SC_Extern,
1553                                            false,
1554                                            /*hasPrototype=*/true);
1555   New->setImplicit();
1556 
1557   // Create Decl objects for each parameter, adding them to the
1558   // FunctionDecl.
1559   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1560     SmallVector<ParmVarDecl*, 16> Params;
1561     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1562       ParmVarDecl *parm =
1563           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1564                               0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
1565       parm->setScopeInfo(0, i);
1566       Params.push_back(parm);
1567     }
1568     New->setParams(Params);
1569   }
1570 
1571   AddKnownFunctionAttributes(New);
1572   RegisterLocallyScopedExternCDecl(New, S);
1573 
1574   // TUScope is the translation-unit scope to insert this function into.
1575   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1576   // relate Scopes to DeclContexts, and probably eliminate CurContext
1577   // entirely, but we're not there yet.
1578   DeclContext *SavedContext = CurContext;
1579   CurContext = Parent;
1580   PushOnScopeChains(New, TUScope);
1581   CurContext = SavedContext;
1582   return New;
1583 }
1584 
1585 /// \brief Filter out any previous declarations that the given declaration
1586 /// should not consider because they are not permitted to conflict, e.g.,
1587 /// because they come from hidden sub-modules and do not refer to the same
1588 /// entity.
1589 static void filterNonConflictingPreviousDecls(ASTContext &context,
1590                                               NamedDecl *decl,
1591                                               LookupResult &previous){
1592   // This is only interesting when modules are enabled.
1593   if (!context.getLangOpts().Modules)
1594     return;
1595 
1596   // Empty sets are uninteresting.
1597   if (previous.empty())
1598     return;
1599 
1600   LookupResult::Filter filter = previous.makeFilter();
1601   while (filter.hasNext()) {
1602     NamedDecl *old = filter.next();
1603 
1604     // Non-hidden declarations are never ignored.
1605     if (!old->isHidden())
1606       continue;
1607 
1608     if (!old->isExternallyVisible())
1609       filter.erase();
1610   }
1611 
1612   filter.done();
1613 }
1614 
1615 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1616   QualType OldType;
1617   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1618     OldType = OldTypedef->getUnderlyingType();
1619   else
1620     OldType = Context.getTypeDeclType(Old);
1621   QualType NewType = New->getUnderlyingType();
1622 
1623   if (NewType->isVariablyModifiedType()) {
1624     // Must not redefine a typedef with a variably-modified type.
1625     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1627       << Kind << NewType;
1628     if (Old->getLocation().isValid())
1629       Diag(Old->getLocation(), diag::note_previous_definition);
1630     New->setInvalidDecl();
1631     return true;
1632   }
1633 
1634   if (OldType != NewType &&
1635       !OldType->isDependentType() &&
1636       !NewType->isDependentType() &&
1637       !Context.hasSameType(OldType, NewType)) {
1638     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1639     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1640       << Kind << NewType << OldType;
1641     if (Old->getLocation().isValid())
1642       Diag(Old->getLocation(), diag::note_previous_definition);
1643     New->setInvalidDecl();
1644     return true;
1645   }
1646   return false;
1647 }
1648 
1649 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1650 /// same name and scope as a previous declaration 'Old'.  Figure out
1651 /// how to resolve this situation, merging decls or emitting
1652 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1653 ///
1654 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1655   // If the new decl is known invalid already, don't bother doing any
1656   // merging checks.
1657   if (New->isInvalidDecl()) return;
1658 
1659   // Allow multiple definitions for ObjC built-in typedefs.
1660   // FIXME: Verify the underlying types are equivalent!
1661   if (getLangOpts().ObjC1) {
1662     const IdentifierInfo *TypeID = New->getIdentifier();
1663     switch (TypeID->getLength()) {
1664     default: break;
1665     case 2:
1666       {
1667         if (!TypeID->isStr("id"))
1668           break;
1669         QualType T = New->getUnderlyingType();
1670         if (!T->isPointerType())
1671           break;
1672         if (!T->isVoidPointerType()) {
1673           QualType PT = T->getAs<PointerType>()->getPointeeType();
1674           if (!PT->isStructureType())
1675             break;
1676         }
1677         Context.setObjCIdRedefinitionType(T);
1678         // Install the built-in type for 'id', ignoring the current definition.
1679         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1680         return;
1681       }
1682     case 5:
1683       if (!TypeID->isStr("Class"))
1684         break;
1685       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1686       // Install the built-in type for 'Class', ignoring the current definition.
1687       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1688       return;
1689     case 3:
1690       if (!TypeID->isStr("SEL"))
1691         break;
1692       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1693       // Install the built-in type for 'SEL', ignoring the current definition.
1694       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1695       return;
1696     }
1697     // Fall through - the typedef name was not a builtin type.
1698   }
1699 
1700   // Verify the old decl was also a type.
1701   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1702   if (!Old) {
1703     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1704       << New->getDeclName();
1705 
1706     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1707     if (OldD->getLocation().isValid())
1708       Diag(OldD->getLocation(), diag::note_previous_definition);
1709 
1710     return New->setInvalidDecl();
1711   }
1712 
1713   // If the old declaration is invalid, just give up here.
1714   if (Old->isInvalidDecl())
1715     return New->setInvalidDecl();
1716 
1717   // If the typedef types are not identical, reject them in all languages and
1718   // with any extensions enabled.
1719   if (isIncompatibleTypedef(Old, New))
1720     return;
1721 
1722   // The types match.  Link up the redeclaration chain and merge attributes if
1723   // the old declaration was a typedef.
1724   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1725     New->setPreviousDecl(Typedef);
1726     mergeDeclAttributes(New, Old);
1727   }
1728 
1729   if (getLangOpts().MicrosoftExt)
1730     return;
1731 
1732   if (getLangOpts().CPlusPlus) {
1733     // C++ [dcl.typedef]p2:
1734     //   In a given non-class scope, a typedef specifier can be used to
1735     //   redefine the name of any type declared in that scope to refer
1736     //   to the type to which it already refers.
1737     if (!isa<CXXRecordDecl>(CurContext))
1738       return;
1739 
1740     // C++0x [dcl.typedef]p4:
1741     //   In a given class scope, a typedef specifier can be used to redefine
1742     //   any class-name declared in that scope that is not also a typedef-name
1743     //   to refer to the type to which it already refers.
1744     //
1745     // This wording came in via DR424, which was a correction to the
1746     // wording in DR56, which accidentally banned code like:
1747     //
1748     //   struct S {
1749     //     typedef struct A { } A;
1750     //   };
1751     //
1752     // in the C++03 standard. We implement the C++0x semantics, which
1753     // allow the above but disallow
1754     //
1755     //   struct S {
1756     //     typedef int I;
1757     //     typedef int I;
1758     //   };
1759     //
1760     // since that was the intent of DR56.
1761     if (!isa<TypedefNameDecl>(Old))
1762       return;
1763 
1764     Diag(New->getLocation(), diag::err_redefinition)
1765       << New->getDeclName();
1766     Diag(Old->getLocation(), diag::note_previous_definition);
1767     return New->setInvalidDecl();
1768   }
1769 
1770   // Modules always permit redefinition of typedefs, as does C11.
1771   if (getLangOpts().Modules || getLangOpts().C11)
1772     return;
1773 
1774   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1775   // is normally mapped to an error, but can be controlled with
1776   // -Wtypedef-redefinition.  If either the original or the redefinition is
1777   // in a system header, don't emit this for compatibility with GCC.
1778   if (getDiagnostics().getSuppressSystemWarnings() &&
1779       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1780        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1781     return;
1782 
1783   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1784     << New->getDeclName();
1785   Diag(Old->getLocation(), diag::note_previous_definition);
1786   return;
1787 }
1788 
1789 /// DeclhasAttr - returns true if decl Declaration already has the target
1790 /// attribute.
1791 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1792   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1793   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1794   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1795     if ((*i)->getKind() == A->getKind()) {
1796       if (Ann) {
1797         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1798           return true;
1799         continue;
1800       }
1801       // FIXME: Don't hardcode this check
1802       if (OA && isa<OwnershipAttr>(*i))
1803         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1804       return true;
1805     }
1806 
1807   return false;
1808 }
1809 
1810 static bool isAttributeTargetADefinition(Decl *D) {
1811   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1812     return VD->isThisDeclarationADefinition();
1813   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1814     return TD->isCompleteDefinition() || TD->isBeingDefined();
1815   return true;
1816 }
1817 
1818 /// Merge alignment attributes from \p Old to \p New, taking into account the
1819 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1820 ///
1821 /// \return \c true if any attributes were added to \p New.
1822 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1823   // Look for alignas attributes on Old, and pick out whichever attribute
1824   // specifies the strictest alignment requirement.
1825   AlignedAttr *OldAlignasAttr = 0;
1826   AlignedAttr *OldStrictestAlignAttr = 0;
1827   unsigned OldAlign = 0;
1828   for (specific_attr_iterator<AlignedAttr>
1829          I = Old->specific_attr_begin<AlignedAttr>(),
1830          E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1831     // FIXME: We have no way of representing inherited dependent alignments
1832     // in a case like:
1833     //   template<int A, int B> struct alignas(A) X;
1834     //   template<int A, int B> struct alignas(B) X {};
1835     // For now, we just ignore any alignas attributes which are not on the
1836     // definition in such a case.
1837     if (I->isAlignmentDependent())
1838       return false;
1839 
1840     if (I->isAlignas())
1841       OldAlignasAttr = *I;
1842 
1843     unsigned Align = I->getAlignment(S.Context);
1844     if (Align > OldAlign) {
1845       OldAlign = Align;
1846       OldStrictestAlignAttr = *I;
1847     }
1848   }
1849 
1850   // Look for alignas attributes on New.
1851   AlignedAttr *NewAlignasAttr = 0;
1852   unsigned NewAlign = 0;
1853   for (specific_attr_iterator<AlignedAttr>
1854          I = New->specific_attr_begin<AlignedAttr>(),
1855          E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1856     if (I->isAlignmentDependent())
1857       return false;
1858 
1859     if (I->isAlignas())
1860       NewAlignasAttr = *I;
1861 
1862     unsigned Align = I->getAlignment(S.Context);
1863     if (Align > NewAlign)
1864       NewAlign = Align;
1865   }
1866 
1867   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1868     // Both declarations have 'alignas' attributes. We require them to match.
1869     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1870     // fall short. (If two declarations both have alignas, they must both match
1871     // every definition, and so must match each other if there is a definition.)
1872 
1873     // If either declaration only contains 'alignas(0)' specifiers, then it
1874     // specifies the natural alignment for the type.
1875     if (OldAlign == 0 || NewAlign == 0) {
1876       QualType Ty;
1877       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1878         Ty = VD->getType();
1879       else
1880         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1881 
1882       if (OldAlign == 0)
1883         OldAlign = S.Context.getTypeAlign(Ty);
1884       if (NewAlign == 0)
1885         NewAlign = S.Context.getTypeAlign(Ty);
1886     }
1887 
1888     if (OldAlign != NewAlign) {
1889       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1890         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1891         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1892       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1893     }
1894   }
1895 
1896   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1897     // C++11 [dcl.align]p6:
1898     //   if any declaration of an entity has an alignment-specifier,
1899     //   every defining declaration of that entity shall specify an
1900     //   equivalent alignment.
1901     // C11 6.7.5/7:
1902     //   If the definition of an object does not have an alignment
1903     //   specifier, any other declaration of that object shall also
1904     //   have no alignment specifier.
1905     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1906       << OldAlignasAttr;
1907     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1908       << OldAlignasAttr;
1909   }
1910 
1911   bool AnyAdded = false;
1912 
1913   // Ensure we have an attribute representing the strictest alignment.
1914   if (OldAlign > NewAlign) {
1915     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1916     Clone->setInherited(true);
1917     New->addAttr(Clone);
1918     AnyAdded = true;
1919   }
1920 
1921   // Ensure we have an alignas attribute if the old declaration had one.
1922   if (OldAlignasAttr && !NewAlignasAttr &&
1923       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1924     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1925     Clone->setInherited(true);
1926     New->addAttr(Clone);
1927     AnyAdded = true;
1928   }
1929 
1930   return AnyAdded;
1931 }
1932 
1933 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1934                                bool Override) {
1935   InheritableAttr *NewAttr = NULL;
1936   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1937   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1938     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1939                                       AA->getIntroduced(), AA->getDeprecated(),
1940                                       AA->getObsoleted(), AA->getUnavailable(),
1941                                       AA->getMessage(), Override,
1942                                       AttrSpellingListIndex);
1943   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1944     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1945                                     AttrSpellingListIndex);
1946   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1947     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1948                                         AttrSpellingListIndex);
1949   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1950     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1951                                    AttrSpellingListIndex);
1952   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1953     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1954                                    AttrSpellingListIndex);
1955   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1956     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1957                                 FA->getFormatIdx(), FA->getFirstArg(),
1958                                 AttrSpellingListIndex);
1959   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1960     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1961                                  AttrSpellingListIndex);
1962   else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
1963     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1964                                        AttrSpellingListIndex,
1965                                        IA->getSemanticSpelling());
1966   else if (isa<AlignedAttr>(Attr))
1967     // AlignedAttrs are handled separately, because we need to handle all
1968     // such attributes on a declaration at the same time.
1969     NewAttr = 0;
1970   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
1971     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1972 
1973   if (NewAttr) {
1974     NewAttr->setInherited(true);
1975     D->addAttr(NewAttr);
1976     return true;
1977   }
1978 
1979   return false;
1980 }
1981 
1982 static const Decl *getDefinition(const Decl *D) {
1983   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1984     return TD->getDefinition();
1985   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1986     const VarDecl *Def = VD->getDefinition();
1987     if (Def)
1988       return Def;
1989     return VD->getActingDefinition();
1990   }
1991   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1992     const FunctionDecl* Def;
1993     if (FD->isDefined(Def))
1994       return Def;
1995   }
1996   return NULL;
1997 }
1998 
1999 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2000   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2001        I != E; ++I) {
2002     Attr *Attribute = *I;
2003     if (Attribute->getKind() == Kind)
2004       return true;
2005   }
2006   return false;
2007 }
2008 
2009 /// checkNewAttributesAfterDef - If we already have a definition, check that
2010 /// there are no new attributes in this declaration.
2011 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2012   if (!New->hasAttrs())
2013     return;
2014 
2015   const Decl *Def = getDefinition(Old);
2016   if (!Def || Def == New)
2017     return;
2018 
2019   AttrVec &NewAttributes = New->getAttrs();
2020   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2021     const Attr *NewAttribute = NewAttributes[I];
2022 
2023     if (isa<AliasAttr>(NewAttribute)) {
2024       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2025         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2026       else {
2027         VarDecl *VD = cast<VarDecl>(New);
2028         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2029                                 VarDecl::TentativeDefinition
2030                             ? diag::err_alias_after_tentative
2031                             : diag::err_redefinition;
2032         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2033         S.Diag(Def->getLocation(), diag::note_previous_definition);
2034         VD->setInvalidDecl();
2035       }
2036       ++I;
2037       continue;
2038     }
2039 
2040     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2041       // Tentative definitions are only interesting for the alias check above.
2042       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2043         ++I;
2044         continue;
2045       }
2046     }
2047 
2048     if (hasAttribute(Def, NewAttribute->getKind())) {
2049       ++I;
2050       continue; // regular attr merging will take care of validating this.
2051     }
2052 
2053     if (isa<C11NoReturnAttr>(NewAttribute)) {
2054       // C's _Noreturn is allowed to be added to a function after it is defined.
2055       ++I;
2056       continue;
2057     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2058       if (AA->isAlignas()) {
2059         // C++11 [dcl.align]p6:
2060         //   if any declaration of an entity has an alignment-specifier,
2061         //   every defining declaration of that entity shall specify an
2062         //   equivalent alignment.
2063         // C11 6.7.5/7:
2064         //   If the definition of an object does not have an alignment
2065         //   specifier, any other declaration of that object shall also
2066         //   have no alignment specifier.
2067         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2068           << AA;
2069         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2070           << AA;
2071         NewAttributes.erase(NewAttributes.begin() + I);
2072         --E;
2073         continue;
2074       }
2075     }
2076 
2077     S.Diag(NewAttribute->getLocation(),
2078            diag::warn_attribute_precede_definition);
2079     S.Diag(Def->getLocation(), diag::note_previous_definition);
2080     NewAttributes.erase(NewAttributes.begin() + I);
2081     --E;
2082   }
2083 }
2084 
2085 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2086 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2087                                AvailabilityMergeKind AMK) {
2088   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2089     UsedAttr *NewAttr = OldAttr->clone(Context);
2090     NewAttr->setInherited(true);
2091     New->addAttr(NewAttr);
2092   }
2093 
2094   if (!Old->hasAttrs() && !New->hasAttrs())
2095     return;
2096 
2097   // attributes declared post-definition are currently ignored
2098   checkNewAttributesAfterDef(*this, New, Old);
2099 
2100   if (!Old->hasAttrs())
2101     return;
2102 
2103   bool foundAny = New->hasAttrs();
2104 
2105   // Ensure that any moving of objects within the allocated map is done before
2106   // we process them.
2107   if (!foundAny) New->setAttrs(AttrVec());
2108 
2109   for (specific_attr_iterator<InheritableAttr>
2110          i = Old->specific_attr_begin<InheritableAttr>(),
2111          e = Old->specific_attr_end<InheritableAttr>();
2112        i != e; ++i) {
2113     bool Override = false;
2114     // Ignore deprecated/unavailable/availability attributes if requested.
2115     if (isa<DeprecatedAttr>(*i) ||
2116         isa<UnavailableAttr>(*i) ||
2117         isa<AvailabilityAttr>(*i)) {
2118       switch (AMK) {
2119       case AMK_None:
2120         continue;
2121 
2122       case AMK_Redeclaration:
2123         break;
2124 
2125       case AMK_Override:
2126         Override = true;
2127         break;
2128       }
2129     }
2130 
2131     // Already handled.
2132     if (isa<UsedAttr>(*i))
2133       continue;
2134 
2135     if (mergeDeclAttribute(*this, New, *i, Override))
2136       foundAny = true;
2137   }
2138 
2139   if (mergeAlignedAttrs(*this, New, Old))
2140     foundAny = true;
2141 
2142   if (!foundAny) New->dropAttrs();
2143 }
2144 
2145 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2146 /// to the new one.
2147 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2148                                      const ParmVarDecl *oldDecl,
2149                                      Sema &S) {
2150   // C++11 [dcl.attr.depend]p2:
2151   //   The first declaration of a function shall specify the
2152   //   carries_dependency attribute for its declarator-id if any declaration
2153   //   of the function specifies the carries_dependency attribute.
2154   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2155   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2156     S.Diag(CDA->getLocation(),
2157            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2158     // Find the first declaration of the parameter.
2159     // FIXME: Should we build redeclaration chains for function parameters?
2160     const FunctionDecl *FirstFD =
2161       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2162     const ParmVarDecl *FirstVD =
2163       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2164     S.Diag(FirstVD->getLocation(),
2165            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2166   }
2167 
2168   if (!oldDecl->hasAttrs())
2169     return;
2170 
2171   bool foundAny = newDecl->hasAttrs();
2172 
2173   // Ensure that any moving of objects within the allocated map is
2174   // done before we process them.
2175   if (!foundAny) newDecl->setAttrs(AttrVec());
2176 
2177   for (specific_attr_iterator<InheritableParamAttr>
2178        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2179        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2180     if (!DeclHasAttr(newDecl, *i)) {
2181       InheritableAttr *newAttr =
2182         cast<InheritableParamAttr>((*i)->clone(S.Context));
2183       newAttr->setInherited(true);
2184       newDecl->addAttr(newAttr);
2185       foundAny = true;
2186     }
2187   }
2188 
2189   if (!foundAny) newDecl->dropAttrs();
2190 }
2191 
2192 namespace {
2193 
2194 /// Used in MergeFunctionDecl to keep track of function parameters in
2195 /// C.
2196 struct GNUCompatibleParamWarning {
2197   ParmVarDecl *OldParm;
2198   ParmVarDecl *NewParm;
2199   QualType PromotedType;
2200 };
2201 
2202 }
2203 
2204 /// getSpecialMember - get the special member enum for a method.
2205 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2206   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2207     if (Ctor->isDefaultConstructor())
2208       return Sema::CXXDefaultConstructor;
2209 
2210     if (Ctor->isCopyConstructor())
2211       return Sema::CXXCopyConstructor;
2212 
2213     if (Ctor->isMoveConstructor())
2214       return Sema::CXXMoveConstructor;
2215   } else if (isa<CXXDestructorDecl>(MD)) {
2216     return Sema::CXXDestructor;
2217   } else if (MD->isCopyAssignmentOperator()) {
2218     return Sema::CXXCopyAssignment;
2219   } else if (MD->isMoveAssignmentOperator()) {
2220     return Sema::CXXMoveAssignment;
2221   }
2222 
2223   return Sema::CXXInvalid;
2224 }
2225 
2226 /// canRedefineFunction - checks if a function can be redefined. Currently,
2227 /// only extern inline functions can be redefined, and even then only in
2228 /// GNU89 mode.
2229 static bool canRedefineFunction(const FunctionDecl *FD,
2230                                 const LangOptions& LangOpts) {
2231   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2232           !LangOpts.CPlusPlus &&
2233           FD->isInlineSpecified() &&
2234           FD->getStorageClass() == SC_Extern);
2235 }
2236 
2237 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2238   const AttributedType *AT = T->getAs<AttributedType>();
2239   while (AT && !AT->isCallingConv())
2240     AT = AT->getModifiedType()->getAs<AttributedType>();
2241   return AT;
2242 }
2243 
2244 template <typename T>
2245 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2246   const DeclContext *DC = Old->getDeclContext();
2247   if (DC->isRecord())
2248     return false;
2249 
2250   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2251   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2252     return true;
2253   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2254     return true;
2255   return false;
2256 }
2257 
2258 /// MergeFunctionDecl - We just parsed a function 'New' from
2259 /// declarator D which has the same name and scope as a previous
2260 /// declaration 'Old'.  Figure out how to resolve this situation,
2261 /// merging decls or emitting diagnostics as appropriate.
2262 ///
2263 /// In C++, New and Old must be declarations that are not
2264 /// overloaded. Use IsOverload to determine whether New and Old are
2265 /// overloaded, and to select the Old declaration that New should be
2266 /// merged with.
2267 ///
2268 /// Returns true if there was an error, false otherwise.
2269 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2270                              Scope *S, bool MergeTypeWithOld) {
2271   // Verify the old decl was also a function.
2272   FunctionDecl *Old = OldD->getAsFunction();
2273   if (!Old) {
2274     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2275       if (New->getFriendObjectKind()) {
2276         Diag(New->getLocation(), diag::err_using_decl_friend);
2277         Diag(Shadow->getTargetDecl()->getLocation(),
2278              diag::note_using_decl_target);
2279         Diag(Shadow->getUsingDecl()->getLocation(),
2280              diag::note_using_decl) << 0;
2281         return true;
2282       }
2283 
2284       // C++11 [namespace.udecl]p14:
2285       //   If a function declaration in namespace scope or block scope has the
2286       //   same name and the same parameter-type-list as a function introduced
2287       //   by a using-declaration, and the declarations do not declare the same
2288       //   function, the program is ill-formed.
2289 
2290       // Check whether the two declarations might declare the same function.
2291       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2292       if (Old &&
2293           !Old->getDeclContext()->getRedeclContext()->Equals(
2294               New->getDeclContext()->getRedeclContext()) &&
2295           !(Old->isExternC() && New->isExternC()))
2296         Old = 0;
2297 
2298       if (!Old) {
2299         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2300         Diag(Shadow->getTargetDecl()->getLocation(),
2301              diag::note_using_decl_target);
2302         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2303         return true;
2304       }
2305       OldD = Old;
2306     } else {
2307       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2308         << New->getDeclName();
2309       Diag(OldD->getLocation(), diag::note_previous_definition);
2310       return true;
2311     }
2312   }
2313 
2314   // If the old declaration is invalid, just give up here.
2315   if (Old->isInvalidDecl())
2316     return true;
2317 
2318   // Determine whether the previous declaration was a definition,
2319   // implicit declaration, or a declaration.
2320   diag::kind PrevDiag;
2321   SourceLocation OldLocation = Old->getLocation();
2322   if (Old->isThisDeclarationADefinition())
2323     PrevDiag = diag::note_previous_definition;
2324   else if (Old->isImplicit()) {
2325     PrevDiag = diag::note_previous_implicit_declaration;
2326     if (OldLocation.isInvalid())
2327       OldLocation = New->getLocation();
2328   } else
2329     PrevDiag = diag::note_previous_declaration;
2330 
2331   // Don't complain about this if we're in GNU89 mode and the old function
2332   // is an extern inline function.
2333   // Don't complain about specializations. They are not supposed to have
2334   // storage classes.
2335   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2336       New->getStorageClass() == SC_Static &&
2337       Old->hasExternalFormalLinkage() &&
2338       !New->getTemplateSpecializationInfo() &&
2339       !canRedefineFunction(Old, getLangOpts())) {
2340     if (getLangOpts().MicrosoftExt) {
2341       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2342       Diag(OldLocation, PrevDiag);
2343     } else {
2344       Diag(New->getLocation(), diag::err_static_non_static) << New;
2345       Diag(OldLocation, PrevDiag);
2346       return true;
2347     }
2348   }
2349 
2350 
2351   // If a function is first declared with a calling convention, but is later
2352   // declared or defined without one, all following decls assume the calling
2353   // convention of the first.
2354   //
2355   // It's OK if a function is first declared without a calling convention,
2356   // but is later declared or defined with the default calling convention.
2357   //
2358   // To test if either decl has an explicit calling convention, we look for
2359   // AttributedType sugar nodes on the type as written.  If they are missing or
2360   // were canonicalized away, we assume the calling convention was implicit.
2361   //
2362   // Note also that we DO NOT return at this point, because we still have
2363   // other tests to run.
2364   QualType OldQType = Context.getCanonicalType(Old->getType());
2365   QualType NewQType = Context.getCanonicalType(New->getType());
2366   const FunctionType *OldType = cast<FunctionType>(OldQType);
2367   const FunctionType *NewType = cast<FunctionType>(NewQType);
2368   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2369   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2370   bool RequiresAdjustment = false;
2371 
2372   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2373     FunctionDecl *First = Old->getFirstDecl();
2374     const FunctionType *FT =
2375         First->getType().getCanonicalType()->castAs<FunctionType>();
2376     FunctionType::ExtInfo FI = FT->getExtInfo();
2377     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2378     if (!NewCCExplicit) {
2379       // Inherit the CC from the previous declaration if it was specified
2380       // there but not here.
2381       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2382       RequiresAdjustment = true;
2383     } else {
2384       // Calling conventions aren't compatible, so complain.
2385       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2386       Diag(New->getLocation(), diag::err_cconv_change)
2387         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2388         << !FirstCCExplicit
2389         << (!FirstCCExplicit ? "" :
2390             FunctionType::getNameForCallConv(FI.getCC()));
2391 
2392       // Put the note on the first decl, since it is the one that matters.
2393       Diag(First->getLocation(), diag::note_previous_declaration);
2394       return true;
2395     }
2396   }
2397 
2398   // FIXME: diagnose the other way around?
2399   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2400     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2401     RequiresAdjustment = true;
2402   }
2403 
2404   // Merge regparm attribute.
2405   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2406       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2407     if (NewTypeInfo.getHasRegParm()) {
2408       Diag(New->getLocation(), diag::err_regparm_mismatch)
2409         << NewType->getRegParmType()
2410         << OldType->getRegParmType();
2411       Diag(OldLocation, diag::note_previous_declaration);
2412       return true;
2413     }
2414 
2415     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2416     RequiresAdjustment = true;
2417   }
2418 
2419   // Merge ns_returns_retained attribute.
2420   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2421     if (NewTypeInfo.getProducesResult()) {
2422       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2423       Diag(OldLocation, diag::note_previous_declaration);
2424       return true;
2425     }
2426 
2427     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2428     RequiresAdjustment = true;
2429   }
2430 
2431   if (RequiresAdjustment) {
2432     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2433     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2434     New->setType(QualType(AdjustedType, 0));
2435     NewQType = Context.getCanonicalType(New->getType());
2436     NewType = cast<FunctionType>(NewQType);
2437   }
2438 
2439   // If this redeclaration makes the function inline, we may need to add it to
2440   // UndefinedButUsed.
2441   if (!Old->isInlined() && New->isInlined() &&
2442       !New->hasAttr<GNUInlineAttr>() &&
2443       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2444       Old->isUsed(false) &&
2445       !Old->isDefined() && !New->isThisDeclarationADefinition())
2446     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2447                                            SourceLocation()));
2448 
2449   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2450   // about it.
2451   if (New->hasAttr<GNUInlineAttr>() &&
2452       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2453     UndefinedButUsed.erase(Old->getCanonicalDecl());
2454   }
2455 
2456   if (getLangOpts().CPlusPlus) {
2457     // (C++98 13.1p2):
2458     //   Certain function declarations cannot be overloaded:
2459     //     -- Function declarations that differ only in the return type
2460     //        cannot be overloaded.
2461 
2462     // Go back to the type source info to compare the declared return types,
2463     // per C++1y [dcl.type.auto]p13:
2464     //   Redeclarations or specializations of a function or function template
2465     //   with a declared return type that uses a placeholder type shall also
2466     //   use that placeholder, not a deduced type.
2467     QualType OldDeclaredReturnType =
2468         (Old->getTypeSourceInfo()
2469              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2470              : OldType)->getReturnType();
2471     QualType NewDeclaredReturnType =
2472         (New->getTypeSourceInfo()
2473              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2474              : NewType)->getReturnType();
2475     QualType ResQT;
2476     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2477         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2478           New->isLocalExternDecl())) {
2479       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2480           OldDeclaredReturnType->isObjCObjectPointerType())
2481         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2482       if (ResQT.isNull()) {
2483         if (New->isCXXClassMember() && New->isOutOfLine())
2484           Diag(New->getLocation(),
2485                diag::err_member_def_does_not_match_ret_type) << New;
2486         else
2487           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2488         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2489         return true;
2490       }
2491       else
2492         NewQType = ResQT;
2493     }
2494 
2495     QualType OldReturnType = OldType->getReturnType();
2496     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2497     if (OldReturnType != NewReturnType) {
2498       // If this function has a deduced return type and has already been
2499       // defined, copy the deduced value from the old declaration.
2500       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2501       if (OldAT && OldAT->isDeduced()) {
2502         New->setType(
2503             SubstAutoType(New->getType(),
2504                           OldAT->isDependentType() ? Context.DependentTy
2505                                                    : OldAT->getDeducedType()));
2506         NewQType = Context.getCanonicalType(
2507             SubstAutoType(NewQType,
2508                           OldAT->isDependentType() ? Context.DependentTy
2509                                                    : OldAT->getDeducedType()));
2510       }
2511     }
2512 
2513     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2514     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2515     if (OldMethod && NewMethod) {
2516       // Preserve triviality.
2517       NewMethod->setTrivial(OldMethod->isTrivial());
2518 
2519       // MSVC allows explicit template specialization at class scope:
2520       // 2 CXXMethodDecls referring to the same function will be injected.
2521       // We don't want a redeclaration error.
2522       bool IsClassScopeExplicitSpecialization =
2523                               OldMethod->isFunctionTemplateSpecialization() &&
2524                               NewMethod->isFunctionTemplateSpecialization();
2525       bool isFriend = NewMethod->getFriendObjectKind();
2526 
2527       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2528           !IsClassScopeExplicitSpecialization) {
2529         //    -- Member function declarations with the same name and the
2530         //       same parameter types cannot be overloaded if any of them
2531         //       is a static member function declaration.
2532         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2533           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2534           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2535           return true;
2536         }
2537 
2538         // C++ [class.mem]p1:
2539         //   [...] A member shall not be declared twice in the
2540         //   member-specification, except that a nested class or member
2541         //   class template can be declared and then later defined.
2542         if (ActiveTemplateInstantiations.empty()) {
2543           unsigned NewDiag;
2544           if (isa<CXXConstructorDecl>(OldMethod))
2545             NewDiag = diag::err_constructor_redeclared;
2546           else if (isa<CXXDestructorDecl>(NewMethod))
2547             NewDiag = diag::err_destructor_redeclared;
2548           else if (isa<CXXConversionDecl>(NewMethod))
2549             NewDiag = diag::err_conv_function_redeclared;
2550           else
2551             NewDiag = diag::err_member_redeclared;
2552 
2553           Diag(New->getLocation(), NewDiag);
2554         } else {
2555           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2556             << New << New->getType();
2557         }
2558         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2559 
2560       // Complain if this is an explicit declaration of a special
2561       // member that was initially declared implicitly.
2562       //
2563       // As an exception, it's okay to befriend such methods in order
2564       // to permit the implicit constructor/destructor/operator calls.
2565       } else if (OldMethod->isImplicit()) {
2566         if (isFriend) {
2567           NewMethod->setImplicit();
2568         } else {
2569           Diag(NewMethod->getLocation(),
2570                diag::err_definition_of_implicitly_declared_member)
2571             << New << getSpecialMember(OldMethod);
2572           return true;
2573         }
2574       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2575         Diag(NewMethod->getLocation(),
2576              diag::err_definition_of_explicitly_defaulted_member)
2577           << getSpecialMember(OldMethod);
2578         return true;
2579       }
2580     }
2581 
2582     // C++11 [dcl.attr.noreturn]p1:
2583     //   The first declaration of a function shall specify the noreturn
2584     //   attribute if any declaration of that function specifies the noreturn
2585     //   attribute.
2586     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2587     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2588       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2589       Diag(Old->getFirstDecl()->getLocation(),
2590            diag::note_noreturn_missing_first_decl);
2591     }
2592 
2593     // C++11 [dcl.attr.depend]p2:
2594     //   The first declaration of a function shall specify the
2595     //   carries_dependency attribute for its declarator-id if any declaration
2596     //   of the function specifies the carries_dependency attribute.
2597     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2598     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2599       Diag(CDA->getLocation(),
2600            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2601       Diag(Old->getFirstDecl()->getLocation(),
2602            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2603     }
2604 
2605     // (C++98 8.3.5p3):
2606     //   All declarations for a function shall agree exactly in both the
2607     //   return type and the parameter-type-list.
2608     // We also want to respect all the extended bits except noreturn.
2609 
2610     // noreturn should now match unless the old type info didn't have it.
2611     QualType OldQTypeForComparison = OldQType;
2612     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2613       assert(OldQType == QualType(OldType, 0));
2614       const FunctionType *OldTypeForComparison
2615         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2616       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2617       assert(OldQTypeForComparison.isCanonical());
2618     }
2619 
2620     if (haveIncompatibleLanguageLinkages(Old, New)) {
2621       // As a special case, retain the language linkage from previous
2622       // declarations of a friend function as an extension.
2623       //
2624       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2625       // and is useful because there's otherwise no way to specify language
2626       // linkage within class scope.
2627       //
2628       // Check cautiously as the friend object kind isn't yet complete.
2629       if (New->getFriendObjectKind() != Decl::FOK_None) {
2630         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2631         Diag(OldLocation, PrevDiag);
2632       } else {
2633         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2634         Diag(OldLocation, PrevDiag);
2635         return true;
2636       }
2637     }
2638 
2639     if (OldQTypeForComparison == NewQType)
2640       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2641 
2642     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2643         New->isLocalExternDecl()) {
2644       // It's OK if we couldn't merge types for a local function declaraton
2645       // if either the old or new type is dependent. We'll merge the types
2646       // when we instantiate the function.
2647       return false;
2648     }
2649 
2650     // Fall through for conflicting redeclarations and redefinitions.
2651   }
2652 
2653   // C: Function types need to be compatible, not identical. This handles
2654   // duplicate function decls like "void f(int); void f(enum X);" properly.
2655   if (!getLangOpts().CPlusPlus &&
2656       Context.typesAreCompatible(OldQType, NewQType)) {
2657     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2658     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2659     const FunctionProtoType *OldProto = 0;
2660     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2661         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2662       // The old declaration provided a function prototype, but the
2663       // new declaration does not. Merge in the prototype.
2664       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2665       SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2666                                            OldProto->param_type_end());
2667       NewQType =
2668           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2669                                   OldProto->getExtProtoInfo());
2670       New->setType(NewQType);
2671       New->setHasInheritedPrototype();
2672 
2673       // Synthesize a parameter for each argument type.
2674       SmallVector<ParmVarDecl*, 16> Params;
2675       for (FunctionProtoType::param_type_iterator
2676                ParamType = OldProto->param_type_begin(),
2677                ParamEnd = OldProto->param_type_end();
2678            ParamType != ParamEnd; ++ParamType) {
2679         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2680                                                  SourceLocation(),
2681                                                  SourceLocation(), 0,
2682                                                  *ParamType, /*TInfo=*/0,
2683                                                  SC_None,
2684                                                  0);
2685         Param->setScopeInfo(0, Params.size());
2686         Param->setImplicit();
2687         Params.push_back(Param);
2688       }
2689 
2690       New->setParams(Params);
2691     }
2692 
2693     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2694   }
2695 
2696   // GNU C permits a K&R definition to follow a prototype declaration
2697   // if the declared types of the parameters in the K&R definition
2698   // match the types in the prototype declaration, even when the
2699   // promoted types of the parameters from the K&R definition differ
2700   // from the types in the prototype. GCC then keeps the types from
2701   // the prototype.
2702   //
2703   // If a variadic prototype is followed by a non-variadic K&R definition,
2704   // the K&R definition becomes variadic.  This is sort of an edge case, but
2705   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2706   // C99 6.9.1p8.
2707   if (!getLangOpts().CPlusPlus &&
2708       Old->hasPrototype() && !New->hasPrototype() &&
2709       New->getType()->getAs<FunctionProtoType>() &&
2710       Old->getNumParams() == New->getNumParams()) {
2711     SmallVector<QualType, 16> ArgTypes;
2712     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2713     const FunctionProtoType *OldProto
2714       = Old->getType()->getAs<FunctionProtoType>();
2715     const FunctionProtoType *NewProto
2716       = New->getType()->getAs<FunctionProtoType>();
2717 
2718     // Determine whether this is the GNU C extension.
2719     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2720                                                NewProto->getReturnType());
2721     bool LooseCompatible = !MergedReturn.isNull();
2722     for (unsigned Idx = 0, End = Old->getNumParams();
2723          LooseCompatible && Idx != End; ++Idx) {
2724       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2725       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2726       if (Context.typesAreCompatible(OldParm->getType(),
2727                                      NewProto->getParamType(Idx))) {
2728         ArgTypes.push_back(NewParm->getType());
2729       } else if (Context.typesAreCompatible(OldParm->getType(),
2730                                             NewParm->getType(),
2731                                             /*CompareUnqualified=*/true)) {
2732         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2733                                            NewProto->getParamType(Idx) };
2734         Warnings.push_back(Warn);
2735         ArgTypes.push_back(NewParm->getType());
2736       } else
2737         LooseCompatible = false;
2738     }
2739 
2740     if (LooseCompatible) {
2741       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2742         Diag(Warnings[Warn].NewParm->getLocation(),
2743              diag::ext_param_promoted_not_compatible_with_prototype)
2744           << Warnings[Warn].PromotedType
2745           << Warnings[Warn].OldParm->getType();
2746         if (Warnings[Warn].OldParm->getLocation().isValid())
2747           Diag(Warnings[Warn].OldParm->getLocation(),
2748                diag::note_previous_declaration);
2749       }
2750 
2751       if (MergeTypeWithOld)
2752         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2753                                              OldProto->getExtProtoInfo()));
2754       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2755     }
2756 
2757     // Fall through to diagnose conflicting types.
2758   }
2759 
2760   // A function that has already been declared has been redeclared or
2761   // defined with a different type; show an appropriate diagnostic.
2762 
2763   // If the previous declaration was an implicitly-generated builtin
2764   // declaration, then at the very least we should use a specialized note.
2765   unsigned BuiltinID;
2766   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2767     // If it's actually a library-defined builtin function like 'malloc'
2768     // or 'printf', just warn about the incompatible redeclaration.
2769     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2770       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2771       Diag(OldLocation, diag::note_previous_builtin_declaration)
2772         << Old << Old->getType();
2773 
2774       // If this is a global redeclaration, just forget hereafter
2775       // about the "builtin-ness" of the function.
2776       //
2777       // Doing this for local extern declarations is problematic.  If
2778       // the builtin declaration remains visible, a second invalid
2779       // local declaration will produce a hard error; if it doesn't
2780       // remain visible, a single bogus local redeclaration (which is
2781       // actually only a warning) could break all the downstream code.
2782       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2783         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2784 
2785       return false;
2786     }
2787 
2788     PrevDiag = diag::note_previous_builtin_declaration;
2789   }
2790 
2791   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2792   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2793   return true;
2794 }
2795 
2796 /// \brief Completes the merge of two function declarations that are
2797 /// known to be compatible.
2798 ///
2799 /// This routine handles the merging of attributes and other
2800 /// properties of function declarations from the old declaration to
2801 /// the new declaration, once we know that New is in fact a
2802 /// redeclaration of Old.
2803 ///
2804 /// \returns false
2805 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2806                                         Scope *S, bool MergeTypeWithOld) {
2807   // Merge the attributes
2808   mergeDeclAttributes(New, Old);
2809 
2810   // Merge "pure" flag.
2811   if (Old->isPure())
2812     New->setPure();
2813 
2814   // Merge "used" flag.
2815   if (Old->getMostRecentDecl()->isUsed(false))
2816     New->setIsUsed();
2817 
2818   // Merge attributes from the parameters.  These can mismatch with K&R
2819   // declarations.
2820   if (New->getNumParams() == Old->getNumParams())
2821     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2822       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2823                                *this);
2824 
2825   if (getLangOpts().CPlusPlus)
2826     return MergeCXXFunctionDecl(New, Old, S);
2827 
2828   // Merge the function types so the we get the composite types for the return
2829   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2830   // was visible.
2831   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2832   if (!Merged.isNull() && MergeTypeWithOld)
2833     New->setType(Merged);
2834 
2835   return false;
2836 }
2837 
2838 
2839 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2840                                 ObjCMethodDecl *oldMethod) {
2841 
2842   // Merge the attributes, including deprecated/unavailable
2843   AvailabilityMergeKind MergeKind =
2844     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2845                                                    : AMK_Override;
2846   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2847 
2848   // Merge attributes from the parameters.
2849   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2850                                        oe = oldMethod->param_end();
2851   for (ObjCMethodDecl::param_iterator
2852          ni = newMethod->param_begin(), ne = newMethod->param_end();
2853        ni != ne && oi != oe; ++ni, ++oi)
2854     mergeParamDeclAttributes(*ni, *oi, *this);
2855 
2856   CheckObjCMethodOverride(newMethod, oldMethod);
2857 }
2858 
2859 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2860 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2861 /// emitting diagnostics as appropriate.
2862 ///
2863 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2864 /// to here in AddInitializerToDecl. We can't check them before the initializer
2865 /// is attached.
2866 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2867                              bool MergeTypeWithOld) {
2868   if (New->isInvalidDecl() || Old->isInvalidDecl())
2869     return;
2870 
2871   QualType MergedT;
2872   if (getLangOpts().CPlusPlus) {
2873     if (New->getType()->isUndeducedType()) {
2874       // We don't know what the new type is until the initializer is attached.
2875       return;
2876     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2877       // These could still be something that needs exception specs checked.
2878       return MergeVarDeclExceptionSpecs(New, Old);
2879     }
2880     // C++ [basic.link]p10:
2881     //   [...] the types specified by all declarations referring to a given
2882     //   object or function shall be identical, except that declarations for an
2883     //   array object can specify array types that differ by the presence or
2884     //   absence of a major array bound (8.3.4).
2885     else if (Old->getType()->isIncompleteArrayType() &&
2886              New->getType()->isArrayType()) {
2887       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2888       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2889       if (Context.hasSameType(OldArray->getElementType(),
2890                               NewArray->getElementType()))
2891         MergedT = New->getType();
2892     } else if (Old->getType()->isArrayType() &&
2893                New->getType()->isIncompleteArrayType()) {
2894       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2895       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2896       if (Context.hasSameType(OldArray->getElementType(),
2897                               NewArray->getElementType()))
2898         MergedT = Old->getType();
2899     } else if (New->getType()->isObjCObjectPointerType() &&
2900                Old->getType()->isObjCObjectPointerType()) {
2901       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2902                                               Old->getType());
2903     }
2904   } else {
2905     // C 6.2.7p2:
2906     //   All declarations that refer to the same object or function shall have
2907     //   compatible type.
2908     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2909   }
2910   if (MergedT.isNull()) {
2911     // It's OK if we couldn't merge types if either type is dependent, for a
2912     // block-scope variable. In other cases (static data members of class
2913     // templates, variable templates, ...), we require the types to be
2914     // equivalent.
2915     // FIXME: The C++ standard doesn't say anything about this.
2916     if ((New->getType()->isDependentType() ||
2917          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2918       // If the old type was dependent, we can't merge with it, so the new type
2919       // becomes dependent for now. We'll reproduce the original type when we
2920       // instantiate the TypeSourceInfo for the variable.
2921       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2922         New->setType(Context.DependentTy);
2923       return;
2924     }
2925 
2926     // FIXME: Even if this merging succeeds, some other non-visible declaration
2927     // of this variable might have an incompatible type. For instance:
2928     //
2929     //   extern int arr[];
2930     //   void f() { extern int arr[2]; }
2931     //   void g() { extern int arr[3]; }
2932     //
2933     // Neither C nor C++ requires a diagnostic for this, but we should still try
2934     // to diagnose it.
2935     Diag(New->getLocation(), diag::err_redefinition_different_type)
2936       << New->getDeclName() << New->getType() << Old->getType();
2937     Diag(Old->getLocation(), diag::note_previous_definition);
2938     return New->setInvalidDecl();
2939   }
2940 
2941   // Don't actually update the type on the new declaration if the old
2942   // declaration was an extern declaration in a different scope.
2943   if (MergeTypeWithOld)
2944     New->setType(MergedT);
2945 }
2946 
2947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2948                                   LookupResult &Previous) {
2949   // C11 6.2.7p4:
2950   //   For an identifier with internal or external linkage declared
2951   //   in a scope in which a prior declaration of that identifier is
2952   //   visible, if the prior declaration specifies internal or
2953   //   external linkage, the type of the identifier at the later
2954   //   declaration becomes the composite type.
2955   //
2956   // If the variable isn't visible, we do not merge with its type.
2957   if (Previous.isShadowed())
2958     return false;
2959 
2960   if (S.getLangOpts().CPlusPlus) {
2961     // C++11 [dcl.array]p3:
2962     //   If there is a preceding declaration of the entity in the same
2963     //   scope in which the bound was specified, an omitted array bound
2964     //   is taken to be the same as in that earlier declaration.
2965     return NewVD->isPreviousDeclInSameBlockScope() ||
2966            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2967             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2968   } else {
2969     // If the old declaration was function-local, don't merge with its
2970     // type unless we're in the same function.
2971     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2972            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2973   }
2974 }
2975 
2976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2977 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2978 /// situation, merging decls or emitting diagnostics as appropriate.
2979 ///
2980 /// Tentative definition rules (C99 6.9.2p2) are checked by
2981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2982 /// definitions here, since the initializer hasn't been attached.
2983 ///
2984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2985   // If the new decl is already invalid, don't do any other checking.
2986   if (New->isInvalidDecl())
2987     return;
2988 
2989   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2990 
2991   // Verify the old decl was also a variable or variable template.
2992   VarDecl *Old = 0;
2993   VarTemplateDecl *OldTemplate = 0;
2994   if (Previous.isSingleResult()) {
2995     if (NewTemplate) {
2996       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2997       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2998     } else
2999       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3000   }
3001   if (!Old) {
3002     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3003       << New->getDeclName();
3004     Diag(Previous.getRepresentativeDecl()->getLocation(),
3005          diag::note_previous_definition);
3006     return New->setInvalidDecl();
3007   }
3008 
3009   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3010     return;
3011 
3012   // Ensure the template parameters are compatible.
3013   if (NewTemplate &&
3014       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3015                                       OldTemplate->getTemplateParameters(),
3016                                       /*Complain=*/true, TPL_TemplateMatch))
3017     return;
3018 
3019   // C++ [class.mem]p1:
3020   //   A member shall not be declared twice in the member-specification [...]
3021   //
3022   // Here, we need only consider static data members.
3023   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3024     Diag(New->getLocation(), diag::err_duplicate_member)
3025       << New->getIdentifier();
3026     Diag(Old->getLocation(), diag::note_previous_declaration);
3027     New->setInvalidDecl();
3028   }
3029 
3030   mergeDeclAttributes(New, Old);
3031   // Warn if an already-declared variable is made a weak_import in a subsequent
3032   // declaration
3033   if (New->hasAttr<WeakImportAttr>() &&
3034       Old->getStorageClass() == SC_None &&
3035       !Old->hasAttr<WeakImportAttr>()) {
3036     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3037     Diag(Old->getLocation(), diag::note_previous_definition);
3038     // Remove weak_import attribute on new declaration.
3039     New->dropAttr<WeakImportAttr>();
3040   }
3041 
3042   // Merge the types.
3043   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3044 
3045   if (New->isInvalidDecl())
3046     return;
3047 
3048   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3049   if (New->getStorageClass() == SC_Static &&
3050       !New->isStaticDataMember() &&
3051       Old->hasExternalFormalLinkage()) {
3052     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3053     Diag(Old->getLocation(), diag::note_previous_definition);
3054     return New->setInvalidDecl();
3055   }
3056   // C99 6.2.2p4:
3057   //   For an identifier declared with the storage-class specifier
3058   //   extern in a scope in which a prior declaration of that
3059   //   identifier is visible,23) if the prior declaration specifies
3060   //   internal or external linkage, the linkage of the identifier at
3061   //   the later declaration is the same as the linkage specified at
3062   //   the prior declaration. If no prior declaration is visible, or
3063   //   if the prior declaration specifies no linkage, then the
3064   //   identifier has external linkage.
3065   if (New->hasExternalStorage() && Old->hasLinkage())
3066     /* Okay */;
3067   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3068            !New->isStaticDataMember() &&
3069            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3070     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3071     Diag(Old->getLocation(), diag::note_previous_definition);
3072     return New->setInvalidDecl();
3073   }
3074 
3075   // Check if extern is followed by non-extern and vice-versa.
3076   if (New->hasExternalStorage() &&
3077       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3078     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3079     Diag(Old->getLocation(), diag::note_previous_definition);
3080     return New->setInvalidDecl();
3081   }
3082   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3083       !New->hasExternalStorage()) {
3084     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3085     Diag(Old->getLocation(), diag::note_previous_definition);
3086     return New->setInvalidDecl();
3087   }
3088 
3089   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3090 
3091   // FIXME: The test for external storage here seems wrong? We still
3092   // need to check for mismatches.
3093   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3094       // Don't complain about out-of-line definitions of static members.
3095       !(Old->getLexicalDeclContext()->isRecord() &&
3096         !New->getLexicalDeclContext()->isRecord())) {
3097     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3098     Diag(Old->getLocation(), diag::note_previous_definition);
3099     return New->setInvalidDecl();
3100   }
3101 
3102   if (New->getTLSKind() != Old->getTLSKind()) {
3103     if (!Old->getTLSKind()) {
3104       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3105       Diag(Old->getLocation(), diag::note_previous_declaration);
3106     } else if (!New->getTLSKind()) {
3107       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3108       Diag(Old->getLocation(), diag::note_previous_declaration);
3109     } else {
3110       // Do not allow redeclaration to change the variable between requiring
3111       // static and dynamic initialization.
3112       // FIXME: GCC allows this, but uses the TLS keyword on the first
3113       // declaration to determine the kind. Do we need to be compatible here?
3114       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3115         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3116       Diag(Old->getLocation(), diag::note_previous_declaration);
3117     }
3118   }
3119 
3120   // C++ doesn't have tentative definitions, so go right ahead and check here.
3121   const VarDecl *Def;
3122   if (getLangOpts().CPlusPlus &&
3123       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3124       (Def = Old->getDefinition())) {
3125     Diag(New->getLocation(), diag::err_redefinition) << New;
3126     Diag(Def->getLocation(), diag::note_previous_definition);
3127     New->setInvalidDecl();
3128     return;
3129   }
3130 
3131   if (haveIncompatibleLanguageLinkages(Old, New)) {
3132     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3133     Diag(Old->getLocation(), diag::note_previous_definition);
3134     New->setInvalidDecl();
3135     return;
3136   }
3137 
3138   // Merge "used" flag.
3139   if (Old->getMostRecentDecl()->isUsed(false))
3140     New->setIsUsed();
3141 
3142   // Keep a chain of previous declarations.
3143   New->setPreviousDecl(Old);
3144   if (NewTemplate)
3145     NewTemplate->setPreviousDecl(OldTemplate);
3146 
3147   // Inherit access appropriately.
3148   New->setAccess(Old->getAccess());
3149   if (NewTemplate)
3150     NewTemplate->setAccess(New->getAccess());
3151 }
3152 
3153 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3154 /// no declarator (e.g. "struct foo;") is parsed.
3155 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3156                                        DeclSpec &DS) {
3157   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3158 }
3159 
3160 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3161   if (!S.Context.getLangOpts().CPlusPlus)
3162     return;
3163 
3164   if (isa<CXXRecordDecl>(Tag->getParent())) {
3165     // If this tag is the direct child of a class, number it if
3166     // it is anonymous.
3167     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3168       return;
3169     MangleNumberingContext &MCtx =
3170         S.Context.getManglingNumberContext(Tag->getParent());
3171     S.Context.setManglingNumber(
3172         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3173     return;
3174   }
3175 
3176   // If this tag isn't a direct child of a class, number it if it is local.
3177   Decl *ManglingContextDecl;
3178   if (MangleNumberingContext *MCtx =
3179           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3180                                           ManglingContextDecl)) {
3181     S.Context.setManglingNumber(
3182         Tag,
3183         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3184   }
3185 }
3186 
3187 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3188 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3189 /// parameters to cope with template friend declarations.
3190 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3191                                        DeclSpec &DS,
3192                                        MultiTemplateParamsArg TemplateParams,
3193                                        bool IsExplicitInstantiation) {
3194   Decl *TagD = 0;
3195   TagDecl *Tag = 0;
3196   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3197       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3198       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3199       DS.getTypeSpecType() == DeclSpec::TST_union ||
3200       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3201     TagD = DS.getRepAsDecl();
3202 
3203     if (!TagD) // We probably had an error
3204       return 0;
3205 
3206     // Note that the above type specs guarantee that the
3207     // type rep is a Decl, whereas in many of the others
3208     // it's a Type.
3209     if (isa<TagDecl>(TagD))
3210       Tag = cast<TagDecl>(TagD);
3211     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3212       Tag = CTD->getTemplatedDecl();
3213   }
3214 
3215   if (Tag) {
3216     HandleTagNumbering(*this, Tag, S);
3217     Tag->setFreeStanding();
3218     if (Tag->isInvalidDecl())
3219       return Tag;
3220   }
3221 
3222   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3223     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3224     // or incomplete types shall not be restrict-qualified."
3225     if (TypeQuals & DeclSpec::TQ_restrict)
3226       Diag(DS.getRestrictSpecLoc(),
3227            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3228            << DS.getSourceRange();
3229   }
3230 
3231   if (DS.isConstexprSpecified()) {
3232     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3233     // and definitions of functions and variables.
3234     if (Tag)
3235       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3236         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3237             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3238             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3239             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3240     else
3241       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3242     // Don't emit warnings after this error.
3243     return TagD;
3244   }
3245 
3246   DiagnoseFunctionSpecifiers(DS);
3247 
3248   if (DS.isFriendSpecified()) {
3249     // If we're dealing with a decl but not a TagDecl, assume that
3250     // whatever routines created it handled the friendship aspect.
3251     if (TagD && !Tag)
3252       return 0;
3253     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3254   }
3255 
3256   CXXScopeSpec &SS = DS.getTypeSpecScope();
3257   bool IsExplicitSpecialization =
3258     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3259   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3260       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3261     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3262     // nested-name-specifier unless it is an explicit instantiation
3263     // or an explicit specialization.
3264     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3265     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3266       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3267           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3268           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3269           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3270       << SS.getRange();
3271     return 0;
3272   }
3273 
3274   // Track whether this decl-specifier declares anything.
3275   bool DeclaresAnything = true;
3276 
3277   // Handle anonymous struct definitions.
3278   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3279     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3280         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3281       if (getLangOpts().CPlusPlus ||
3282           Record->getDeclContext()->isRecord())
3283         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3284 
3285       DeclaresAnything = false;
3286     }
3287   }
3288 
3289   // Check for Microsoft C extension: anonymous struct member.
3290   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3291       CurContext->isRecord() &&
3292       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3293     // Handle 2 kinds of anonymous struct:
3294     //   struct STRUCT;
3295     // and
3296     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3297     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3298     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3299         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3300          DS.getRepAsType().get()->isStructureType())) {
3301       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3302         << DS.getSourceRange();
3303       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3304     }
3305   }
3306 
3307   // Skip all the checks below if we have a type error.
3308   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3309       (TagD && TagD->isInvalidDecl()))
3310     return TagD;
3311 
3312   if (getLangOpts().CPlusPlus &&
3313       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3314     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3315       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3316           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3317         DeclaresAnything = false;
3318 
3319   if (!DS.isMissingDeclaratorOk()) {
3320     // Customize diagnostic for a typedef missing a name.
3321     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3322       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3323         << DS.getSourceRange();
3324     else
3325       DeclaresAnything = false;
3326   }
3327 
3328   if (DS.isModulePrivateSpecified() &&
3329       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3330     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3331       << Tag->getTagKind()
3332       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3333 
3334   ActOnDocumentableDecl(TagD);
3335 
3336   // C 6.7/2:
3337   //   A declaration [...] shall declare at least a declarator [...], a tag,
3338   //   or the members of an enumeration.
3339   // C++ [dcl.dcl]p3:
3340   //   [If there are no declarators], and except for the declaration of an
3341   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3342   //   names into the program, or shall redeclare a name introduced by a
3343   //   previous declaration.
3344   if (!DeclaresAnything) {
3345     // In C, we allow this as a (popular) extension / bug. Don't bother
3346     // producing further diagnostics for redundant qualifiers after this.
3347     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3348     return TagD;
3349   }
3350 
3351   // C++ [dcl.stc]p1:
3352   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3353   //   init-declarator-list of the declaration shall not be empty.
3354   // C++ [dcl.fct.spec]p1:
3355   //   If a cv-qualifier appears in a decl-specifier-seq, the
3356   //   init-declarator-list of the declaration shall not be empty.
3357   //
3358   // Spurious qualifiers here appear to be valid in C.
3359   unsigned DiagID = diag::warn_standalone_specifier;
3360   if (getLangOpts().CPlusPlus)
3361     DiagID = diag::ext_standalone_specifier;
3362 
3363   // Note that a linkage-specification sets a storage class, but
3364   // 'extern "C" struct foo;' is actually valid and not theoretically
3365   // useless.
3366   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3367     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3368       Diag(DS.getStorageClassSpecLoc(), DiagID)
3369         << DeclSpec::getSpecifierName(SCS);
3370 
3371   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3372     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3373       << DeclSpec::getSpecifierName(TSCS);
3374   if (DS.getTypeQualifiers()) {
3375     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3376       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3377     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3378       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3379     // Restrict is covered above.
3380     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3381       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3382   }
3383 
3384   // Warn about ignored type attributes, for example:
3385   // __attribute__((aligned)) struct A;
3386   // Attributes should be placed after tag to apply to type declaration.
3387   if (!DS.getAttributes().empty()) {
3388     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3389     if (TypeSpecType == DeclSpec::TST_class ||
3390         TypeSpecType == DeclSpec::TST_struct ||
3391         TypeSpecType == DeclSpec::TST_interface ||
3392         TypeSpecType == DeclSpec::TST_union ||
3393         TypeSpecType == DeclSpec::TST_enum) {
3394       AttributeList* attrs = DS.getAttributes().getList();
3395       while (attrs) {
3396         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3397         << attrs->getName()
3398         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3399             TypeSpecType == DeclSpec::TST_struct ? 1 :
3400             TypeSpecType == DeclSpec::TST_union ? 2 :
3401             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3402         attrs = attrs->getNext();
3403       }
3404     }
3405   }
3406 
3407   return TagD;
3408 }
3409 
3410 /// We are trying to inject an anonymous member into the given scope;
3411 /// check if there's an existing declaration that can't be overloaded.
3412 ///
3413 /// \return true if this is a forbidden redeclaration
3414 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3415                                          Scope *S,
3416                                          DeclContext *Owner,
3417                                          DeclarationName Name,
3418                                          SourceLocation NameLoc,
3419                                          unsigned diagnostic) {
3420   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3421                  Sema::ForRedeclaration);
3422   if (!SemaRef.LookupName(R, S)) return false;
3423 
3424   if (R.getAsSingle<TagDecl>())
3425     return false;
3426 
3427   // Pick a representative declaration.
3428   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3429   assert(PrevDecl && "Expected a non-null Decl");
3430 
3431   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3432     return false;
3433 
3434   SemaRef.Diag(NameLoc, diagnostic) << Name;
3435   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3436 
3437   return true;
3438 }
3439 
3440 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3441 /// anonymous struct or union AnonRecord into the owning context Owner
3442 /// and scope S. This routine will be invoked just after we realize
3443 /// that an unnamed union or struct is actually an anonymous union or
3444 /// struct, e.g.,
3445 ///
3446 /// @code
3447 /// union {
3448 ///   int i;
3449 ///   float f;
3450 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3451 ///    // f into the surrounding scope.x
3452 /// @endcode
3453 ///
3454 /// This routine is recursive, injecting the names of nested anonymous
3455 /// structs/unions into the owning context and scope as well.
3456 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3457                                          DeclContext *Owner,
3458                                          RecordDecl *AnonRecord,
3459                                          AccessSpecifier AS,
3460                                          SmallVectorImpl<NamedDecl *> &Chaining,
3461                                          bool MSAnonStruct) {
3462   unsigned diagKind
3463     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3464                             : diag::err_anonymous_struct_member_redecl;
3465 
3466   bool Invalid = false;
3467 
3468   // Look every FieldDecl and IndirectFieldDecl with a name.
3469   for (auto *D : AnonRecord->decls()) {
3470     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3471         cast<NamedDecl>(D)->getDeclName()) {
3472       ValueDecl *VD = cast<ValueDecl>(D);
3473       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3474                                        VD->getLocation(), diagKind)) {
3475         // C++ [class.union]p2:
3476         //   The names of the members of an anonymous union shall be
3477         //   distinct from the names of any other entity in the
3478         //   scope in which the anonymous union is declared.
3479         Invalid = true;
3480       } else {
3481         // C++ [class.union]p2:
3482         //   For the purpose of name lookup, after the anonymous union
3483         //   definition, the members of the anonymous union are
3484         //   considered to have been defined in the scope in which the
3485         //   anonymous union is declared.
3486         unsigned OldChainingSize = Chaining.size();
3487         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3488           for (auto *PI : IF->chain())
3489             Chaining.push_back(PI);
3490         else
3491           Chaining.push_back(VD);
3492 
3493         assert(Chaining.size() >= 2);
3494         NamedDecl **NamedChain =
3495           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3496         for (unsigned i = 0; i < Chaining.size(); i++)
3497           NamedChain[i] = Chaining[i];
3498 
3499         IndirectFieldDecl* IndirectField =
3500           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3501                                     VD->getIdentifier(), VD->getType(),
3502                                     NamedChain, Chaining.size());
3503 
3504         IndirectField->setAccess(AS);
3505         IndirectField->setImplicit();
3506         SemaRef.PushOnScopeChains(IndirectField, S);
3507 
3508         // That includes picking up the appropriate access specifier.
3509         if (AS != AS_none) IndirectField->setAccess(AS);
3510 
3511         Chaining.resize(OldChainingSize);
3512       }
3513     }
3514   }
3515 
3516   return Invalid;
3517 }
3518 
3519 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3520 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3521 /// illegal input values are mapped to SC_None.
3522 static StorageClass
3523 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3524   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3525   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3526          "Parser allowed 'typedef' as storage class VarDecl.");
3527   switch (StorageClassSpec) {
3528   case DeclSpec::SCS_unspecified:    return SC_None;
3529   case DeclSpec::SCS_extern:
3530     if (DS.isExternInLinkageSpec())
3531       return SC_None;
3532     return SC_Extern;
3533   case DeclSpec::SCS_static:         return SC_Static;
3534   case DeclSpec::SCS_auto:           return SC_Auto;
3535   case DeclSpec::SCS_register:       return SC_Register;
3536   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3537     // Illegal SCSs map to None: error reporting is up to the caller.
3538   case DeclSpec::SCS_mutable:        // Fall through.
3539   case DeclSpec::SCS_typedef:        return SC_None;
3540   }
3541   llvm_unreachable("unknown storage class specifier");
3542 }
3543 
3544 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3545   assert(Record->hasInClassInitializer());
3546 
3547   for (const auto *I : Record->decls()) {
3548     const auto *FD = dyn_cast<FieldDecl>(I);
3549     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3550       FD = IFD->getAnonField();
3551     if (FD && FD->hasInClassInitializer())
3552       return FD->getLocation();
3553   }
3554 
3555   llvm_unreachable("couldn't find in-class initializer");
3556 }
3557 
3558 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3559                                       SourceLocation DefaultInitLoc) {
3560   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3561     return;
3562 
3563   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3564   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3565 }
3566 
3567 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3568                                       CXXRecordDecl *AnonUnion) {
3569   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3570     return;
3571 
3572   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3573 }
3574 
3575 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3576 /// anonymous structure or union. Anonymous unions are a C++ feature
3577 /// (C++ [class.union]) and a C11 feature; anonymous structures
3578 /// are a C11 feature and GNU C++ extension.
3579 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3580                                         AccessSpecifier AS,
3581                                         RecordDecl *Record,
3582                                         const PrintingPolicy &Policy) {
3583   DeclContext *Owner = Record->getDeclContext();
3584 
3585   // Diagnose whether this anonymous struct/union is an extension.
3586   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3587     Diag(Record->getLocation(), diag::ext_anonymous_union);
3588   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3589     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3590   else if (!Record->isUnion() && !getLangOpts().C11)
3591     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3592 
3593   // C and C++ require different kinds of checks for anonymous
3594   // structs/unions.
3595   bool Invalid = false;
3596   if (getLangOpts().CPlusPlus) {
3597     const char* PrevSpec = 0;
3598     unsigned DiagID;
3599     if (Record->isUnion()) {
3600       // C++ [class.union]p6:
3601       //   Anonymous unions declared in a named namespace or in the
3602       //   global namespace shall be declared static.
3603       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3604           (isa<TranslationUnitDecl>(Owner) ||
3605            (isa<NamespaceDecl>(Owner) &&
3606             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3607         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3608           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3609 
3610         // Recover by adding 'static'.
3611         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3612                                PrevSpec, DiagID, Policy);
3613       }
3614       // C++ [class.union]p6:
3615       //   A storage class is not allowed in a declaration of an
3616       //   anonymous union in a class scope.
3617       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3618                isa<RecordDecl>(Owner)) {
3619         Diag(DS.getStorageClassSpecLoc(),
3620              diag::err_anonymous_union_with_storage_spec)
3621           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3622 
3623         // Recover by removing the storage specifier.
3624         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3625                                SourceLocation(),
3626                                PrevSpec, DiagID, Context.getPrintingPolicy());
3627       }
3628     }
3629 
3630     // Ignore const/volatile/restrict qualifiers.
3631     if (DS.getTypeQualifiers()) {
3632       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3633         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3634           << Record->isUnion() << "const"
3635           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3636       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3637         Diag(DS.getVolatileSpecLoc(),
3638              diag::ext_anonymous_struct_union_qualified)
3639           << Record->isUnion() << "volatile"
3640           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3641       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3642         Diag(DS.getRestrictSpecLoc(),
3643              diag::ext_anonymous_struct_union_qualified)
3644           << Record->isUnion() << "restrict"
3645           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3646       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3647         Diag(DS.getAtomicSpecLoc(),
3648              diag::ext_anonymous_struct_union_qualified)
3649           << Record->isUnion() << "_Atomic"
3650           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3651 
3652       DS.ClearTypeQualifiers();
3653     }
3654 
3655     // C++ [class.union]p2:
3656     //   The member-specification of an anonymous union shall only
3657     //   define non-static data members. [Note: nested types and
3658     //   functions cannot be declared within an anonymous union. ]
3659     for (auto *Mem : Record->decls()) {
3660       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3661         // C++ [class.union]p3:
3662         //   An anonymous union shall not have private or protected
3663         //   members (clause 11).
3664         assert(FD->getAccess() != AS_none);
3665         if (FD->getAccess() != AS_public) {
3666           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3667             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3668           Invalid = true;
3669         }
3670 
3671         // C++ [class.union]p1
3672         //   An object of a class with a non-trivial constructor, a non-trivial
3673         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3674         //   assignment operator cannot be a member of a union, nor can an
3675         //   array of such objects.
3676         if (CheckNontrivialField(FD))
3677           Invalid = true;
3678       } else if (Mem->isImplicit()) {
3679         // Any implicit members are fine.
3680       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3681         // This is a type that showed up in an
3682         // elaborated-type-specifier inside the anonymous struct or
3683         // union, but which actually declares a type outside of the
3684         // anonymous struct or union. It's okay.
3685       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3686         if (!MemRecord->isAnonymousStructOrUnion() &&
3687             MemRecord->getDeclName()) {
3688           // Visual C++ allows type definition in anonymous struct or union.
3689           if (getLangOpts().MicrosoftExt)
3690             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3691               << (int)Record->isUnion();
3692           else {
3693             // This is a nested type declaration.
3694             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3695               << (int)Record->isUnion();
3696             Invalid = true;
3697           }
3698         } else {
3699           // This is an anonymous type definition within another anonymous type.
3700           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3701           // not part of standard C++.
3702           Diag(MemRecord->getLocation(),
3703                diag::ext_anonymous_record_with_anonymous_type)
3704             << (int)Record->isUnion();
3705         }
3706       } else if (isa<AccessSpecDecl>(Mem)) {
3707         // Any access specifier is fine.
3708       } else {
3709         // We have something that isn't a non-static data
3710         // member. Complain about it.
3711         unsigned DK = diag::err_anonymous_record_bad_member;
3712         if (isa<TypeDecl>(Mem))
3713           DK = diag::err_anonymous_record_with_type;
3714         else if (isa<FunctionDecl>(Mem))
3715           DK = diag::err_anonymous_record_with_function;
3716         else if (isa<VarDecl>(Mem))
3717           DK = diag::err_anonymous_record_with_static;
3718 
3719         // Visual C++ allows type definition in anonymous struct or union.
3720         if (getLangOpts().MicrosoftExt &&
3721             DK == diag::err_anonymous_record_with_type)
3722           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3723             << (int)Record->isUnion();
3724         else {
3725           Diag(Mem->getLocation(), DK)
3726               << (int)Record->isUnion();
3727           Invalid = true;
3728         }
3729       }
3730     }
3731 
3732     // C++11 [class.union]p8 (DR1460):
3733     //   At most one variant member of a union may have a
3734     //   brace-or-equal-initializer.
3735     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3736         Owner->isRecord())
3737       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3738                                 cast<CXXRecordDecl>(Record));
3739   }
3740 
3741   if (!Record->isUnion() && !Owner->isRecord()) {
3742     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3743       << (int)getLangOpts().CPlusPlus;
3744     Invalid = true;
3745   }
3746 
3747   // Mock up a declarator.
3748   Declarator Dc(DS, Declarator::MemberContext);
3749   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3750   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3751 
3752   // Create a declaration for this anonymous struct/union.
3753   NamedDecl *Anon = 0;
3754   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3755     Anon = FieldDecl::Create(Context, OwningClass,
3756                              DS.getLocStart(),
3757                              Record->getLocation(),
3758                              /*IdentifierInfo=*/0,
3759                              Context.getTypeDeclType(Record),
3760                              TInfo,
3761                              /*BitWidth=*/0, /*Mutable=*/false,
3762                              /*InitStyle=*/ICIS_NoInit);
3763     Anon->setAccess(AS);
3764     if (getLangOpts().CPlusPlus)
3765       FieldCollector->Add(cast<FieldDecl>(Anon));
3766   } else {
3767     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3768     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3769     if (SCSpec == DeclSpec::SCS_mutable) {
3770       // mutable can only appear on non-static class members, so it's always
3771       // an error here
3772       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3773       Invalid = true;
3774       SC = SC_None;
3775     }
3776 
3777     Anon = VarDecl::Create(Context, Owner,
3778                            DS.getLocStart(),
3779                            Record->getLocation(), /*IdentifierInfo=*/0,
3780                            Context.getTypeDeclType(Record),
3781                            TInfo, SC);
3782 
3783     // Default-initialize the implicit variable. This initialization will be
3784     // trivial in almost all cases, except if a union member has an in-class
3785     // initializer:
3786     //   union { int n = 0; };
3787     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3788   }
3789   Anon->setImplicit();
3790 
3791   // Mark this as an anonymous struct/union type.
3792   Record->setAnonymousStructOrUnion(true);
3793 
3794   // Add the anonymous struct/union object to the current
3795   // context. We'll be referencing this object when we refer to one of
3796   // its members.
3797   Owner->addDecl(Anon);
3798 
3799   // Inject the members of the anonymous struct/union into the owning
3800   // context and into the identifier resolver chain for name lookup
3801   // purposes.
3802   SmallVector<NamedDecl*, 2> Chain;
3803   Chain.push_back(Anon);
3804 
3805   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3806                                           Chain, false))
3807     Invalid = true;
3808 
3809   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3810     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3811       Decl *ManglingContextDecl;
3812       if (MangleNumberingContext *MCtx =
3813               getCurrentMangleNumberContext(NewVD->getDeclContext(),
3814                                             ManglingContextDecl)) {
3815         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
3816         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3817       }
3818     }
3819   }
3820 
3821   if (Invalid)
3822     Anon->setInvalidDecl();
3823 
3824   return Anon;
3825 }
3826 
3827 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3828 /// Microsoft C anonymous structure.
3829 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3830 /// Example:
3831 ///
3832 /// struct A { int a; };
3833 /// struct B { struct A; int b; };
3834 ///
3835 /// void foo() {
3836 ///   B var;
3837 ///   var.a = 3;
3838 /// }
3839 ///
3840 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3841                                            RecordDecl *Record) {
3842 
3843   // If there is no Record, get the record via the typedef.
3844   if (!Record)
3845     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3846 
3847   // Mock up a declarator.
3848   Declarator Dc(DS, Declarator::TypeNameContext);
3849   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3850   assert(TInfo && "couldn't build declarator info for anonymous struct");
3851 
3852   // Create a declaration for this anonymous struct.
3853   NamedDecl* Anon = FieldDecl::Create(Context,
3854                              cast<RecordDecl>(CurContext),
3855                              DS.getLocStart(),
3856                              DS.getLocStart(),
3857                              /*IdentifierInfo=*/0,
3858                              Context.getTypeDeclType(Record),
3859                              TInfo,
3860                              /*BitWidth=*/0, /*Mutable=*/false,
3861                              /*InitStyle=*/ICIS_NoInit);
3862   Anon->setImplicit();
3863 
3864   // Add the anonymous struct object to the current context.
3865   CurContext->addDecl(Anon);
3866 
3867   // Inject the members of the anonymous struct into the current
3868   // context and into the identifier resolver chain for name lookup
3869   // purposes.
3870   SmallVector<NamedDecl*, 2> Chain;
3871   Chain.push_back(Anon);
3872 
3873   RecordDecl *RecordDef = Record->getDefinition();
3874   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3875                                                         RecordDef, AS_none,
3876                                                         Chain, true))
3877     Anon->setInvalidDecl();
3878 
3879   return Anon;
3880 }
3881 
3882 /// GetNameForDeclarator - Determine the full declaration name for the
3883 /// given Declarator.
3884 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3885   return GetNameFromUnqualifiedId(D.getName());
3886 }
3887 
3888 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3889 DeclarationNameInfo
3890 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3891   DeclarationNameInfo NameInfo;
3892   NameInfo.setLoc(Name.StartLocation);
3893 
3894   switch (Name.getKind()) {
3895 
3896   case UnqualifiedId::IK_ImplicitSelfParam:
3897   case UnqualifiedId::IK_Identifier:
3898     NameInfo.setName(Name.Identifier);
3899     NameInfo.setLoc(Name.StartLocation);
3900     return NameInfo;
3901 
3902   case UnqualifiedId::IK_OperatorFunctionId:
3903     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3904                                            Name.OperatorFunctionId.Operator));
3905     NameInfo.setLoc(Name.StartLocation);
3906     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3907       = Name.OperatorFunctionId.SymbolLocations[0];
3908     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3909       = Name.EndLocation.getRawEncoding();
3910     return NameInfo;
3911 
3912   case UnqualifiedId::IK_LiteralOperatorId:
3913     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3914                                                            Name.Identifier));
3915     NameInfo.setLoc(Name.StartLocation);
3916     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3917     return NameInfo;
3918 
3919   case UnqualifiedId::IK_ConversionFunctionId: {
3920     TypeSourceInfo *TInfo;
3921     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3922     if (Ty.isNull())
3923       return DeclarationNameInfo();
3924     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3925                                                Context.getCanonicalType(Ty)));
3926     NameInfo.setLoc(Name.StartLocation);
3927     NameInfo.setNamedTypeInfo(TInfo);
3928     return NameInfo;
3929   }
3930 
3931   case UnqualifiedId::IK_ConstructorName: {
3932     TypeSourceInfo *TInfo;
3933     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3934     if (Ty.isNull())
3935       return DeclarationNameInfo();
3936     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3937                                               Context.getCanonicalType(Ty)));
3938     NameInfo.setLoc(Name.StartLocation);
3939     NameInfo.setNamedTypeInfo(TInfo);
3940     return NameInfo;
3941   }
3942 
3943   case UnqualifiedId::IK_ConstructorTemplateId: {
3944     // In well-formed code, we can only have a constructor
3945     // template-id that refers to the current context, so go there
3946     // to find the actual type being constructed.
3947     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3948     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3949       return DeclarationNameInfo();
3950 
3951     // Determine the type of the class being constructed.
3952     QualType CurClassType = Context.getTypeDeclType(CurClass);
3953 
3954     // FIXME: Check two things: that the template-id names the same type as
3955     // CurClassType, and that the template-id does not occur when the name
3956     // was qualified.
3957 
3958     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3959                                     Context.getCanonicalType(CurClassType)));
3960     NameInfo.setLoc(Name.StartLocation);
3961     // FIXME: should we retrieve TypeSourceInfo?
3962     NameInfo.setNamedTypeInfo(0);
3963     return NameInfo;
3964   }
3965 
3966   case UnqualifiedId::IK_DestructorName: {
3967     TypeSourceInfo *TInfo;
3968     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3969     if (Ty.isNull())
3970       return DeclarationNameInfo();
3971     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3972                                               Context.getCanonicalType(Ty)));
3973     NameInfo.setLoc(Name.StartLocation);
3974     NameInfo.setNamedTypeInfo(TInfo);
3975     return NameInfo;
3976   }
3977 
3978   case UnqualifiedId::IK_TemplateId: {
3979     TemplateName TName = Name.TemplateId->Template.get();
3980     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3981     return Context.getNameForTemplate(TName, TNameLoc);
3982   }
3983 
3984   } // switch (Name.getKind())
3985 
3986   llvm_unreachable("Unknown name kind");
3987 }
3988 
3989 static QualType getCoreType(QualType Ty) {
3990   do {
3991     if (Ty->isPointerType() || Ty->isReferenceType())
3992       Ty = Ty->getPointeeType();
3993     else if (Ty->isArrayType())
3994       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3995     else
3996       return Ty.withoutLocalFastQualifiers();
3997   } while (true);
3998 }
3999 
4000 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4001 /// and Definition have "nearly" matching parameters. This heuristic is
4002 /// used to improve diagnostics in the case where an out-of-line function
4003 /// definition doesn't match any declaration within the class or namespace.
4004 /// Also sets Params to the list of indices to the parameters that differ
4005 /// between the declaration and the definition. If hasSimilarParameters
4006 /// returns true and Params is empty, then all of the parameters match.
4007 static bool hasSimilarParameters(ASTContext &Context,
4008                                      FunctionDecl *Declaration,
4009                                      FunctionDecl *Definition,
4010                                      SmallVectorImpl<unsigned> &Params) {
4011   Params.clear();
4012   if (Declaration->param_size() != Definition->param_size())
4013     return false;
4014   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4015     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4016     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4017 
4018     // The parameter types are identical
4019     if (Context.hasSameType(DefParamTy, DeclParamTy))
4020       continue;
4021 
4022     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4023     QualType DefParamBaseTy = getCoreType(DefParamTy);
4024     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4025     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4026 
4027     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4028         (DeclTyName && DeclTyName == DefTyName))
4029       Params.push_back(Idx);
4030     else  // The two parameters aren't even close
4031       return false;
4032   }
4033 
4034   return true;
4035 }
4036 
4037 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4038 /// declarator needs to be rebuilt in the current instantiation.
4039 /// Any bits of declarator which appear before the name are valid for
4040 /// consideration here.  That's specifically the type in the decl spec
4041 /// and the base type in any member-pointer chunks.
4042 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4043                                                     DeclarationName Name) {
4044   // The types we specifically need to rebuild are:
4045   //   - typenames, typeofs, and decltypes
4046   //   - types which will become injected class names
4047   // Of course, we also need to rebuild any type referencing such a
4048   // type.  It's safest to just say "dependent", but we call out a
4049   // few cases here.
4050 
4051   DeclSpec &DS = D.getMutableDeclSpec();
4052   switch (DS.getTypeSpecType()) {
4053   case DeclSpec::TST_typename:
4054   case DeclSpec::TST_typeofType:
4055   case DeclSpec::TST_underlyingType:
4056   case DeclSpec::TST_atomic: {
4057     // Grab the type from the parser.
4058     TypeSourceInfo *TSI = 0;
4059     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4060     if (T.isNull() || !T->isDependentType()) break;
4061 
4062     // Make sure there's a type source info.  This isn't really much
4063     // of a waste; most dependent types should have type source info
4064     // attached already.
4065     if (!TSI)
4066       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4067 
4068     // Rebuild the type in the current instantiation.
4069     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4070     if (!TSI) return true;
4071 
4072     // Store the new type back in the decl spec.
4073     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4074     DS.UpdateTypeRep(LocType);
4075     break;
4076   }
4077 
4078   case DeclSpec::TST_decltype:
4079   case DeclSpec::TST_typeofExpr: {
4080     Expr *E = DS.getRepAsExpr();
4081     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4082     if (Result.isInvalid()) return true;
4083     DS.UpdateExprRep(Result.get());
4084     break;
4085   }
4086 
4087   default:
4088     // Nothing to do for these decl specs.
4089     break;
4090   }
4091 
4092   // It doesn't matter what order we do this in.
4093   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4094     DeclaratorChunk &Chunk = D.getTypeObject(I);
4095 
4096     // The only type information in the declarator which can come
4097     // before the declaration name is the base type of a member
4098     // pointer.
4099     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4100       continue;
4101 
4102     // Rebuild the scope specifier in-place.
4103     CXXScopeSpec &SS = Chunk.Mem.Scope();
4104     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4105       return true;
4106   }
4107 
4108   return false;
4109 }
4110 
4111 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4112   D.setFunctionDefinitionKind(FDK_Declaration);
4113   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4114 
4115   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4116       Dcl && Dcl->getDeclContext()->isFileContext())
4117     Dcl->setTopLevelDeclInObjCContainer();
4118 
4119   return Dcl;
4120 }
4121 
4122 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4123 ///   If T is the name of a class, then each of the following shall have a
4124 ///   name different from T:
4125 ///     - every static data member of class T;
4126 ///     - every member function of class T
4127 ///     - every member of class T that is itself a type;
4128 /// \returns true if the declaration name violates these rules.
4129 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4130                                    DeclarationNameInfo NameInfo) {
4131   DeclarationName Name = NameInfo.getName();
4132 
4133   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4134     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4135       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4136       return true;
4137     }
4138 
4139   return false;
4140 }
4141 
4142 /// \brief Diagnose a declaration whose declarator-id has the given
4143 /// nested-name-specifier.
4144 ///
4145 /// \param SS The nested-name-specifier of the declarator-id.
4146 ///
4147 /// \param DC The declaration context to which the nested-name-specifier
4148 /// resolves.
4149 ///
4150 /// \param Name The name of the entity being declared.
4151 ///
4152 /// \param Loc The location of the name of the entity being declared.
4153 ///
4154 /// \returns true if we cannot safely recover from this error, false otherwise.
4155 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4156                                         DeclarationName Name,
4157                                         SourceLocation Loc) {
4158   DeclContext *Cur = CurContext;
4159   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4160     Cur = Cur->getParent();
4161 
4162   // If the user provided a superfluous scope specifier that refers back to the
4163   // class in which the entity is already declared, diagnose and ignore it.
4164   //
4165   // class X {
4166   //   void X::f();
4167   // };
4168   //
4169   // Note, it was once ill-formed to give redundant qualification in all
4170   // contexts, but that rule was removed by DR482.
4171   if (Cur->Equals(DC)) {
4172     if (Cur->isRecord()) {
4173       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4174                                       : diag::err_member_extra_qualification)
4175         << Name << FixItHint::CreateRemoval(SS.getRange());
4176       SS.clear();
4177     } else {
4178       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4179     }
4180     return false;
4181   }
4182 
4183   // Check whether the qualifying scope encloses the scope of the original
4184   // declaration.
4185   if (!Cur->Encloses(DC)) {
4186     if (Cur->isRecord())
4187       Diag(Loc, diag::err_member_qualification)
4188         << Name << SS.getRange();
4189     else if (isa<TranslationUnitDecl>(DC))
4190       Diag(Loc, diag::err_invalid_declarator_global_scope)
4191         << Name << SS.getRange();
4192     else if (isa<FunctionDecl>(Cur))
4193       Diag(Loc, diag::err_invalid_declarator_in_function)
4194         << Name << SS.getRange();
4195     else if (isa<BlockDecl>(Cur))
4196       Diag(Loc, diag::err_invalid_declarator_in_block)
4197         << Name << SS.getRange();
4198     else
4199       Diag(Loc, diag::err_invalid_declarator_scope)
4200       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4201 
4202     return true;
4203   }
4204 
4205   if (Cur->isRecord()) {
4206     // Cannot qualify members within a class.
4207     Diag(Loc, diag::err_member_qualification)
4208       << Name << SS.getRange();
4209     SS.clear();
4210 
4211     // C++ constructors and destructors with incorrect scopes can break
4212     // our AST invariants by having the wrong underlying types. If
4213     // that's the case, then drop this declaration entirely.
4214     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4215          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4216         !Context.hasSameType(Name.getCXXNameType(),
4217                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4218       return true;
4219 
4220     return false;
4221   }
4222 
4223   // C++11 [dcl.meaning]p1:
4224   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4225   //   not begin with a decltype-specifer"
4226   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4227   while (SpecLoc.getPrefix())
4228     SpecLoc = SpecLoc.getPrefix();
4229   if (dyn_cast_or_null<DecltypeType>(
4230         SpecLoc.getNestedNameSpecifier()->getAsType()))
4231     Diag(Loc, diag::err_decltype_in_declarator)
4232       << SpecLoc.getTypeLoc().getSourceRange();
4233 
4234   return false;
4235 }
4236 
4237 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4238                                   MultiTemplateParamsArg TemplateParamLists) {
4239   // TODO: consider using NameInfo for diagnostic.
4240   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4241   DeclarationName Name = NameInfo.getName();
4242 
4243   // All of these full declarators require an identifier.  If it doesn't have
4244   // one, the ParsedFreeStandingDeclSpec action should be used.
4245   if (!Name) {
4246     if (!D.isInvalidType())  // Reject this if we think it is valid.
4247       Diag(D.getDeclSpec().getLocStart(),
4248            diag::err_declarator_need_ident)
4249         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4250     return 0;
4251   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4252     return 0;
4253 
4254   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4255   // we find one that is.
4256   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4257          (S->getFlags() & Scope::TemplateParamScope) != 0)
4258     S = S->getParent();
4259 
4260   DeclContext *DC = CurContext;
4261   if (D.getCXXScopeSpec().isInvalid())
4262     D.setInvalidType();
4263   else if (D.getCXXScopeSpec().isSet()) {
4264     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4265                                         UPPC_DeclarationQualifier))
4266       return 0;
4267 
4268     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4269     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4270     if (!DC || isa<EnumDecl>(DC)) {
4271       // If we could not compute the declaration context, it's because the
4272       // declaration context is dependent but does not refer to a class,
4273       // class template, or class template partial specialization. Complain
4274       // and return early, to avoid the coming semantic disaster.
4275       Diag(D.getIdentifierLoc(),
4276            diag::err_template_qualified_declarator_no_match)
4277         << D.getCXXScopeSpec().getScopeRep()
4278         << D.getCXXScopeSpec().getRange();
4279       return 0;
4280     }
4281     bool IsDependentContext = DC->isDependentContext();
4282 
4283     if (!IsDependentContext &&
4284         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4285       return 0;
4286 
4287     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4288       Diag(D.getIdentifierLoc(),
4289            diag::err_member_def_undefined_record)
4290         << Name << DC << D.getCXXScopeSpec().getRange();
4291       D.setInvalidType();
4292     } else if (!D.getDeclSpec().isFriendSpecified()) {
4293       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4294                                       Name, D.getIdentifierLoc())) {
4295         if (DC->isRecord())
4296           return 0;
4297 
4298         D.setInvalidType();
4299       }
4300     }
4301 
4302     // Check whether we need to rebuild the type of the given
4303     // declaration in the current instantiation.
4304     if (EnteringContext && IsDependentContext &&
4305         TemplateParamLists.size() != 0) {
4306       ContextRAII SavedContext(*this, DC);
4307       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4308         D.setInvalidType();
4309     }
4310   }
4311 
4312   if (DiagnoseClassNameShadow(DC, NameInfo))
4313     // If this is a typedef, we'll end up spewing multiple diagnostics.
4314     // Just return early; it's safer.
4315     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4316       return 0;
4317 
4318   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4319   QualType R = TInfo->getType();
4320 
4321   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4322                                       UPPC_DeclarationType))
4323     D.setInvalidType();
4324 
4325   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4326                         ForRedeclaration);
4327 
4328   // See if this is a redefinition of a variable in the same scope.
4329   if (!D.getCXXScopeSpec().isSet()) {
4330     bool IsLinkageLookup = false;
4331     bool CreateBuiltins = false;
4332 
4333     // If the declaration we're planning to build will be a function
4334     // or object with linkage, then look for another declaration with
4335     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4336     //
4337     // If the declaration we're planning to build will be declared with
4338     // external linkage in the translation unit, create any builtin with
4339     // the same name.
4340     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4341       /* Do nothing*/;
4342     else if (CurContext->isFunctionOrMethod() &&
4343              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4344               R->isFunctionType())) {
4345       IsLinkageLookup = true;
4346       CreateBuiltins =
4347           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4348     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4349                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4350       CreateBuiltins = true;
4351 
4352     if (IsLinkageLookup)
4353       Previous.clear(LookupRedeclarationWithLinkage);
4354 
4355     LookupName(Previous, S, CreateBuiltins);
4356   } else { // Something like "int foo::x;"
4357     LookupQualifiedName(Previous, DC);
4358 
4359     // C++ [dcl.meaning]p1:
4360     //   When the declarator-id is qualified, the declaration shall refer to a
4361     //  previously declared member of the class or namespace to which the
4362     //  qualifier refers (or, in the case of a namespace, of an element of the
4363     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4364     //  thereof; [...]
4365     //
4366     // Note that we already checked the context above, and that we do not have
4367     // enough information to make sure that Previous contains the declaration
4368     // we want to match. For example, given:
4369     //
4370     //   class X {
4371     //     void f();
4372     //     void f(float);
4373     //   };
4374     //
4375     //   void X::f(int) { } // ill-formed
4376     //
4377     // In this case, Previous will point to the overload set
4378     // containing the two f's declared in X, but neither of them
4379     // matches.
4380 
4381     // C++ [dcl.meaning]p1:
4382     //   [...] the member shall not merely have been introduced by a
4383     //   using-declaration in the scope of the class or namespace nominated by
4384     //   the nested-name-specifier of the declarator-id.
4385     RemoveUsingDecls(Previous);
4386   }
4387 
4388   if (Previous.isSingleResult() &&
4389       Previous.getFoundDecl()->isTemplateParameter()) {
4390     // Maybe we will complain about the shadowed template parameter.
4391     if (!D.isInvalidType())
4392       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4393                                       Previous.getFoundDecl());
4394 
4395     // Just pretend that we didn't see the previous declaration.
4396     Previous.clear();
4397   }
4398 
4399   // In C++, the previous declaration we find might be a tag type
4400   // (class or enum). In this case, the new declaration will hide the
4401   // tag type. Note that this does does not apply if we're declaring a
4402   // typedef (C++ [dcl.typedef]p4).
4403   if (Previous.isSingleTagDecl() &&
4404       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4405     Previous.clear();
4406 
4407   // Check that there are no default arguments other than in the parameters
4408   // of a function declaration (C++ only).
4409   if (getLangOpts().CPlusPlus)
4410     CheckExtraCXXDefaultArguments(D);
4411 
4412   NamedDecl *New;
4413 
4414   bool AddToScope = true;
4415   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4416     if (TemplateParamLists.size()) {
4417       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4418       return 0;
4419     }
4420 
4421     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4422   } else if (R->isFunctionType()) {
4423     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4424                                   TemplateParamLists,
4425                                   AddToScope);
4426   } else {
4427     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4428                                   AddToScope);
4429   }
4430 
4431   if (New == 0)
4432     return 0;
4433 
4434   // If this has an identifier and is not an invalid redeclaration or
4435   // function template specialization, add it to the scope stack.
4436   if (New->getDeclName() && AddToScope &&
4437        !(D.isRedeclaration() && New->isInvalidDecl())) {
4438     // Only make a locally-scoped extern declaration visible if it is the first
4439     // declaration of this entity. Qualified lookup for such an entity should
4440     // only find this declaration if there is no visible declaration of it.
4441     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4442     PushOnScopeChains(New, S, AddToContext);
4443     if (!AddToContext)
4444       CurContext->addHiddenDecl(New);
4445   }
4446 
4447   return New;
4448 }
4449 
4450 /// Helper method to turn variable array types into constant array
4451 /// types in certain situations which would otherwise be errors (for
4452 /// GCC compatibility).
4453 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4454                                                     ASTContext &Context,
4455                                                     bool &SizeIsNegative,
4456                                                     llvm::APSInt &Oversized) {
4457   // This method tries to turn a variable array into a constant
4458   // array even when the size isn't an ICE.  This is necessary
4459   // for compatibility with code that depends on gcc's buggy
4460   // constant expression folding, like struct {char x[(int)(char*)2];}
4461   SizeIsNegative = false;
4462   Oversized = 0;
4463 
4464   if (T->isDependentType())
4465     return QualType();
4466 
4467   QualifierCollector Qs;
4468   const Type *Ty = Qs.strip(T);
4469 
4470   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4471     QualType Pointee = PTy->getPointeeType();
4472     QualType FixedType =
4473         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4474                                             Oversized);
4475     if (FixedType.isNull()) return FixedType;
4476     FixedType = Context.getPointerType(FixedType);
4477     return Qs.apply(Context, FixedType);
4478   }
4479   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4480     QualType Inner = PTy->getInnerType();
4481     QualType FixedType =
4482         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4483                                             Oversized);
4484     if (FixedType.isNull()) return FixedType;
4485     FixedType = Context.getParenType(FixedType);
4486     return Qs.apply(Context, FixedType);
4487   }
4488 
4489   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4490   if (!VLATy)
4491     return QualType();
4492   // FIXME: We should probably handle this case
4493   if (VLATy->getElementType()->isVariablyModifiedType())
4494     return QualType();
4495 
4496   llvm::APSInt Res;
4497   if (!VLATy->getSizeExpr() ||
4498       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4499     return QualType();
4500 
4501   // Check whether the array size is negative.
4502   if (Res.isSigned() && Res.isNegative()) {
4503     SizeIsNegative = true;
4504     return QualType();
4505   }
4506 
4507   // Check whether the array is too large to be addressed.
4508   unsigned ActiveSizeBits
4509     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4510                                               Res);
4511   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4512     Oversized = Res;
4513     return QualType();
4514   }
4515 
4516   return Context.getConstantArrayType(VLATy->getElementType(),
4517                                       Res, ArrayType::Normal, 0);
4518 }
4519 
4520 static void
4521 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4522   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4523     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4524     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4525                                       DstPTL.getPointeeLoc());
4526     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4527     return;
4528   }
4529   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4530     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4531     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4532                                       DstPTL.getInnerLoc());
4533     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4534     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4535     return;
4536   }
4537   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4538   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4539   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4540   TypeLoc DstElemTL = DstATL.getElementLoc();
4541   DstElemTL.initializeFullCopy(SrcElemTL);
4542   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4543   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4544   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4545 }
4546 
4547 /// Helper method to turn variable array types into constant array
4548 /// types in certain situations which would otherwise be errors (for
4549 /// GCC compatibility).
4550 static TypeSourceInfo*
4551 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4552                                               ASTContext &Context,
4553                                               bool &SizeIsNegative,
4554                                               llvm::APSInt &Oversized) {
4555   QualType FixedTy
4556     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4557                                           SizeIsNegative, Oversized);
4558   if (FixedTy.isNull())
4559     return 0;
4560   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4561   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4562                                     FixedTInfo->getTypeLoc());
4563   return FixedTInfo;
4564 }
4565 
4566 /// \brief Register the given locally-scoped extern "C" declaration so
4567 /// that it can be found later for redeclarations. We include any extern "C"
4568 /// declaration that is not visible in the translation unit here, not just
4569 /// function-scope declarations.
4570 void
4571 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4572   if (!getLangOpts().CPlusPlus &&
4573       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4574     // Don't need to track declarations in the TU in C.
4575     return;
4576 
4577   // Note that we have a locally-scoped external with this name.
4578   // FIXME: There can be multiple such declarations if they are functions marked
4579   // __attribute__((overloadable)) declared in function scope in C.
4580   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4581 }
4582 
4583 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4584   if (ExternalSource) {
4585     // Load locally-scoped external decls from the external source.
4586     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4587     SmallVector<NamedDecl *, 4> Decls;
4588     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4589     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4590       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4591         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4592       if (Pos == LocallyScopedExternCDecls.end())
4593         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4594     }
4595   }
4596 
4597   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4598   return D ? D->getMostRecentDecl() : 0;
4599 }
4600 
4601 /// \brief Diagnose function specifiers on a declaration of an identifier that
4602 /// does not identify a function.
4603 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4604   // FIXME: We should probably indicate the identifier in question to avoid
4605   // confusion for constructs like "inline int a(), b;"
4606   if (DS.isInlineSpecified())
4607     Diag(DS.getInlineSpecLoc(),
4608          diag::err_inline_non_function);
4609 
4610   if (DS.isVirtualSpecified())
4611     Diag(DS.getVirtualSpecLoc(),
4612          diag::err_virtual_non_function);
4613 
4614   if (DS.isExplicitSpecified())
4615     Diag(DS.getExplicitSpecLoc(),
4616          diag::err_explicit_non_function);
4617 
4618   if (DS.isNoreturnSpecified())
4619     Diag(DS.getNoreturnSpecLoc(),
4620          diag::err_noreturn_non_function);
4621 }
4622 
4623 NamedDecl*
4624 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4625                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4626   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4627   if (D.getCXXScopeSpec().isSet()) {
4628     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4629       << D.getCXXScopeSpec().getRange();
4630     D.setInvalidType();
4631     // Pretend we didn't see the scope specifier.
4632     DC = CurContext;
4633     Previous.clear();
4634   }
4635 
4636   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4637 
4638   if (D.getDeclSpec().isConstexprSpecified())
4639     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4640       << 1;
4641 
4642   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4643     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4644       << D.getName().getSourceRange();
4645     return 0;
4646   }
4647 
4648   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4649   if (!NewTD) return 0;
4650 
4651   // Handle attributes prior to checking for duplicates in MergeVarDecl
4652   ProcessDeclAttributes(S, NewTD, D);
4653 
4654   CheckTypedefForVariablyModifiedType(S, NewTD);
4655 
4656   bool Redeclaration = D.isRedeclaration();
4657   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4658   D.setRedeclaration(Redeclaration);
4659   return ND;
4660 }
4661 
4662 void
4663 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4664   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4665   // then it shall have block scope.
4666   // Note that variably modified types must be fixed before merging the decl so
4667   // that redeclarations will match.
4668   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4669   QualType T = TInfo->getType();
4670   if (T->isVariablyModifiedType()) {
4671     getCurFunction()->setHasBranchProtectedScope();
4672 
4673     if (S->getFnParent() == 0) {
4674       bool SizeIsNegative;
4675       llvm::APSInt Oversized;
4676       TypeSourceInfo *FixedTInfo =
4677         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4678                                                       SizeIsNegative,
4679                                                       Oversized);
4680       if (FixedTInfo) {
4681         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4682         NewTD->setTypeSourceInfo(FixedTInfo);
4683       } else {
4684         if (SizeIsNegative)
4685           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4686         else if (T->isVariableArrayType())
4687           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4688         else if (Oversized.getBoolValue())
4689           Diag(NewTD->getLocation(), diag::err_array_too_large)
4690             << Oversized.toString(10);
4691         else
4692           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4693         NewTD->setInvalidDecl();
4694       }
4695     }
4696   }
4697 }
4698 
4699 
4700 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4701 /// declares a typedef-name, either using the 'typedef' type specifier or via
4702 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4703 NamedDecl*
4704 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4705                            LookupResult &Previous, bool &Redeclaration) {
4706   // Merge the decl with the existing one if appropriate. If the decl is
4707   // in an outer scope, it isn't the same thing.
4708   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4709                        /*AllowInlineNamespace*/false);
4710   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4711   if (!Previous.empty()) {
4712     Redeclaration = true;
4713     MergeTypedefNameDecl(NewTD, Previous);
4714   }
4715 
4716   // If this is the C FILE type, notify the AST context.
4717   if (IdentifierInfo *II = NewTD->getIdentifier())
4718     if (!NewTD->isInvalidDecl() &&
4719         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4720       if (II->isStr("FILE"))
4721         Context.setFILEDecl(NewTD);
4722       else if (II->isStr("jmp_buf"))
4723         Context.setjmp_bufDecl(NewTD);
4724       else if (II->isStr("sigjmp_buf"))
4725         Context.setsigjmp_bufDecl(NewTD);
4726       else if (II->isStr("ucontext_t"))
4727         Context.setucontext_tDecl(NewTD);
4728     }
4729 
4730   return NewTD;
4731 }
4732 
4733 /// \brief Determines whether the given declaration is an out-of-scope
4734 /// previous declaration.
4735 ///
4736 /// This routine should be invoked when name lookup has found a
4737 /// previous declaration (PrevDecl) that is not in the scope where a
4738 /// new declaration by the same name is being introduced. If the new
4739 /// declaration occurs in a local scope, previous declarations with
4740 /// linkage may still be considered previous declarations (C99
4741 /// 6.2.2p4-5, C++ [basic.link]p6).
4742 ///
4743 /// \param PrevDecl the previous declaration found by name
4744 /// lookup
4745 ///
4746 /// \param DC the context in which the new declaration is being
4747 /// declared.
4748 ///
4749 /// \returns true if PrevDecl is an out-of-scope previous declaration
4750 /// for a new delcaration with the same name.
4751 static bool
4752 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4753                                 ASTContext &Context) {
4754   if (!PrevDecl)
4755     return false;
4756 
4757   if (!PrevDecl->hasLinkage())
4758     return false;
4759 
4760   if (Context.getLangOpts().CPlusPlus) {
4761     // C++ [basic.link]p6:
4762     //   If there is a visible declaration of an entity with linkage
4763     //   having the same name and type, ignoring entities declared
4764     //   outside the innermost enclosing namespace scope, the block
4765     //   scope declaration declares that same entity and receives the
4766     //   linkage of the previous declaration.
4767     DeclContext *OuterContext = DC->getRedeclContext();
4768     if (!OuterContext->isFunctionOrMethod())
4769       // This rule only applies to block-scope declarations.
4770       return false;
4771 
4772     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4773     if (PrevOuterContext->isRecord())
4774       // We found a member function: ignore it.
4775       return false;
4776 
4777     // Find the innermost enclosing namespace for the new and
4778     // previous declarations.
4779     OuterContext = OuterContext->getEnclosingNamespaceContext();
4780     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4781 
4782     // The previous declaration is in a different namespace, so it
4783     // isn't the same function.
4784     if (!OuterContext->Equals(PrevOuterContext))
4785       return false;
4786   }
4787 
4788   return true;
4789 }
4790 
4791 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4792   CXXScopeSpec &SS = D.getCXXScopeSpec();
4793   if (!SS.isSet()) return;
4794   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4795 }
4796 
4797 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4798   QualType type = decl->getType();
4799   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4800   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4801     // Various kinds of declaration aren't allowed to be __autoreleasing.
4802     unsigned kind = -1U;
4803     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4804       if (var->hasAttr<BlocksAttr>())
4805         kind = 0; // __block
4806       else if (!var->hasLocalStorage())
4807         kind = 1; // global
4808     } else if (isa<ObjCIvarDecl>(decl)) {
4809       kind = 3; // ivar
4810     } else if (isa<FieldDecl>(decl)) {
4811       kind = 2; // field
4812     }
4813 
4814     if (kind != -1U) {
4815       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4816         << kind;
4817     }
4818   } else if (lifetime == Qualifiers::OCL_None) {
4819     // Try to infer lifetime.
4820     if (!type->isObjCLifetimeType())
4821       return false;
4822 
4823     lifetime = type->getObjCARCImplicitLifetime();
4824     type = Context.getLifetimeQualifiedType(type, lifetime);
4825     decl->setType(type);
4826   }
4827 
4828   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4829     // Thread-local variables cannot have lifetime.
4830     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4831         var->getTLSKind()) {
4832       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4833         << var->getType();
4834       return true;
4835     }
4836   }
4837 
4838   return false;
4839 }
4840 
4841 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4842   // Ensure that an auto decl is deduced otherwise the checks below might cache
4843   // the wrong linkage.
4844   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4845 
4846   // 'weak' only applies to declarations with external linkage.
4847   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4848     if (!ND.isExternallyVisible()) {
4849       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4850       ND.dropAttr<WeakAttr>();
4851     }
4852   }
4853   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4854     if (ND.isExternallyVisible()) {
4855       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4856       ND.dropAttr<WeakRefAttr>();
4857     }
4858   }
4859 
4860   // 'selectany' only applies to externally visible varable declarations.
4861   // It does not apply to functions.
4862   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4863     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4864       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4865       ND.dropAttr<SelectAnyAttr>();
4866     }
4867   }
4868 }
4869 
4870 /// Given that we are within the definition of the given function,
4871 /// will that definition behave like C99's 'inline', where the
4872 /// definition is discarded except for optimization purposes?
4873 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4874   // Try to avoid calling GetGVALinkageForFunction.
4875 
4876   // All cases of this require the 'inline' keyword.
4877   if (!FD->isInlined()) return false;
4878 
4879   // This is only possible in C++ with the gnu_inline attribute.
4880   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4881     return false;
4882 
4883   // Okay, go ahead and call the relatively-more-expensive function.
4884 
4885 #ifndef NDEBUG
4886   // AST quite reasonably asserts that it's working on a function
4887   // definition.  We don't really have a way to tell it that we're
4888   // currently defining the function, so just lie to it in +Asserts
4889   // builds.  This is an awful hack.
4890   FD->setLazyBody(1);
4891 #endif
4892 
4893   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4894 
4895 #ifndef NDEBUG
4896   FD->setLazyBody(0);
4897 #endif
4898 
4899   return isC99Inline;
4900 }
4901 
4902 /// Determine whether a variable is extern "C" prior to attaching
4903 /// an initializer. We can't just call isExternC() here, because that
4904 /// will also compute and cache whether the declaration is externally
4905 /// visible, which might change when we attach the initializer.
4906 ///
4907 /// This can only be used if the declaration is known to not be a
4908 /// redeclaration of an internal linkage declaration.
4909 ///
4910 /// For instance:
4911 ///
4912 ///   auto x = []{};
4913 ///
4914 /// Attaching the initializer here makes this declaration not externally
4915 /// visible, because its type has internal linkage.
4916 ///
4917 /// FIXME: This is a hack.
4918 template<typename T>
4919 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4920   if (S.getLangOpts().CPlusPlus) {
4921     // In C++, the overloadable attribute negates the effects of extern "C".
4922     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4923       return false;
4924   }
4925   return D->isExternC();
4926 }
4927 
4928 static bool shouldConsiderLinkage(const VarDecl *VD) {
4929   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4930   if (DC->isFunctionOrMethod())
4931     return VD->hasExternalStorage();
4932   if (DC->isFileContext())
4933     return true;
4934   if (DC->isRecord())
4935     return false;
4936   llvm_unreachable("Unexpected context");
4937 }
4938 
4939 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4940   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4941   if (DC->isFileContext() || DC->isFunctionOrMethod())
4942     return true;
4943   if (DC->isRecord())
4944     return false;
4945   llvm_unreachable("Unexpected context");
4946 }
4947 
4948 /// Adjust the \c DeclContext for a function or variable that might be a
4949 /// function-local external declaration.
4950 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4951   if (!DC->isFunctionOrMethod())
4952     return false;
4953 
4954   // If this is a local extern function or variable declared within a function
4955   // template, don't add it into the enclosing namespace scope until it is
4956   // instantiated; it might have a dependent type right now.
4957   if (DC->isDependentContext())
4958     return true;
4959 
4960   // C++11 [basic.link]p7:
4961   //   When a block scope declaration of an entity with linkage is not found to
4962   //   refer to some other declaration, then that entity is a member of the
4963   //   innermost enclosing namespace.
4964   //
4965   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4966   // semantically-enclosing namespace, not a lexically-enclosing one.
4967   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4968     DC = DC->getParent();
4969   return true;
4970 }
4971 
4972 NamedDecl *
4973 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4974                               TypeSourceInfo *TInfo, LookupResult &Previous,
4975                               MultiTemplateParamsArg TemplateParamLists,
4976                               bool &AddToScope) {
4977   QualType R = TInfo->getType();
4978   DeclarationName Name = GetNameForDeclarator(D).getName();
4979 
4980   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4981   VarDecl::StorageClass SC =
4982     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4983 
4984   DeclContext *OriginalDC = DC;
4985   bool IsLocalExternDecl = SC == SC_Extern &&
4986                            adjustContextForLocalExternDecl(DC);
4987 
4988   if (getLangOpts().OpenCL) {
4989     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
4990     QualType NR = R;
4991     while (NR->isPointerType()) {
4992       if (NR->isFunctionPointerType()) {
4993         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
4994         D.setInvalidType();
4995         break;
4996       }
4997       NR = NR->getPointeeType();
4998     }
4999 
5000     if (!getOpenCLOptions().cl_khr_fp16) {
5001       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5002       // half array type (unless the cl_khr_fp16 extension is enabled).
5003       if (Context.getBaseElementType(R)->isHalfType()) {
5004         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5005         D.setInvalidType();
5006       }
5007     }
5008   }
5009 
5010   if (SCSpec == DeclSpec::SCS_mutable) {
5011     // mutable can only appear on non-static class members, so it's always
5012     // an error here
5013     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5014     D.setInvalidType();
5015     SC = SC_None;
5016   }
5017 
5018   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5019       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5020                               D.getDeclSpec().getStorageClassSpecLoc())) {
5021     // In C++11, the 'register' storage class specifier is deprecated.
5022     // Suppress the warning in system macros, it's used in macros in some
5023     // popular C system headers, such as in glibc's htonl() macro.
5024     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5025          diag::warn_deprecated_register)
5026       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5027   }
5028 
5029   IdentifierInfo *II = Name.getAsIdentifierInfo();
5030   if (!II) {
5031     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5032       << Name;
5033     return 0;
5034   }
5035 
5036   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5037 
5038   if (!DC->isRecord() && S->getFnParent() == 0) {
5039     // C99 6.9p2: The storage-class specifiers auto and register shall not
5040     // appear in the declaration specifiers in an external declaration.
5041     if (SC == SC_Auto || SC == SC_Register) {
5042       // If this is a register variable with an asm label specified, then this
5043       // is a GNU extension.
5044       if (SC == SC_Register && D.getAsmLabel())
5045         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5046       else
5047         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5048       D.setInvalidType();
5049     }
5050   }
5051 
5052   if (getLangOpts().OpenCL) {
5053     // Set up the special work-group-local storage class for variables in the
5054     // OpenCL __local address space.
5055     if (R.getAddressSpace() == LangAS::opencl_local) {
5056       SC = SC_OpenCLWorkGroupLocal;
5057     }
5058 
5059     // OpenCL v1.2 s6.9.b p4:
5060     // The sampler type cannot be used with the __local and __global address
5061     // space qualifiers.
5062     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5063       R.getAddressSpace() == LangAS::opencl_global)) {
5064       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5065     }
5066 
5067     // OpenCL 1.2 spec, p6.9 r:
5068     // The event type cannot be used to declare a program scope variable.
5069     // The event type cannot be used with the __local, __constant and __global
5070     // address space qualifiers.
5071     if (R->isEventT()) {
5072       if (S->getParent() == 0) {
5073         Diag(D.getLocStart(), diag::err_event_t_global_var);
5074         D.setInvalidType();
5075       }
5076 
5077       if (R.getAddressSpace()) {
5078         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5079         D.setInvalidType();
5080       }
5081     }
5082   }
5083 
5084   bool IsExplicitSpecialization = false;
5085   bool IsVariableTemplateSpecialization = false;
5086   bool IsPartialSpecialization = false;
5087   bool IsVariableTemplate = false;
5088   VarDecl *NewVD = 0;
5089   VarTemplateDecl *NewTemplate = 0;
5090   TemplateParameterList *TemplateParams = 0;
5091   if (!getLangOpts().CPlusPlus) {
5092     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5093                             D.getIdentifierLoc(), II,
5094                             R, TInfo, SC);
5095 
5096     if (D.isInvalidType())
5097       NewVD->setInvalidDecl();
5098   } else {
5099     bool Invalid = false;
5100 
5101     if (DC->isRecord() && !CurContext->isRecord()) {
5102       // This is an out-of-line definition of a static data member.
5103       switch (SC) {
5104       case SC_None:
5105         break;
5106       case SC_Static:
5107         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5108              diag::err_static_out_of_line)
5109           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5110         break;
5111       case SC_Auto:
5112       case SC_Register:
5113       case SC_Extern:
5114         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5115         // to names of variables declared in a block or to function parameters.
5116         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5117         // of class members
5118 
5119         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5120              diag::err_storage_class_for_static_member)
5121           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5122         break;
5123       case SC_PrivateExtern:
5124         llvm_unreachable("C storage class in c++!");
5125       case SC_OpenCLWorkGroupLocal:
5126         llvm_unreachable("OpenCL storage class in c++!");
5127       }
5128     }
5129 
5130     if (SC == SC_Static && CurContext->isRecord()) {
5131       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5132         if (RD->isLocalClass())
5133           Diag(D.getIdentifierLoc(),
5134                diag::err_static_data_member_not_allowed_in_local_class)
5135             << Name << RD->getDeclName();
5136 
5137         // C++98 [class.union]p1: If a union contains a static data member,
5138         // the program is ill-formed. C++11 drops this restriction.
5139         if (RD->isUnion())
5140           Diag(D.getIdentifierLoc(),
5141                getLangOpts().CPlusPlus11
5142                  ? diag::warn_cxx98_compat_static_data_member_in_union
5143                  : diag::ext_static_data_member_in_union) << Name;
5144         // We conservatively disallow static data members in anonymous structs.
5145         else if (!RD->getDeclName())
5146           Diag(D.getIdentifierLoc(),
5147                diag::err_static_data_member_not_allowed_in_anon_struct)
5148             << Name << RD->isUnion();
5149       }
5150     }
5151 
5152     // Match up the template parameter lists with the scope specifier, then
5153     // determine whether we have a template or a template specialization.
5154     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5155         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5156         D.getCXXScopeSpec(), TemplateParamLists,
5157         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5158 
5159     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5160         !TemplateParams) {
5161       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5162 
5163       // We have encountered something that the user meant to be a
5164       // specialization (because it has explicitly-specified template
5165       // arguments) but that was not introduced with a "template<>" (or had
5166       // too few of them).
5167       // FIXME: Differentiate between attempts for explicit instantiations
5168       // (starting with "template") and the rest.
5169       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5170           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5171           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5172                                         "template<> ");
5173       IsExplicitSpecialization = true;
5174       TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5175                                                      SourceLocation(), 0, 0,
5176                                                      SourceLocation());
5177     }
5178 
5179     if (TemplateParams) {
5180       if (!TemplateParams->size() &&
5181           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5182         // There is an extraneous 'template<>' for this variable. Complain
5183         // about it, but allow the declaration of the variable.
5184         Diag(TemplateParams->getTemplateLoc(),
5185              diag::err_template_variable_noparams)
5186           << II
5187           << SourceRange(TemplateParams->getTemplateLoc(),
5188                          TemplateParams->getRAngleLoc());
5189         TemplateParams = 0;
5190       } else {
5191         // Only C++1y supports variable templates (N3651).
5192         Diag(D.getIdentifierLoc(),
5193              getLangOpts().CPlusPlus1y
5194                  ? diag::warn_cxx11_compat_variable_template
5195                  : diag::ext_variable_template);
5196 
5197         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5198           // This is an explicit specialization or a partial specialization.
5199           // FIXME: Check that we can declare a specialization here.
5200           IsVariableTemplateSpecialization = true;
5201           IsPartialSpecialization = TemplateParams->size() > 0;
5202         } else { // if (TemplateParams->size() > 0)
5203           // This is a template declaration.
5204           IsVariableTemplate = true;
5205 
5206           // Check that we can declare a template here.
5207           if (CheckTemplateDeclScope(S, TemplateParams))
5208             return 0;
5209         }
5210       }
5211     }
5212 
5213     if (IsVariableTemplateSpecialization) {
5214       SourceLocation TemplateKWLoc =
5215           TemplateParamLists.size() > 0
5216               ? TemplateParamLists[0]->getTemplateLoc()
5217               : SourceLocation();
5218       DeclResult Res = ActOnVarTemplateSpecialization(
5219           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5220           IsPartialSpecialization);
5221       if (Res.isInvalid())
5222         return 0;
5223       NewVD = cast<VarDecl>(Res.get());
5224       AddToScope = false;
5225     } else
5226       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5227                               D.getIdentifierLoc(), II, R, TInfo, SC);
5228 
5229     // If this is supposed to be a variable template, create it as such.
5230     if (IsVariableTemplate) {
5231       NewTemplate =
5232           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5233                                   TemplateParams, NewVD);
5234       NewVD->setDescribedVarTemplate(NewTemplate);
5235     }
5236 
5237     // If this decl has an auto type in need of deduction, make a note of the
5238     // Decl so we can diagnose uses of it in its own initializer.
5239     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5240       ParsingInitForAutoVars.insert(NewVD);
5241 
5242     if (D.isInvalidType() || Invalid) {
5243       NewVD->setInvalidDecl();
5244       if (NewTemplate)
5245         NewTemplate->setInvalidDecl();
5246     }
5247 
5248     SetNestedNameSpecifier(NewVD, D);
5249 
5250     // If we have any template parameter lists that don't directly belong to
5251     // the variable (matching the scope specifier), store them.
5252     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5253     if (TemplateParamLists.size() > VDTemplateParamLists)
5254       NewVD->setTemplateParameterListsInfo(
5255           Context, TemplateParamLists.size() - VDTemplateParamLists,
5256           TemplateParamLists.data());
5257 
5258     if (D.getDeclSpec().isConstexprSpecified())
5259       NewVD->setConstexpr(true);
5260   }
5261 
5262   // Set the lexical context. If the declarator has a C++ scope specifier, the
5263   // lexical context will be different from the semantic context.
5264   NewVD->setLexicalDeclContext(CurContext);
5265   if (NewTemplate)
5266     NewTemplate->setLexicalDeclContext(CurContext);
5267 
5268   if (IsLocalExternDecl)
5269     NewVD->setLocalExternDecl();
5270 
5271   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5272     if (NewVD->hasLocalStorage()) {
5273       // C++11 [dcl.stc]p4:
5274       //   When thread_local is applied to a variable of block scope the
5275       //   storage-class-specifier static is implied if it does not appear
5276       //   explicitly.
5277       // Core issue: 'static' is not implied if the variable is declared
5278       //   'extern'.
5279       if (SCSpec == DeclSpec::SCS_unspecified &&
5280           TSCS == DeclSpec::TSCS_thread_local &&
5281           DC->isFunctionOrMethod())
5282         NewVD->setTSCSpec(TSCS);
5283       else
5284         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5285              diag::err_thread_non_global)
5286           << DeclSpec::getSpecifierName(TSCS);
5287     } else if (!Context.getTargetInfo().isTLSSupported())
5288       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5289            diag::err_thread_unsupported);
5290     else
5291       NewVD->setTSCSpec(TSCS);
5292   }
5293 
5294   // C99 6.7.4p3
5295   //   An inline definition of a function with external linkage shall
5296   //   not contain a definition of a modifiable object with static or
5297   //   thread storage duration...
5298   // We only apply this when the function is required to be defined
5299   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5300   // that a local variable with thread storage duration still has to
5301   // be marked 'static'.  Also note that it's possible to get these
5302   // semantics in C++ using __attribute__((gnu_inline)).
5303   if (SC == SC_Static && S->getFnParent() != 0 &&
5304       !NewVD->getType().isConstQualified()) {
5305     FunctionDecl *CurFD = getCurFunctionDecl();
5306     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5307       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5308            diag::warn_static_local_in_extern_inline);
5309       MaybeSuggestAddingStaticToDecl(CurFD);
5310     }
5311   }
5312 
5313   if (D.getDeclSpec().isModulePrivateSpecified()) {
5314     if (IsVariableTemplateSpecialization)
5315       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5316           << (IsPartialSpecialization ? 1 : 0)
5317           << FixItHint::CreateRemoval(
5318                  D.getDeclSpec().getModulePrivateSpecLoc());
5319     else if (IsExplicitSpecialization)
5320       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5321         << 2
5322         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5323     else if (NewVD->hasLocalStorage())
5324       Diag(NewVD->getLocation(), diag::err_module_private_local)
5325         << 0 << NewVD->getDeclName()
5326         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5327         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5328     else {
5329       NewVD->setModulePrivate();
5330       if (NewTemplate)
5331         NewTemplate->setModulePrivate();
5332     }
5333   }
5334 
5335   // Handle attributes prior to checking for duplicates in MergeVarDecl
5336   ProcessDeclAttributes(S, NewVD, D);
5337 
5338   if (NewVD->hasAttrs())
5339     CheckAlignasUnderalignment(NewVD);
5340 
5341   if (getLangOpts().CUDA) {
5342     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5343     // storage [duration]."
5344     if (SC == SC_None && S->getFnParent() != 0 &&
5345         (NewVD->hasAttr<CUDASharedAttr>() ||
5346          NewVD->hasAttr<CUDAConstantAttr>())) {
5347       NewVD->setStorageClass(SC_Static);
5348     }
5349   }
5350 
5351   // In auto-retain/release, infer strong retension for variables of
5352   // retainable type.
5353   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5354     NewVD->setInvalidDecl();
5355 
5356   // Handle GNU asm-label extension (encoded as an attribute).
5357   if (Expr *E = (Expr*)D.getAsmLabel()) {
5358     // The parser guarantees this is a string.
5359     StringLiteral *SE = cast<StringLiteral>(E);
5360     StringRef Label = SE->getString();
5361     if (S->getFnParent() != 0) {
5362       switch (SC) {
5363       case SC_None:
5364       case SC_Auto:
5365         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5366         break;
5367       case SC_Register:
5368         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5369           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5370         break;
5371       case SC_Static:
5372       case SC_Extern:
5373       case SC_PrivateExtern:
5374       case SC_OpenCLWorkGroupLocal:
5375         break;
5376       }
5377     }
5378 
5379     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5380                                                 Context, Label, 0));
5381   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5382     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5383       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5384     if (I != ExtnameUndeclaredIdentifiers.end()) {
5385       NewVD->addAttr(I->second);
5386       ExtnameUndeclaredIdentifiers.erase(I);
5387     }
5388   }
5389 
5390   // Diagnose shadowed variables before filtering for scope.
5391   if (D.getCXXScopeSpec().isEmpty())
5392     CheckShadow(S, NewVD, Previous);
5393 
5394   // Don't consider existing declarations that are in a different
5395   // scope and are out-of-semantic-context declarations (if the new
5396   // declaration has linkage).
5397   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5398                        D.getCXXScopeSpec().isNotEmpty() ||
5399                        IsExplicitSpecialization ||
5400                        IsVariableTemplateSpecialization);
5401 
5402   // Check whether the previous declaration is in the same block scope. This
5403   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5404   if (getLangOpts().CPlusPlus &&
5405       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5406     NewVD->setPreviousDeclInSameBlockScope(
5407         Previous.isSingleResult() && !Previous.isShadowed() &&
5408         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5409 
5410   if (!getLangOpts().CPlusPlus) {
5411     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5412   } else {
5413     // If this is an explicit specialization of a static data member, check it.
5414     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5415         CheckMemberSpecialization(NewVD, Previous))
5416       NewVD->setInvalidDecl();
5417 
5418     // Merge the decl with the existing one if appropriate.
5419     if (!Previous.empty()) {
5420       if (Previous.isSingleResult() &&
5421           isa<FieldDecl>(Previous.getFoundDecl()) &&
5422           D.getCXXScopeSpec().isSet()) {
5423         // The user tried to define a non-static data member
5424         // out-of-line (C++ [dcl.meaning]p1).
5425         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5426           << D.getCXXScopeSpec().getRange();
5427         Previous.clear();
5428         NewVD->setInvalidDecl();
5429       }
5430     } else if (D.getCXXScopeSpec().isSet()) {
5431       // No previous declaration in the qualifying scope.
5432       Diag(D.getIdentifierLoc(), diag::err_no_member)
5433         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5434         << D.getCXXScopeSpec().getRange();
5435       NewVD->setInvalidDecl();
5436     }
5437 
5438     if (!IsVariableTemplateSpecialization)
5439       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5440 
5441     if (NewTemplate) {
5442       VarTemplateDecl *PrevVarTemplate =
5443           NewVD->getPreviousDecl()
5444               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5445               : 0;
5446 
5447       // Check the template parameter list of this declaration, possibly
5448       // merging in the template parameter list from the previous variable
5449       // template declaration.
5450       if (CheckTemplateParameterList(
5451               TemplateParams,
5452               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5453                               : 0,
5454               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5455                DC->isDependentContext())
5456                   ? TPC_ClassTemplateMember
5457                   : TPC_VarTemplate))
5458         NewVD->setInvalidDecl();
5459 
5460       // If we are providing an explicit specialization of a static variable
5461       // template, make a note of that.
5462       if (PrevVarTemplate &&
5463           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5464         PrevVarTemplate->setMemberSpecialization();
5465     }
5466   }
5467 
5468   ProcessPragmaWeak(S, NewVD);
5469 
5470   // If this is the first declaration of an extern C variable, update
5471   // the map of such variables.
5472   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5473       isIncompleteDeclExternC(*this, NewVD))
5474     RegisterLocallyScopedExternCDecl(NewVD, S);
5475 
5476   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5477     Decl *ManglingContextDecl;
5478     if (MangleNumberingContext *MCtx =
5479             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5480                                           ManglingContextDecl)) {
5481       Context.setManglingNumber(
5482           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5483       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5484     }
5485   }
5486 
5487   if (NewTemplate) {
5488     if (NewVD->isInvalidDecl())
5489       NewTemplate->setInvalidDecl();
5490     ActOnDocumentableDecl(NewTemplate);
5491     return NewTemplate;
5492   }
5493 
5494   return NewVD;
5495 }
5496 
5497 /// \brief Diagnose variable or built-in function shadowing.  Implements
5498 /// -Wshadow.
5499 ///
5500 /// This method is called whenever a VarDecl is added to a "useful"
5501 /// scope.
5502 ///
5503 /// \param S the scope in which the shadowing name is being declared
5504 /// \param R the lookup of the name
5505 ///
5506 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5507   // Return if warning is ignored.
5508   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5509         DiagnosticsEngine::Ignored)
5510     return;
5511 
5512   // Don't diagnose declarations at file scope.
5513   if (D->hasGlobalStorage())
5514     return;
5515 
5516   DeclContext *NewDC = D->getDeclContext();
5517 
5518   // Only diagnose if we're shadowing an unambiguous field or variable.
5519   if (R.getResultKind() != LookupResult::Found)
5520     return;
5521 
5522   NamedDecl* ShadowedDecl = R.getFoundDecl();
5523   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5524     return;
5525 
5526   // Fields are not shadowed by variables in C++ static methods.
5527   if (isa<FieldDecl>(ShadowedDecl))
5528     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5529       if (MD->isStatic())
5530         return;
5531 
5532   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5533     if (shadowedVar->isExternC()) {
5534       // For shadowing external vars, make sure that we point to the global
5535       // declaration, not a locally scoped extern declaration.
5536       for (auto I : shadowedVar->redecls())
5537         if (I->isFileVarDecl()) {
5538           ShadowedDecl = I;
5539           break;
5540         }
5541     }
5542 
5543   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5544 
5545   // Only warn about certain kinds of shadowing for class members.
5546   if (NewDC && NewDC->isRecord()) {
5547     // In particular, don't warn about shadowing non-class members.
5548     if (!OldDC->isRecord())
5549       return;
5550 
5551     // TODO: should we warn about static data members shadowing
5552     // static data members from base classes?
5553 
5554     // TODO: don't diagnose for inaccessible shadowed members.
5555     // This is hard to do perfectly because we might friend the
5556     // shadowing context, but that's just a false negative.
5557   }
5558 
5559   // Determine what kind of declaration we're shadowing.
5560   unsigned Kind;
5561   if (isa<RecordDecl>(OldDC)) {
5562     if (isa<FieldDecl>(ShadowedDecl))
5563       Kind = 3; // field
5564     else
5565       Kind = 2; // static data member
5566   } else if (OldDC->isFileContext())
5567     Kind = 1; // global
5568   else
5569     Kind = 0; // local
5570 
5571   DeclarationName Name = R.getLookupName();
5572 
5573   // Emit warning and note.
5574   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5575     return;
5576   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5577   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5578 }
5579 
5580 /// \brief Check -Wshadow without the advantage of a previous lookup.
5581 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5582   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5583         DiagnosticsEngine::Ignored)
5584     return;
5585 
5586   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5587                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5588   LookupName(R, S);
5589   CheckShadow(S, D, R);
5590 }
5591 
5592 /// Check for conflict between this global or extern "C" declaration and
5593 /// previous global or extern "C" declarations. This is only used in C++.
5594 template<typename T>
5595 static bool checkGlobalOrExternCConflict(
5596     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5597   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5598   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5599 
5600   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5601     // The common case: this global doesn't conflict with any extern "C"
5602     // declaration.
5603     return false;
5604   }
5605 
5606   if (Prev) {
5607     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5608       // Both the old and new declarations have C language linkage. This is a
5609       // redeclaration.
5610       Previous.clear();
5611       Previous.addDecl(Prev);
5612       return true;
5613     }
5614 
5615     // This is a global, non-extern "C" declaration, and there is a previous
5616     // non-global extern "C" declaration. Diagnose if this is a variable
5617     // declaration.
5618     if (!isa<VarDecl>(ND))
5619       return false;
5620   } else {
5621     // The declaration is extern "C". Check for any declaration in the
5622     // translation unit which might conflict.
5623     if (IsGlobal) {
5624       // We have already performed the lookup into the translation unit.
5625       IsGlobal = false;
5626       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5627            I != E; ++I) {
5628         if (isa<VarDecl>(*I)) {
5629           Prev = *I;
5630           break;
5631         }
5632       }
5633     } else {
5634       DeclContext::lookup_result R =
5635           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5636       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5637            I != E; ++I) {
5638         if (isa<VarDecl>(*I)) {
5639           Prev = *I;
5640           break;
5641         }
5642         // FIXME: If we have any other entity with this name in global scope,
5643         // the declaration is ill-formed, but that is a defect: it breaks the
5644         // 'stat' hack, for instance. Only variables can have mangled name
5645         // clashes with extern "C" declarations, so only they deserve a
5646         // diagnostic.
5647       }
5648     }
5649 
5650     if (!Prev)
5651       return false;
5652   }
5653 
5654   // Use the first declaration's location to ensure we point at something which
5655   // is lexically inside an extern "C" linkage-spec.
5656   assert(Prev && "should have found a previous declaration to diagnose");
5657   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5658     Prev = FD->getFirstDecl();
5659   else
5660     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5661 
5662   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5663     << IsGlobal << ND;
5664   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5665     << IsGlobal;
5666   return false;
5667 }
5668 
5669 /// Apply special rules for handling extern "C" declarations. Returns \c true
5670 /// if we have found that this is a redeclaration of some prior entity.
5671 ///
5672 /// Per C++ [dcl.link]p6:
5673 ///   Two declarations [for a function or variable] with C language linkage
5674 ///   with the same name that appear in different scopes refer to the same
5675 ///   [entity]. An entity with C language linkage shall not be declared with
5676 ///   the same name as an entity in global scope.
5677 template<typename T>
5678 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5679                                                   LookupResult &Previous) {
5680   if (!S.getLangOpts().CPlusPlus) {
5681     // In C, when declaring a global variable, look for a corresponding 'extern'
5682     // variable declared in function scope. We don't need this in C++, because
5683     // we find local extern decls in the surrounding file-scope DeclContext.
5684     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5685       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5686         Previous.clear();
5687         Previous.addDecl(Prev);
5688         return true;
5689       }
5690     }
5691     return false;
5692   }
5693 
5694   // A declaration in the translation unit can conflict with an extern "C"
5695   // declaration.
5696   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5697     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5698 
5699   // An extern "C" declaration can conflict with a declaration in the
5700   // translation unit or can be a redeclaration of an extern "C" declaration
5701   // in another scope.
5702   if (isIncompleteDeclExternC(S,ND))
5703     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5704 
5705   // Neither global nor extern "C": nothing to do.
5706   return false;
5707 }
5708 
5709 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5710   // If the decl is already known invalid, don't check it.
5711   if (NewVD->isInvalidDecl())
5712     return;
5713 
5714   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5715   QualType T = TInfo->getType();
5716 
5717   // Defer checking an 'auto' type until its initializer is attached.
5718   if (T->isUndeducedType())
5719     return;
5720 
5721   if (T->isObjCObjectType()) {
5722     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5723       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5724     T = Context.getObjCObjectPointerType(T);
5725     NewVD->setType(T);
5726   }
5727 
5728   // Emit an error if an address space was applied to decl with local storage.
5729   // This includes arrays of objects with address space qualifiers, but not
5730   // automatic variables that point to other address spaces.
5731   // ISO/IEC TR 18037 S5.1.2
5732   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5733     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5734     NewVD->setInvalidDecl();
5735     return;
5736   }
5737 
5738   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5739   // __constant address space.
5740   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5741       && T.getAddressSpace() != LangAS::opencl_constant
5742       && !T->isSamplerT()){
5743     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5744     NewVD->setInvalidDecl();
5745     return;
5746   }
5747 
5748   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5749   // scope.
5750   if ((getLangOpts().OpenCLVersion >= 120)
5751       && NewVD->isStaticLocal()) {
5752     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5753     NewVD->setInvalidDecl();
5754     return;
5755   }
5756 
5757   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5758       && !NewVD->hasAttr<BlocksAttr>()) {
5759     if (getLangOpts().getGC() != LangOptions::NonGC)
5760       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5761     else {
5762       assert(!getLangOpts().ObjCAutoRefCount);
5763       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5764     }
5765   }
5766 
5767   bool isVM = T->isVariablyModifiedType();
5768   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5769       NewVD->hasAttr<BlocksAttr>())
5770     getCurFunction()->setHasBranchProtectedScope();
5771 
5772   if ((isVM && NewVD->hasLinkage()) ||
5773       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5774     bool SizeIsNegative;
5775     llvm::APSInt Oversized;
5776     TypeSourceInfo *FixedTInfo =
5777       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5778                                                     SizeIsNegative, Oversized);
5779     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5780       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5781       // FIXME: This won't give the correct result for
5782       // int a[10][n];
5783       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5784 
5785       if (NewVD->isFileVarDecl())
5786         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5787         << SizeRange;
5788       else if (NewVD->isStaticLocal())
5789         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5790         << SizeRange;
5791       else
5792         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5793         << SizeRange;
5794       NewVD->setInvalidDecl();
5795       return;
5796     }
5797 
5798     if (FixedTInfo == 0) {
5799       if (NewVD->isFileVarDecl())
5800         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5801       else
5802         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5803       NewVD->setInvalidDecl();
5804       return;
5805     }
5806 
5807     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5808     NewVD->setType(FixedTInfo->getType());
5809     NewVD->setTypeSourceInfo(FixedTInfo);
5810   }
5811 
5812   if (T->isVoidType()) {
5813     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5814     //                    of objects and functions.
5815     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5816       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5817         << T;
5818       NewVD->setInvalidDecl();
5819       return;
5820     }
5821   }
5822 
5823   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5824     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5825     NewVD->setInvalidDecl();
5826     return;
5827   }
5828 
5829   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5830     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5831     NewVD->setInvalidDecl();
5832     return;
5833   }
5834 
5835   if (NewVD->isConstexpr() && !T->isDependentType() &&
5836       RequireLiteralType(NewVD->getLocation(), T,
5837                          diag::err_constexpr_var_non_literal)) {
5838     // Can't perform this check until the type is deduced.
5839     NewVD->setInvalidDecl();
5840     return;
5841   }
5842 }
5843 
5844 /// \brief Perform semantic checking on a newly-created variable
5845 /// declaration.
5846 ///
5847 /// This routine performs all of the type-checking required for a
5848 /// variable declaration once it has been built. It is used both to
5849 /// check variables after they have been parsed and their declarators
5850 /// have been translated into a declaration, and to check variables
5851 /// that have been instantiated from a template.
5852 ///
5853 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5854 ///
5855 /// Returns true if the variable declaration is a redeclaration.
5856 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5857   CheckVariableDeclarationType(NewVD);
5858 
5859   // If the decl is already known invalid, don't check it.
5860   if (NewVD->isInvalidDecl())
5861     return false;
5862 
5863   // If we did not find anything by this name, look for a non-visible
5864   // extern "C" declaration with the same name.
5865   if (Previous.empty() &&
5866       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5867     Previous.setShadowed();
5868 
5869   // Filter out any non-conflicting previous declarations.
5870   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5871 
5872   if (!Previous.empty()) {
5873     MergeVarDecl(NewVD, Previous);
5874     return true;
5875   }
5876   return false;
5877 }
5878 
5879 /// \brief Data used with FindOverriddenMethod
5880 struct FindOverriddenMethodData {
5881   Sema *S;
5882   CXXMethodDecl *Method;
5883 };
5884 
5885 /// \brief Member lookup function that determines whether a given C++
5886 /// method overrides a method in a base class, to be used with
5887 /// CXXRecordDecl::lookupInBases().
5888 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5889                                  CXXBasePath &Path,
5890                                  void *UserData) {
5891   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5892 
5893   FindOverriddenMethodData *Data
5894     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5895 
5896   DeclarationName Name = Data->Method->getDeclName();
5897 
5898   // FIXME: Do we care about other names here too?
5899   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5900     // We really want to find the base class destructor here.
5901     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5902     CanQualType CT = Data->S->Context.getCanonicalType(T);
5903 
5904     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5905   }
5906 
5907   for (Path.Decls = BaseRecord->lookup(Name);
5908        !Path.Decls.empty();
5909        Path.Decls = Path.Decls.slice(1)) {
5910     NamedDecl *D = Path.Decls.front();
5911     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5912       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5913         return true;
5914     }
5915   }
5916 
5917   return false;
5918 }
5919 
5920 namespace {
5921   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5922 }
5923 /// \brief Report an error regarding overriding, along with any relevant
5924 /// overriden methods.
5925 ///
5926 /// \param DiagID the primary error to report.
5927 /// \param MD the overriding method.
5928 /// \param OEK which overrides to include as notes.
5929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5930                             OverrideErrorKind OEK = OEK_All) {
5931   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5932   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5933                                       E = MD->end_overridden_methods();
5934        I != E; ++I) {
5935     // This check (& the OEK parameter) could be replaced by a predicate, but
5936     // without lambdas that would be overkill. This is still nicer than writing
5937     // out the diag loop 3 times.
5938     if ((OEK == OEK_All) ||
5939         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5940         (OEK == OEK_Deleted && (*I)->isDeleted()))
5941       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5942   }
5943 }
5944 
5945 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5946 /// and if so, check that it's a valid override and remember it.
5947 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5948   // Look for virtual methods in base classes that this method might override.
5949   CXXBasePaths Paths;
5950   FindOverriddenMethodData Data;
5951   Data.Method = MD;
5952   Data.S = this;
5953   bool hasDeletedOverridenMethods = false;
5954   bool hasNonDeletedOverridenMethods = false;
5955   bool AddedAny = false;
5956   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5957     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5958          E = Paths.found_decls_end(); I != E; ++I) {
5959       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5960         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5961         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5962             !CheckOverridingFunctionAttributes(MD, OldMD) &&
5963             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5964             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5965           hasDeletedOverridenMethods |= OldMD->isDeleted();
5966           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5967           AddedAny = true;
5968         }
5969       }
5970     }
5971   }
5972 
5973   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5974     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5975   }
5976   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5977     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5978   }
5979 
5980   return AddedAny;
5981 }
5982 
5983 namespace {
5984   // Struct for holding all of the extra arguments needed by
5985   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5986   struct ActOnFDArgs {
5987     Scope *S;
5988     Declarator &D;
5989     MultiTemplateParamsArg TemplateParamLists;
5990     bool AddToScope;
5991   };
5992 }
5993 
5994 namespace {
5995 
5996 // Callback to only accept typo corrections that have a non-zero edit distance.
5997 // Also only accept corrections that have the same parent decl.
5998 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5999  public:
6000   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6001                             CXXRecordDecl *Parent)
6002       : Context(Context), OriginalFD(TypoFD),
6003         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
6004 
6005   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6006     if (candidate.getEditDistance() == 0)
6007       return false;
6008 
6009     SmallVector<unsigned, 1> MismatchedParams;
6010     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6011                                           CDeclEnd = candidate.end();
6012          CDecl != CDeclEnd; ++CDecl) {
6013       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6014 
6015       if (FD && !FD->hasBody() &&
6016           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6017         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6018           CXXRecordDecl *Parent = MD->getParent();
6019           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6020             return true;
6021         } else if (!ExpectedParent) {
6022           return true;
6023         }
6024       }
6025     }
6026 
6027     return false;
6028   }
6029 
6030  private:
6031   ASTContext &Context;
6032   FunctionDecl *OriginalFD;
6033   CXXRecordDecl *ExpectedParent;
6034 };
6035 
6036 }
6037 
6038 /// \brief Generate diagnostics for an invalid function redeclaration.
6039 ///
6040 /// This routine handles generating the diagnostic messages for an invalid
6041 /// function redeclaration, including finding possible similar declarations
6042 /// or performing typo correction if there are no previous declarations with
6043 /// the same name.
6044 ///
6045 /// Returns a NamedDecl iff typo correction was performed and substituting in
6046 /// the new declaration name does not cause new errors.
6047 static NamedDecl *DiagnoseInvalidRedeclaration(
6048     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6049     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6050   DeclarationName Name = NewFD->getDeclName();
6051   DeclContext *NewDC = NewFD->getDeclContext();
6052   SmallVector<unsigned, 1> MismatchedParams;
6053   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6054   TypoCorrection Correction;
6055   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6056   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6057                                    : diag::err_member_decl_does_not_match;
6058   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6059                     IsLocalFriend ? Sema::LookupLocalFriendName
6060                                   : Sema::LookupOrdinaryName,
6061                     Sema::ForRedeclaration);
6062 
6063   NewFD->setInvalidDecl();
6064   if (IsLocalFriend)
6065     SemaRef.LookupName(Prev, S);
6066   else
6067     SemaRef.LookupQualifiedName(Prev, NewDC);
6068   assert(!Prev.isAmbiguous() &&
6069          "Cannot have an ambiguity in previous-declaration lookup");
6070   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6071   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6072                                       MD ? MD->getParent() : 0);
6073   if (!Prev.empty()) {
6074     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6075          Func != FuncEnd; ++Func) {
6076       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6077       if (FD &&
6078           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6079         // Add 1 to the index so that 0 can mean the mismatch didn't
6080         // involve a parameter
6081         unsigned ParamNum =
6082             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6083         NearMatches.push_back(std::make_pair(FD, ParamNum));
6084       }
6085     }
6086   // If the qualified name lookup yielded nothing, try typo correction
6087   } else if ((Correction = SemaRef.CorrectTypo(
6088                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6089                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6090                  IsLocalFriend ? 0 : NewDC))) {
6091     // Set up everything for the call to ActOnFunctionDeclarator
6092     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6093                               ExtraArgs.D.getIdentifierLoc());
6094     Previous.clear();
6095     Previous.setLookupName(Correction.getCorrection());
6096     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6097                                     CDeclEnd = Correction.end();
6098          CDecl != CDeclEnd; ++CDecl) {
6099       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6100       if (FD && !FD->hasBody() &&
6101           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6102         Previous.addDecl(FD);
6103       }
6104     }
6105     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6106 
6107     NamedDecl *Result;
6108     // Retry building the function declaration with the new previous
6109     // declarations, and with errors suppressed.
6110     {
6111       // Trap errors.
6112       Sema::SFINAETrap Trap(SemaRef);
6113 
6114       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6115       // pieces need to verify the typo-corrected C++ declaration and hopefully
6116       // eliminate the need for the parameter pack ExtraArgs.
6117       Result = SemaRef.ActOnFunctionDeclarator(
6118           ExtraArgs.S, ExtraArgs.D,
6119           Correction.getCorrectionDecl()->getDeclContext(),
6120           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6121           ExtraArgs.AddToScope);
6122 
6123       if (Trap.hasErrorOccurred())
6124         Result = 0;
6125     }
6126 
6127     if (Result) {
6128       // Determine which correction we picked.
6129       Decl *Canonical = Result->getCanonicalDecl();
6130       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6131            I != E; ++I)
6132         if ((*I)->getCanonicalDecl() == Canonical)
6133           Correction.setCorrectionDecl(*I);
6134 
6135       SemaRef.diagnoseTypo(
6136           Correction,
6137           SemaRef.PDiag(IsLocalFriend
6138                           ? diag::err_no_matching_local_friend_suggest
6139                           : diag::err_member_decl_does_not_match_suggest)
6140             << Name << NewDC << IsDefinition);
6141       return Result;
6142     }
6143 
6144     // Pretend the typo correction never occurred
6145     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6146                               ExtraArgs.D.getIdentifierLoc());
6147     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6148     Previous.clear();
6149     Previous.setLookupName(Name);
6150   }
6151 
6152   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6153       << Name << NewDC << IsDefinition << NewFD->getLocation();
6154 
6155   bool NewFDisConst = false;
6156   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6157     NewFDisConst = NewMD->isConst();
6158 
6159   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6160        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6161        NearMatch != NearMatchEnd; ++NearMatch) {
6162     FunctionDecl *FD = NearMatch->first;
6163     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6164     bool FDisConst = MD && MD->isConst();
6165     bool IsMember = MD || !IsLocalFriend;
6166 
6167     // FIXME: These notes are poorly worded for the local friend case.
6168     if (unsigned Idx = NearMatch->second) {
6169       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6170       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6171       if (Loc.isInvalid()) Loc = FD->getLocation();
6172       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6173                                  : diag::note_local_decl_close_param_match)
6174         << Idx << FDParam->getType()
6175         << NewFD->getParamDecl(Idx - 1)->getType();
6176     } else if (FDisConst != NewFDisConst) {
6177       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6178           << NewFDisConst << FD->getSourceRange().getEnd();
6179     } else
6180       SemaRef.Diag(FD->getLocation(),
6181                    IsMember ? diag::note_member_def_close_match
6182                             : diag::note_local_decl_close_match);
6183   }
6184   return 0;
6185 }
6186 
6187 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6188                                                           Declarator &D) {
6189   switch (D.getDeclSpec().getStorageClassSpec()) {
6190   default: llvm_unreachable("Unknown storage class!");
6191   case DeclSpec::SCS_auto:
6192   case DeclSpec::SCS_register:
6193   case DeclSpec::SCS_mutable:
6194     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6195                  diag::err_typecheck_sclass_func);
6196     D.setInvalidType();
6197     break;
6198   case DeclSpec::SCS_unspecified: break;
6199   case DeclSpec::SCS_extern:
6200     if (D.getDeclSpec().isExternInLinkageSpec())
6201       return SC_None;
6202     return SC_Extern;
6203   case DeclSpec::SCS_static: {
6204     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6205       // C99 6.7.1p5:
6206       //   The declaration of an identifier for a function that has
6207       //   block scope shall have no explicit storage-class specifier
6208       //   other than extern
6209       // See also (C++ [dcl.stc]p4).
6210       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6211                    diag::err_static_block_func);
6212       break;
6213     } else
6214       return SC_Static;
6215   }
6216   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6217   }
6218 
6219   // No explicit storage class has already been returned
6220   return SC_None;
6221 }
6222 
6223 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6224                                            DeclContext *DC, QualType &R,
6225                                            TypeSourceInfo *TInfo,
6226                                            FunctionDecl::StorageClass SC,
6227                                            bool &IsVirtualOkay) {
6228   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6229   DeclarationName Name = NameInfo.getName();
6230 
6231   FunctionDecl *NewFD = 0;
6232   bool isInline = D.getDeclSpec().isInlineSpecified();
6233 
6234   if (!SemaRef.getLangOpts().CPlusPlus) {
6235     // Determine whether the function was written with a
6236     // prototype. This true when:
6237     //   - there is a prototype in the declarator, or
6238     //   - the type R of the function is some kind of typedef or other reference
6239     //     to a type name (which eventually refers to a function type).
6240     bool HasPrototype =
6241       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6242       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6243 
6244     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6245                                  D.getLocStart(), NameInfo, R,
6246                                  TInfo, SC, isInline,
6247                                  HasPrototype, false);
6248     if (D.isInvalidType())
6249       NewFD->setInvalidDecl();
6250 
6251     // Set the lexical context.
6252     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6253 
6254     return NewFD;
6255   }
6256 
6257   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6258   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6259 
6260   // Check that the return type is not an abstract class type.
6261   // For record types, this is done by the AbstractClassUsageDiagnoser once
6262   // the class has been completely parsed.
6263   if (!DC->isRecord() &&
6264       SemaRef.RequireNonAbstractType(
6265           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6266           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6267     D.setInvalidType();
6268 
6269   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6270     // This is a C++ constructor declaration.
6271     assert(DC->isRecord() &&
6272            "Constructors can only be declared in a member context");
6273 
6274     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6275     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6276                                       D.getLocStart(), NameInfo,
6277                                       R, TInfo, isExplicit, isInline,
6278                                       /*isImplicitlyDeclared=*/false,
6279                                       isConstexpr);
6280 
6281   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6282     // This is a C++ destructor declaration.
6283     if (DC->isRecord()) {
6284       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6285       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6286       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6287                                         SemaRef.Context, Record,
6288                                         D.getLocStart(),
6289                                         NameInfo, R, TInfo, isInline,
6290                                         /*isImplicitlyDeclared=*/false);
6291 
6292       // If the class is complete, then we now create the implicit exception
6293       // specification. If the class is incomplete or dependent, we can't do
6294       // it yet.
6295       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6296           Record->getDefinition() && !Record->isBeingDefined() &&
6297           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6298         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6299       }
6300 
6301       IsVirtualOkay = true;
6302       return NewDD;
6303 
6304     } else {
6305       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6306       D.setInvalidType();
6307 
6308       // Create a FunctionDecl to satisfy the function definition parsing
6309       // code path.
6310       return FunctionDecl::Create(SemaRef.Context, DC,
6311                                   D.getLocStart(),
6312                                   D.getIdentifierLoc(), Name, R, TInfo,
6313                                   SC, isInline,
6314                                   /*hasPrototype=*/true, isConstexpr);
6315     }
6316 
6317   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6318     if (!DC->isRecord()) {
6319       SemaRef.Diag(D.getIdentifierLoc(),
6320            diag::err_conv_function_not_member);
6321       return 0;
6322     }
6323 
6324     SemaRef.CheckConversionDeclarator(D, R, SC);
6325     IsVirtualOkay = true;
6326     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6327                                      D.getLocStart(), NameInfo,
6328                                      R, TInfo, isInline, isExplicit,
6329                                      isConstexpr, SourceLocation());
6330 
6331   } else if (DC->isRecord()) {
6332     // If the name of the function is the same as the name of the record,
6333     // then this must be an invalid constructor that has a return type.
6334     // (The parser checks for a return type and makes the declarator a
6335     // constructor if it has no return type).
6336     if (Name.getAsIdentifierInfo() &&
6337         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6338       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6339         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6340         << SourceRange(D.getIdentifierLoc());
6341       return 0;
6342     }
6343 
6344     // This is a C++ method declaration.
6345     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6346                                                cast<CXXRecordDecl>(DC),
6347                                                D.getLocStart(), NameInfo, R,
6348                                                TInfo, SC, isInline,
6349                                                isConstexpr, SourceLocation());
6350     IsVirtualOkay = !Ret->isStatic();
6351     return Ret;
6352   } else {
6353     // Determine whether the function was written with a
6354     // prototype. This true when:
6355     //   - we're in C++ (where every function has a prototype),
6356     return FunctionDecl::Create(SemaRef.Context, DC,
6357                                 D.getLocStart(),
6358                                 NameInfo, R, TInfo, SC, isInline,
6359                                 true/*HasPrototype*/, isConstexpr);
6360   }
6361 }
6362 
6363 enum OpenCLParamType {
6364   ValidKernelParam,
6365   PtrPtrKernelParam,
6366   PtrKernelParam,
6367   InvalidKernelParam,
6368   RecordKernelParam
6369 };
6370 
6371 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6372   if (PT->isPointerType()) {
6373     QualType PointeeType = PT->getPointeeType();
6374     return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6375   }
6376 
6377   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6378   // be used as builtin types.
6379 
6380   if (PT->isImageType())
6381     return PtrKernelParam;
6382 
6383   if (PT->isBooleanType())
6384     return InvalidKernelParam;
6385 
6386   if (PT->isEventT())
6387     return InvalidKernelParam;
6388 
6389   if (PT->isHalfType())
6390     return InvalidKernelParam;
6391 
6392   if (PT->isRecordType())
6393     return RecordKernelParam;
6394 
6395   return ValidKernelParam;
6396 }
6397 
6398 static void checkIsValidOpenCLKernelParameter(
6399   Sema &S,
6400   Declarator &D,
6401   ParmVarDecl *Param,
6402   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6403   QualType PT = Param->getType();
6404 
6405   // Cache the valid types we encounter to avoid rechecking structs that are
6406   // used again
6407   if (ValidTypes.count(PT.getTypePtr()))
6408     return;
6409 
6410   switch (getOpenCLKernelParameterType(PT)) {
6411   case PtrPtrKernelParam:
6412     // OpenCL v1.2 s6.9.a:
6413     // A kernel function argument cannot be declared as a
6414     // pointer to a pointer type.
6415     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6416     D.setInvalidType();
6417     return;
6418 
6419     // OpenCL v1.2 s6.9.k:
6420     // Arguments to kernel functions in a program cannot be declared with the
6421     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6422     // uintptr_t or a struct and/or union that contain fields declared to be
6423     // one of these built-in scalar types.
6424 
6425   case InvalidKernelParam:
6426     // OpenCL v1.2 s6.8 n:
6427     // A kernel function argument cannot be declared
6428     // of event_t type.
6429     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6430     D.setInvalidType();
6431     return;
6432 
6433   case PtrKernelParam:
6434   case ValidKernelParam:
6435     ValidTypes.insert(PT.getTypePtr());
6436     return;
6437 
6438   case RecordKernelParam:
6439     break;
6440   }
6441 
6442   // Track nested structs we will inspect
6443   SmallVector<const Decl *, 4> VisitStack;
6444 
6445   // Track where we are in the nested structs. Items will migrate from
6446   // VisitStack to HistoryStack as we do the DFS for bad field.
6447   SmallVector<const FieldDecl *, 4> HistoryStack;
6448   HistoryStack.push_back((const FieldDecl *) 0);
6449 
6450   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6451   VisitStack.push_back(PD);
6452 
6453   assert(VisitStack.back() && "First decl null?");
6454 
6455   do {
6456     const Decl *Next = VisitStack.pop_back_val();
6457     if (!Next) {
6458       assert(!HistoryStack.empty());
6459       // Found a marker, we have gone up a level
6460       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6461         ValidTypes.insert(Hist->getType().getTypePtr());
6462 
6463       continue;
6464     }
6465 
6466     // Adds everything except the original parameter declaration (which is not a
6467     // field itself) to the history stack.
6468     const RecordDecl *RD;
6469     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6470       HistoryStack.push_back(Field);
6471       RD = Field->getType()->castAs<RecordType>()->getDecl();
6472     } else {
6473       RD = cast<RecordDecl>(Next);
6474     }
6475 
6476     // Add a null marker so we know when we've gone back up a level
6477     VisitStack.push_back((const Decl *) 0);
6478 
6479     for (RecordDecl::field_iterator I = RD->field_begin(),
6480            E = RD->field_end(); I != E; ++I) {
6481       const FieldDecl *FD = *I;
6482       QualType QT = FD->getType();
6483 
6484       if (ValidTypes.count(QT.getTypePtr()))
6485         continue;
6486 
6487       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6488       if (ParamType == ValidKernelParam)
6489         continue;
6490 
6491       if (ParamType == RecordKernelParam) {
6492         VisitStack.push_back(FD);
6493         continue;
6494       }
6495 
6496       // OpenCL v1.2 s6.9.p:
6497       // Arguments to kernel functions that are declared to be a struct or union
6498       // do not allow OpenCL objects to be passed as elements of the struct or
6499       // union.
6500       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6501         S.Diag(Param->getLocation(),
6502                diag::err_record_with_pointers_kernel_param)
6503           << PT->isUnionType()
6504           << PT;
6505       } else {
6506         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6507       }
6508 
6509       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6510         << PD->getDeclName();
6511 
6512       // We have an error, now let's go back up through history and show where
6513       // the offending field came from
6514       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6515              E = HistoryStack.end(); I != E; ++I) {
6516         const FieldDecl *OuterField = *I;
6517         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6518           << OuterField->getType();
6519       }
6520 
6521       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6522         << QT->isPointerType()
6523         << QT;
6524       D.setInvalidType();
6525       return;
6526     }
6527   } while (!VisitStack.empty());
6528 }
6529 
6530 NamedDecl*
6531 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6532                               TypeSourceInfo *TInfo, LookupResult &Previous,
6533                               MultiTemplateParamsArg TemplateParamLists,
6534                               bool &AddToScope) {
6535   QualType R = TInfo->getType();
6536 
6537   assert(R.getTypePtr()->isFunctionType());
6538 
6539   // TODO: consider using NameInfo for diagnostic.
6540   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6541   DeclarationName Name = NameInfo.getName();
6542   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6543 
6544   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6545     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6546          diag::err_invalid_thread)
6547       << DeclSpec::getSpecifierName(TSCS);
6548 
6549   if (D.isFirstDeclarationOfMember())
6550     adjustMemberFunctionCC(R, D.isStaticMember());
6551 
6552   bool isFriend = false;
6553   FunctionTemplateDecl *FunctionTemplate = 0;
6554   bool isExplicitSpecialization = false;
6555   bool isFunctionTemplateSpecialization = false;
6556 
6557   bool isDependentClassScopeExplicitSpecialization = false;
6558   bool HasExplicitTemplateArgs = false;
6559   TemplateArgumentListInfo TemplateArgs;
6560 
6561   bool isVirtualOkay = false;
6562 
6563   DeclContext *OriginalDC = DC;
6564   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6565 
6566   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6567                                               isVirtualOkay);
6568   if (!NewFD) return 0;
6569 
6570   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6571     NewFD->setTopLevelDeclInObjCContainer();
6572 
6573   // Set the lexical context. If this is a function-scope declaration, or has a
6574   // C++ scope specifier, or is the object of a friend declaration, the lexical
6575   // context will be different from the semantic context.
6576   NewFD->setLexicalDeclContext(CurContext);
6577 
6578   if (IsLocalExternDecl)
6579     NewFD->setLocalExternDecl();
6580 
6581   if (getLangOpts().CPlusPlus) {
6582     bool isInline = D.getDeclSpec().isInlineSpecified();
6583     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6584     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6585     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6586     isFriend = D.getDeclSpec().isFriendSpecified();
6587     if (isFriend && !isInline && D.isFunctionDefinition()) {
6588       // C++ [class.friend]p5
6589       //   A function can be defined in a friend declaration of a
6590       //   class . . . . Such a function is implicitly inline.
6591       NewFD->setImplicitlyInline();
6592     }
6593 
6594     // If this is a method defined in an __interface, and is not a constructor
6595     // or an overloaded operator, then set the pure flag (isVirtual will already
6596     // return true).
6597     if (const CXXRecordDecl *Parent =
6598           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6599       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6600         NewFD->setPure(true);
6601     }
6602 
6603     SetNestedNameSpecifier(NewFD, D);
6604     isExplicitSpecialization = false;
6605     isFunctionTemplateSpecialization = false;
6606     if (D.isInvalidType())
6607       NewFD->setInvalidDecl();
6608 
6609     // Match up the template parameter lists with the scope specifier, then
6610     // determine whether we have a template or a template specialization.
6611     bool Invalid = false;
6612     if (TemplateParameterList *TemplateParams =
6613             MatchTemplateParametersToScopeSpecifier(
6614                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6615                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6616                 isExplicitSpecialization, Invalid)) {
6617       if (TemplateParams->size() > 0) {
6618         // This is a function template
6619 
6620         // Check that we can declare a template here.
6621         if (CheckTemplateDeclScope(S, TemplateParams))
6622           return 0;
6623 
6624         // A destructor cannot be a template.
6625         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6626           Diag(NewFD->getLocation(), diag::err_destructor_template);
6627           return 0;
6628         }
6629 
6630         // If we're adding a template to a dependent context, we may need to
6631         // rebuilding some of the types used within the template parameter list,
6632         // now that we know what the current instantiation is.
6633         if (DC->isDependentContext()) {
6634           ContextRAII SavedContext(*this, DC);
6635           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6636             Invalid = true;
6637         }
6638 
6639 
6640         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6641                                                         NewFD->getLocation(),
6642                                                         Name, TemplateParams,
6643                                                         NewFD);
6644         FunctionTemplate->setLexicalDeclContext(CurContext);
6645         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6646 
6647         // For source fidelity, store the other template param lists.
6648         if (TemplateParamLists.size() > 1) {
6649           NewFD->setTemplateParameterListsInfo(Context,
6650                                                TemplateParamLists.size() - 1,
6651                                                TemplateParamLists.data());
6652         }
6653       } else {
6654         // This is a function template specialization.
6655         isFunctionTemplateSpecialization = true;
6656         // For source fidelity, store all the template param lists.
6657         NewFD->setTemplateParameterListsInfo(Context,
6658                                              TemplateParamLists.size(),
6659                                              TemplateParamLists.data());
6660 
6661         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6662         if (isFriend) {
6663           // We want to remove the "template<>", found here.
6664           SourceRange RemoveRange = TemplateParams->getSourceRange();
6665 
6666           // If we remove the template<> and the name is not a
6667           // template-id, we're actually silently creating a problem:
6668           // the friend declaration will refer to an untemplated decl,
6669           // and clearly the user wants a template specialization.  So
6670           // we need to insert '<>' after the name.
6671           SourceLocation InsertLoc;
6672           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6673             InsertLoc = D.getName().getSourceRange().getEnd();
6674             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6675           }
6676 
6677           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6678             << Name << RemoveRange
6679             << FixItHint::CreateRemoval(RemoveRange)
6680             << FixItHint::CreateInsertion(InsertLoc, "<>");
6681         }
6682       }
6683     }
6684     else {
6685       // All template param lists were matched against the scope specifier:
6686       // this is NOT (an explicit specialization of) a template.
6687       if (TemplateParamLists.size() > 0)
6688         // For source fidelity, store all the template param lists.
6689         NewFD->setTemplateParameterListsInfo(Context,
6690                                              TemplateParamLists.size(),
6691                                              TemplateParamLists.data());
6692     }
6693 
6694     if (Invalid) {
6695       NewFD->setInvalidDecl();
6696       if (FunctionTemplate)
6697         FunctionTemplate->setInvalidDecl();
6698     }
6699 
6700     // C++ [dcl.fct.spec]p5:
6701     //   The virtual specifier shall only be used in declarations of
6702     //   nonstatic class member functions that appear within a
6703     //   member-specification of a class declaration; see 10.3.
6704     //
6705     if (isVirtual && !NewFD->isInvalidDecl()) {
6706       if (!isVirtualOkay) {
6707         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6708              diag::err_virtual_non_function);
6709       } else if (!CurContext->isRecord()) {
6710         // 'virtual' was specified outside of the class.
6711         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6712              diag::err_virtual_out_of_class)
6713           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6714       } else if (NewFD->getDescribedFunctionTemplate()) {
6715         // C++ [temp.mem]p3:
6716         //  A member function template shall not be virtual.
6717         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6718              diag::err_virtual_member_function_template)
6719           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6720       } else {
6721         // Okay: Add virtual to the method.
6722         NewFD->setVirtualAsWritten(true);
6723       }
6724 
6725       if (getLangOpts().CPlusPlus1y &&
6726           NewFD->getReturnType()->isUndeducedType())
6727         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6728     }
6729 
6730     if (getLangOpts().CPlusPlus1y &&
6731         (NewFD->isDependentContext() ||
6732          (isFriend && CurContext->isDependentContext())) &&
6733         NewFD->getReturnType()->isUndeducedType()) {
6734       // If the function template is referenced directly (for instance, as a
6735       // member of the current instantiation), pretend it has a dependent type.
6736       // This is not really justified by the standard, but is the only sane
6737       // thing to do.
6738       // FIXME: For a friend function, we have not marked the function as being
6739       // a friend yet, so 'isDependentContext' on the FD doesn't work.
6740       const FunctionProtoType *FPT =
6741           NewFD->getType()->castAs<FunctionProtoType>();
6742       QualType Result =
6743           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
6744       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
6745                                              FPT->getExtProtoInfo()));
6746     }
6747 
6748     // C++ [dcl.fct.spec]p3:
6749     //  The inline specifier shall not appear on a block scope function
6750     //  declaration.
6751     if (isInline && !NewFD->isInvalidDecl()) {
6752       if (CurContext->isFunctionOrMethod()) {
6753         // 'inline' is not allowed on block scope function declaration.
6754         Diag(D.getDeclSpec().getInlineSpecLoc(),
6755              diag::err_inline_declaration_block_scope) << Name
6756           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6757       }
6758     }
6759 
6760     // C++ [dcl.fct.spec]p6:
6761     //  The explicit specifier shall be used only in the declaration of a
6762     //  constructor or conversion function within its class definition;
6763     //  see 12.3.1 and 12.3.2.
6764     if (isExplicit && !NewFD->isInvalidDecl()) {
6765       if (!CurContext->isRecord()) {
6766         // 'explicit' was specified outside of the class.
6767         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6768              diag::err_explicit_out_of_class)
6769           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6770       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6771                  !isa<CXXConversionDecl>(NewFD)) {
6772         // 'explicit' was specified on a function that wasn't a constructor
6773         // or conversion function.
6774         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6775              diag::err_explicit_non_ctor_or_conv_function)
6776           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6777       }
6778     }
6779 
6780     if (isConstexpr) {
6781       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6782       // are implicitly inline.
6783       NewFD->setImplicitlyInline();
6784 
6785       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6786       // be either constructors or to return a literal type. Therefore,
6787       // destructors cannot be declared constexpr.
6788       if (isa<CXXDestructorDecl>(NewFD))
6789         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6790     }
6791 
6792     // If __module_private__ was specified, mark the function accordingly.
6793     if (D.getDeclSpec().isModulePrivateSpecified()) {
6794       if (isFunctionTemplateSpecialization) {
6795         SourceLocation ModulePrivateLoc
6796           = D.getDeclSpec().getModulePrivateSpecLoc();
6797         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6798           << 0
6799           << FixItHint::CreateRemoval(ModulePrivateLoc);
6800       } else {
6801         NewFD->setModulePrivate();
6802         if (FunctionTemplate)
6803           FunctionTemplate->setModulePrivate();
6804       }
6805     }
6806 
6807     if (isFriend) {
6808       if (FunctionTemplate) {
6809         FunctionTemplate->setObjectOfFriendDecl();
6810         FunctionTemplate->setAccess(AS_public);
6811       }
6812       NewFD->setObjectOfFriendDecl();
6813       NewFD->setAccess(AS_public);
6814     }
6815 
6816     // If a function is defined as defaulted or deleted, mark it as such now.
6817     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6818     // definition kind to FDK_Definition.
6819     switch (D.getFunctionDefinitionKind()) {
6820       case FDK_Declaration:
6821       case FDK_Definition:
6822         break;
6823 
6824       case FDK_Defaulted:
6825         NewFD->setDefaulted();
6826         break;
6827 
6828       case FDK_Deleted:
6829         NewFD->setDeletedAsWritten();
6830         break;
6831     }
6832 
6833     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6834         D.isFunctionDefinition()) {
6835       // C++ [class.mfct]p2:
6836       //   A member function may be defined (8.4) in its class definition, in
6837       //   which case it is an inline member function (7.1.2)
6838       NewFD->setImplicitlyInline();
6839     }
6840 
6841     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6842         !CurContext->isRecord()) {
6843       // C++ [class.static]p1:
6844       //   A data or function member of a class may be declared static
6845       //   in a class definition, in which case it is a static member of
6846       //   the class.
6847 
6848       // Complain about the 'static' specifier if it's on an out-of-line
6849       // member function definition.
6850       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6851            diag::err_static_out_of_line)
6852         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6853     }
6854 
6855     // C++11 [except.spec]p15:
6856     //   A deallocation function with no exception-specification is treated
6857     //   as if it were specified with noexcept(true).
6858     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6859     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6860          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6861         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6862       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6863       EPI.ExceptionSpecType = EST_BasicNoexcept;
6864       NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
6865                                              FPT->getParamTypes(), EPI));
6866     }
6867   }
6868 
6869   // Filter out previous declarations that don't match the scope.
6870   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6871                        D.getCXXScopeSpec().isNotEmpty() ||
6872                        isExplicitSpecialization ||
6873                        isFunctionTemplateSpecialization);
6874 
6875   // Handle GNU asm-label extension (encoded as an attribute).
6876   if (Expr *E = (Expr*) D.getAsmLabel()) {
6877     // The parser guarantees this is a string.
6878     StringLiteral *SE = cast<StringLiteral>(E);
6879     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6880                                                 SE->getString(), 0));
6881   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6882     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6883       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6884     if (I != ExtnameUndeclaredIdentifiers.end()) {
6885       NewFD->addAttr(I->second);
6886       ExtnameUndeclaredIdentifiers.erase(I);
6887     }
6888   }
6889 
6890   // Copy the parameter declarations from the declarator D to the function
6891   // declaration NewFD, if they are available.  First scavenge them into Params.
6892   SmallVector<ParmVarDecl*, 16> Params;
6893   if (D.isFunctionDeclarator()) {
6894     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6895 
6896     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6897     // function that takes no arguments, not a function that takes a
6898     // single void argument.
6899     // We let through "const void" here because Sema::GetTypeForDeclarator
6900     // already checks for that case.
6901     if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6902         FTI.Params[0].Param &&
6903         cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
6904       // Empty arg list, don't push any params.
6905     } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
6906       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6907         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6908         assert(Param->getDeclContext() != NewFD && "Was set before ?");
6909         Param->setDeclContext(NewFD);
6910         Params.push_back(Param);
6911 
6912         if (Param->isInvalidDecl())
6913           NewFD->setInvalidDecl();
6914       }
6915     }
6916 
6917   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6918     // When we're declaring a function with a typedef, typeof, etc as in the
6919     // following example, we'll need to synthesize (unnamed)
6920     // parameters for use in the declaration.
6921     //
6922     // @code
6923     // typedef void fn(int);
6924     // fn f;
6925     // @endcode
6926 
6927     // Synthesize a parameter for each argument type.
6928     for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
6929                                                 AE = FT->param_type_end();
6930          AI != AE; ++AI) {
6931       ParmVarDecl *Param =
6932         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6933       Param->setScopeInfo(0, Params.size());
6934       Params.push_back(Param);
6935     }
6936   } else {
6937     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6938            "Should not need args for typedef of non-prototype fn");
6939   }
6940 
6941   // Finally, we know we have the right number of parameters, install them.
6942   NewFD->setParams(Params);
6943 
6944   // Find all anonymous symbols defined during the declaration of this function
6945   // and add to NewFD. This lets us track decls such 'enum Y' in:
6946   //
6947   //   void f(enum Y {AA} x) {}
6948   //
6949   // which would otherwise incorrectly end up in the translation unit scope.
6950   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6951   DeclsInPrototypeScope.clear();
6952 
6953   if (D.getDeclSpec().isNoreturnSpecified())
6954     NewFD->addAttr(
6955         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6956                                        Context, 0));
6957 
6958   // Functions returning a variably modified type violate C99 6.7.5.2p2
6959   // because all functions have linkage.
6960   if (!NewFD->isInvalidDecl() &&
6961       NewFD->getReturnType()->isVariablyModifiedType()) {
6962     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6963     NewFD->setInvalidDecl();
6964   }
6965 
6966   // Handle attributes.
6967   ProcessDeclAttributes(S, NewFD, D);
6968 
6969   QualType RetType = NewFD->getReturnType();
6970   const CXXRecordDecl *Ret = RetType->isRecordType() ?
6971       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6972   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6973       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6974     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6975     // Attach WarnUnusedResult to functions returning types with that attribute.
6976     // Don't apply the attribute to that type's own non-static member functions
6977     // (to avoid warning on things like assignment operators)
6978     if (!MD || MD->getParent() != Ret)
6979       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
6980   }
6981 
6982   if (getLangOpts().OpenCL) {
6983     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6984     // type declaration will generate a compilation error.
6985     unsigned AddressSpace = RetType.getAddressSpace();
6986     if (AddressSpace == LangAS::opencl_local ||
6987         AddressSpace == LangAS::opencl_global ||
6988         AddressSpace == LangAS::opencl_constant) {
6989       Diag(NewFD->getLocation(),
6990            diag::err_opencl_return_value_with_address_space);
6991       NewFD->setInvalidDecl();
6992     }
6993   }
6994 
6995   if (!getLangOpts().CPlusPlus) {
6996     // Perform semantic checking on the function declaration.
6997     bool isExplicitSpecialization=false;
6998     if (!NewFD->isInvalidDecl() && NewFD->isMain())
6999       CheckMain(NewFD, D.getDeclSpec());
7000 
7001     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7002       CheckMSVCRTEntryPoint(NewFD);
7003 
7004     if (!NewFD->isInvalidDecl())
7005       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7006                                                   isExplicitSpecialization));
7007     else if (!Previous.empty())
7008       // Make graceful recovery from an invalid redeclaration.
7009       D.setRedeclaration(true);
7010     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7011             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7012            "previous declaration set still overloaded");
7013   } else {
7014     // C++11 [replacement.functions]p3:
7015     //  The program's definitions shall not be specified as inline.
7016     //
7017     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7018     //
7019     // Suppress the diagnostic if the function is __attribute__((used)), since
7020     // that forces an external definition to be emitted.
7021     if (D.getDeclSpec().isInlineSpecified() &&
7022         NewFD->isReplaceableGlobalAllocationFunction() &&
7023         !NewFD->hasAttr<UsedAttr>())
7024       Diag(D.getDeclSpec().getInlineSpecLoc(),
7025            diag::ext_operator_new_delete_declared_inline)
7026         << NewFD->getDeclName();
7027 
7028     // If the declarator is a template-id, translate the parser's template
7029     // argument list into our AST format.
7030     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7031       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7032       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7033       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7034       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7035                                          TemplateId->NumArgs);
7036       translateTemplateArguments(TemplateArgsPtr,
7037                                  TemplateArgs);
7038 
7039       HasExplicitTemplateArgs = true;
7040 
7041       if (NewFD->isInvalidDecl()) {
7042         HasExplicitTemplateArgs = false;
7043       } else if (FunctionTemplate) {
7044         // Function template with explicit template arguments.
7045         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7046           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7047 
7048         HasExplicitTemplateArgs = false;
7049       } else if (!isFunctionTemplateSpecialization &&
7050                  !D.getDeclSpec().isFriendSpecified()) {
7051         // We have encountered something that the user meant to be a
7052         // specialization (because it has explicitly-specified template
7053         // arguments) but that was not introduced with a "template<>" (or had
7054         // too few of them).
7055         // FIXME: Differentiate between attempts for explicit instantiations
7056         // (starting with "template") and the rest.
7057         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7058           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7059           << FixItHint::CreateInsertion(
7060                                     D.getDeclSpec().getLocStart(),
7061                                         "template<> ");
7062         isFunctionTemplateSpecialization = true;
7063       } else {
7064         // "friend void foo<>(int);" is an implicit specialization decl.
7065         isFunctionTemplateSpecialization = true;
7066       }
7067     } else if (isFriend && isFunctionTemplateSpecialization) {
7068       // This combination is only possible in a recovery case;  the user
7069       // wrote something like:
7070       //   template <> friend void foo(int);
7071       // which we're recovering from as if the user had written:
7072       //   friend void foo<>(int);
7073       // Go ahead and fake up a template id.
7074       HasExplicitTemplateArgs = true;
7075         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7076       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7077     }
7078 
7079     // If it's a friend (and only if it's a friend), it's possible
7080     // that either the specialized function type or the specialized
7081     // template is dependent, and therefore matching will fail.  In
7082     // this case, don't check the specialization yet.
7083     bool InstantiationDependent = false;
7084     if (isFunctionTemplateSpecialization && isFriend &&
7085         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7086          TemplateSpecializationType::anyDependentTemplateArguments(
7087             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7088             InstantiationDependent))) {
7089       assert(HasExplicitTemplateArgs &&
7090              "friend function specialization without template args");
7091       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7092                                                        Previous))
7093         NewFD->setInvalidDecl();
7094     } else if (isFunctionTemplateSpecialization) {
7095       if (CurContext->isDependentContext() && CurContext->isRecord()
7096           && !isFriend) {
7097         isDependentClassScopeExplicitSpecialization = true;
7098         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7099           diag::ext_function_specialization_in_class :
7100           diag::err_function_specialization_in_class)
7101           << NewFD->getDeclName();
7102       } else if (CheckFunctionTemplateSpecialization(NewFD,
7103                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7104                                                      Previous))
7105         NewFD->setInvalidDecl();
7106 
7107       // C++ [dcl.stc]p1:
7108       //   A storage-class-specifier shall not be specified in an explicit
7109       //   specialization (14.7.3)
7110       FunctionTemplateSpecializationInfo *Info =
7111           NewFD->getTemplateSpecializationInfo();
7112       if (Info && SC != SC_None) {
7113         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7114           Diag(NewFD->getLocation(),
7115                diag::err_explicit_specialization_inconsistent_storage_class)
7116             << SC
7117             << FixItHint::CreateRemoval(
7118                                       D.getDeclSpec().getStorageClassSpecLoc());
7119 
7120         else
7121           Diag(NewFD->getLocation(),
7122                diag::ext_explicit_specialization_storage_class)
7123             << FixItHint::CreateRemoval(
7124                                       D.getDeclSpec().getStorageClassSpecLoc());
7125       }
7126 
7127     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7128       if (CheckMemberSpecialization(NewFD, Previous))
7129           NewFD->setInvalidDecl();
7130     }
7131 
7132     // Perform semantic checking on the function declaration.
7133     if (!isDependentClassScopeExplicitSpecialization) {
7134       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7135         CheckMain(NewFD, D.getDeclSpec());
7136 
7137       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7138         CheckMSVCRTEntryPoint(NewFD);
7139 
7140       if (!NewFD->isInvalidDecl())
7141         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7142                                                     isExplicitSpecialization));
7143     }
7144 
7145     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7146             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7147            "previous declaration set still overloaded");
7148 
7149     NamedDecl *PrincipalDecl = (FunctionTemplate
7150                                 ? cast<NamedDecl>(FunctionTemplate)
7151                                 : NewFD);
7152 
7153     if (isFriend && D.isRedeclaration()) {
7154       AccessSpecifier Access = AS_public;
7155       if (!NewFD->isInvalidDecl())
7156         Access = NewFD->getPreviousDecl()->getAccess();
7157 
7158       NewFD->setAccess(Access);
7159       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7160     }
7161 
7162     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7163         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7164       PrincipalDecl->setNonMemberOperator();
7165 
7166     // If we have a function template, check the template parameter
7167     // list. This will check and merge default template arguments.
7168     if (FunctionTemplate) {
7169       FunctionTemplateDecl *PrevTemplate =
7170                                      FunctionTemplate->getPreviousDecl();
7171       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7172                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7173                             D.getDeclSpec().isFriendSpecified()
7174                               ? (D.isFunctionDefinition()
7175                                    ? TPC_FriendFunctionTemplateDefinition
7176                                    : TPC_FriendFunctionTemplate)
7177                               : (D.getCXXScopeSpec().isSet() &&
7178                                  DC && DC->isRecord() &&
7179                                  DC->isDependentContext())
7180                                   ? TPC_ClassTemplateMember
7181                                   : TPC_FunctionTemplate);
7182     }
7183 
7184     if (NewFD->isInvalidDecl()) {
7185       // Ignore all the rest of this.
7186     } else if (!D.isRedeclaration()) {
7187       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7188                                        AddToScope };
7189       // Fake up an access specifier if it's supposed to be a class member.
7190       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7191         NewFD->setAccess(AS_public);
7192 
7193       // Qualified decls generally require a previous declaration.
7194       if (D.getCXXScopeSpec().isSet()) {
7195         // ...with the major exception of templated-scope or
7196         // dependent-scope friend declarations.
7197 
7198         // TODO: we currently also suppress this check in dependent
7199         // contexts because (1) the parameter depth will be off when
7200         // matching friend templates and (2) we might actually be
7201         // selecting a friend based on a dependent factor.  But there
7202         // are situations where these conditions don't apply and we
7203         // can actually do this check immediately.
7204         if (isFriend &&
7205             (TemplateParamLists.size() ||
7206              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7207              CurContext->isDependentContext())) {
7208           // ignore these
7209         } else {
7210           // The user tried to provide an out-of-line definition for a
7211           // function that is a member of a class or namespace, but there
7212           // was no such member function declared (C++ [class.mfct]p2,
7213           // C++ [namespace.memdef]p2). For example:
7214           //
7215           // class X {
7216           //   void f() const;
7217           // };
7218           //
7219           // void X::f() { } // ill-formed
7220           //
7221           // Complain about this problem, and attempt to suggest close
7222           // matches (e.g., those that differ only in cv-qualifiers and
7223           // whether the parameter types are references).
7224 
7225           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7226                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7227             AddToScope = ExtraArgs.AddToScope;
7228             return Result;
7229           }
7230         }
7231 
7232         // Unqualified local friend declarations are required to resolve
7233         // to something.
7234       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7235         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7236                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7237           AddToScope = ExtraArgs.AddToScope;
7238           return Result;
7239         }
7240       }
7241 
7242     } else if (!D.isFunctionDefinition() &&
7243                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7244                !isFriend && !isFunctionTemplateSpecialization &&
7245                !isExplicitSpecialization) {
7246       // An out-of-line member function declaration must also be a
7247       // definition (C++ [class.mfct]p2).
7248       // Note that this is not the case for explicit specializations of
7249       // function templates or member functions of class templates, per
7250       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7251       // extension for compatibility with old SWIG code which likes to
7252       // generate them.
7253       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7254         << D.getCXXScopeSpec().getRange();
7255     }
7256   }
7257 
7258   ProcessPragmaWeak(S, NewFD);
7259   checkAttributesAfterMerging(*this, *NewFD);
7260 
7261   AddKnownFunctionAttributes(NewFD);
7262 
7263   if (NewFD->hasAttr<OverloadableAttr>() &&
7264       !NewFD->getType()->getAs<FunctionProtoType>()) {
7265     Diag(NewFD->getLocation(),
7266          diag::err_attribute_overloadable_no_prototype)
7267       << NewFD;
7268 
7269     // Turn this into a variadic function with no parameters.
7270     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7271     FunctionProtoType::ExtProtoInfo EPI(
7272         Context.getDefaultCallingConvention(true, false));
7273     EPI.Variadic = true;
7274     EPI.ExtInfo = FT->getExtInfo();
7275 
7276     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7277     NewFD->setType(R);
7278   }
7279 
7280   // If there's a #pragma GCC visibility in scope, and this isn't a class
7281   // member, set the visibility of this function.
7282   if (!DC->isRecord() && NewFD->isExternallyVisible())
7283     AddPushedVisibilityAttribute(NewFD);
7284 
7285   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7286   // marking the function.
7287   AddCFAuditedAttribute(NewFD);
7288 
7289   // If this is the first declaration of an extern C variable, update
7290   // the map of such variables.
7291   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7292       isIncompleteDeclExternC(*this, NewFD))
7293     RegisterLocallyScopedExternCDecl(NewFD, S);
7294 
7295   // Set this FunctionDecl's range up to the right paren.
7296   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7297 
7298   if (getLangOpts().CPlusPlus) {
7299     if (FunctionTemplate) {
7300       if (NewFD->isInvalidDecl())
7301         FunctionTemplate->setInvalidDecl();
7302       return FunctionTemplate;
7303     }
7304   }
7305 
7306   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7307     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7308     if ((getLangOpts().OpenCLVersion >= 120)
7309         && (SC == SC_Static)) {
7310       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7311       D.setInvalidType();
7312     }
7313 
7314     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7315     if (!NewFD->getReturnType()->isVoidType()) {
7316       Diag(D.getIdentifierLoc(),
7317            diag::err_expected_kernel_void_return_type);
7318       D.setInvalidType();
7319     }
7320 
7321     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7322     for (auto Param : NewFD->params())
7323       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7324   }
7325 
7326   MarkUnusedFileScopedDecl(NewFD);
7327 
7328   if (getLangOpts().CUDA)
7329     if (IdentifierInfo *II = NewFD->getIdentifier())
7330       if (!NewFD->isInvalidDecl() &&
7331           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7332         if (II->isStr("cudaConfigureCall")) {
7333           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7334             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7335 
7336           Context.setcudaConfigureCallDecl(NewFD);
7337         }
7338       }
7339 
7340   // Here we have an function template explicit specialization at class scope.
7341   // The actually specialization will be postponed to template instatiation
7342   // time via the ClassScopeFunctionSpecializationDecl node.
7343   if (isDependentClassScopeExplicitSpecialization) {
7344     ClassScopeFunctionSpecializationDecl *NewSpec =
7345                          ClassScopeFunctionSpecializationDecl::Create(
7346                                 Context, CurContext, SourceLocation(),
7347                                 cast<CXXMethodDecl>(NewFD),
7348                                 HasExplicitTemplateArgs, TemplateArgs);
7349     CurContext->addDecl(NewSpec);
7350     AddToScope = false;
7351   }
7352 
7353   return NewFD;
7354 }
7355 
7356 /// \brief Perform semantic checking of a new function declaration.
7357 ///
7358 /// Performs semantic analysis of the new function declaration
7359 /// NewFD. This routine performs all semantic checking that does not
7360 /// require the actual declarator involved in the declaration, and is
7361 /// used both for the declaration of functions as they are parsed
7362 /// (called via ActOnDeclarator) and for the declaration of functions
7363 /// that have been instantiated via C++ template instantiation (called
7364 /// via InstantiateDecl).
7365 ///
7366 /// \param IsExplicitSpecialization whether this new function declaration is
7367 /// an explicit specialization of the previous declaration.
7368 ///
7369 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7370 ///
7371 /// \returns true if the function declaration is a redeclaration.
7372 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7373                                     LookupResult &Previous,
7374                                     bool IsExplicitSpecialization) {
7375   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7376          "Variably modified return types are not handled here");
7377 
7378   // Determine whether the type of this function should be merged with
7379   // a previous visible declaration. This never happens for functions in C++,
7380   // and always happens in C if the previous declaration was visible.
7381   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7382                                !Previous.isShadowed();
7383 
7384   // Filter out any non-conflicting previous declarations.
7385   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7386 
7387   bool Redeclaration = false;
7388   NamedDecl *OldDecl = 0;
7389 
7390   // Merge or overload the declaration with an existing declaration of
7391   // the same name, if appropriate.
7392   if (!Previous.empty()) {
7393     // Determine whether NewFD is an overload of PrevDecl or
7394     // a declaration that requires merging. If it's an overload,
7395     // there's no more work to do here; we'll just add the new
7396     // function to the scope.
7397     if (!AllowOverloadingOfFunction(Previous, Context)) {
7398       NamedDecl *Candidate = Previous.getFoundDecl();
7399       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7400         Redeclaration = true;
7401         OldDecl = Candidate;
7402       }
7403     } else {
7404       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7405                             /*NewIsUsingDecl*/ false)) {
7406       case Ovl_Match:
7407         Redeclaration = true;
7408         break;
7409 
7410       case Ovl_NonFunction:
7411         Redeclaration = true;
7412         break;
7413 
7414       case Ovl_Overload:
7415         Redeclaration = false;
7416         break;
7417       }
7418 
7419       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7420         // If a function name is overloadable in C, then every function
7421         // with that name must be marked "overloadable".
7422         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7423           << Redeclaration << NewFD;
7424         NamedDecl *OverloadedDecl = 0;
7425         if (Redeclaration)
7426           OverloadedDecl = OldDecl;
7427         else if (!Previous.empty())
7428           OverloadedDecl = Previous.getRepresentativeDecl();
7429         if (OverloadedDecl)
7430           Diag(OverloadedDecl->getLocation(),
7431                diag::note_attribute_overloadable_prev_overload);
7432         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7433       }
7434     }
7435   }
7436 
7437   // Check for a previous extern "C" declaration with this name.
7438   if (!Redeclaration &&
7439       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7440     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7441     if (!Previous.empty()) {
7442       // This is an extern "C" declaration with the same name as a previous
7443       // declaration, and thus redeclares that entity...
7444       Redeclaration = true;
7445       OldDecl = Previous.getFoundDecl();
7446       MergeTypeWithPrevious = false;
7447 
7448       // ... except in the presence of __attribute__((overloadable)).
7449       if (OldDecl->hasAttr<OverloadableAttr>()) {
7450         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7451           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7452             << Redeclaration << NewFD;
7453           Diag(Previous.getFoundDecl()->getLocation(),
7454                diag::note_attribute_overloadable_prev_overload);
7455           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7456         }
7457         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7458           Redeclaration = false;
7459           OldDecl = 0;
7460         }
7461       }
7462     }
7463   }
7464 
7465   // C++11 [dcl.constexpr]p8:
7466   //   A constexpr specifier for a non-static member function that is not
7467   //   a constructor declares that member function to be const.
7468   //
7469   // This needs to be delayed until we know whether this is an out-of-line
7470   // definition of a static member function.
7471   //
7472   // This rule is not present in C++1y, so we produce a backwards
7473   // compatibility warning whenever it happens in C++11.
7474   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7475   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7476       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7477       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7478     CXXMethodDecl *OldMD = 0;
7479     if (OldDecl)
7480       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7481     if (!OldMD || !OldMD->isStatic()) {
7482       const FunctionProtoType *FPT =
7483         MD->getType()->castAs<FunctionProtoType>();
7484       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7485       EPI.TypeQuals |= Qualifiers::Const;
7486       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7487                                           FPT->getParamTypes(), EPI));
7488 
7489       // Warn that we did this, if we're not performing template instantiation.
7490       // In that case, we'll have warned already when the template was defined.
7491       if (ActiveTemplateInstantiations.empty()) {
7492         SourceLocation AddConstLoc;
7493         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7494                 .IgnoreParens().getAs<FunctionTypeLoc>())
7495           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7496 
7497         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7498           << FixItHint::CreateInsertion(AddConstLoc, " const");
7499       }
7500     }
7501   }
7502 
7503   if (Redeclaration) {
7504     // NewFD and OldDecl represent declarations that need to be
7505     // merged.
7506     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7507       NewFD->setInvalidDecl();
7508       return Redeclaration;
7509     }
7510 
7511     Previous.clear();
7512     Previous.addDecl(OldDecl);
7513 
7514     if (FunctionTemplateDecl *OldTemplateDecl
7515                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7516       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7517       FunctionTemplateDecl *NewTemplateDecl
7518         = NewFD->getDescribedFunctionTemplate();
7519       assert(NewTemplateDecl && "Template/non-template mismatch");
7520       if (CXXMethodDecl *Method
7521             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7522         Method->setAccess(OldTemplateDecl->getAccess());
7523         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7524       }
7525 
7526       // If this is an explicit specialization of a member that is a function
7527       // template, mark it as a member specialization.
7528       if (IsExplicitSpecialization &&
7529           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7530         NewTemplateDecl->setMemberSpecialization();
7531         assert(OldTemplateDecl->isMemberSpecialization());
7532       }
7533 
7534     } else {
7535       // This needs to happen first so that 'inline' propagates.
7536       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7537 
7538       if (isa<CXXMethodDecl>(NewFD)) {
7539         // A valid redeclaration of a C++ method must be out-of-line,
7540         // but (unfortunately) it's not necessarily a definition
7541         // because of templates, which means that the previous
7542         // declaration is not necessarily from the class definition.
7543 
7544         // For just setting the access, that doesn't matter.
7545         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7546         NewFD->setAccess(oldMethod->getAccess());
7547 
7548         // Update the key-function state if necessary for this ABI.
7549         if (NewFD->isInlined() &&
7550             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7551           // setNonKeyFunction needs to work with the original
7552           // declaration from the class definition, and isVirtual() is
7553           // just faster in that case, so map back to that now.
7554           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7555           if (oldMethod->isVirtual()) {
7556             Context.setNonKeyFunction(oldMethod);
7557           }
7558         }
7559       }
7560     }
7561   }
7562 
7563   // Semantic checking for this function declaration (in isolation).
7564   if (getLangOpts().CPlusPlus) {
7565     // C++-specific checks.
7566     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7567       CheckConstructor(Constructor);
7568     } else if (CXXDestructorDecl *Destructor =
7569                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7570       CXXRecordDecl *Record = Destructor->getParent();
7571       QualType ClassType = Context.getTypeDeclType(Record);
7572 
7573       // FIXME: Shouldn't we be able to perform this check even when the class
7574       // type is dependent? Both gcc and edg can handle that.
7575       if (!ClassType->isDependentType()) {
7576         DeclarationName Name
7577           = Context.DeclarationNames.getCXXDestructorName(
7578                                         Context.getCanonicalType(ClassType));
7579         if (NewFD->getDeclName() != Name) {
7580           Diag(NewFD->getLocation(), diag::err_destructor_name);
7581           NewFD->setInvalidDecl();
7582           return Redeclaration;
7583         }
7584       }
7585     } else if (CXXConversionDecl *Conversion
7586                = dyn_cast<CXXConversionDecl>(NewFD)) {
7587       ActOnConversionDeclarator(Conversion);
7588     }
7589 
7590     // Find any virtual functions that this function overrides.
7591     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7592       if (!Method->isFunctionTemplateSpecialization() &&
7593           !Method->getDescribedFunctionTemplate() &&
7594           Method->isCanonicalDecl()) {
7595         if (AddOverriddenMethods(Method->getParent(), Method)) {
7596           // If the function was marked as "static", we have a problem.
7597           if (NewFD->getStorageClass() == SC_Static) {
7598             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7599           }
7600         }
7601       }
7602 
7603       if (Method->isStatic())
7604         checkThisInStaticMemberFunctionType(Method);
7605     }
7606 
7607     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7608     if (NewFD->isOverloadedOperator() &&
7609         CheckOverloadedOperatorDeclaration(NewFD)) {
7610       NewFD->setInvalidDecl();
7611       return Redeclaration;
7612     }
7613 
7614     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7615     if (NewFD->getLiteralIdentifier() &&
7616         CheckLiteralOperatorDeclaration(NewFD)) {
7617       NewFD->setInvalidDecl();
7618       return Redeclaration;
7619     }
7620 
7621     // In C++, check default arguments now that we have merged decls. Unless
7622     // the lexical context is the class, because in this case this is done
7623     // during delayed parsing anyway.
7624     if (!CurContext->isRecord())
7625       CheckCXXDefaultArguments(NewFD);
7626 
7627     // If this function declares a builtin function, check the type of this
7628     // declaration against the expected type for the builtin.
7629     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7630       ASTContext::GetBuiltinTypeError Error;
7631       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7632       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7633       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7634         // The type of this function differs from the type of the builtin,
7635         // so forget about the builtin entirely.
7636         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7637       }
7638     }
7639 
7640     // If this function is declared as being extern "C", then check to see if
7641     // the function returns a UDT (class, struct, or union type) that is not C
7642     // compatible, and if it does, warn the user.
7643     // But, issue any diagnostic on the first declaration only.
7644     if (NewFD->isExternC() && Previous.empty()) {
7645       QualType R = NewFD->getReturnType();
7646       if (R->isIncompleteType() && !R->isVoidType())
7647         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7648             << NewFD << R;
7649       else if (!R.isPODType(Context) && !R->isVoidType() &&
7650                !R->isObjCObjectPointerType())
7651         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7652     }
7653   }
7654   return Redeclaration;
7655 }
7656 
7657 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7658   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7659   if (!TSI)
7660     return SourceRange();
7661 
7662   TypeLoc TL = TSI->getTypeLoc();
7663   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7664   if (!FunctionTL)
7665     return SourceRange();
7666 
7667   TypeLoc ResultTL = FunctionTL.getReturnLoc();
7668   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7669     return ResultTL.getSourceRange();
7670 
7671   return SourceRange();
7672 }
7673 
7674 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7675   // C++11 [basic.start.main]p3:
7676   //   A program that [...] declares main to be inline, static or
7677   //   constexpr is ill-formed.
7678   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7679   //   appear in a declaration of main.
7680   // static main is not an error under C99, but we should warn about it.
7681   // We accept _Noreturn main as an extension.
7682   if (FD->getStorageClass() == SC_Static)
7683     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7684          ? diag::err_static_main : diag::warn_static_main)
7685       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7686   if (FD->isInlineSpecified())
7687     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7688       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7689   if (DS.isNoreturnSpecified()) {
7690     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7691     SourceRange NoreturnRange(NoreturnLoc,
7692                               PP.getLocForEndOfToken(NoreturnLoc));
7693     Diag(NoreturnLoc, diag::ext_noreturn_main);
7694     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7695       << FixItHint::CreateRemoval(NoreturnRange);
7696   }
7697   if (FD->isConstexpr()) {
7698     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7699       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7700     FD->setConstexpr(false);
7701   }
7702 
7703   if (getLangOpts().OpenCL) {
7704     Diag(FD->getLocation(), diag::err_opencl_no_main)
7705         << FD->hasAttr<OpenCLKernelAttr>();
7706     FD->setInvalidDecl();
7707     return;
7708   }
7709 
7710   QualType T = FD->getType();
7711   assert(T->isFunctionType() && "function decl is not of function type");
7712   const FunctionType* FT = T->castAs<FunctionType>();
7713 
7714   // All the standards say that main() should should return 'int'.
7715   if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
7716     // In C and C++, main magically returns 0 if you fall off the end;
7717     // set the flag which tells us that.
7718     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7719     FD->setHasImplicitReturnZero(true);
7720 
7721   // In C with GNU extensions we allow main() to have non-integer return
7722   // type, but we should warn about the extension, and we disable the
7723   // implicit-return-zero rule.
7724   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7725     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7726 
7727     SourceRange ResultRange = getResultSourceRange(FD);
7728     if (ResultRange.isValid())
7729       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7730           << FixItHint::CreateReplacement(ResultRange, "int");
7731 
7732   // Otherwise, this is just a flat-out error.
7733   } else {
7734     SourceRange ResultRange = getResultSourceRange(FD);
7735     if (ResultRange.isValid())
7736       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7737           << FixItHint::CreateReplacement(ResultRange, "int");
7738     else
7739       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7740 
7741     FD->setInvalidDecl(true);
7742   }
7743 
7744   // Treat protoless main() as nullary.
7745   if (isa<FunctionNoProtoType>(FT)) return;
7746 
7747   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7748   unsigned nparams = FTP->getNumParams();
7749   assert(FD->getNumParams() == nparams);
7750 
7751   bool HasExtraParameters = (nparams > 3);
7752 
7753   // Darwin passes an undocumented fourth argument of type char**.  If
7754   // other platforms start sprouting these, the logic below will start
7755   // getting shifty.
7756   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7757     HasExtraParameters = false;
7758 
7759   if (HasExtraParameters) {
7760     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7761     FD->setInvalidDecl(true);
7762     nparams = 3;
7763   }
7764 
7765   // FIXME: a lot of the following diagnostics would be improved
7766   // if we had some location information about types.
7767 
7768   QualType CharPP =
7769     Context.getPointerType(Context.getPointerType(Context.CharTy));
7770   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7771 
7772   for (unsigned i = 0; i < nparams; ++i) {
7773     QualType AT = FTP->getParamType(i);
7774 
7775     bool mismatch = true;
7776 
7777     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7778       mismatch = false;
7779     else if (Expected[i] == CharPP) {
7780       // As an extension, the following forms are okay:
7781       //   char const **
7782       //   char const * const *
7783       //   char * const *
7784 
7785       QualifierCollector qs;
7786       const PointerType* PT;
7787       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7788           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7789           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7790                               Context.CharTy)) {
7791         qs.removeConst();
7792         mismatch = !qs.empty();
7793       }
7794     }
7795 
7796     if (mismatch) {
7797       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7798       // TODO: suggest replacing given type with expected type
7799       FD->setInvalidDecl(true);
7800     }
7801   }
7802 
7803   if (nparams == 1 && !FD->isInvalidDecl()) {
7804     Diag(FD->getLocation(), diag::warn_main_one_arg);
7805   }
7806 
7807   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7808     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7809     FD->setInvalidDecl();
7810   }
7811 }
7812 
7813 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7814   QualType T = FD->getType();
7815   assert(T->isFunctionType() && "function decl is not of function type");
7816   const FunctionType *FT = T->castAs<FunctionType>();
7817 
7818   // Set an implicit return of 'zero' if the function can return some integral,
7819   // enumeration, pointer or nullptr type.
7820   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7821       FT->getReturnType()->isAnyPointerType() ||
7822       FT->getReturnType()->isNullPtrType())
7823     // DllMain is exempt because a return value of zero means it failed.
7824     if (FD->getName() != "DllMain")
7825       FD->setHasImplicitReturnZero(true);
7826 
7827   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7828     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7829     FD->setInvalidDecl();
7830   }
7831 }
7832 
7833 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7834   // FIXME: Need strict checking.  In C89, we need to check for
7835   // any assignment, increment, decrement, function-calls, or
7836   // commas outside of a sizeof.  In C99, it's the same list,
7837   // except that the aforementioned are allowed in unevaluated
7838   // expressions.  Everything else falls under the
7839   // "may accept other forms of constant expressions" exception.
7840   // (We never end up here for C++, so the constant expression
7841   // rules there don't matter.)
7842   if (Init->isConstantInitializer(Context, false))
7843     return false;
7844   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7845     << Init->getSourceRange();
7846   return true;
7847 }
7848 
7849 namespace {
7850   // Visits an initialization expression to see if OrigDecl is evaluated in
7851   // its own initialization and throws a warning if it does.
7852   class SelfReferenceChecker
7853       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7854     Sema &S;
7855     Decl *OrigDecl;
7856     bool isRecordType;
7857     bool isPODType;
7858     bool isReferenceType;
7859 
7860   public:
7861     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7862 
7863     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7864                                                     S(S), OrigDecl(OrigDecl) {
7865       isPODType = false;
7866       isRecordType = false;
7867       isReferenceType = false;
7868       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7869         isPODType = VD->getType().isPODType(S.Context);
7870         isRecordType = VD->getType()->isRecordType();
7871         isReferenceType = VD->getType()->isReferenceType();
7872       }
7873     }
7874 
7875     // For most expressions, the cast is directly above the DeclRefExpr.
7876     // For conditional operators, the cast can be outside the conditional
7877     // operator if both expressions are DeclRefExpr's.
7878     void HandleValue(Expr *E) {
7879       if (isReferenceType)
7880         return;
7881       E = E->IgnoreParenImpCasts();
7882       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7883         HandleDeclRefExpr(DRE);
7884         return;
7885       }
7886 
7887       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7888         HandleValue(CO->getTrueExpr());
7889         HandleValue(CO->getFalseExpr());
7890         return;
7891       }
7892 
7893       if (isa<MemberExpr>(E)) {
7894         Expr *Base = E->IgnoreParenImpCasts();
7895         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7896           // Check for static member variables and don't warn on them.
7897           if (!isa<FieldDecl>(ME->getMemberDecl()))
7898             return;
7899           Base = ME->getBase()->IgnoreParenImpCasts();
7900         }
7901         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7902           HandleDeclRefExpr(DRE);
7903         return;
7904       }
7905     }
7906 
7907     // Reference types are handled here since all uses of references are
7908     // bad, not just r-value uses.
7909     void VisitDeclRefExpr(DeclRefExpr *E) {
7910       if (isReferenceType)
7911         HandleDeclRefExpr(E);
7912     }
7913 
7914     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7915       if (E->getCastKind() == CK_LValueToRValue ||
7916           (isRecordType && E->getCastKind() == CK_NoOp))
7917         HandleValue(E->getSubExpr());
7918 
7919       Inherited::VisitImplicitCastExpr(E);
7920     }
7921 
7922     void VisitMemberExpr(MemberExpr *E) {
7923       // Don't warn on arrays since they can be treated as pointers.
7924       if (E->getType()->canDecayToPointerType()) return;
7925 
7926       // Warn when a non-static method call is followed by non-static member
7927       // field accesses, which is followed by a DeclRefExpr.
7928       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7929       bool Warn = (MD && !MD->isStatic());
7930       Expr *Base = E->getBase()->IgnoreParenImpCasts();
7931       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7932         if (!isa<FieldDecl>(ME->getMemberDecl()))
7933           Warn = false;
7934         Base = ME->getBase()->IgnoreParenImpCasts();
7935       }
7936 
7937       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7938         if (Warn)
7939           HandleDeclRefExpr(DRE);
7940         return;
7941       }
7942 
7943       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7944       // Visit that expression.
7945       Visit(Base);
7946     }
7947 
7948     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7949       if (E->getNumArgs() > 0)
7950         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7951           HandleDeclRefExpr(DRE);
7952 
7953       Inherited::VisitCXXOperatorCallExpr(E);
7954     }
7955 
7956     void VisitUnaryOperator(UnaryOperator *E) {
7957       // For POD record types, addresses of its own members are well-defined.
7958       if (E->getOpcode() == UO_AddrOf && isRecordType &&
7959           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7960         if (!isPODType)
7961           HandleValue(E->getSubExpr());
7962         return;
7963       }
7964       Inherited::VisitUnaryOperator(E);
7965     }
7966 
7967     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7968 
7969     void HandleDeclRefExpr(DeclRefExpr *DRE) {
7970       Decl* ReferenceDecl = DRE->getDecl();
7971       if (OrigDecl != ReferenceDecl) return;
7972       unsigned diag;
7973       if (isReferenceType) {
7974         diag = diag::warn_uninit_self_reference_in_reference_init;
7975       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7976         diag = diag::warn_static_self_reference_in_init;
7977       } else {
7978         diag = diag::warn_uninit_self_reference_in_init;
7979       }
7980 
7981       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7982                             S.PDiag(diag)
7983                               << DRE->getNameInfo().getName()
7984                               << OrigDecl->getLocation()
7985                               << DRE->getSourceRange());
7986     }
7987   };
7988 
7989   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7990   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7991                                  bool DirectInit) {
7992     // Parameters arguments are occassionially constructed with itself,
7993     // for instance, in recursive functions.  Skip them.
7994     if (isa<ParmVarDecl>(OrigDecl))
7995       return;
7996 
7997     E = E->IgnoreParens();
7998 
7999     // Skip checking T a = a where T is not a record or reference type.
8000     // Doing so is a way to silence uninitialized warnings.
8001     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8002       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8003         if (ICE->getCastKind() == CK_LValueToRValue)
8004           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8005             if (DRE->getDecl() == OrigDecl)
8006               return;
8007 
8008     SelfReferenceChecker(S, OrigDecl).Visit(E);
8009   }
8010 }
8011 
8012 /// AddInitializerToDecl - Adds the initializer Init to the
8013 /// declaration dcl. If DirectInit is true, this is C++ direct
8014 /// initialization rather than copy initialization.
8015 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8016                                 bool DirectInit, bool TypeMayContainAuto) {
8017   // If there is no declaration, there was an error parsing it.  Just ignore
8018   // the initializer.
8019   if (RealDecl == 0 || RealDecl->isInvalidDecl())
8020     return;
8021 
8022   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8023     // With declarators parsed the way they are, the parser cannot
8024     // distinguish between a normal initializer and a pure-specifier.
8025     // Thus this grotesque test.
8026     IntegerLiteral *IL;
8027     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8028         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8029       CheckPureMethod(Method, Init->getSourceRange());
8030     else {
8031       Diag(Method->getLocation(), diag::err_member_function_initialization)
8032         << Method->getDeclName() << Init->getSourceRange();
8033       Method->setInvalidDecl();
8034     }
8035     return;
8036   }
8037 
8038   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8039   if (!VDecl) {
8040     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8041     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8042     RealDecl->setInvalidDecl();
8043     return;
8044   }
8045   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8046 
8047   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8048   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8049     Expr *DeduceInit = Init;
8050     // Initializer could be a C++ direct-initializer. Deduction only works if it
8051     // contains exactly one expression.
8052     if (CXXDirectInit) {
8053       if (CXXDirectInit->getNumExprs() == 0) {
8054         // It isn't possible to write this directly, but it is possible to
8055         // end up in this situation with "auto x(some_pack...);"
8056         Diag(CXXDirectInit->getLocStart(),
8057              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8058                                     : diag::err_auto_var_init_no_expression)
8059           << VDecl->getDeclName() << VDecl->getType()
8060           << VDecl->getSourceRange();
8061         RealDecl->setInvalidDecl();
8062         return;
8063       } else if (CXXDirectInit->getNumExprs() > 1) {
8064         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8065              VDecl->isInitCapture()
8066                  ? diag::err_init_capture_multiple_expressions
8067                  : diag::err_auto_var_init_multiple_expressions)
8068           << VDecl->getDeclName() << VDecl->getType()
8069           << VDecl->getSourceRange();
8070         RealDecl->setInvalidDecl();
8071         return;
8072       } else {
8073         DeduceInit = CXXDirectInit->getExpr(0);
8074       }
8075     }
8076 
8077     // Expressions default to 'id' when we're in a debugger.
8078     bool DefaultedToAuto = false;
8079     if (getLangOpts().DebuggerCastResultToId &&
8080         Init->getType() == Context.UnknownAnyTy) {
8081       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8082       if (Result.isInvalid()) {
8083         VDecl->setInvalidDecl();
8084         return;
8085       }
8086       Init = Result.take();
8087       DefaultedToAuto = true;
8088     }
8089 
8090     QualType DeducedType;
8091     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8092             DAR_Failed)
8093       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8094     if (DeducedType.isNull()) {
8095       RealDecl->setInvalidDecl();
8096       return;
8097     }
8098     VDecl->setType(DeducedType);
8099     assert(VDecl->isLinkageValid());
8100 
8101     // In ARC, infer lifetime.
8102     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8103       VDecl->setInvalidDecl();
8104 
8105     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8106     // 'id' instead of a specific object type prevents most of our usual checks.
8107     // We only want to warn outside of template instantiations, though:
8108     // inside a template, the 'id' could have come from a parameter.
8109     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8110         DeducedType->isObjCIdType()) {
8111       SourceLocation Loc =
8112           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8113       Diag(Loc, diag::warn_auto_var_is_id)
8114         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8115     }
8116 
8117     // If this is a redeclaration, check that the type we just deduced matches
8118     // the previously declared type.
8119     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8120       // We never need to merge the type, because we cannot form an incomplete
8121       // array of auto, nor deduce such a type.
8122       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8123     }
8124 
8125     // Check the deduced type is valid for a variable declaration.
8126     CheckVariableDeclarationType(VDecl);
8127     if (VDecl->isInvalidDecl())
8128       return;
8129   }
8130 
8131   // dllimport cannot be used on variable definitions.
8132   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8133     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8134     VDecl->setInvalidDecl();
8135     return;
8136   }
8137 
8138   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8139     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8140     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8141     VDecl->setInvalidDecl();
8142     return;
8143   }
8144 
8145   if (!VDecl->getType()->isDependentType()) {
8146     // A definition must end up with a complete type, which means it must be
8147     // complete with the restriction that an array type might be completed by
8148     // the initializer; note that later code assumes this restriction.
8149     QualType BaseDeclType = VDecl->getType();
8150     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8151       BaseDeclType = Array->getElementType();
8152     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8153                             diag::err_typecheck_decl_incomplete_type)) {
8154       RealDecl->setInvalidDecl();
8155       return;
8156     }
8157 
8158     // The variable can not have an abstract class type.
8159     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8160                                diag::err_abstract_type_in_decl,
8161                                AbstractVariableType))
8162       VDecl->setInvalidDecl();
8163   }
8164 
8165   const VarDecl *Def;
8166   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8167     Diag(VDecl->getLocation(), diag::err_redefinition)
8168       << VDecl->getDeclName();
8169     Diag(Def->getLocation(), diag::note_previous_definition);
8170     VDecl->setInvalidDecl();
8171     return;
8172   }
8173 
8174   const VarDecl* PrevInit = 0;
8175   if (getLangOpts().CPlusPlus) {
8176     // C++ [class.static.data]p4
8177     //   If a static data member is of const integral or const
8178     //   enumeration type, its declaration in the class definition can
8179     //   specify a constant-initializer which shall be an integral
8180     //   constant expression (5.19). In that case, the member can appear
8181     //   in integral constant expressions. The member shall still be
8182     //   defined in a namespace scope if it is used in the program and the
8183     //   namespace scope definition shall not contain an initializer.
8184     //
8185     // We already performed a redefinition check above, but for static
8186     // data members we also need to check whether there was an in-class
8187     // declaration with an initializer.
8188     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8189       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8190           << VDecl->getDeclName();
8191       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8192       return;
8193     }
8194 
8195     if (VDecl->hasLocalStorage())
8196       getCurFunction()->setHasBranchProtectedScope();
8197 
8198     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8199       VDecl->setInvalidDecl();
8200       return;
8201     }
8202   }
8203 
8204   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8205   // a kernel function cannot be initialized."
8206   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8207     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8208     VDecl->setInvalidDecl();
8209     return;
8210   }
8211 
8212   // Get the decls type and save a reference for later, since
8213   // CheckInitializerTypes may change it.
8214   QualType DclT = VDecl->getType(), SavT = DclT;
8215 
8216   // Expressions default to 'id' when we're in a debugger
8217   // and we are assigning it to a variable of Objective-C pointer type.
8218   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8219       Init->getType() == Context.UnknownAnyTy) {
8220     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8221     if (Result.isInvalid()) {
8222       VDecl->setInvalidDecl();
8223       return;
8224     }
8225     Init = Result.take();
8226   }
8227 
8228   // Perform the initialization.
8229   if (!VDecl->isInvalidDecl()) {
8230     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8231     InitializationKind Kind
8232       = DirectInit ?
8233           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8234                                                            Init->getLocStart(),
8235                                                            Init->getLocEnd())
8236                         : InitializationKind::CreateDirectList(
8237                                                           VDecl->getLocation())
8238                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8239                                                     Init->getLocStart());
8240 
8241     MultiExprArg Args = Init;
8242     if (CXXDirectInit)
8243       Args = MultiExprArg(CXXDirectInit->getExprs(),
8244                           CXXDirectInit->getNumExprs());
8245 
8246     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8247     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8248     if (Result.isInvalid()) {
8249       VDecl->setInvalidDecl();
8250       return;
8251     }
8252 
8253     Init = Result.takeAs<Expr>();
8254   }
8255 
8256   // Check for self-references within variable initializers.
8257   // Variables declared within a function/method body (except for references)
8258   // are handled by a dataflow analysis.
8259   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8260       VDecl->getType()->isReferenceType()) {
8261     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8262   }
8263 
8264   // If the type changed, it means we had an incomplete type that was
8265   // completed by the initializer. For example:
8266   //   int ary[] = { 1, 3, 5 };
8267   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8268   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8269     VDecl->setType(DclT);
8270 
8271   if (!VDecl->isInvalidDecl()) {
8272     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8273 
8274     if (VDecl->hasAttr<BlocksAttr>())
8275       checkRetainCycles(VDecl, Init);
8276 
8277     // It is safe to assign a weak reference into a strong variable.
8278     // Although this code can still have problems:
8279     //   id x = self.weakProp;
8280     //   id y = self.weakProp;
8281     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8282     // paths through the function. This should be revisited if
8283     // -Wrepeated-use-of-weak is made flow-sensitive.
8284     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8285       DiagnosticsEngine::Level Level =
8286         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8287                                  Init->getLocStart());
8288       if (Level != DiagnosticsEngine::Ignored)
8289         getCurFunction()->markSafeWeakUse(Init);
8290     }
8291   }
8292 
8293   // The initialization is usually a full-expression.
8294   //
8295   // FIXME: If this is a braced initialization of an aggregate, it is not
8296   // an expression, and each individual field initializer is a separate
8297   // full-expression. For instance, in:
8298   //
8299   //   struct Temp { ~Temp(); };
8300   //   struct S { S(Temp); };
8301   //   struct T { S a, b; } t = { Temp(), Temp() }
8302   //
8303   // we should destroy the first Temp before constructing the second.
8304   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8305                                           false,
8306                                           VDecl->isConstexpr());
8307   if (Result.isInvalid()) {
8308     VDecl->setInvalidDecl();
8309     return;
8310   }
8311   Init = Result.take();
8312 
8313   // Attach the initializer to the decl.
8314   VDecl->setInit(Init);
8315 
8316   if (VDecl->isLocalVarDecl()) {
8317     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8318     // static storage duration shall be constant expressions or string literals.
8319     // C++ does not have this restriction.
8320     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8321       if (VDecl->getStorageClass() == SC_Static)
8322         CheckForConstantInitializer(Init, DclT);
8323       // C89 is stricter than C99 for non-static aggregate types.
8324       // C89 6.5.7p3: All the expressions [...] in an initializer list
8325       // for an object that has aggregate or union type shall be
8326       // constant expressions.
8327       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8328                isa<InitListExpr>(Init) &&
8329                !Init->isConstantInitializer(Context, false))
8330         Diag(Init->getExprLoc(),
8331              diag::ext_aggregate_init_not_constant)
8332           << Init->getSourceRange();
8333     }
8334   } else if (VDecl->isStaticDataMember() &&
8335              VDecl->getLexicalDeclContext()->isRecord()) {
8336     // This is an in-class initialization for a static data member, e.g.,
8337     //
8338     // struct S {
8339     //   static const int value = 17;
8340     // };
8341 
8342     // C++ [class.mem]p4:
8343     //   A member-declarator can contain a constant-initializer only
8344     //   if it declares a static member (9.4) of const integral or
8345     //   const enumeration type, see 9.4.2.
8346     //
8347     // C++11 [class.static.data]p3:
8348     //   If a non-volatile const static data member is of integral or
8349     //   enumeration type, its declaration in the class definition can
8350     //   specify a brace-or-equal-initializer in which every initalizer-clause
8351     //   that is an assignment-expression is a constant expression. A static
8352     //   data member of literal type can be declared in the class definition
8353     //   with the constexpr specifier; if so, its declaration shall specify a
8354     //   brace-or-equal-initializer in which every initializer-clause that is
8355     //   an assignment-expression is a constant expression.
8356 
8357     // Do nothing on dependent types.
8358     if (DclT->isDependentType()) {
8359 
8360     // Allow any 'static constexpr' members, whether or not they are of literal
8361     // type. We separately check that every constexpr variable is of literal
8362     // type.
8363     } else if (VDecl->isConstexpr()) {
8364 
8365     // Require constness.
8366     } else if (!DclT.isConstQualified()) {
8367       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8368         << Init->getSourceRange();
8369       VDecl->setInvalidDecl();
8370 
8371     // We allow integer constant expressions in all cases.
8372     } else if (DclT->isIntegralOrEnumerationType()) {
8373       // Check whether the expression is a constant expression.
8374       SourceLocation Loc;
8375       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8376         // In C++11, a non-constexpr const static data member with an
8377         // in-class initializer cannot be volatile.
8378         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8379       else if (Init->isValueDependent())
8380         ; // Nothing to check.
8381       else if (Init->isIntegerConstantExpr(Context, &Loc))
8382         ; // Ok, it's an ICE!
8383       else if (Init->isEvaluatable(Context)) {
8384         // If we can constant fold the initializer through heroics, accept it,
8385         // but report this as a use of an extension for -pedantic.
8386         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8387           << Init->getSourceRange();
8388       } else {
8389         // Otherwise, this is some crazy unknown case.  Report the issue at the
8390         // location provided by the isIntegerConstantExpr failed check.
8391         Diag(Loc, diag::err_in_class_initializer_non_constant)
8392           << Init->getSourceRange();
8393         VDecl->setInvalidDecl();
8394       }
8395 
8396     // We allow foldable floating-point constants as an extension.
8397     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8398       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8399       // it anyway and provide a fixit to add the 'constexpr'.
8400       if (getLangOpts().CPlusPlus11) {
8401         Diag(VDecl->getLocation(),
8402              diag::ext_in_class_initializer_float_type_cxx11)
8403             << DclT << Init->getSourceRange();
8404         Diag(VDecl->getLocStart(),
8405              diag::note_in_class_initializer_float_type_cxx11)
8406             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8407       } else {
8408         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8409           << DclT << Init->getSourceRange();
8410 
8411         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8412           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8413             << Init->getSourceRange();
8414           VDecl->setInvalidDecl();
8415         }
8416       }
8417 
8418     // Suggest adding 'constexpr' in C++11 for literal types.
8419     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8420       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8421         << DclT << Init->getSourceRange()
8422         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8423       VDecl->setConstexpr(true);
8424 
8425     } else {
8426       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8427         << DclT << Init->getSourceRange();
8428       VDecl->setInvalidDecl();
8429     }
8430   } else if (VDecl->isFileVarDecl()) {
8431     if (VDecl->getStorageClass() == SC_Extern &&
8432         (!getLangOpts().CPlusPlus ||
8433          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8434            VDecl->isExternC())) &&
8435         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8436       Diag(VDecl->getLocation(), diag::warn_extern_init);
8437 
8438     // C99 6.7.8p4. All file scoped initializers need to be constant.
8439     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8440       CheckForConstantInitializer(Init, DclT);
8441     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8442              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8443              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8444              !Init->isConstantInitializer(
8445                  Context, VDecl->getType()->isReferenceType())) {
8446       // GNU C++98 edits for __thread, [basic.start.init]p4:
8447       //   An object of thread storage duration shall not require dynamic
8448       //   initialization.
8449       // FIXME: Need strict checking here.
8450       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8451       if (getLangOpts().CPlusPlus11)
8452         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8453     }
8454   }
8455 
8456   // We will represent direct-initialization similarly to copy-initialization:
8457   //    int x(1);  -as-> int x = 1;
8458   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8459   //
8460   // Clients that want to distinguish between the two forms, can check for
8461   // direct initializer using VarDecl::getInitStyle().
8462   // A major benefit is that clients that don't particularly care about which
8463   // exactly form was it (like the CodeGen) can handle both cases without
8464   // special case code.
8465 
8466   // C++ 8.5p11:
8467   // The form of initialization (using parentheses or '=') is generally
8468   // insignificant, but does matter when the entity being initialized has a
8469   // class type.
8470   if (CXXDirectInit) {
8471     assert(DirectInit && "Call-style initializer must be direct init.");
8472     VDecl->setInitStyle(VarDecl::CallInit);
8473   } else if (DirectInit) {
8474     // This must be list-initialization. No other way is direct-initialization.
8475     VDecl->setInitStyle(VarDecl::ListInit);
8476   }
8477 
8478   CheckCompleteVariableDeclaration(VDecl);
8479 }
8480 
8481 /// ActOnInitializerError - Given that there was an error parsing an
8482 /// initializer for the given declaration, try to return to some form
8483 /// of sanity.
8484 void Sema::ActOnInitializerError(Decl *D) {
8485   // Our main concern here is re-establishing invariants like "a
8486   // variable's type is either dependent or complete".
8487   if (!D || D->isInvalidDecl()) return;
8488 
8489   VarDecl *VD = dyn_cast<VarDecl>(D);
8490   if (!VD) return;
8491 
8492   // Auto types are meaningless if we can't make sense of the initializer.
8493   if (ParsingInitForAutoVars.count(D)) {
8494     D->setInvalidDecl();
8495     return;
8496   }
8497 
8498   QualType Ty = VD->getType();
8499   if (Ty->isDependentType()) return;
8500 
8501   // Require a complete type.
8502   if (RequireCompleteType(VD->getLocation(),
8503                           Context.getBaseElementType(Ty),
8504                           diag::err_typecheck_decl_incomplete_type)) {
8505     VD->setInvalidDecl();
8506     return;
8507   }
8508 
8509   // Require an abstract type.
8510   if (RequireNonAbstractType(VD->getLocation(), Ty,
8511                              diag::err_abstract_type_in_decl,
8512                              AbstractVariableType)) {
8513     VD->setInvalidDecl();
8514     return;
8515   }
8516 
8517   // Don't bother complaining about constructors or destructors,
8518   // though.
8519 }
8520 
8521 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8522                                   bool TypeMayContainAuto) {
8523   // If there is no declaration, there was an error parsing it. Just ignore it.
8524   if (RealDecl == 0)
8525     return;
8526 
8527   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8528     QualType Type = Var->getType();
8529 
8530     // C++11 [dcl.spec.auto]p3
8531     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8532       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8533         << Var->getDeclName() << Type;
8534       Var->setInvalidDecl();
8535       return;
8536     }
8537 
8538     // C++11 [class.static.data]p3: A static data member can be declared with
8539     // the constexpr specifier; if so, its declaration shall specify
8540     // a brace-or-equal-initializer.
8541     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8542     // the definition of a variable [...] or the declaration of a static data
8543     // member.
8544     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8545       if (Var->isStaticDataMember())
8546         Diag(Var->getLocation(),
8547              diag::err_constexpr_static_mem_var_requires_init)
8548           << Var->getDeclName();
8549       else
8550         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8551       Var->setInvalidDecl();
8552       return;
8553     }
8554 
8555     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8556     // be initialized.
8557     if (!Var->isInvalidDecl() &&
8558         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8559         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
8560       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8561       Var->setInvalidDecl();
8562       return;
8563     }
8564 
8565     switch (Var->isThisDeclarationADefinition()) {
8566     case VarDecl::Definition:
8567       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8568         break;
8569 
8570       // We have an out-of-line definition of a static data member
8571       // that has an in-class initializer, so we type-check this like
8572       // a declaration.
8573       //
8574       // Fall through
8575 
8576     case VarDecl::DeclarationOnly:
8577       // It's only a declaration.
8578 
8579       // Block scope. C99 6.7p7: If an identifier for an object is
8580       // declared with no linkage (C99 6.2.2p6), the type for the
8581       // object shall be complete.
8582       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8583           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8584           RequireCompleteType(Var->getLocation(), Type,
8585                               diag::err_typecheck_decl_incomplete_type))
8586         Var->setInvalidDecl();
8587 
8588       // Make sure that the type is not abstract.
8589       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8590           RequireNonAbstractType(Var->getLocation(), Type,
8591                                  diag::err_abstract_type_in_decl,
8592                                  AbstractVariableType))
8593         Var->setInvalidDecl();
8594       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8595           Var->getStorageClass() == SC_PrivateExtern) {
8596         Diag(Var->getLocation(), diag::warn_private_extern);
8597         Diag(Var->getLocation(), diag::note_private_extern);
8598       }
8599 
8600       return;
8601 
8602     case VarDecl::TentativeDefinition:
8603       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8604       // object that has file scope without an initializer, and without a
8605       // storage-class specifier or with the storage-class specifier "static",
8606       // constitutes a tentative definition. Note: A tentative definition with
8607       // external linkage is valid (C99 6.2.2p5).
8608       if (!Var->isInvalidDecl()) {
8609         if (const IncompleteArrayType *ArrayT
8610                                     = Context.getAsIncompleteArrayType(Type)) {
8611           if (RequireCompleteType(Var->getLocation(),
8612                                   ArrayT->getElementType(),
8613                                   diag::err_illegal_decl_array_incomplete_type))
8614             Var->setInvalidDecl();
8615         } else if (Var->getStorageClass() == SC_Static) {
8616           // C99 6.9.2p3: If the declaration of an identifier for an object is
8617           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8618           // declared type shall not be an incomplete type.
8619           // NOTE: code such as the following
8620           //     static struct s;
8621           //     struct s { int a; };
8622           // is accepted by gcc. Hence here we issue a warning instead of
8623           // an error and we do not invalidate the static declaration.
8624           // NOTE: to avoid multiple warnings, only check the first declaration.
8625           if (Var->isFirstDecl())
8626             RequireCompleteType(Var->getLocation(), Type,
8627                                 diag::ext_typecheck_decl_incomplete_type);
8628         }
8629       }
8630 
8631       // Record the tentative definition; we're done.
8632       if (!Var->isInvalidDecl())
8633         TentativeDefinitions.push_back(Var);
8634       return;
8635     }
8636 
8637     // Provide a specific diagnostic for uninitialized variable
8638     // definitions with incomplete array type.
8639     if (Type->isIncompleteArrayType()) {
8640       Diag(Var->getLocation(),
8641            diag::err_typecheck_incomplete_array_needs_initializer);
8642       Var->setInvalidDecl();
8643       return;
8644     }
8645 
8646     // Provide a specific diagnostic for uninitialized variable
8647     // definitions with reference type.
8648     if (Type->isReferenceType()) {
8649       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8650         << Var->getDeclName()
8651         << SourceRange(Var->getLocation(), Var->getLocation());
8652       Var->setInvalidDecl();
8653       return;
8654     }
8655 
8656     // Do not attempt to type-check the default initializer for a
8657     // variable with dependent type.
8658     if (Type->isDependentType())
8659       return;
8660 
8661     if (Var->isInvalidDecl())
8662       return;
8663 
8664     if (RequireCompleteType(Var->getLocation(),
8665                             Context.getBaseElementType(Type),
8666                             diag::err_typecheck_decl_incomplete_type)) {
8667       Var->setInvalidDecl();
8668       return;
8669     }
8670 
8671     // The variable can not have an abstract class type.
8672     if (RequireNonAbstractType(Var->getLocation(), Type,
8673                                diag::err_abstract_type_in_decl,
8674                                AbstractVariableType)) {
8675       Var->setInvalidDecl();
8676       return;
8677     }
8678 
8679     // Check for jumps past the implicit initializer.  C++0x
8680     // clarifies that this applies to a "variable with automatic
8681     // storage duration", not a "local variable".
8682     // C++11 [stmt.dcl]p3
8683     //   A program that jumps from a point where a variable with automatic
8684     //   storage duration is not in scope to a point where it is in scope is
8685     //   ill-formed unless the variable has scalar type, class type with a
8686     //   trivial default constructor and a trivial destructor, a cv-qualified
8687     //   version of one of these types, or an array of one of the preceding
8688     //   types and is declared without an initializer.
8689     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8690       if (const RecordType *Record
8691             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8692         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8693         // Mark the function for further checking even if the looser rules of
8694         // C++11 do not require such checks, so that we can diagnose
8695         // incompatibilities with C++98.
8696         if (!CXXRecord->isPOD())
8697           getCurFunction()->setHasBranchProtectedScope();
8698       }
8699     }
8700 
8701     // C++03 [dcl.init]p9:
8702     //   If no initializer is specified for an object, and the
8703     //   object is of (possibly cv-qualified) non-POD class type (or
8704     //   array thereof), the object shall be default-initialized; if
8705     //   the object is of const-qualified type, the underlying class
8706     //   type shall have a user-declared default
8707     //   constructor. Otherwise, if no initializer is specified for
8708     //   a non- static object, the object and its subobjects, if
8709     //   any, have an indeterminate initial value); if the object
8710     //   or any of its subobjects are of const-qualified type, the
8711     //   program is ill-formed.
8712     // C++0x [dcl.init]p11:
8713     //   If no initializer is specified for an object, the object is
8714     //   default-initialized; [...].
8715     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8716     InitializationKind Kind
8717       = InitializationKind::CreateDefault(Var->getLocation());
8718 
8719     InitializationSequence InitSeq(*this, Entity, Kind, None);
8720     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8721     if (Init.isInvalid())
8722       Var->setInvalidDecl();
8723     else if (Init.get()) {
8724       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8725       // This is important for template substitution.
8726       Var->setInitStyle(VarDecl::CallInit);
8727     }
8728 
8729     CheckCompleteVariableDeclaration(Var);
8730   }
8731 }
8732 
8733 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8734   VarDecl *VD = dyn_cast<VarDecl>(D);
8735   if (!VD) {
8736     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8737     D->setInvalidDecl();
8738     return;
8739   }
8740 
8741   VD->setCXXForRangeDecl(true);
8742 
8743   // for-range-declaration cannot be given a storage class specifier.
8744   int Error = -1;
8745   switch (VD->getStorageClass()) {
8746   case SC_None:
8747     break;
8748   case SC_Extern:
8749     Error = 0;
8750     break;
8751   case SC_Static:
8752     Error = 1;
8753     break;
8754   case SC_PrivateExtern:
8755     Error = 2;
8756     break;
8757   case SC_Auto:
8758     Error = 3;
8759     break;
8760   case SC_Register:
8761     Error = 4;
8762     break;
8763   case SC_OpenCLWorkGroupLocal:
8764     llvm_unreachable("Unexpected storage class");
8765   }
8766   if (VD->isConstexpr())
8767     Error = 5;
8768   if (Error != -1) {
8769     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8770       << VD->getDeclName() << Error;
8771     D->setInvalidDecl();
8772   }
8773 }
8774 
8775 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8776   if (var->isInvalidDecl()) return;
8777 
8778   // In ARC, don't allow jumps past the implicit initialization of a
8779   // local retaining variable.
8780   if (getLangOpts().ObjCAutoRefCount &&
8781       var->hasLocalStorage()) {
8782     switch (var->getType().getObjCLifetime()) {
8783     case Qualifiers::OCL_None:
8784     case Qualifiers::OCL_ExplicitNone:
8785     case Qualifiers::OCL_Autoreleasing:
8786       break;
8787 
8788     case Qualifiers::OCL_Weak:
8789     case Qualifiers::OCL_Strong:
8790       getCurFunction()->setHasBranchProtectedScope();
8791       break;
8792     }
8793   }
8794 
8795   // Warn about externally-visible variables being defined without a
8796   // prior declaration.  We only want to do this for global
8797   // declarations, but we also specifically need to avoid doing it for
8798   // class members because the linkage of an anonymous class can
8799   // change if it's later given a typedef name.
8800   if (var->isThisDeclarationADefinition() &&
8801       var->getDeclContext()->getRedeclContext()->isFileContext() &&
8802       var->isExternallyVisible() && var->hasLinkage() &&
8803       getDiagnostics().getDiagnosticLevel(
8804                        diag::warn_missing_variable_declarations,
8805                        var->getLocation())) {
8806     // Find a previous declaration that's not a definition.
8807     VarDecl *prev = var->getPreviousDecl();
8808     while (prev && prev->isThisDeclarationADefinition())
8809       prev = prev->getPreviousDecl();
8810 
8811     if (!prev)
8812       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8813   }
8814 
8815   if (var->getTLSKind() == VarDecl::TLS_Static &&
8816       var->getType().isDestructedType()) {
8817     // GNU C++98 edits for __thread, [basic.start.term]p3:
8818     //   The type of an object with thread storage duration shall not
8819     //   have a non-trivial destructor.
8820     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8821     if (getLangOpts().CPlusPlus11)
8822       Diag(var->getLocation(), diag::note_use_thread_local);
8823   }
8824 
8825   // All the following checks are C++ only.
8826   if (!getLangOpts().CPlusPlus) return;
8827 
8828   QualType type = var->getType();
8829   if (type->isDependentType()) return;
8830 
8831   // __block variables might require us to capture a copy-initializer.
8832   if (var->hasAttr<BlocksAttr>()) {
8833     // It's currently invalid to ever have a __block variable with an
8834     // array type; should we diagnose that here?
8835 
8836     // Regardless, we don't want to ignore array nesting when
8837     // constructing this copy.
8838     if (type->isStructureOrClassType()) {
8839       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8840       SourceLocation poi = var->getLocation();
8841       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8842       ExprResult result
8843         = PerformMoveOrCopyInitialization(
8844             InitializedEntity::InitializeBlock(poi, type, false),
8845             var, var->getType(), varRef, /*AllowNRVO=*/true);
8846       if (!result.isInvalid()) {
8847         result = MaybeCreateExprWithCleanups(result);
8848         Expr *init = result.takeAs<Expr>();
8849         Context.setBlockVarCopyInits(var, init);
8850       }
8851     }
8852   }
8853 
8854   Expr *Init = var->getInit();
8855   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8856   QualType baseType = Context.getBaseElementType(type);
8857 
8858   if (!var->getDeclContext()->isDependentContext() &&
8859       Init && !Init->isValueDependent()) {
8860     if (IsGlobal && !var->isConstexpr() &&
8861         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8862                                             var->getLocation())
8863           != DiagnosticsEngine::Ignored) {
8864       // Warn about globals which don't have a constant initializer.  Don't
8865       // warn about globals with a non-trivial destructor because we already
8866       // warned about them.
8867       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8868       if (!(RD && !RD->hasTrivialDestructor()) &&
8869           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8870         Diag(var->getLocation(), diag::warn_global_constructor)
8871           << Init->getSourceRange();
8872     }
8873 
8874     if (var->isConstexpr()) {
8875       SmallVector<PartialDiagnosticAt, 8> Notes;
8876       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8877         SourceLocation DiagLoc = var->getLocation();
8878         // If the note doesn't add any useful information other than a source
8879         // location, fold it into the primary diagnostic.
8880         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8881               diag::note_invalid_subexpr_in_const_expr) {
8882           DiagLoc = Notes[0].first;
8883           Notes.clear();
8884         }
8885         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8886           << var << Init->getSourceRange();
8887         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8888           Diag(Notes[I].first, Notes[I].second);
8889       }
8890     } else if (var->isUsableInConstantExpressions(Context)) {
8891       // Check whether the initializer of a const variable of integral or
8892       // enumeration type is an ICE now, since we can't tell whether it was
8893       // initialized by a constant expression if we check later.
8894       var->checkInitIsICE();
8895     }
8896   }
8897 
8898   // Require the destructor.
8899   if (const RecordType *recordType = baseType->getAs<RecordType>())
8900     FinalizeVarWithDestructor(var, recordType);
8901 }
8902 
8903 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8904 /// any semantic actions necessary after any initializer has been attached.
8905 void
8906 Sema::FinalizeDeclaration(Decl *ThisDecl) {
8907   // Note that we are no longer parsing the initializer for this declaration.
8908   ParsingInitForAutoVars.erase(ThisDecl);
8909 
8910   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8911   if (!VD)
8912     return;
8913 
8914   checkAttributesAfterMerging(*this, *VD);
8915 
8916   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8917     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8918       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
8919       VD->dropAttr<UsedAttr>();
8920     }
8921   }
8922 
8923   if (!VD->isInvalidDecl() &&
8924       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8925     if (const VarDecl *Def = VD->getDefinition()) {
8926       if (Def->hasAttr<AliasAttr>()) {
8927         Diag(VD->getLocation(), diag::err_tentative_after_alias)
8928             << VD->getDeclName();
8929         Diag(Def->getLocation(), diag::note_previous_definition);
8930         VD->setInvalidDecl();
8931       }
8932     }
8933   }
8934 
8935   const DeclContext *DC = VD->getDeclContext();
8936   // If there's a #pragma GCC visibility in scope, and this isn't a class
8937   // member, set the visibility of this variable.
8938   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
8939     AddPushedVisibilityAttribute(VD);
8940 
8941   if (VD->isFileVarDecl())
8942     MarkUnusedFileScopedDecl(VD);
8943 
8944   // Now we have parsed the initializer and can update the table of magic
8945   // tag values.
8946   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8947       !VD->getType()->isIntegralOrEnumerationType())
8948     return;
8949 
8950   for (specific_attr_iterator<TypeTagForDatatypeAttr>
8951          I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8952          E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8953        I != E; ++I) {
8954     const Expr *MagicValueExpr = VD->getInit();
8955     if (!MagicValueExpr) {
8956       continue;
8957     }
8958     llvm::APSInt MagicValueInt;
8959     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8960       Diag(I->getRange().getBegin(),
8961            diag::err_type_tag_for_datatype_not_ice)
8962         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8963       continue;
8964     }
8965     if (MagicValueInt.getActiveBits() > 64) {
8966       Diag(I->getRange().getBegin(),
8967            diag::err_type_tag_for_datatype_too_large)
8968         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8969       continue;
8970     }
8971     uint64_t MagicValue = MagicValueInt.getZExtValue();
8972     RegisterTypeTagForDatatype(I->getArgumentKind(),
8973                                MagicValue,
8974                                I->getMatchingCType(),
8975                                I->getLayoutCompatible(),
8976                                I->getMustBeNull());
8977   }
8978 }
8979 
8980 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8981                                                    ArrayRef<Decl *> Group) {
8982   SmallVector<Decl*, 8> Decls;
8983 
8984   if (DS.isTypeSpecOwned())
8985     Decls.push_back(DS.getRepAsDecl());
8986 
8987   DeclaratorDecl *FirstDeclaratorInGroup = 0;
8988   for (unsigned i = 0, e = Group.size(); i != e; ++i)
8989     if (Decl *D = Group[i]) {
8990       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8991         if (!FirstDeclaratorInGroup)
8992           FirstDeclaratorInGroup = DD;
8993       Decls.push_back(D);
8994     }
8995 
8996   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8997     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8998       HandleTagNumbering(*this, Tag, S);
8999       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9000         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9001     }
9002   }
9003 
9004   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9005 }
9006 
9007 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9008 /// group, performing any necessary semantic checking.
9009 Sema::DeclGroupPtrTy
9010 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
9011                            bool TypeMayContainAuto) {
9012   // C++0x [dcl.spec.auto]p7:
9013   //   If the type deduced for the template parameter U is not the same in each
9014   //   deduction, the program is ill-formed.
9015   // FIXME: When initializer-list support is added, a distinction is needed
9016   // between the deduced type U and the deduced type which 'auto' stands for.
9017   //   auto a = 0, b = { 1, 2, 3 };
9018   // is legal because the deduced type U is 'int' in both cases.
9019   if (TypeMayContainAuto && Group.size() > 1) {
9020     QualType Deduced;
9021     CanQualType DeducedCanon;
9022     VarDecl *DeducedDecl = 0;
9023     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9024       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9025         AutoType *AT = D->getType()->getContainedAutoType();
9026         // Don't reissue diagnostics when instantiating a template.
9027         if (AT && D->isInvalidDecl())
9028           break;
9029         QualType U = AT ? AT->getDeducedType() : QualType();
9030         if (!U.isNull()) {
9031           CanQualType UCanon = Context.getCanonicalType(U);
9032           if (Deduced.isNull()) {
9033             Deduced = U;
9034             DeducedCanon = UCanon;
9035             DeducedDecl = D;
9036           } else if (DeducedCanon != UCanon) {
9037             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9038                  diag::err_auto_different_deductions)
9039               << (AT->isDecltypeAuto() ? 1 : 0)
9040               << Deduced << DeducedDecl->getDeclName()
9041               << U << D->getDeclName()
9042               << DeducedDecl->getInit()->getSourceRange()
9043               << D->getInit()->getSourceRange();
9044             D->setInvalidDecl();
9045             break;
9046           }
9047         }
9048       }
9049     }
9050   }
9051 
9052   ActOnDocumentableDecls(Group);
9053 
9054   return DeclGroupPtrTy::make(
9055       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9056 }
9057 
9058 void Sema::ActOnDocumentableDecl(Decl *D) {
9059   ActOnDocumentableDecls(D);
9060 }
9061 
9062 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9063   // Don't parse the comment if Doxygen diagnostics are ignored.
9064   if (Group.empty() || !Group[0])
9065    return;
9066 
9067   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9068                                Group[0]->getLocation())
9069         == DiagnosticsEngine::Ignored)
9070     return;
9071 
9072   if (Group.size() >= 2) {
9073     // This is a decl group.  Normally it will contain only declarations
9074     // produced from declarator list.  But in case we have any definitions or
9075     // additional declaration references:
9076     //   'typedef struct S {} S;'
9077     //   'typedef struct S *S;'
9078     //   'struct S *pS;'
9079     // FinalizeDeclaratorGroup adds these as separate declarations.
9080     Decl *MaybeTagDecl = Group[0];
9081     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9082       Group = Group.slice(1);
9083     }
9084   }
9085 
9086   // See if there are any new comments that are not attached to a decl.
9087   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9088   if (!Comments.empty() &&
9089       !Comments.back()->isAttached()) {
9090     // There is at least one comment that not attached to a decl.
9091     // Maybe it should be attached to one of these decls?
9092     //
9093     // Note that this way we pick up not only comments that precede the
9094     // declaration, but also comments that *follow* the declaration -- thanks to
9095     // the lookahead in the lexer: we've consumed the semicolon and looked
9096     // ahead through comments.
9097     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9098       Context.getCommentForDecl(Group[i], &PP);
9099   }
9100 }
9101 
9102 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9103 /// to introduce parameters into function prototype scope.
9104 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9105   const DeclSpec &DS = D.getDeclSpec();
9106 
9107   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9108 
9109   // C++03 [dcl.stc]p2 also permits 'auto'.
9110   VarDecl::StorageClass StorageClass = SC_None;
9111   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9112     StorageClass = SC_Register;
9113   } else if (getLangOpts().CPlusPlus &&
9114              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9115     StorageClass = SC_Auto;
9116   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9117     Diag(DS.getStorageClassSpecLoc(),
9118          diag::err_invalid_storage_class_in_func_decl);
9119     D.getMutableDeclSpec().ClearStorageClassSpecs();
9120   }
9121 
9122   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9123     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9124       << DeclSpec::getSpecifierName(TSCS);
9125   if (DS.isConstexprSpecified())
9126     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9127       << 0;
9128 
9129   DiagnoseFunctionSpecifiers(DS);
9130 
9131   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9132   QualType parmDeclType = TInfo->getType();
9133 
9134   if (getLangOpts().CPlusPlus) {
9135     // Check that there are no default arguments inside the type of this
9136     // parameter.
9137     CheckExtraCXXDefaultArguments(D);
9138 
9139     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9140     if (D.getCXXScopeSpec().isSet()) {
9141       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9142         << D.getCXXScopeSpec().getRange();
9143       D.getCXXScopeSpec().clear();
9144     }
9145   }
9146 
9147   // Ensure we have a valid name
9148   IdentifierInfo *II = 0;
9149   if (D.hasName()) {
9150     II = D.getIdentifier();
9151     if (!II) {
9152       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9153         << GetNameForDeclarator(D).getName();
9154       D.setInvalidType(true);
9155     }
9156   }
9157 
9158   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9159   if (II) {
9160     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9161                    ForRedeclaration);
9162     LookupName(R, S);
9163     if (R.isSingleResult()) {
9164       NamedDecl *PrevDecl = R.getFoundDecl();
9165       if (PrevDecl->isTemplateParameter()) {
9166         // Maybe we will complain about the shadowed template parameter.
9167         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9168         // Just pretend that we didn't see the previous declaration.
9169         PrevDecl = 0;
9170       } else if (S->isDeclScope(PrevDecl)) {
9171         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9172         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9173 
9174         // Recover by removing the name
9175         II = 0;
9176         D.SetIdentifier(0, D.getIdentifierLoc());
9177         D.setInvalidType(true);
9178       }
9179     }
9180   }
9181 
9182   // Temporarily put parameter variables in the translation unit, not
9183   // the enclosing context.  This prevents them from accidentally
9184   // looking like class members in C++.
9185   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9186                                     D.getLocStart(),
9187                                     D.getIdentifierLoc(), II,
9188                                     parmDeclType, TInfo,
9189                                     StorageClass);
9190 
9191   if (D.isInvalidType())
9192     New->setInvalidDecl();
9193 
9194   assert(S->isFunctionPrototypeScope());
9195   assert(S->getFunctionPrototypeDepth() >= 1);
9196   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9197                     S->getNextFunctionPrototypeIndex());
9198 
9199   // Add the parameter declaration into this scope.
9200   S->AddDecl(New);
9201   if (II)
9202     IdResolver.AddDecl(New);
9203 
9204   ProcessDeclAttributes(S, New, D);
9205 
9206   if (D.getDeclSpec().isModulePrivateSpecified())
9207     Diag(New->getLocation(), diag::err_module_private_local)
9208       << 1 << New->getDeclName()
9209       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9210       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9211 
9212   if (New->hasAttr<BlocksAttr>()) {
9213     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9214   }
9215   return New;
9216 }
9217 
9218 /// \brief Synthesizes a variable for a parameter arising from a
9219 /// typedef.
9220 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9221                                               SourceLocation Loc,
9222                                               QualType T) {
9223   /* FIXME: setting StartLoc == Loc.
9224      Would it be worth to modify callers so as to provide proper source
9225      location for the unnamed parameters, embedding the parameter's type? */
9226   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9227                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9228                                            SC_None, 0);
9229   Param->setImplicit();
9230   return Param;
9231 }
9232 
9233 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9234                                     ParmVarDecl * const *ParamEnd) {
9235   // Don't diagnose unused-parameter errors in template instantiations; we
9236   // will already have done so in the template itself.
9237   if (!ActiveTemplateInstantiations.empty())
9238     return;
9239 
9240   for (; Param != ParamEnd; ++Param) {
9241     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9242         !(*Param)->hasAttr<UnusedAttr>()) {
9243       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9244         << (*Param)->getDeclName();
9245     }
9246   }
9247 }
9248 
9249 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9250                                                   ParmVarDecl * const *ParamEnd,
9251                                                   QualType ReturnTy,
9252                                                   NamedDecl *D) {
9253   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9254     return;
9255 
9256   // Warn if the return value is pass-by-value and larger than the specified
9257   // threshold.
9258   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9259     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9260     if (Size > LangOpts.NumLargeByValueCopy)
9261       Diag(D->getLocation(), diag::warn_return_value_size)
9262           << D->getDeclName() << Size;
9263   }
9264 
9265   // Warn if any parameter is pass-by-value and larger than the specified
9266   // threshold.
9267   for (; Param != ParamEnd; ++Param) {
9268     QualType T = (*Param)->getType();
9269     if (T->isDependentType() || !T.isPODType(Context))
9270       continue;
9271     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9272     if (Size > LangOpts.NumLargeByValueCopy)
9273       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9274           << (*Param)->getDeclName() << Size;
9275   }
9276 }
9277 
9278 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9279                                   SourceLocation NameLoc, IdentifierInfo *Name,
9280                                   QualType T, TypeSourceInfo *TSInfo,
9281                                   VarDecl::StorageClass StorageClass) {
9282   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9283   if (getLangOpts().ObjCAutoRefCount &&
9284       T.getObjCLifetime() == Qualifiers::OCL_None &&
9285       T->isObjCLifetimeType()) {
9286 
9287     Qualifiers::ObjCLifetime lifetime;
9288 
9289     // Special cases for arrays:
9290     //   - if it's const, use __unsafe_unretained
9291     //   - otherwise, it's an error
9292     if (T->isArrayType()) {
9293       if (!T.isConstQualified()) {
9294         DelayedDiagnostics.add(
9295             sema::DelayedDiagnostic::makeForbiddenType(
9296             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9297       }
9298       lifetime = Qualifiers::OCL_ExplicitNone;
9299     } else {
9300       lifetime = T->getObjCARCImplicitLifetime();
9301     }
9302     T = Context.getLifetimeQualifiedType(T, lifetime);
9303   }
9304 
9305   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9306                                          Context.getAdjustedParameterType(T),
9307                                          TSInfo,
9308                                          StorageClass, 0);
9309 
9310   // Parameters can not be abstract class types.
9311   // For record types, this is done by the AbstractClassUsageDiagnoser once
9312   // the class has been completely parsed.
9313   if (!CurContext->isRecord() &&
9314       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9315                              AbstractParamType))
9316     New->setInvalidDecl();
9317 
9318   // Parameter declarators cannot be interface types. All ObjC objects are
9319   // passed by reference.
9320   if (T->isObjCObjectType()) {
9321     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9322     Diag(NameLoc,
9323          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9324       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9325     T = Context.getObjCObjectPointerType(T);
9326     New->setType(T);
9327   }
9328 
9329   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9330   // duration shall not be qualified by an address-space qualifier."
9331   // Since all parameters have automatic store duration, they can not have
9332   // an address space.
9333   if (T.getAddressSpace() != 0) {
9334     Diag(NameLoc, diag::err_arg_with_address_space);
9335     New->setInvalidDecl();
9336   }
9337 
9338   return New;
9339 }
9340 
9341 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9342                                            SourceLocation LocAfterDecls) {
9343   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9344 
9345   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9346   // for a K&R function.
9347   if (!FTI.hasPrototype) {
9348     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
9349       --i;
9350       if (FTI.Params[i].Param == 0) {
9351         SmallString<256> Code;
9352         llvm::raw_svector_ostream(Code)
9353             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
9354         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9355             << FTI.Params[i].Ident
9356             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9357 
9358         // Implicitly declare the argument as type 'int' for lack of a better
9359         // type.
9360         AttributeFactory attrs;
9361         DeclSpec DS(attrs);
9362         const char* PrevSpec; // unused
9363         unsigned DiagID; // unused
9364         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9365                            DiagID, Context.getPrintingPolicy());
9366         // Use the identifier location for the type source range.
9367         DS.SetRangeStart(FTI.Params[i].IdentLoc);
9368         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
9369         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9370         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9371         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
9372       }
9373     }
9374   }
9375 }
9376 
9377 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9378   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9379   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9380   Scope *ParentScope = FnBodyScope->getParent();
9381 
9382   D.setFunctionDefinitionKind(FDK_Definition);
9383   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9384   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9385 }
9386 
9387 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9388                              const FunctionDecl*& PossibleZeroParamPrototype) {
9389   // Don't warn about invalid declarations.
9390   if (FD->isInvalidDecl())
9391     return false;
9392 
9393   // Or declarations that aren't global.
9394   if (!FD->isGlobal())
9395     return false;
9396 
9397   // Don't warn about C++ member functions.
9398   if (isa<CXXMethodDecl>(FD))
9399     return false;
9400 
9401   // Don't warn about 'main'.
9402   if (FD->isMain())
9403     return false;
9404 
9405   // Don't warn about inline functions.
9406   if (FD->isInlined())
9407     return false;
9408 
9409   // Don't warn about function templates.
9410   if (FD->getDescribedFunctionTemplate())
9411     return false;
9412 
9413   // Don't warn about function template specializations.
9414   if (FD->isFunctionTemplateSpecialization())
9415     return false;
9416 
9417   // Don't warn for OpenCL kernels.
9418   if (FD->hasAttr<OpenCLKernelAttr>())
9419     return false;
9420 
9421   bool MissingPrototype = true;
9422   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9423        Prev; Prev = Prev->getPreviousDecl()) {
9424     // Ignore any declarations that occur in function or method
9425     // scope, because they aren't visible from the header.
9426     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9427       continue;
9428 
9429     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9430     if (FD->getNumParams() == 0)
9431       PossibleZeroParamPrototype = Prev;
9432     break;
9433   }
9434 
9435   return MissingPrototype;
9436 }
9437 
9438 void
9439 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9440                                    const FunctionDecl *EffectiveDefinition) {
9441   // Don't complain if we're in GNU89 mode and the previous definition
9442   // was an extern inline function.
9443   const FunctionDecl *Definition = EffectiveDefinition;
9444   if (!Definition)
9445     if (!FD->isDefined(Definition))
9446       return;
9447 
9448   if (canRedefineFunction(Definition, getLangOpts()))
9449     return;
9450 
9451   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9452       Definition->getStorageClass() == SC_Extern)
9453     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9454         << FD->getDeclName() << getLangOpts().CPlusPlus;
9455   else
9456     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9457 
9458   Diag(Definition->getLocation(), diag::note_previous_definition);
9459   FD->setInvalidDecl();
9460 }
9461 
9462 
9463 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9464                                    Sema &S) {
9465   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9466 
9467   LambdaScopeInfo *LSI = S.PushLambdaScope();
9468   LSI->CallOperator = CallOperator;
9469   LSI->Lambda = LambdaClass;
9470   LSI->ReturnType = CallOperator->getReturnType();
9471   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9472 
9473   if (LCD == LCD_None)
9474     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9475   else if (LCD == LCD_ByCopy)
9476     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9477   else if (LCD == LCD_ByRef)
9478     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9479   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9480 
9481   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9482   LSI->Mutable = !CallOperator->isConst();
9483 
9484   // Add the captures to the LSI so they can be noted as already
9485   // captured within tryCaptureVar.
9486   for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9487       CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9488     if (C->capturesVariable()) {
9489       VarDecl *VD = C->getCapturedVar();
9490       if (VD->isInitCapture())
9491         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9492       QualType CaptureType = VD->getType();
9493       const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9494       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9495           /*RefersToEnclosingLocal*/true, C->getLocation(),
9496           /*EllipsisLoc*/C->isPackExpansion()
9497                          ? C->getEllipsisLoc() : SourceLocation(),
9498           CaptureType, /*Expr*/ 0);
9499 
9500     } else if (C->capturesThis()) {
9501       LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9502                               S.getCurrentThisType(), /*Expr*/ 0);
9503     }
9504   }
9505 }
9506 
9507 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9508   // Clear the last template instantiation error context.
9509   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9510 
9511   if (!D)
9512     return D;
9513   FunctionDecl *FD = 0;
9514 
9515   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9516     FD = FunTmpl->getTemplatedDecl();
9517   else
9518     FD = cast<FunctionDecl>(D);
9519   // If we are instantiating a generic lambda call operator, push
9520   // a LambdaScopeInfo onto the function stack.  But use the information
9521   // that's already been calculated (ActOnLambdaExpr) to prime the current
9522   // LambdaScopeInfo.
9523   // When the template operator is being specialized, the LambdaScopeInfo,
9524   // has to be properly restored so that tryCaptureVariable doesn't try
9525   // and capture any new variables. In addition when calculating potential
9526   // captures during transformation of nested lambdas, it is necessary to
9527   // have the LSI properly restored.
9528   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9529     assert(ActiveTemplateInstantiations.size() &&
9530       "There should be an active template instantiation on the stack "
9531       "when instantiating a generic lambda!");
9532     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9533   }
9534   else
9535     // Enter a new function scope
9536     PushFunctionScope();
9537 
9538   // See if this is a redefinition.
9539   if (!FD->isLateTemplateParsed())
9540     CheckForFunctionRedefinition(FD);
9541 
9542   // Builtin functions cannot be defined.
9543   if (unsigned BuiltinID = FD->getBuiltinID()) {
9544     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9545         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9546       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9547       FD->setInvalidDecl();
9548     }
9549   }
9550 
9551   // The return type of a function definition must be complete
9552   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9553   QualType ResultType = FD->getReturnType();
9554   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9555       !FD->isInvalidDecl() &&
9556       RequireCompleteType(FD->getLocation(), ResultType,
9557                           diag::err_func_def_incomplete_result))
9558     FD->setInvalidDecl();
9559 
9560   // GNU warning -Wmissing-prototypes:
9561   //   Warn if a global function is defined without a previous
9562   //   prototype declaration. This warning is issued even if the
9563   //   definition itself provides a prototype. The aim is to detect
9564   //   global functions that fail to be declared in header files.
9565   const FunctionDecl *PossibleZeroParamPrototype = 0;
9566   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9567     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9568 
9569     if (PossibleZeroParamPrototype) {
9570       // We found a declaration that is not a prototype,
9571       // but that could be a zero-parameter prototype
9572       if (TypeSourceInfo *TI =
9573               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9574         TypeLoc TL = TI->getTypeLoc();
9575         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9576           Diag(PossibleZeroParamPrototype->getLocation(),
9577                diag::note_declaration_not_a_prototype)
9578             << PossibleZeroParamPrototype
9579             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9580       }
9581     }
9582   }
9583 
9584   if (FnBodyScope)
9585     PushDeclContext(FnBodyScope, FD);
9586 
9587   // Check the validity of our function parameters
9588   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9589                            /*CheckParameterNames=*/true);
9590 
9591   // Introduce our parameters into the function scope
9592   for (auto Param : FD->params()) {
9593     Param->setOwningFunction(FD);
9594 
9595     // If this has an identifier, add it to the scope stack.
9596     if (Param->getIdentifier() && FnBodyScope) {
9597       CheckShadow(FnBodyScope, Param);
9598 
9599       PushOnScopeChains(Param, FnBodyScope);
9600     }
9601   }
9602 
9603   // If we had any tags defined in the function prototype,
9604   // introduce them into the function scope.
9605   if (FnBodyScope) {
9606     for (ArrayRef<NamedDecl *>::iterator
9607              I = FD->getDeclsInPrototypeScope().begin(),
9608              E = FD->getDeclsInPrototypeScope().end();
9609          I != E; ++I) {
9610       NamedDecl *D = *I;
9611 
9612       // Some of these decls (like enums) may have been pinned to the translation unit
9613       // for lack of a real context earlier. If so, remove from the translation unit
9614       // and reattach to the current context.
9615       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9616         // Is the decl actually in the context?
9617         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9618           if (DI == D) {
9619             Context.getTranslationUnitDecl()->removeDecl(D);
9620             break;
9621           }
9622         }
9623         // Either way, reassign the lexical decl context to our FunctionDecl.
9624         D->setLexicalDeclContext(CurContext);
9625       }
9626 
9627       // If the decl has a non-null name, make accessible in the current scope.
9628       if (!D->getName().empty())
9629         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9630 
9631       // Similarly, dive into enums and fish their constants out, making them
9632       // accessible in this scope.
9633       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9634         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9635                EE = ED->enumerator_end(); EI != EE; ++EI)
9636           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9637       }
9638     }
9639   }
9640 
9641   // Ensure that the function's exception specification is instantiated.
9642   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9643     ResolveExceptionSpec(D->getLocation(), FPT);
9644 
9645   // Checking attributes of current function definition
9646   // dllimport attribute.
9647   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9648   if (DA && (!FD->hasAttr<DLLExportAttr>())) {
9649     // dllimport attribute cannot be directly applied to definition.
9650     // Microsoft accepts dllimport for functions defined within class scope.
9651     if (!DA->isInherited() &&
9652         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9653       Diag(FD->getLocation(),
9654            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9655         << DA;
9656       FD->setInvalidDecl();
9657       return D;
9658     }
9659 
9660     // Visual C++ appears to not think this is an issue, so only issue
9661     // a warning when Microsoft extensions are disabled.
9662     if (!LangOpts.MicrosoftExt) {
9663       // If a symbol previously declared dllimport is later defined, the
9664       // attribute is ignored in subsequent references, and a warning is
9665       // emitted.
9666       Diag(FD->getLocation(),
9667            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9668         << FD << DA;
9669     }
9670   }
9671   // We want to attach documentation to original Decl (which might be
9672   // a function template).
9673   ActOnDocumentableDecl(D);
9674   return D;
9675 }
9676 
9677 /// \brief Given the set of return statements within a function body,
9678 /// compute the variables that are subject to the named return value
9679 /// optimization.
9680 ///
9681 /// Each of the variables that is subject to the named return value
9682 /// optimization will be marked as NRVO variables in the AST, and any
9683 /// return statement that has a marked NRVO variable as its NRVO candidate can
9684 /// use the named return value optimization.
9685 ///
9686 /// This function applies a very simplistic algorithm for NRVO: if every return
9687 /// statement in the function has the same NRVO candidate, that candidate is
9688 /// the NRVO variable.
9689 ///
9690 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9691 /// statements and the lifetimes of the NRVO candidates. We should be able to
9692 /// find a maximal set of NRVO variables.
9693 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9694   ReturnStmt **Returns = Scope->Returns.data();
9695 
9696   const VarDecl *NRVOCandidate = 0;
9697   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9698     if (!Returns[I]->getNRVOCandidate())
9699       return;
9700 
9701     if (!NRVOCandidate)
9702       NRVOCandidate = Returns[I]->getNRVOCandidate();
9703     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9704       return;
9705   }
9706 
9707   if (NRVOCandidate)
9708     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9709 }
9710 
9711 bool Sema::canSkipFunctionBody(Decl *D) {
9712   // We cannot skip the body of a function (or function template) which is
9713   // constexpr, since we may need to evaluate its body in order to parse the
9714   // rest of the file.
9715   // We cannot skip the body of a function with an undeduced return type,
9716   // because any callers of that function need to know the type.
9717   if (const FunctionDecl *FD = D->getAsFunction())
9718     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
9719       return false;
9720   return Consumer.shouldSkipFunctionBody(D);
9721 }
9722 
9723 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9724   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9725     FD->setHasSkippedBody();
9726   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9727     MD->setHasSkippedBody();
9728   return ActOnFinishFunctionBody(Decl, 0);
9729 }
9730 
9731 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9732   return ActOnFinishFunctionBody(D, BodyArg, false);
9733 }
9734 
9735 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9736                                     bool IsInstantiation) {
9737   FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
9738 
9739   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9740   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9741 
9742   if (FD) {
9743     FD->setBody(Body);
9744 
9745     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9746         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
9747       // If the function has a deduced result type but contains no 'return'
9748       // statements, the result type as written must be exactly 'auto', and
9749       // the deduced result type is 'void'.
9750       if (!FD->getReturnType()->getAs<AutoType>()) {
9751         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9752             << FD->getReturnType();
9753         FD->setInvalidDecl();
9754       } else {
9755         // Substitute 'void' for the 'auto' in the type.
9756         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9757             IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
9758         Context.adjustDeducedFunctionResultType(
9759             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9760       }
9761     }
9762 
9763     // The only way to be included in UndefinedButUsed is if there is an
9764     // ODR use before the definition. Avoid the expensive map lookup if this
9765     // is the first declaration.
9766     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9767       if (!FD->isExternallyVisible())
9768         UndefinedButUsed.erase(FD);
9769       else if (FD->isInlined() &&
9770                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9771                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9772         UndefinedButUsed.erase(FD);
9773     }
9774 
9775     // If the function implicitly returns zero (like 'main') or is naked,
9776     // don't complain about missing return statements.
9777     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9778       WP.disableCheckFallThrough();
9779 
9780     // MSVC permits the use of pure specifier (=0) on function definition,
9781     // defined at class scope, warn about this non-standard construct.
9782     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9783       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9784 
9785     if (!FD->isInvalidDecl()) {
9786       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9787       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9788                                              FD->getReturnType(), FD);
9789 
9790       // If this is a constructor, we need a vtable.
9791       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9792         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9793 
9794       // Try to apply the named return value optimization. We have to check
9795       // if we can do this here because lambdas keep return statements around
9796       // to deduce an implicit return type.
9797       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
9798           !FD->isDependentContext())
9799         computeNRVO(Body, getCurFunction());
9800     }
9801 
9802     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9803            "Function parsing confused");
9804   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9805     assert(MD == getCurMethodDecl() && "Method parsing confused");
9806     MD->setBody(Body);
9807     if (!MD->isInvalidDecl()) {
9808       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9809       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9810                                              MD->getReturnType(), MD);
9811 
9812       if (Body)
9813         computeNRVO(Body, getCurFunction());
9814     }
9815     if (getCurFunction()->ObjCShouldCallSuper) {
9816       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9817         << MD->getSelector().getAsString();
9818       getCurFunction()->ObjCShouldCallSuper = false;
9819     }
9820     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9821       const ObjCMethodDecl *InitMethod = 0;
9822       bool isDesignated =
9823           MD->isDesignatedInitializerForTheInterface(&InitMethod);
9824       assert(isDesignated && InitMethod);
9825       (void)isDesignated;
9826       Diag(MD->getLocation(),
9827            diag::warn_objc_designated_init_missing_super_call);
9828       Diag(InitMethod->getLocation(),
9829            diag::note_objc_designated_init_marked_here);
9830       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9831     }
9832     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9833       Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9834       getCurFunction()->ObjCWarnForNoInitDelegation = false;
9835     }
9836   } else {
9837     return 0;
9838   }
9839 
9840   assert(!getCurFunction()->ObjCShouldCallSuper &&
9841          "This should only be set for ObjC methods, which should have been "
9842          "handled in the block above.");
9843 
9844   // Verify and clean out per-function state.
9845   if (Body) {
9846     // C++ constructors that have function-try-blocks can't have return
9847     // statements in the handlers of that block. (C++ [except.handle]p14)
9848     // Verify this.
9849     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9850       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9851 
9852     // Verify that gotos and switch cases don't jump into scopes illegally.
9853     if (getCurFunction()->NeedsScopeChecking() &&
9854         !dcl->isInvalidDecl() &&
9855         !hasAnyUnrecoverableErrorsInThisFunction() &&
9856         !PP.isCodeCompletionEnabled())
9857       DiagnoseInvalidJumps(Body);
9858 
9859     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9860       if (!Destructor->getParent()->isDependentType())
9861         CheckDestructor(Destructor);
9862 
9863       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9864                                              Destructor->getParent());
9865     }
9866 
9867     // If any errors have occurred, clear out any temporaries that may have
9868     // been leftover. This ensures that these temporaries won't be picked up for
9869     // deletion in some later function.
9870     if (PP.getDiagnostics().hasErrorOccurred() ||
9871         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9872       DiscardCleanupsInEvaluationContext();
9873     }
9874     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9875         !isa<FunctionTemplateDecl>(dcl)) {
9876       // Since the body is valid, issue any analysis-based warnings that are
9877       // enabled.
9878       ActivePolicy = &WP;
9879     }
9880 
9881     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9882         (!CheckConstexprFunctionDecl(FD) ||
9883          !CheckConstexprFunctionBody(FD, Body)))
9884       FD->setInvalidDecl();
9885 
9886     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9887     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9888     assert(MaybeODRUseExprs.empty() &&
9889            "Leftover expressions for odr-use checking");
9890   }
9891 
9892   if (!IsInstantiation)
9893     PopDeclContext();
9894 
9895   PopFunctionScopeInfo(ActivePolicy, dcl);
9896   // If any errors have occurred, clear out any temporaries that may have
9897   // been leftover. This ensures that these temporaries won't be picked up for
9898   // deletion in some later function.
9899   if (getDiagnostics().hasErrorOccurred()) {
9900     DiscardCleanupsInEvaluationContext();
9901   }
9902 
9903   return dcl;
9904 }
9905 
9906 
9907 /// When we finish delayed parsing of an attribute, we must attach it to the
9908 /// relevant Decl.
9909 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9910                                        ParsedAttributes &Attrs) {
9911   // Always attach attributes to the underlying decl.
9912   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9913     D = TD->getTemplatedDecl();
9914   ProcessDeclAttributeList(S, D, Attrs.getList());
9915 
9916   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9917     if (Method->isStatic())
9918       checkThisInStaticMemberFunctionAttributes(Method);
9919 }
9920 
9921 
9922 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9923 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9924 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9925                                           IdentifierInfo &II, Scope *S) {
9926   // Before we produce a declaration for an implicitly defined
9927   // function, see whether there was a locally-scoped declaration of
9928   // this name as a function or variable. If so, use that
9929   // (non-visible) declaration, and complain about it.
9930   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9931     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9932     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9933     return ExternCPrev;
9934   }
9935 
9936   // Extension in C99.  Legal in C90, but warn about it.
9937   unsigned diag_id;
9938   if (II.getName().startswith("__builtin_"))
9939     diag_id = diag::warn_builtin_unknown;
9940   else if (getLangOpts().C99)
9941     diag_id = diag::ext_implicit_function_decl;
9942   else
9943     diag_id = diag::warn_implicit_function_decl;
9944   Diag(Loc, diag_id) << &II;
9945 
9946   // Because typo correction is expensive, only do it if the implicit
9947   // function declaration is going to be treated as an error.
9948   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9949     TypoCorrection Corrected;
9950     DeclFilterCCC<FunctionDecl> Validator;
9951     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9952                                       LookupOrdinaryName, S, 0, Validator)))
9953       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9954                    /*ErrorRecovery*/false);
9955   }
9956 
9957   // Set a Declarator for the implicit definition: int foo();
9958   const char *Dummy;
9959   AttributeFactory attrFactory;
9960   DeclSpec DS(attrFactory);
9961   unsigned DiagID;
9962   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9963                                   Context.getPrintingPolicy());
9964   (void)Error; // Silence warning.
9965   assert(!Error && "Error setting up implicit decl!");
9966   SourceLocation NoLoc;
9967   Declarator D(DS, Declarator::BlockContext);
9968   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9969                                              /*IsAmbiguous=*/false,
9970                                              /*RParenLoc=*/NoLoc,
9971                                              /*ArgInfo=*/0,
9972                                              /*NumArgs=*/0,
9973                                              /*EllipsisLoc=*/NoLoc,
9974                                              /*RParenLoc=*/NoLoc,
9975                                              /*TypeQuals=*/0,
9976                                              /*RefQualifierIsLvalueRef=*/true,
9977                                              /*RefQualifierLoc=*/NoLoc,
9978                                              /*ConstQualifierLoc=*/NoLoc,
9979                                              /*VolatileQualifierLoc=*/NoLoc,
9980                                              /*MutableLoc=*/NoLoc,
9981                                              EST_None,
9982                                              /*ESpecLoc=*/NoLoc,
9983                                              /*Exceptions=*/0,
9984                                              /*ExceptionRanges=*/0,
9985                                              /*NumExceptions=*/0,
9986                                              /*NoexceptExpr=*/0,
9987                                              Loc, Loc, D),
9988                 DS.getAttributes(),
9989                 SourceLocation());
9990   D.SetIdentifier(&II, Loc);
9991 
9992   // Insert this function into translation-unit scope.
9993 
9994   DeclContext *PrevDC = CurContext;
9995   CurContext = Context.getTranslationUnitDecl();
9996 
9997   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9998   FD->setImplicit();
9999 
10000   CurContext = PrevDC;
10001 
10002   AddKnownFunctionAttributes(FD);
10003 
10004   return FD;
10005 }
10006 
10007 /// \brief Adds any function attributes that we know a priori based on
10008 /// the declaration of this function.
10009 ///
10010 /// These attributes can apply both to implicitly-declared builtins
10011 /// (like __builtin___printf_chk) or to library-declared functions
10012 /// like NSLog or printf.
10013 ///
10014 /// We need to check for duplicate attributes both here and where user-written
10015 /// attributes are applied to declarations.
10016 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10017   if (FD->isInvalidDecl())
10018     return;
10019 
10020   // If this is a built-in function, map its builtin attributes to
10021   // actual attributes.
10022   if (unsigned BuiltinID = FD->getBuiltinID()) {
10023     // Handle printf-formatting attributes.
10024     unsigned FormatIdx;
10025     bool HasVAListArg;
10026     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10027       if (!FD->hasAttr<FormatAttr>()) {
10028         const char *fmt = "printf";
10029         unsigned int NumParams = FD->getNumParams();
10030         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10031             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10032           fmt = "NSString";
10033         FD->addAttr(FormatAttr::CreateImplicit(Context,
10034                                                &Context.Idents.get(fmt),
10035                                                FormatIdx+1,
10036                                                HasVAListArg ? 0 : FormatIdx+2,
10037                                                FD->getLocation()));
10038       }
10039     }
10040     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10041                                              HasVAListArg)) {
10042      if (!FD->hasAttr<FormatAttr>())
10043        FD->addAttr(FormatAttr::CreateImplicit(Context,
10044                                               &Context.Idents.get("scanf"),
10045                                               FormatIdx+1,
10046                                               HasVAListArg ? 0 : FormatIdx+2,
10047                                               FD->getLocation()));
10048     }
10049 
10050     // Mark const if we don't care about errno and that is the only
10051     // thing preventing the function from being const. This allows
10052     // IRgen to use LLVM intrinsics for such functions.
10053     if (!getLangOpts().MathErrno &&
10054         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10055       if (!FD->hasAttr<ConstAttr>())
10056         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10057     }
10058 
10059     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10060         !FD->hasAttr<ReturnsTwiceAttr>())
10061       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10062                                          FD->getLocation()));
10063     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10064       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10065     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10066       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10067   }
10068 
10069   IdentifierInfo *Name = FD->getIdentifier();
10070   if (!Name)
10071     return;
10072   if ((!getLangOpts().CPlusPlus &&
10073        FD->getDeclContext()->isTranslationUnit()) ||
10074       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10075        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10076        LinkageSpecDecl::lang_c)) {
10077     // Okay: this could be a libc/libm/Objective-C function we know
10078     // about.
10079   } else
10080     return;
10081 
10082   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10083     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10084     // target-specific builtins, perhaps?
10085     if (!FD->hasAttr<FormatAttr>())
10086       FD->addAttr(FormatAttr::CreateImplicit(Context,
10087                                              &Context.Idents.get("printf"), 2,
10088                                              Name->isStr("vasprintf") ? 0 : 3,
10089                                              FD->getLocation()));
10090   }
10091 
10092   if (Name->isStr("__CFStringMakeConstantString")) {
10093     // We already have a __builtin___CFStringMakeConstantString,
10094     // but builds that use -fno-constant-cfstrings don't go through that.
10095     if (!FD->hasAttr<FormatArgAttr>())
10096       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10097                                                 FD->getLocation()));
10098   }
10099 }
10100 
10101 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10102                                     TypeSourceInfo *TInfo) {
10103   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10104   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10105 
10106   if (!TInfo) {
10107     assert(D.isInvalidType() && "no declarator info for valid type");
10108     TInfo = Context.getTrivialTypeSourceInfo(T);
10109   }
10110 
10111   // Scope manipulation handled by caller.
10112   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10113                                            D.getLocStart(),
10114                                            D.getIdentifierLoc(),
10115                                            D.getIdentifier(),
10116                                            TInfo);
10117 
10118   // Bail out immediately if we have an invalid declaration.
10119   if (D.isInvalidType()) {
10120     NewTD->setInvalidDecl();
10121     return NewTD;
10122   }
10123 
10124   if (D.getDeclSpec().isModulePrivateSpecified()) {
10125     if (CurContext->isFunctionOrMethod())
10126       Diag(NewTD->getLocation(), diag::err_module_private_local)
10127         << 2 << NewTD->getDeclName()
10128         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10129         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10130     else
10131       NewTD->setModulePrivate();
10132   }
10133 
10134   // C++ [dcl.typedef]p8:
10135   //   If the typedef declaration defines an unnamed class (or
10136   //   enum), the first typedef-name declared by the declaration
10137   //   to be that class type (or enum type) is used to denote the
10138   //   class type (or enum type) for linkage purposes only.
10139   // We need to check whether the type was declared in the declaration.
10140   switch (D.getDeclSpec().getTypeSpecType()) {
10141   case TST_enum:
10142   case TST_struct:
10143   case TST_interface:
10144   case TST_union:
10145   case TST_class: {
10146     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10147 
10148     // Do nothing if the tag is not anonymous or already has an
10149     // associated typedef (from an earlier typedef in this decl group).
10150     if (tagFromDeclSpec->getIdentifier()) break;
10151     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10152 
10153     // A well-formed anonymous tag must always be a TUK_Definition.
10154     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10155 
10156     // The type must match the tag exactly;  no qualifiers allowed.
10157     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10158       break;
10159 
10160     // If we've already computed linkage for the anonymous tag, then
10161     // adding a typedef name for the anonymous decl can change that
10162     // linkage, which might be a serious problem.  Diagnose this as
10163     // unsupported and ignore the typedef name.  TODO: we should
10164     // pursue this as a language defect and establish a formal rule
10165     // for how to handle it.
10166     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10167       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10168 
10169       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10170       tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10171                                           getLangOpts());
10172 
10173       llvm::SmallString<40> textToInsert;
10174       textToInsert += ' ';
10175       textToInsert += D.getIdentifier()->getName();
10176       Diag(tagLoc, diag::note_typedef_changes_linkage)
10177         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10178       break;
10179     }
10180 
10181     // Otherwise, set this is the anon-decl typedef for the tag.
10182     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10183     break;
10184   }
10185 
10186   default:
10187     break;
10188   }
10189 
10190   return NewTD;
10191 }
10192 
10193 
10194 /// \brief Check that this is a valid underlying type for an enum declaration.
10195 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10196   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10197   QualType T = TI->getType();
10198 
10199   if (T->isDependentType())
10200     return false;
10201 
10202   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10203     if (BT->isInteger())
10204       return false;
10205 
10206   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10207   return true;
10208 }
10209 
10210 /// Check whether this is a valid redeclaration of a previous enumeration.
10211 /// \return true if the redeclaration was invalid.
10212 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10213                                   QualType EnumUnderlyingTy,
10214                                   const EnumDecl *Prev) {
10215   bool IsFixed = !EnumUnderlyingTy.isNull();
10216 
10217   if (IsScoped != Prev->isScoped()) {
10218     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10219       << Prev->isScoped();
10220     Diag(Prev->getLocation(), diag::note_previous_declaration);
10221     return true;
10222   }
10223 
10224   if (IsFixed && Prev->isFixed()) {
10225     if (!EnumUnderlyingTy->isDependentType() &&
10226         !Prev->getIntegerType()->isDependentType() &&
10227         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10228                                         Prev->getIntegerType())) {
10229       // TODO: Highlight the underlying type of the redeclaration.
10230       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10231         << EnumUnderlyingTy << Prev->getIntegerType();
10232       Diag(Prev->getLocation(), diag::note_previous_declaration)
10233           << Prev->getIntegerTypeRange();
10234       return true;
10235     }
10236   } else if (IsFixed != Prev->isFixed()) {
10237     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10238       << Prev->isFixed();
10239     Diag(Prev->getLocation(), diag::note_previous_declaration);
10240     return true;
10241   }
10242 
10243   return false;
10244 }
10245 
10246 /// \brief Get diagnostic %select index for tag kind for
10247 /// redeclaration diagnostic message.
10248 /// WARNING: Indexes apply to particular diagnostics only!
10249 ///
10250 /// \returns diagnostic %select index.
10251 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10252   switch (Tag) {
10253   case TTK_Struct: return 0;
10254   case TTK_Interface: return 1;
10255   case TTK_Class:  return 2;
10256   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10257   }
10258 }
10259 
10260 /// \brief Determine if tag kind is a class-key compatible with
10261 /// class for redeclaration (class, struct, or __interface).
10262 ///
10263 /// \returns true iff the tag kind is compatible.
10264 static bool isClassCompatTagKind(TagTypeKind Tag)
10265 {
10266   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10267 }
10268 
10269 /// \brief Determine whether a tag with a given kind is acceptable
10270 /// as a redeclaration of the given tag declaration.
10271 ///
10272 /// \returns true if the new tag kind is acceptable, false otherwise.
10273 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10274                                         TagTypeKind NewTag, bool isDefinition,
10275                                         SourceLocation NewTagLoc,
10276                                         const IdentifierInfo &Name) {
10277   // C++ [dcl.type.elab]p3:
10278   //   The class-key or enum keyword present in the
10279   //   elaborated-type-specifier shall agree in kind with the
10280   //   declaration to which the name in the elaborated-type-specifier
10281   //   refers. This rule also applies to the form of
10282   //   elaborated-type-specifier that declares a class-name or
10283   //   friend class since it can be construed as referring to the
10284   //   definition of the class. Thus, in any
10285   //   elaborated-type-specifier, the enum keyword shall be used to
10286   //   refer to an enumeration (7.2), the union class-key shall be
10287   //   used to refer to a union (clause 9), and either the class or
10288   //   struct class-key shall be used to refer to a class (clause 9)
10289   //   declared using the class or struct class-key.
10290   TagTypeKind OldTag = Previous->getTagKind();
10291   if (!isDefinition || !isClassCompatTagKind(NewTag))
10292     if (OldTag == NewTag)
10293       return true;
10294 
10295   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10296     // Warn about the struct/class tag mismatch.
10297     bool isTemplate = false;
10298     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10299       isTemplate = Record->getDescribedClassTemplate();
10300 
10301     if (!ActiveTemplateInstantiations.empty()) {
10302       // In a template instantiation, do not offer fix-its for tag mismatches
10303       // since they usually mess up the template instead of fixing the problem.
10304       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10305         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10306         << getRedeclDiagFromTagKind(OldTag);
10307       return true;
10308     }
10309 
10310     if (isDefinition) {
10311       // On definitions, check previous tags and issue a fix-it for each
10312       // one that doesn't match the current tag.
10313       if (Previous->getDefinition()) {
10314         // Don't suggest fix-its for redefinitions.
10315         return true;
10316       }
10317 
10318       bool previousMismatch = false;
10319       for (auto I : Previous->redecls()) {
10320         if (I->getTagKind() != NewTag) {
10321           if (!previousMismatch) {
10322             previousMismatch = true;
10323             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10324               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10325               << getRedeclDiagFromTagKind(I->getTagKind());
10326           }
10327           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10328             << getRedeclDiagFromTagKind(NewTag)
10329             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10330                  TypeWithKeyword::getTagTypeKindName(NewTag));
10331         }
10332       }
10333       return true;
10334     }
10335 
10336     // Check for a previous definition.  If current tag and definition
10337     // are same type, do nothing.  If no definition, but disagree with
10338     // with previous tag type, give a warning, but no fix-it.
10339     const TagDecl *Redecl = Previous->getDefinition() ?
10340                             Previous->getDefinition() : Previous;
10341     if (Redecl->getTagKind() == NewTag) {
10342       return true;
10343     }
10344 
10345     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10346       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10347       << getRedeclDiagFromTagKind(OldTag);
10348     Diag(Redecl->getLocation(), diag::note_previous_use);
10349 
10350     // If there is a previous definition, suggest a fix-it.
10351     if (Previous->getDefinition()) {
10352         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10353           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10354           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10355                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10356     }
10357 
10358     return true;
10359   }
10360   return false;
10361 }
10362 
10363 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10364 /// former case, Name will be non-null.  In the later case, Name will be null.
10365 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10366 /// reference/declaration/definition of a tag.
10367 ///
10368 /// IsTypeSpecifier is true if this is a type-specifier (or
10369 /// trailing-type-specifier) other than one in an alias-declaration.
10370 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10371                      SourceLocation KWLoc, CXXScopeSpec &SS,
10372                      IdentifierInfo *Name, SourceLocation NameLoc,
10373                      AttributeList *Attr, AccessSpecifier AS,
10374                      SourceLocation ModulePrivateLoc,
10375                      MultiTemplateParamsArg TemplateParameterLists,
10376                      bool &OwnedDecl, bool &IsDependent,
10377                      SourceLocation ScopedEnumKWLoc,
10378                      bool ScopedEnumUsesClassTag,
10379                      TypeResult UnderlyingType,
10380                      bool IsTypeSpecifier) {
10381   // If this is not a definition, it must have a name.
10382   IdentifierInfo *OrigName = Name;
10383   assert((Name != 0 || TUK == TUK_Definition) &&
10384          "Nameless record must be a definition!");
10385   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10386 
10387   OwnedDecl = false;
10388   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10389   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10390 
10391   // FIXME: Check explicit specializations more carefully.
10392   bool isExplicitSpecialization = false;
10393   bool Invalid = false;
10394 
10395   // We only need to do this matching if we have template parameters
10396   // or a scope specifier, which also conveniently avoids this work
10397   // for non-C++ cases.
10398   if (TemplateParameterLists.size() > 0 ||
10399       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10400     if (TemplateParameterList *TemplateParams =
10401             MatchTemplateParametersToScopeSpecifier(
10402                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10403                 isExplicitSpecialization, Invalid)) {
10404       if (Kind == TTK_Enum) {
10405         Diag(KWLoc, diag::err_enum_template);
10406         return 0;
10407       }
10408 
10409       if (TemplateParams->size() > 0) {
10410         // This is a declaration or definition of a class template (which may
10411         // be a member of another template).
10412 
10413         if (Invalid)
10414           return 0;
10415 
10416         OwnedDecl = false;
10417         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10418                                                SS, Name, NameLoc, Attr,
10419                                                TemplateParams, AS,
10420                                                ModulePrivateLoc,
10421                                                TemplateParameterLists.size()-1,
10422                                                TemplateParameterLists.data());
10423         return Result.get();
10424       } else {
10425         // The "template<>" header is extraneous.
10426         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10427           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10428         isExplicitSpecialization = true;
10429       }
10430     }
10431   }
10432 
10433   // Figure out the underlying type if this a enum declaration. We need to do
10434   // this early, because it's needed to detect if this is an incompatible
10435   // redeclaration.
10436   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10437 
10438   if (Kind == TTK_Enum) {
10439     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10440       // No underlying type explicitly specified, or we failed to parse the
10441       // type, default to int.
10442       EnumUnderlying = Context.IntTy.getTypePtr();
10443     else if (UnderlyingType.get()) {
10444       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10445       // integral type; any cv-qualification is ignored.
10446       TypeSourceInfo *TI = 0;
10447       GetTypeFromParser(UnderlyingType.get(), &TI);
10448       EnumUnderlying = TI;
10449 
10450       if (CheckEnumUnderlyingType(TI))
10451         // Recover by falling back to int.
10452         EnumUnderlying = Context.IntTy.getTypePtr();
10453 
10454       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10455                                           UPPC_FixedUnderlyingType))
10456         EnumUnderlying = Context.IntTy.getTypePtr();
10457 
10458     } else if (getLangOpts().MSVCCompat)
10459       // Microsoft enums are always of int type.
10460       EnumUnderlying = Context.IntTy.getTypePtr();
10461   }
10462 
10463   DeclContext *SearchDC = CurContext;
10464   DeclContext *DC = CurContext;
10465   bool isStdBadAlloc = false;
10466 
10467   RedeclarationKind Redecl = ForRedeclaration;
10468   if (TUK == TUK_Friend || TUK == TUK_Reference)
10469     Redecl = NotForRedeclaration;
10470 
10471   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10472   bool FriendSawTagOutsideEnclosingNamespace = false;
10473   if (Name && SS.isNotEmpty()) {
10474     // We have a nested-name tag ('struct foo::bar').
10475 
10476     // Check for invalid 'foo::'.
10477     if (SS.isInvalid()) {
10478       Name = 0;
10479       goto CreateNewDecl;
10480     }
10481 
10482     // If this is a friend or a reference to a class in a dependent
10483     // context, don't try to make a decl for it.
10484     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10485       DC = computeDeclContext(SS, false);
10486       if (!DC) {
10487         IsDependent = true;
10488         return 0;
10489       }
10490     } else {
10491       DC = computeDeclContext(SS, true);
10492       if (!DC) {
10493         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10494           << SS.getRange();
10495         return 0;
10496       }
10497     }
10498 
10499     if (RequireCompleteDeclContext(SS, DC))
10500       return 0;
10501 
10502     SearchDC = DC;
10503     // Look-up name inside 'foo::'.
10504     LookupQualifiedName(Previous, DC);
10505 
10506     if (Previous.isAmbiguous())
10507       return 0;
10508 
10509     if (Previous.empty()) {
10510       // Name lookup did not find anything. However, if the
10511       // nested-name-specifier refers to the current instantiation,
10512       // and that current instantiation has any dependent base
10513       // classes, we might find something at instantiation time: treat
10514       // this as a dependent elaborated-type-specifier.
10515       // But this only makes any sense for reference-like lookups.
10516       if (Previous.wasNotFoundInCurrentInstantiation() &&
10517           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10518         IsDependent = true;
10519         return 0;
10520       }
10521 
10522       // A tag 'foo::bar' must already exist.
10523       Diag(NameLoc, diag::err_not_tag_in_scope)
10524         << Kind << Name << DC << SS.getRange();
10525       Name = 0;
10526       Invalid = true;
10527       goto CreateNewDecl;
10528     }
10529   } else if (Name) {
10530     // If this is a named struct, check to see if there was a previous forward
10531     // declaration or definition.
10532     // FIXME: We're looking into outer scopes here, even when we
10533     // shouldn't be. Doing so can result in ambiguities that we
10534     // shouldn't be diagnosing.
10535     LookupName(Previous, S);
10536 
10537     // When declaring or defining a tag, ignore ambiguities introduced
10538     // by types using'ed into this scope.
10539     if (Previous.isAmbiguous() &&
10540         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10541       LookupResult::Filter F = Previous.makeFilter();
10542       while (F.hasNext()) {
10543         NamedDecl *ND = F.next();
10544         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10545           F.erase();
10546       }
10547       F.done();
10548     }
10549 
10550     // C++11 [namespace.memdef]p3:
10551     //   If the name in a friend declaration is neither qualified nor
10552     //   a template-id and the declaration is a function or an
10553     //   elaborated-type-specifier, the lookup to determine whether
10554     //   the entity has been previously declared shall not consider
10555     //   any scopes outside the innermost enclosing namespace.
10556     //
10557     // Does it matter that this should be by scope instead of by
10558     // semantic context?
10559     if (!Previous.empty() && TUK == TUK_Friend) {
10560       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10561       LookupResult::Filter F = Previous.makeFilter();
10562       while (F.hasNext()) {
10563         NamedDecl *ND = F.next();
10564         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10565         if (DC->isFileContext() &&
10566             !EnclosingNS->Encloses(ND->getDeclContext())) {
10567           F.erase();
10568           FriendSawTagOutsideEnclosingNamespace = true;
10569         }
10570       }
10571       F.done();
10572     }
10573 
10574     // Note:  there used to be some attempt at recovery here.
10575     if (Previous.isAmbiguous())
10576       return 0;
10577 
10578     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10579       // FIXME: This makes sure that we ignore the contexts associated
10580       // with C structs, unions, and enums when looking for a matching
10581       // tag declaration or definition. See the similar lookup tweak
10582       // in Sema::LookupName; is there a better way to deal with this?
10583       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10584         SearchDC = SearchDC->getParent();
10585     }
10586   } else if (S->isFunctionPrototypeScope()) {
10587     // If this is an enum declaration in function prototype scope, set its
10588     // initial context to the translation unit.
10589     // FIXME: [citation needed]
10590     SearchDC = Context.getTranslationUnitDecl();
10591   }
10592 
10593   if (Previous.isSingleResult() &&
10594       Previous.getFoundDecl()->isTemplateParameter()) {
10595     // Maybe we will complain about the shadowed template parameter.
10596     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10597     // Just pretend that we didn't see the previous declaration.
10598     Previous.clear();
10599   }
10600 
10601   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10602       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10603     // This is a declaration of or a reference to "std::bad_alloc".
10604     isStdBadAlloc = true;
10605 
10606     if (Previous.empty() && StdBadAlloc) {
10607       // std::bad_alloc has been implicitly declared (but made invisible to
10608       // name lookup). Fill in this implicit declaration as the previous
10609       // declaration, so that the declarations get chained appropriately.
10610       Previous.addDecl(getStdBadAlloc());
10611     }
10612   }
10613 
10614   // If we didn't find a previous declaration, and this is a reference
10615   // (or friend reference), move to the correct scope.  In C++, we
10616   // also need to do a redeclaration lookup there, just in case
10617   // there's a shadow friend decl.
10618   if (Name && Previous.empty() &&
10619       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10620     if (Invalid) goto CreateNewDecl;
10621     assert(SS.isEmpty());
10622 
10623     if (TUK == TUK_Reference) {
10624       // C++ [basic.scope.pdecl]p5:
10625       //   -- for an elaborated-type-specifier of the form
10626       //
10627       //          class-key identifier
10628       //
10629       //      if the elaborated-type-specifier is used in the
10630       //      decl-specifier-seq or parameter-declaration-clause of a
10631       //      function defined in namespace scope, the identifier is
10632       //      declared as a class-name in the namespace that contains
10633       //      the declaration; otherwise, except as a friend
10634       //      declaration, the identifier is declared in the smallest
10635       //      non-class, non-function-prototype scope that contains the
10636       //      declaration.
10637       //
10638       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10639       // C structs and unions.
10640       //
10641       // It is an error in C++ to declare (rather than define) an enum
10642       // type, including via an elaborated type specifier.  We'll
10643       // diagnose that later; for now, declare the enum in the same
10644       // scope as we would have picked for any other tag type.
10645       //
10646       // GNU C also supports this behavior as part of its incomplete
10647       // enum types extension, while GNU C++ does not.
10648       //
10649       // Find the context where we'll be declaring the tag.
10650       // FIXME: We would like to maintain the current DeclContext as the
10651       // lexical context,
10652       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10653         SearchDC = SearchDC->getParent();
10654 
10655       // Find the scope where we'll be declaring the tag.
10656       while (S->isClassScope() ||
10657              (getLangOpts().CPlusPlus &&
10658               S->isFunctionPrototypeScope()) ||
10659              ((S->getFlags() & Scope::DeclScope) == 0) ||
10660              (S->getEntity() && S->getEntity()->isTransparentContext()))
10661         S = S->getParent();
10662     } else {
10663       assert(TUK == TUK_Friend);
10664       // C++ [namespace.memdef]p3:
10665       //   If a friend declaration in a non-local class first declares a
10666       //   class or function, the friend class or function is a member of
10667       //   the innermost enclosing namespace.
10668       SearchDC = SearchDC->getEnclosingNamespaceContext();
10669     }
10670 
10671     // In C++, we need to do a redeclaration lookup to properly
10672     // diagnose some problems.
10673     if (getLangOpts().CPlusPlus) {
10674       Previous.setRedeclarationKind(ForRedeclaration);
10675       LookupQualifiedName(Previous, SearchDC);
10676     }
10677   }
10678 
10679   if (!Previous.empty()) {
10680     NamedDecl *PrevDecl = Previous.getFoundDecl();
10681     NamedDecl *DirectPrevDecl =
10682         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
10683 
10684     // It's okay to have a tag decl in the same scope as a typedef
10685     // which hides a tag decl in the same scope.  Finding this
10686     // insanity with a redeclaration lookup can only actually happen
10687     // in C++.
10688     //
10689     // This is also okay for elaborated-type-specifiers, which is
10690     // technically forbidden by the current standard but which is
10691     // okay according to the likely resolution of an open issue;
10692     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10693     if (getLangOpts().CPlusPlus) {
10694       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10695         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10696           TagDecl *Tag = TT->getDecl();
10697           if (Tag->getDeclName() == Name &&
10698               Tag->getDeclContext()->getRedeclContext()
10699                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10700             PrevDecl = Tag;
10701             Previous.clear();
10702             Previous.addDecl(Tag);
10703             Previous.resolveKind();
10704           }
10705         }
10706       }
10707     }
10708 
10709     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10710       // If this is a use of a previous tag, or if the tag is already declared
10711       // in the same scope (so that the definition/declaration completes or
10712       // rementions the tag), reuse the decl.
10713       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10714           isDeclInScope(DirectPrevDecl, SearchDC, S,
10715                         SS.isNotEmpty() || isExplicitSpecialization)) {
10716         // Make sure that this wasn't declared as an enum and now used as a
10717         // struct or something similar.
10718         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10719                                           TUK == TUK_Definition, KWLoc,
10720                                           *Name)) {
10721           bool SafeToContinue
10722             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10723                Kind != TTK_Enum);
10724           if (SafeToContinue)
10725             Diag(KWLoc, diag::err_use_with_wrong_tag)
10726               << Name
10727               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10728                                               PrevTagDecl->getKindName());
10729           else
10730             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10731           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10732 
10733           if (SafeToContinue)
10734             Kind = PrevTagDecl->getTagKind();
10735           else {
10736             // Recover by making this an anonymous redefinition.
10737             Name = 0;
10738             Previous.clear();
10739             Invalid = true;
10740           }
10741         }
10742 
10743         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10744           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10745 
10746           // If this is an elaborated-type-specifier for a scoped enumeration,
10747           // the 'class' keyword is not necessary and not permitted.
10748           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10749             if (ScopedEnum)
10750               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10751                 << PrevEnum->isScoped()
10752                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10753             return PrevTagDecl;
10754           }
10755 
10756           QualType EnumUnderlyingTy;
10757           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10758             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
10759           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10760             EnumUnderlyingTy = QualType(T, 0);
10761 
10762           // All conflicts with previous declarations are recovered by
10763           // returning the previous declaration, unless this is a definition,
10764           // in which case we want the caller to bail out.
10765           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10766                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10767             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10768         }
10769 
10770         // C++11 [class.mem]p1:
10771         //   A member shall not be declared twice in the member-specification,
10772         //   except that a nested class or member class template can be declared
10773         //   and then later defined.
10774         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10775             S->isDeclScope(PrevDecl)) {
10776           Diag(NameLoc, diag::ext_member_redeclared);
10777           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10778         }
10779 
10780         if (!Invalid) {
10781           // If this is a use, just return the declaration we found.
10782 
10783           // FIXME: In the future, return a variant or some other clue
10784           // for the consumer of this Decl to know it doesn't own it.
10785           // For our current ASTs this shouldn't be a problem, but will
10786           // need to be changed with DeclGroups.
10787           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10788                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10789             return PrevTagDecl;
10790 
10791           // Diagnose attempts to redefine a tag.
10792           if (TUK == TUK_Definition) {
10793             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10794               // If we're defining a specialization and the previous definition
10795               // is from an implicit instantiation, don't emit an error
10796               // here; we'll catch this in the general case below.
10797               bool IsExplicitSpecializationAfterInstantiation = false;
10798               if (isExplicitSpecialization) {
10799                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10800                   IsExplicitSpecializationAfterInstantiation =
10801                     RD->getTemplateSpecializationKind() !=
10802                     TSK_ExplicitSpecialization;
10803                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10804                   IsExplicitSpecializationAfterInstantiation =
10805                     ED->getTemplateSpecializationKind() !=
10806                     TSK_ExplicitSpecialization;
10807               }
10808 
10809               if (!IsExplicitSpecializationAfterInstantiation) {
10810                 // A redeclaration in function prototype scope in C isn't
10811                 // visible elsewhere, so merely issue a warning.
10812                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10813                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10814                 else
10815                   Diag(NameLoc, diag::err_redefinition) << Name;
10816                 Diag(Def->getLocation(), diag::note_previous_definition);
10817                 // If this is a redefinition, recover by making this
10818                 // struct be anonymous, which will make any later
10819                 // references get the previous definition.
10820                 Name = 0;
10821                 Previous.clear();
10822                 Invalid = true;
10823               }
10824             } else {
10825               // If the type is currently being defined, complain
10826               // about a nested redefinition.
10827               const TagType *Tag
10828                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10829               if (Tag->isBeingDefined()) {
10830                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10831                 Diag(PrevTagDecl->getLocation(),
10832                      diag::note_previous_definition);
10833                 Name = 0;
10834                 Previous.clear();
10835                 Invalid = true;
10836               }
10837             }
10838 
10839             // Okay, this is definition of a previously declared or referenced
10840             // tag PrevDecl. We're going to create a new Decl for it.
10841           }
10842         }
10843         // If we get here we have (another) forward declaration or we
10844         // have a definition.  Just create a new decl.
10845 
10846       } else {
10847         // If we get here, this is a definition of a new tag type in a nested
10848         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10849         // new decl/type.  We set PrevDecl to NULL so that the entities
10850         // have distinct types.
10851         Previous.clear();
10852       }
10853       // If we get here, we're going to create a new Decl. If PrevDecl
10854       // is non-NULL, it's a definition of the tag declared by
10855       // PrevDecl. If it's NULL, we have a new definition.
10856 
10857 
10858     // Otherwise, PrevDecl is not a tag, but was found with tag
10859     // lookup.  This is only actually possible in C++, where a few
10860     // things like templates still live in the tag namespace.
10861     } else {
10862       // Use a better diagnostic if an elaborated-type-specifier
10863       // found the wrong kind of type on the first
10864       // (non-redeclaration) lookup.
10865       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10866           !Previous.isForRedeclaration()) {
10867         unsigned Kind = 0;
10868         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10869         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10870         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10871         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10872         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10873         Invalid = true;
10874 
10875       // Otherwise, only diagnose if the declaration is in scope.
10876       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10877                                 SS.isNotEmpty() || isExplicitSpecialization)) {
10878         // do nothing
10879 
10880       // Diagnose implicit declarations introduced by elaborated types.
10881       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10882         unsigned Kind = 0;
10883         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10884         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10885         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10886         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10887         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10888         Invalid = true;
10889 
10890       // Otherwise it's a declaration.  Call out a particularly common
10891       // case here.
10892       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10893         unsigned Kind = 0;
10894         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10895         Diag(NameLoc, diag::err_tag_definition_of_typedef)
10896           << Name << Kind << TND->getUnderlyingType();
10897         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10898         Invalid = true;
10899 
10900       // Otherwise, diagnose.
10901       } else {
10902         // The tag name clashes with something else in the target scope,
10903         // issue an error and recover by making this tag be anonymous.
10904         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10905         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10906         Name = 0;
10907         Invalid = true;
10908       }
10909 
10910       // The existing declaration isn't relevant to us; we're in a
10911       // new scope, so clear out the previous declaration.
10912       Previous.clear();
10913     }
10914   }
10915 
10916 CreateNewDecl:
10917 
10918   TagDecl *PrevDecl = 0;
10919   if (Previous.isSingleResult())
10920     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10921 
10922   // If there is an identifier, use the location of the identifier as the
10923   // location of the decl, otherwise use the location of the struct/union
10924   // keyword.
10925   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10926 
10927   // Otherwise, create a new declaration. If there is a previous
10928   // declaration of the same entity, the two will be linked via
10929   // PrevDecl.
10930   TagDecl *New;
10931 
10932   bool IsForwardReference = false;
10933   if (Kind == TTK_Enum) {
10934     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10935     // enum X { A, B, C } D;    D should chain to X.
10936     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10937                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10938                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10939     // If this is an undefined enum, warn.
10940     if (TUK != TUK_Definition && !Invalid) {
10941       TagDecl *Def;
10942       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10943           cast<EnumDecl>(New)->isFixed()) {
10944         // C++0x: 7.2p2: opaque-enum-declaration.
10945         // Conflicts are diagnosed above. Do nothing.
10946       }
10947       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10948         Diag(Loc, diag::ext_forward_ref_enum_def)
10949           << New;
10950         Diag(Def->getLocation(), diag::note_previous_definition);
10951       } else {
10952         unsigned DiagID = diag::ext_forward_ref_enum;
10953         if (getLangOpts().MSVCCompat)
10954           DiagID = diag::ext_ms_forward_ref_enum;
10955         else if (getLangOpts().CPlusPlus)
10956           DiagID = diag::err_forward_ref_enum;
10957         Diag(Loc, DiagID);
10958 
10959         // If this is a forward-declared reference to an enumeration, make a
10960         // note of it; we won't actually be introducing the declaration into
10961         // the declaration context.
10962         if (TUK == TUK_Reference)
10963           IsForwardReference = true;
10964       }
10965     }
10966 
10967     if (EnumUnderlying) {
10968       EnumDecl *ED = cast<EnumDecl>(New);
10969       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10970         ED->setIntegerTypeSourceInfo(TI);
10971       else
10972         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10973       ED->setPromotionType(ED->getIntegerType());
10974     }
10975 
10976   } else {
10977     // struct/union/class
10978 
10979     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10980     // struct X { int A; } D;    D should chain to X.
10981     if (getLangOpts().CPlusPlus) {
10982       // FIXME: Look for a way to use RecordDecl for simple structs.
10983       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10984                                   cast_or_null<CXXRecordDecl>(PrevDecl));
10985 
10986       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10987         StdBadAlloc = cast<CXXRecordDecl>(New);
10988     } else
10989       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10990                                cast_or_null<RecordDecl>(PrevDecl));
10991   }
10992 
10993   // C++11 [dcl.type]p3:
10994   //   A type-specifier-seq shall not define a class or enumeration [...].
10995   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
10996     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
10997       << Context.getTagDeclType(New);
10998     Invalid = true;
10999   }
11000 
11001   // Maybe add qualifier info.
11002   if (SS.isNotEmpty()) {
11003     if (SS.isSet()) {
11004       // If this is either a declaration or a definition, check the
11005       // nested-name-specifier against the current context. We don't do this
11006       // for explicit specializations, because they have similar checking
11007       // (with more specific diagnostics) in the call to
11008       // CheckMemberSpecialization, below.
11009       if (!isExplicitSpecialization &&
11010           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11011           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11012         Invalid = true;
11013 
11014       New->setQualifierInfo(SS.getWithLocInContext(Context));
11015       if (TemplateParameterLists.size() > 0) {
11016         New->setTemplateParameterListsInfo(Context,
11017                                            TemplateParameterLists.size(),
11018                                            TemplateParameterLists.data());
11019       }
11020     }
11021     else
11022       Invalid = true;
11023   }
11024 
11025   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11026     // Add alignment attributes if necessary; these attributes are checked when
11027     // the ASTContext lays out the structure.
11028     //
11029     // It is important for implementing the correct semantics that this
11030     // happen here (in act on tag decl). The #pragma pack stack is
11031     // maintained as a result of parser callbacks which can occur at
11032     // many points during the parsing of a struct declaration (because
11033     // the #pragma tokens are effectively skipped over during the
11034     // parsing of the struct).
11035     if (TUK == TUK_Definition) {
11036       AddAlignmentAttributesForRecord(RD);
11037       AddMsStructLayoutForRecord(RD);
11038     }
11039   }
11040 
11041   if (ModulePrivateLoc.isValid()) {
11042     if (isExplicitSpecialization)
11043       Diag(New->getLocation(), diag::err_module_private_specialization)
11044         << 2
11045         << FixItHint::CreateRemoval(ModulePrivateLoc);
11046     // __module_private__ does not apply to local classes. However, we only
11047     // diagnose this as an error when the declaration specifiers are
11048     // freestanding. Here, we just ignore the __module_private__.
11049     else if (!SearchDC->isFunctionOrMethod())
11050       New->setModulePrivate();
11051   }
11052 
11053   // If this is a specialization of a member class (of a class template),
11054   // check the specialization.
11055   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11056     Invalid = true;
11057 
11058   if (Invalid)
11059     New->setInvalidDecl();
11060 
11061   if (Attr)
11062     ProcessDeclAttributeList(S, New, Attr);
11063 
11064   // If we're declaring or defining a tag in function prototype scope in C,
11065   // note that this type can only be used within the function and add it to
11066   // the list of decls to inject into the function definition scope.
11067   if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11068       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11069     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11070     DeclsInPrototypeScope.push_back(New);
11071   }
11072 
11073   // Set the lexical context. If the tag has a C++ scope specifier, the
11074   // lexical context will be different from the semantic context.
11075   New->setLexicalDeclContext(CurContext);
11076 
11077   // Mark this as a friend decl if applicable.
11078   // In Microsoft mode, a friend declaration also acts as a forward
11079   // declaration so we always pass true to setObjectOfFriendDecl to make
11080   // the tag name visible.
11081   if (TUK == TUK_Friend)
11082     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11083                                getLangOpts().MicrosoftExt);
11084 
11085   // Set the access specifier.
11086   if (!Invalid && SearchDC->isRecord())
11087     SetMemberAccessSpecifier(New, PrevDecl, AS);
11088 
11089   if (TUK == TUK_Definition)
11090     New->startDefinition();
11091 
11092   // If this has an identifier, add it to the scope stack.
11093   if (TUK == TUK_Friend) {
11094     // We might be replacing an existing declaration in the lookup tables;
11095     // if so, borrow its access specifier.
11096     if (PrevDecl)
11097       New->setAccess(PrevDecl->getAccess());
11098 
11099     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11100     DC->makeDeclVisibleInContext(New);
11101     if (Name) // can be null along some error paths
11102       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11103         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11104   } else if (Name) {
11105     S = getNonFieldDeclScope(S);
11106     PushOnScopeChains(New, S, !IsForwardReference);
11107     if (IsForwardReference)
11108       SearchDC->makeDeclVisibleInContext(New);
11109 
11110   } else {
11111     CurContext->addDecl(New);
11112   }
11113 
11114   // If this is the C FILE type, notify the AST context.
11115   if (IdentifierInfo *II = New->getIdentifier())
11116     if (!New->isInvalidDecl() &&
11117         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11118         II->isStr("FILE"))
11119       Context.setFILEDecl(New);
11120 
11121   if (PrevDecl)
11122     mergeDeclAttributes(New, PrevDecl);
11123 
11124   // If there's a #pragma GCC visibility in scope, set the visibility of this
11125   // record.
11126   AddPushedVisibilityAttribute(New);
11127 
11128   OwnedDecl = true;
11129   // In C++, don't return an invalid declaration. We can't recover well from
11130   // the cases where we make the type anonymous.
11131   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11132 }
11133 
11134 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11135   AdjustDeclIfTemplate(TagD);
11136   TagDecl *Tag = cast<TagDecl>(TagD);
11137 
11138   // Enter the tag context.
11139   PushDeclContext(S, Tag);
11140 
11141   ActOnDocumentableDecl(TagD);
11142 
11143   // If there's a #pragma GCC visibility in scope, set the visibility of this
11144   // record.
11145   AddPushedVisibilityAttribute(Tag);
11146 }
11147 
11148 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11149   assert(isa<ObjCContainerDecl>(IDecl) &&
11150          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11151   DeclContext *OCD = cast<DeclContext>(IDecl);
11152   assert(getContainingDC(OCD) == CurContext &&
11153       "The next DeclContext should be lexically contained in the current one.");
11154   CurContext = OCD;
11155   return IDecl;
11156 }
11157 
11158 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11159                                            SourceLocation FinalLoc,
11160                                            bool IsFinalSpelledSealed,
11161                                            SourceLocation LBraceLoc) {
11162   AdjustDeclIfTemplate(TagD);
11163   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11164 
11165   FieldCollector->StartClass();
11166 
11167   if (!Record->getIdentifier())
11168     return;
11169 
11170   if (FinalLoc.isValid())
11171     Record->addAttr(new (Context)
11172                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11173 
11174   // C++ [class]p2:
11175   //   [...] The class-name is also inserted into the scope of the
11176   //   class itself; this is known as the injected-class-name. For
11177   //   purposes of access checking, the injected-class-name is treated
11178   //   as if it were a public member name.
11179   CXXRecordDecl *InjectedClassName
11180     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11181                             Record->getLocStart(), Record->getLocation(),
11182                             Record->getIdentifier(),
11183                             /*PrevDecl=*/0,
11184                             /*DelayTypeCreation=*/true);
11185   Context.getTypeDeclType(InjectedClassName, Record);
11186   InjectedClassName->setImplicit();
11187   InjectedClassName->setAccess(AS_public);
11188   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11189       InjectedClassName->setDescribedClassTemplate(Template);
11190   PushOnScopeChains(InjectedClassName, S);
11191   assert(InjectedClassName->isInjectedClassName() &&
11192          "Broken injected-class-name");
11193 }
11194 
11195 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11196                                     SourceLocation RBraceLoc) {
11197   AdjustDeclIfTemplate(TagD);
11198   TagDecl *Tag = cast<TagDecl>(TagD);
11199   Tag->setRBraceLoc(RBraceLoc);
11200 
11201   // Make sure we "complete" the definition even it is invalid.
11202   if (Tag->isBeingDefined()) {
11203     assert(Tag->isInvalidDecl() && "We should already have completed it");
11204     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11205       RD->completeDefinition();
11206   }
11207 
11208   if (isa<CXXRecordDecl>(Tag))
11209     FieldCollector->FinishClass();
11210 
11211   // Exit this scope of this tag's definition.
11212   PopDeclContext();
11213 
11214   if (getCurLexicalContext()->isObjCContainer() &&
11215       Tag->getDeclContext()->isFileContext())
11216     Tag->setTopLevelDeclInObjCContainer();
11217 
11218   // Notify the consumer that we've defined a tag.
11219   if (!Tag->isInvalidDecl())
11220     Consumer.HandleTagDeclDefinition(Tag);
11221 }
11222 
11223 void Sema::ActOnObjCContainerFinishDefinition() {
11224   // Exit this scope of this interface definition.
11225   PopDeclContext();
11226 }
11227 
11228 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11229   assert(DC == CurContext && "Mismatch of container contexts");
11230   OriginalLexicalContext = DC;
11231   ActOnObjCContainerFinishDefinition();
11232 }
11233 
11234 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11235   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11236   OriginalLexicalContext = 0;
11237 }
11238 
11239 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11240   AdjustDeclIfTemplate(TagD);
11241   TagDecl *Tag = cast<TagDecl>(TagD);
11242   Tag->setInvalidDecl();
11243 
11244   // Make sure we "complete" the definition even it is invalid.
11245   if (Tag->isBeingDefined()) {
11246     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11247       RD->completeDefinition();
11248   }
11249 
11250   // We're undoing ActOnTagStartDefinition here, not
11251   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11252   // the FieldCollector.
11253 
11254   PopDeclContext();
11255 }
11256 
11257 // Note that FieldName may be null for anonymous bitfields.
11258 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11259                                 IdentifierInfo *FieldName,
11260                                 QualType FieldTy, bool IsMsStruct,
11261                                 Expr *BitWidth, bool *ZeroWidth) {
11262   // Default to true; that shouldn't confuse checks for emptiness
11263   if (ZeroWidth)
11264     *ZeroWidth = true;
11265 
11266   // C99 6.7.2.1p4 - verify the field type.
11267   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11268   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11269     // Handle incomplete types with specific error.
11270     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11271       return ExprError();
11272     if (FieldName)
11273       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11274         << FieldName << FieldTy << BitWidth->getSourceRange();
11275     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11276       << FieldTy << BitWidth->getSourceRange();
11277   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11278                                              UPPC_BitFieldWidth))
11279     return ExprError();
11280 
11281   // If the bit-width is type- or value-dependent, don't try to check
11282   // it now.
11283   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11284     return Owned(BitWidth);
11285 
11286   llvm::APSInt Value;
11287   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11288   if (ICE.isInvalid())
11289     return ICE;
11290   BitWidth = ICE.take();
11291 
11292   if (Value != 0 && ZeroWidth)
11293     *ZeroWidth = false;
11294 
11295   // Zero-width bitfield is ok for anonymous field.
11296   if (Value == 0 && FieldName)
11297     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11298 
11299   if (Value.isSigned() && Value.isNegative()) {
11300     if (FieldName)
11301       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11302                << FieldName << Value.toString(10);
11303     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11304       << Value.toString(10);
11305   }
11306 
11307   if (!FieldTy->isDependentType()) {
11308     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11309     if (Value.getZExtValue() > TypeSize) {
11310       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11311           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11312         if (FieldName)
11313           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11314             << FieldName << (unsigned)Value.getZExtValue()
11315             << (unsigned)TypeSize;
11316 
11317         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11318           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11319       }
11320 
11321       if (FieldName)
11322         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11323           << FieldName << (unsigned)Value.getZExtValue()
11324           << (unsigned)TypeSize;
11325       else
11326         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11327           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11328     }
11329   }
11330 
11331   return Owned(BitWidth);
11332 }
11333 
11334 /// ActOnField - Each field of a C struct/union is passed into this in order
11335 /// to create a FieldDecl object for it.
11336 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11337                        Declarator &D, Expr *BitfieldWidth) {
11338   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11339                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11340                                /*InitStyle=*/ICIS_NoInit, AS_public);
11341   return Res;
11342 }
11343 
11344 /// HandleField - Analyze a field of a C struct or a C++ data member.
11345 ///
11346 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11347                              SourceLocation DeclStart,
11348                              Declarator &D, Expr *BitWidth,
11349                              InClassInitStyle InitStyle,
11350                              AccessSpecifier AS) {
11351   IdentifierInfo *II = D.getIdentifier();
11352   SourceLocation Loc = DeclStart;
11353   if (II) Loc = D.getIdentifierLoc();
11354 
11355   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11356   QualType T = TInfo->getType();
11357   if (getLangOpts().CPlusPlus) {
11358     CheckExtraCXXDefaultArguments(D);
11359 
11360     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11361                                         UPPC_DataMemberType)) {
11362       D.setInvalidType();
11363       T = Context.IntTy;
11364       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11365     }
11366   }
11367 
11368   // TR 18037 does not allow fields to be declared with address spaces.
11369   if (T.getQualifiers().hasAddressSpace()) {
11370     Diag(Loc, diag::err_field_with_address_space);
11371     D.setInvalidType();
11372   }
11373 
11374   // OpenCL 1.2 spec, s6.9 r:
11375   // The event type cannot be used to declare a structure or union field.
11376   if (LangOpts.OpenCL && T->isEventT()) {
11377     Diag(Loc, diag::err_event_t_struct_field);
11378     D.setInvalidType();
11379   }
11380 
11381   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11382 
11383   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11384     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11385          diag::err_invalid_thread)
11386       << DeclSpec::getSpecifierName(TSCS);
11387 
11388   // Check to see if this name was declared as a member previously
11389   NamedDecl *PrevDecl = 0;
11390   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11391   LookupName(Previous, S);
11392   switch (Previous.getResultKind()) {
11393     case LookupResult::Found:
11394     case LookupResult::FoundUnresolvedValue:
11395       PrevDecl = Previous.getAsSingle<NamedDecl>();
11396       break;
11397 
11398     case LookupResult::FoundOverloaded:
11399       PrevDecl = Previous.getRepresentativeDecl();
11400       break;
11401 
11402     case LookupResult::NotFound:
11403     case LookupResult::NotFoundInCurrentInstantiation:
11404     case LookupResult::Ambiguous:
11405       break;
11406   }
11407   Previous.suppressDiagnostics();
11408 
11409   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11410     // Maybe we will complain about the shadowed template parameter.
11411     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11412     // Just pretend that we didn't see the previous declaration.
11413     PrevDecl = 0;
11414   }
11415 
11416   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11417     PrevDecl = 0;
11418 
11419   bool Mutable
11420     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11421   SourceLocation TSSL = D.getLocStart();
11422   FieldDecl *NewFD
11423     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11424                      TSSL, AS, PrevDecl, &D);
11425 
11426   if (NewFD->isInvalidDecl())
11427     Record->setInvalidDecl();
11428 
11429   if (D.getDeclSpec().isModulePrivateSpecified())
11430     NewFD->setModulePrivate();
11431 
11432   if (NewFD->isInvalidDecl() && PrevDecl) {
11433     // Don't introduce NewFD into scope; there's already something
11434     // with the same name in the same scope.
11435   } else if (II) {
11436     PushOnScopeChains(NewFD, S);
11437   } else
11438     Record->addDecl(NewFD);
11439 
11440   return NewFD;
11441 }
11442 
11443 /// \brief Build a new FieldDecl and check its well-formedness.
11444 ///
11445 /// This routine builds a new FieldDecl given the fields name, type,
11446 /// record, etc. \p PrevDecl should refer to any previous declaration
11447 /// with the same name and in the same scope as the field to be
11448 /// created.
11449 ///
11450 /// \returns a new FieldDecl.
11451 ///
11452 /// \todo The Declarator argument is a hack. It will be removed once
11453 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11454                                 TypeSourceInfo *TInfo,
11455                                 RecordDecl *Record, SourceLocation Loc,
11456                                 bool Mutable, Expr *BitWidth,
11457                                 InClassInitStyle InitStyle,
11458                                 SourceLocation TSSL,
11459                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11460                                 Declarator *D) {
11461   IdentifierInfo *II = Name.getAsIdentifierInfo();
11462   bool InvalidDecl = false;
11463   if (D) InvalidDecl = D->isInvalidType();
11464 
11465   // If we receive a broken type, recover by assuming 'int' and
11466   // marking this declaration as invalid.
11467   if (T.isNull()) {
11468     InvalidDecl = true;
11469     T = Context.IntTy;
11470   }
11471 
11472   QualType EltTy = Context.getBaseElementType(T);
11473   if (!EltTy->isDependentType()) {
11474     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11475       // Fields of incomplete type force their record to be invalid.
11476       Record->setInvalidDecl();
11477       InvalidDecl = true;
11478     } else {
11479       NamedDecl *Def;
11480       EltTy->isIncompleteType(&Def);
11481       if (Def && Def->isInvalidDecl()) {
11482         Record->setInvalidDecl();
11483         InvalidDecl = true;
11484       }
11485     }
11486   }
11487 
11488   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11489   if (BitWidth && getLangOpts().OpenCL) {
11490     Diag(Loc, diag::err_opencl_bitfields);
11491     InvalidDecl = true;
11492   }
11493 
11494   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11495   // than a variably modified type.
11496   if (!InvalidDecl && T->isVariablyModifiedType()) {
11497     bool SizeIsNegative;
11498     llvm::APSInt Oversized;
11499 
11500     TypeSourceInfo *FixedTInfo =
11501       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11502                                                     SizeIsNegative,
11503                                                     Oversized);
11504     if (FixedTInfo) {
11505       Diag(Loc, diag::warn_illegal_constant_array_size);
11506       TInfo = FixedTInfo;
11507       T = FixedTInfo->getType();
11508     } else {
11509       if (SizeIsNegative)
11510         Diag(Loc, diag::err_typecheck_negative_array_size);
11511       else if (Oversized.getBoolValue())
11512         Diag(Loc, diag::err_array_too_large)
11513           << Oversized.toString(10);
11514       else
11515         Diag(Loc, diag::err_typecheck_field_variable_size);
11516       InvalidDecl = true;
11517     }
11518   }
11519 
11520   // Fields can not have abstract class types
11521   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11522                                              diag::err_abstract_type_in_decl,
11523                                              AbstractFieldType))
11524     InvalidDecl = true;
11525 
11526   bool ZeroWidth = false;
11527   // If this is declared as a bit-field, check the bit-field.
11528   if (!InvalidDecl && BitWidth) {
11529     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11530                               &ZeroWidth).take();
11531     if (!BitWidth) {
11532       InvalidDecl = true;
11533       BitWidth = 0;
11534       ZeroWidth = false;
11535     }
11536   }
11537 
11538   // Check that 'mutable' is consistent with the type of the declaration.
11539   if (!InvalidDecl && Mutable) {
11540     unsigned DiagID = 0;
11541     if (T->isReferenceType())
11542       DiagID = diag::err_mutable_reference;
11543     else if (T.isConstQualified())
11544       DiagID = diag::err_mutable_const;
11545 
11546     if (DiagID) {
11547       SourceLocation ErrLoc = Loc;
11548       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11549         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11550       Diag(ErrLoc, DiagID);
11551       Mutable = false;
11552       InvalidDecl = true;
11553     }
11554   }
11555 
11556   // C++11 [class.union]p8 (DR1460):
11557   //   At most one variant member of a union may have a
11558   //   brace-or-equal-initializer.
11559   if (InitStyle != ICIS_NoInit)
11560     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11561 
11562   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11563                                        BitWidth, Mutable, InitStyle);
11564   if (InvalidDecl)
11565     NewFD->setInvalidDecl();
11566 
11567   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11568     Diag(Loc, diag::err_duplicate_member) << II;
11569     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11570     NewFD->setInvalidDecl();
11571   }
11572 
11573   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11574     if (Record->isUnion()) {
11575       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11576         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11577         if (RDecl->getDefinition()) {
11578           // C++ [class.union]p1: An object of a class with a non-trivial
11579           // constructor, a non-trivial copy constructor, a non-trivial
11580           // destructor, or a non-trivial copy assignment operator
11581           // cannot be a member of a union, nor can an array of such
11582           // objects.
11583           if (CheckNontrivialField(NewFD))
11584             NewFD->setInvalidDecl();
11585         }
11586       }
11587 
11588       // C++ [class.union]p1: If a union contains a member of reference type,
11589       // the program is ill-formed, except when compiling with MSVC extensions
11590       // enabled.
11591       if (EltTy->isReferenceType()) {
11592         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11593                                     diag::ext_union_member_of_reference_type :
11594                                     diag::err_union_member_of_reference_type)
11595           << NewFD->getDeclName() << EltTy;
11596         if (!getLangOpts().MicrosoftExt)
11597           NewFD->setInvalidDecl();
11598       }
11599     }
11600   }
11601 
11602   // FIXME: We need to pass in the attributes given an AST
11603   // representation, not a parser representation.
11604   if (D) {
11605     // FIXME: The current scope is almost... but not entirely... correct here.
11606     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11607 
11608     if (NewFD->hasAttrs())
11609       CheckAlignasUnderalignment(NewFD);
11610   }
11611 
11612   // In auto-retain/release, infer strong retension for fields of
11613   // retainable type.
11614   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11615     NewFD->setInvalidDecl();
11616 
11617   if (T.isObjCGCWeak())
11618     Diag(Loc, diag::warn_attribute_weak_on_field);
11619 
11620   NewFD->setAccess(AS);
11621   return NewFD;
11622 }
11623 
11624 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11625   assert(FD);
11626   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11627 
11628   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11629     return false;
11630 
11631   QualType EltTy = Context.getBaseElementType(FD->getType());
11632   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11633     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11634     if (RDecl->getDefinition()) {
11635       // We check for copy constructors before constructors
11636       // because otherwise we'll never get complaints about
11637       // copy constructors.
11638 
11639       CXXSpecialMember member = CXXInvalid;
11640       // We're required to check for any non-trivial constructors. Since the
11641       // implicit default constructor is suppressed if there are any
11642       // user-declared constructors, we just need to check that there is a
11643       // trivial default constructor and a trivial copy constructor. (We don't
11644       // worry about move constructors here, since this is a C++98 check.)
11645       if (RDecl->hasNonTrivialCopyConstructor())
11646         member = CXXCopyConstructor;
11647       else if (!RDecl->hasTrivialDefaultConstructor())
11648         member = CXXDefaultConstructor;
11649       else if (RDecl->hasNonTrivialCopyAssignment())
11650         member = CXXCopyAssignment;
11651       else if (RDecl->hasNonTrivialDestructor())
11652         member = CXXDestructor;
11653 
11654       if (member != CXXInvalid) {
11655         if (!getLangOpts().CPlusPlus11 &&
11656             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11657           // Objective-C++ ARC: it is an error to have a non-trivial field of
11658           // a union. However, system headers in Objective-C programs
11659           // occasionally have Objective-C lifetime objects within unions,
11660           // and rather than cause the program to fail, we make those
11661           // members unavailable.
11662           SourceLocation Loc = FD->getLocation();
11663           if (getSourceManager().isInSystemHeader(Loc)) {
11664             if (!FD->hasAttr<UnavailableAttr>())
11665               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11666                                   "this system field has retaining ownership",
11667                                   Loc));
11668             return false;
11669           }
11670         }
11671 
11672         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11673                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11674                diag::err_illegal_union_or_anon_struct_member)
11675           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11676         DiagnoseNontrivial(RDecl, member);
11677         return !getLangOpts().CPlusPlus11;
11678       }
11679     }
11680   }
11681 
11682   return false;
11683 }
11684 
11685 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11686 ///  AST enum value.
11687 static ObjCIvarDecl::AccessControl
11688 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11689   switch (ivarVisibility) {
11690   default: llvm_unreachable("Unknown visitibility kind");
11691   case tok::objc_private: return ObjCIvarDecl::Private;
11692   case tok::objc_public: return ObjCIvarDecl::Public;
11693   case tok::objc_protected: return ObjCIvarDecl::Protected;
11694   case tok::objc_package: return ObjCIvarDecl::Package;
11695   }
11696 }
11697 
11698 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11699 /// in order to create an IvarDecl object for it.
11700 Decl *Sema::ActOnIvar(Scope *S,
11701                                 SourceLocation DeclStart,
11702                                 Declarator &D, Expr *BitfieldWidth,
11703                                 tok::ObjCKeywordKind Visibility) {
11704 
11705   IdentifierInfo *II = D.getIdentifier();
11706   Expr *BitWidth = (Expr*)BitfieldWidth;
11707   SourceLocation Loc = DeclStart;
11708   if (II) Loc = D.getIdentifierLoc();
11709 
11710   // FIXME: Unnamed fields can be handled in various different ways, for
11711   // example, unnamed unions inject all members into the struct namespace!
11712 
11713   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11714   QualType T = TInfo->getType();
11715 
11716   if (BitWidth) {
11717     // 6.7.2.1p3, 6.7.2.1p4
11718     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11719     if (!BitWidth)
11720       D.setInvalidType();
11721   } else {
11722     // Not a bitfield.
11723 
11724     // validate II.
11725 
11726   }
11727   if (T->isReferenceType()) {
11728     Diag(Loc, diag::err_ivar_reference_type);
11729     D.setInvalidType();
11730   }
11731   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11732   // than a variably modified type.
11733   else if (T->isVariablyModifiedType()) {
11734     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11735     D.setInvalidType();
11736   }
11737 
11738   // Get the visibility (access control) for this ivar.
11739   ObjCIvarDecl::AccessControl ac =
11740     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11741                                         : ObjCIvarDecl::None;
11742   // Must set ivar's DeclContext to its enclosing interface.
11743   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11744   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11745     return 0;
11746   ObjCContainerDecl *EnclosingContext;
11747   if (ObjCImplementationDecl *IMPDecl =
11748       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11749     if (LangOpts.ObjCRuntime.isFragile()) {
11750     // Case of ivar declared in an implementation. Context is that of its class.
11751       EnclosingContext = IMPDecl->getClassInterface();
11752       assert(EnclosingContext && "Implementation has no class interface!");
11753     }
11754     else
11755       EnclosingContext = EnclosingDecl;
11756   } else {
11757     if (ObjCCategoryDecl *CDecl =
11758         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11759       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11760         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11761         return 0;
11762       }
11763     }
11764     EnclosingContext = EnclosingDecl;
11765   }
11766 
11767   // Construct the decl.
11768   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11769                                              DeclStart, Loc, II, T,
11770                                              TInfo, ac, (Expr *)BitfieldWidth);
11771 
11772   if (II) {
11773     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11774                                            ForRedeclaration);
11775     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11776         && !isa<TagDecl>(PrevDecl)) {
11777       Diag(Loc, diag::err_duplicate_member) << II;
11778       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11779       NewID->setInvalidDecl();
11780     }
11781   }
11782 
11783   // Process attributes attached to the ivar.
11784   ProcessDeclAttributes(S, NewID, D);
11785 
11786   if (D.isInvalidType())
11787     NewID->setInvalidDecl();
11788 
11789   // In ARC, infer 'retaining' for ivars of retainable type.
11790   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11791     NewID->setInvalidDecl();
11792 
11793   if (D.getDeclSpec().isModulePrivateSpecified())
11794     NewID->setModulePrivate();
11795 
11796   if (II) {
11797     // FIXME: When interfaces are DeclContexts, we'll need to add
11798     // these to the interface.
11799     S->AddDecl(NewID);
11800     IdResolver.AddDecl(NewID);
11801   }
11802 
11803   if (LangOpts.ObjCRuntime.isNonFragile() &&
11804       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11805     Diag(Loc, diag::warn_ivars_in_interface);
11806 
11807   return NewID;
11808 }
11809 
11810 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11811 /// class and class extensions. For every class \@interface and class
11812 /// extension \@interface, if the last ivar is a bitfield of any type,
11813 /// then add an implicit `char :0` ivar to the end of that interface.
11814 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11815                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11816   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11817     return;
11818 
11819   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11820   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11821 
11822   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11823     return;
11824   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11825   if (!ID) {
11826     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11827       if (!CD->IsClassExtension())
11828         return;
11829     }
11830     // No need to add this to end of @implementation.
11831     else
11832       return;
11833   }
11834   // All conditions are met. Add a new bitfield to the tail end of ivars.
11835   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11836   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11837 
11838   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11839                               DeclLoc, DeclLoc, 0,
11840                               Context.CharTy,
11841                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11842                                                                DeclLoc),
11843                               ObjCIvarDecl::Private, BW,
11844                               true);
11845   AllIvarDecls.push_back(Ivar);
11846 }
11847 
11848 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11849                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11850                        SourceLocation RBrac, AttributeList *Attr) {
11851   assert(EnclosingDecl && "missing record or interface decl");
11852 
11853   // If this is an Objective-C @implementation or category and we have
11854   // new fields here we should reset the layout of the interface since
11855   // it will now change.
11856   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11857     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11858     switch (DC->getKind()) {
11859     default: break;
11860     case Decl::ObjCCategory:
11861       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11862       break;
11863     case Decl::ObjCImplementation:
11864       Context.
11865         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11866       break;
11867     }
11868   }
11869 
11870   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11871 
11872   // Start counting up the number of named members; make sure to include
11873   // members of anonymous structs and unions in the total.
11874   unsigned NumNamedMembers = 0;
11875   if (Record) {
11876     for (const auto *I : Record->decls()) {
11877       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
11878         if (IFD->getDeclName())
11879           ++NumNamedMembers;
11880     }
11881   }
11882 
11883   // Verify that all the fields are okay.
11884   SmallVector<FieldDecl*, 32> RecFields;
11885 
11886   bool ARCErrReported = false;
11887   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11888        i != end; ++i) {
11889     FieldDecl *FD = cast<FieldDecl>(*i);
11890 
11891     // Get the type for the field.
11892     const Type *FDTy = FD->getType().getTypePtr();
11893 
11894     if (!FD->isAnonymousStructOrUnion()) {
11895       // Remember all fields written by the user.
11896       RecFields.push_back(FD);
11897     }
11898 
11899     // If the field is already invalid for some reason, don't emit more
11900     // diagnostics about it.
11901     if (FD->isInvalidDecl()) {
11902       EnclosingDecl->setInvalidDecl();
11903       continue;
11904     }
11905 
11906     // C99 6.7.2.1p2:
11907     //   A structure or union shall not contain a member with
11908     //   incomplete or function type (hence, a structure shall not
11909     //   contain an instance of itself, but may contain a pointer to
11910     //   an instance of itself), except that the last member of a
11911     //   structure with more than one named member may have incomplete
11912     //   array type; such a structure (and any union containing,
11913     //   possibly recursively, a member that is such a structure)
11914     //   shall not be a member of a structure or an element of an
11915     //   array.
11916     if (FDTy->isFunctionType()) {
11917       // Field declared as a function.
11918       Diag(FD->getLocation(), diag::err_field_declared_as_function)
11919         << FD->getDeclName();
11920       FD->setInvalidDecl();
11921       EnclosingDecl->setInvalidDecl();
11922       continue;
11923     } else if (FDTy->isIncompleteArrayType() && Record &&
11924                ((i + 1 == Fields.end() && !Record->isUnion()) ||
11925                 ((getLangOpts().MicrosoftExt ||
11926                   getLangOpts().CPlusPlus) &&
11927                  (i + 1 == Fields.end() || Record->isUnion())))) {
11928       // Flexible array member.
11929       // Microsoft and g++ is more permissive regarding flexible array.
11930       // It will accept flexible array in union and also
11931       // as the sole element of a struct/class.
11932       unsigned DiagID = 0;
11933       if (Record->isUnion())
11934         DiagID = getLangOpts().MicrosoftExt
11935                      ? diag::ext_flexible_array_union_ms
11936                      : getLangOpts().CPlusPlus
11937                            ? diag::ext_flexible_array_union_gnu
11938                            : diag::err_flexible_array_union;
11939       else if (Fields.size() == 1)
11940         DiagID = getLangOpts().MicrosoftExt
11941                      ? diag::ext_flexible_array_empty_aggregate_ms
11942                      : getLangOpts().CPlusPlus
11943                            ? diag::ext_flexible_array_empty_aggregate_gnu
11944                            : NumNamedMembers < 1
11945                                  ? diag::err_flexible_array_empty_aggregate
11946                                  : 0;
11947 
11948       if (DiagID)
11949         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11950                                         << Record->getTagKind();
11951       // While the layout of types that contain virtual bases is not specified
11952       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11953       // virtual bases after the derived members.  This would make a flexible
11954       // array member declared at the end of an object not adjacent to the end
11955       // of the type.
11956       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11957         if (RD->getNumVBases() != 0)
11958           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11959             << FD->getDeclName() << Record->getTagKind();
11960       if (!getLangOpts().C99)
11961         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11962           << FD->getDeclName() << Record->getTagKind();
11963 
11964       // If the element type has a non-trivial destructor, we would not
11965       // implicitly destroy the elements, so disallow it for now.
11966       //
11967       // FIXME: GCC allows this. We should probably either implicitly delete
11968       // the destructor of the containing class, or just allow this.
11969       QualType BaseElem = Context.getBaseElementType(FD->getType());
11970       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11971         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
11972           << FD->getDeclName() << FD->getType();
11973         FD->setInvalidDecl();
11974         EnclosingDecl->setInvalidDecl();
11975         continue;
11976       }
11977       // Okay, we have a legal flexible array member at the end of the struct.
11978       if (Record)
11979         Record->setHasFlexibleArrayMember(true);
11980     } else if (!FDTy->isDependentType() &&
11981                RequireCompleteType(FD->getLocation(), FD->getType(),
11982                                    diag::err_field_incomplete)) {
11983       // Incomplete type
11984       FD->setInvalidDecl();
11985       EnclosingDecl->setInvalidDecl();
11986       continue;
11987     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11988       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11989         // If this is a member of a union, then entire union becomes "flexible".
11990         if (Record && Record->isUnion()) {
11991           Record->setHasFlexibleArrayMember(true);
11992         } else {
11993           // If this is a struct/class and this is not the last element, reject
11994           // it.  Note that GCC supports variable sized arrays in the middle of
11995           // structures.
11996           if (i + 1 != Fields.end())
11997             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11998               << FD->getDeclName() << FD->getType();
11999           else {
12000             // We support flexible arrays at the end of structs in
12001             // other structs as an extension.
12002             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12003               << FD->getDeclName();
12004             if (Record)
12005               Record->setHasFlexibleArrayMember(true);
12006           }
12007         }
12008       }
12009       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12010           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12011                                  diag::err_abstract_type_in_decl,
12012                                  AbstractIvarType)) {
12013         // Ivars can not have abstract class types
12014         FD->setInvalidDecl();
12015       }
12016       if (Record && FDTTy->getDecl()->hasObjectMember())
12017         Record->setHasObjectMember(true);
12018       if (Record && FDTTy->getDecl()->hasVolatileMember())
12019         Record->setHasVolatileMember(true);
12020     } else if (FDTy->isObjCObjectType()) {
12021       /// A field cannot be an Objective-c object
12022       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12023         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12024       QualType T = Context.getObjCObjectPointerType(FD->getType());
12025       FD->setType(T);
12026     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12027                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12028       // It's an error in ARC if a field has lifetime.
12029       // We don't want to report this in a system header, though,
12030       // so we just make the field unavailable.
12031       // FIXME: that's really not sufficient; we need to make the type
12032       // itself invalid to, say, initialize or copy.
12033       QualType T = FD->getType();
12034       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12035       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12036         SourceLocation loc = FD->getLocation();
12037         if (getSourceManager().isInSystemHeader(loc)) {
12038           if (!FD->hasAttr<UnavailableAttr>()) {
12039             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12040                               "this system field has retaining ownership",
12041                               loc));
12042           }
12043         } else {
12044           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12045             << T->isBlockPointerType() << Record->getTagKind();
12046         }
12047         ARCErrReported = true;
12048       }
12049     } else if (getLangOpts().ObjC1 &&
12050                getLangOpts().getGC() != LangOptions::NonGC &&
12051                Record && !Record->hasObjectMember()) {
12052       if (FD->getType()->isObjCObjectPointerType() ||
12053           FD->getType().isObjCGCStrong())
12054         Record->setHasObjectMember(true);
12055       else if (Context.getAsArrayType(FD->getType())) {
12056         QualType BaseType = Context.getBaseElementType(FD->getType());
12057         if (BaseType->isRecordType() &&
12058             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12059           Record->setHasObjectMember(true);
12060         else if (BaseType->isObjCObjectPointerType() ||
12061                  BaseType.isObjCGCStrong())
12062                Record->setHasObjectMember(true);
12063       }
12064     }
12065     if (Record && FD->getType().isVolatileQualified())
12066       Record->setHasVolatileMember(true);
12067     // Keep track of the number of named members.
12068     if (FD->getIdentifier())
12069       ++NumNamedMembers;
12070   }
12071 
12072   // Okay, we successfully defined 'Record'.
12073   if (Record) {
12074     bool Completed = false;
12075     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12076       if (!CXXRecord->isInvalidDecl()) {
12077         // Set access bits correctly on the directly-declared conversions.
12078         for (CXXRecordDecl::conversion_iterator
12079                I = CXXRecord->conversion_begin(),
12080                E = CXXRecord->conversion_end(); I != E; ++I)
12081           I.setAccess((*I)->getAccess());
12082 
12083         if (!CXXRecord->isDependentType()) {
12084           if (CXXRecord->hasUserDeclaredDestructor()) {
12085             // Adjust user-defined destructor exception spec.
12086             if (getLangOpts().CPlusPlus11)
12087               AdjustDestructorExceptionSpec(CXXRecord,
12088                                             CXXRecord->getDestructor());
12089           }
12090 
12091           // Add any implicitly-declared members to this class.
12092           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12093 
12094           // If we have virtual base classes, we may end up finding multiple
12095           // final overriders for a given virtual function. Check for this
12096           // problem now.
12097           if (CXXRecord->getNumVBases()) {
12098             CXXFinalOverriderMap FinalOverriders;
12099             CXXRecord->getFinalOverriders(FinalOverriders);
12100 
12101             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12102                                              MEnd = FinalOverriders.end();
12103                  M != MEnd; ++M) {
12104               for (OverridingMethods::iterator SO = M->second.begin(),
12105                                             SOEnd = M->second.end();
12106                    SO != SOEnd; ++SO) {
12107                 assert(SO->second.size() > 0 &&
12108                        "Virtual function without overridding functions?");
12109                 if (SO->second.size() == 1)
12110                   continue;
12111 
12112                 // C++ [class.virtual]p2:
12113                 //   In a derived class, if a virtual member function of a base
12114                 //   class subobject has more than one final overrider the
12115                 //   program is ill-formed.
12116                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12117                   << (const NamedDecl *)M->first << Record;
12118                 Diag(M->first->getLocation(),
12119                      diag::note_overridden_virtual_function);
12120                 for (OverridingMethods::overriding_iterator
12121                           OM = SO->second.begin(),
12122                        OMEnd = SO->second.end();
12123                      OM != OMEnd; ++OM)
12124                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12125                     << (const NamedDecl *)M->first << OM->Method->getParent();
12126 
12127                 Record->setInvalidDecl();
12128               }
12129             }
12130             CXXRecord->completeDefinition(&FinalOverriders);
12131             Completed = true;
12132           }
12133         }
12134       }
12135     }
12136 
12137     if (!Completed)
12138       Record->completeDefinition();
12139 
12140     if (Record->hasAttrs()) {
12141       CheckAlignasUnderalignment(Record);
12142 
12143       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12144         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12145                                            IA->getRange(), IA->getBestCase(),
12146                                            IA->getSemanticSpelling());
12147     }
12148 
12149     // Check if the structure/union declaration is a type that can have zero
12150     // size in C. For C this is a language extension, for C++ it may cause
12151     // compatibility problems.
12152     bool CheckForZeroSize;
12153     if (!getLangOpts().CPlusPlus) {
12154       CheckForZeroSize = true;
12155     } else {
12156       // For C++ filter out types that cannot be referenced in C code.
12157       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12158       CheckForZeroSize =
12159           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12160           !CXXRecord->isDependentType() &&
12161           CXXRecord->isCLike();
12162     }
12163     if (CheckForZeroSize) {
12164       bool ZeroSize = true;
12165       bool IsEmpty = true;
12166       unsigned NonBitFields = 0;
12167       for (RecordDecl::field_iterator I = Record->field_begin(),
12168                                       E = Record->field_end();
12169            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12170         IsEmpty = false;
12171         if (I->isUnnamedBitfield()) {
12172           if (I->getBitWidthValue(Context) > 0)
12173             ZeroSize = false;
12174         } else {
12175           ++NonBitFields;
12176           QualType FieldType = I->getType();
12177           if (FieldType->isIncompleteType() ||
12178               !Context.getTypeSizeInChars(FieldType).isZero())
12179             ZeroSize = false;
12180         }
12181       }
12182 
12183       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12184       // allowed in C++, but warn if its declaration is inside
12185       // extern "C" block.
12186       if (ZeroSize) {
12187         Diag(RecLoc, getLangOpts().CPlusPlus ?
12188                          diag::warn_zero_size_struct_union_in_extern_c :
12189                          diag::warn_zero_size_struct_union_compat)
12190           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12191       }
12192 
12193       // Structs without named members are extension in C (C99 6.7.2.1p7),
12194       // but are accepted by GCC.
12195       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12196         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12197                                diag::ext_no_named_members_in_struct_union)
12198           << Record->isUnion();
12199       }
12200     }
12201   } else {
12202     ObjCIvarDecl **ClsFields =
12203       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12204     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12205       ID->setEndOfDefinitionLoc(RBrac);
12206       // Add ivar's to class's DeclContext.
12207       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12208         ClsFields[i]->setLexicalDeclContext(ID);
12209         ID->addDecl(ClsFields[i]);
12210       }
12211       // Must enforce the rule that ivars in the base classes may not be
12212       // duplicates.
12213       if (ID->getSuperClass())
12214         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12215     } else if (ObjCImplementationDecl *IMPDecl =
12216                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12217       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12218       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12219         // Ivar declared in @implementation never belongs to the implementation.
12220         // Only it is in implementation's lexical context.
12221         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12222       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12223       IMPDecl->setIvarLBraceLoc(LBrac);
12224       IMPDecl->setIvarRBraceLoc(RBrac);
12225     } else if (ObjCCategoryDecl *CDecl =
12226                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12227       // case of ivars in class extension; all other cases have been
12228       // reported as errors elsewhere.
12229       // FIXME. Class extension does not have a LocEnd field.
12230       // CDecl->setLocEnd(RBrac);
12231       // Add ivar's to class extension's DeclContext.
12232       // Diagnose redeclaration of private ivars.
12233       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12234       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12235         if (IDecl) {
12236           if (const ObjCIvarDecl *ClsIvar =
12237               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12238             Diag(ClsFields[i]->getLocation(),
12239                  diag::err_duplicate_ivar_declaration);
12240             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12241             continue;
12242           }
12243           for (ObjCInterfaceDecl::known_extensions_iterator
12244                  Ext = IDecl->known_extensions_begin(),
12245                  ExtEnd = IDecl->known_extensions_end();
12246                Ext != ExtEnd; ++Ext) {
12247             if (const ObjCIvarDecl *ClsExtIvar
12248                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12249               Diag(ClsFields[i]->getLocation(),
12250                    diag::err_duplicate_ivar_declaration);
12251               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12252               continue;
12253             }
12254           }
12255         }
12256         ClsFields[i]->setLexicalDeclContext(CDecl);
12257         CDecl->addDecl(ClsFields[i]);
12258       }
12259       CDecl->setIvarLBraceLoc(LBrac);
12260       CDecl->setIvarRBraceLoc(RBrac);
12261     }
12262   }
12263 
12264   if (Attr)
12265     ProcessDeclAttributeList(S, Record, Attr);
12266 }
12267 
12268 /// \brief Determine whether the given integral value is representable within
12269 /// the given type T.
12270 static bool isRepresentableIntegerValue(ASTContext &Context,
12271                                         llvm::APSInt &Value,
12272                                         QualType T) {
12273   assert(T->isIntegralType(Context) && "Integral type required!");
12274   unsigned BitWidth = Context.getIntWidth(T);
12275 
12276   if (Value.isUnsigned() || Value.isNonNegative()) {
12277     if (T->isSignedIntegerOrEnumerationType())
12278       --BitWidth;
12279     return Value.getActiveBits() <= BitWidth;
12280   }
12281   return Value.getMinSignedBits() <= BitWidth;
12282 }
12283 
12284 // \brief Given an integral type, return the next larger integral type
12285 // (or a NULL type of no such type exists).
12286 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12287   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12288   // enum checking below.
12289   assert(T->isIntegralType(Context) && "Integral type required!");
12290   const unsigned NumTypes = 4;
12291   QualType SignedIntegralTypes[NumTypes] = {
12292     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12293   };
12294   QualType UnsignedIntegralTypes[NumTypes] = {
12295     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12296     Context.UnsignedLongLongTy
12297   };
12298 
12299   unsigned BitWidth = Context.getTypeSize(T);
12300   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12301                                                         : UnsignedIntegralTypes;
12302   for (unsigned I = 0; I != NumTypes; ++I)
12303     if (Context.getTypeSize(Types[I]) > BitWidth)
12304       return Types[I];
12305 
12306   return QualType();
12307 }
12308 
12309 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12310                                           EnumConstantDecl *LastEnumConst,
12311                                           SourceLocation IdLoc,
12312                                           IdentifierInfo *Id,
12313                                           Expr *Val) {
12314   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12315   llvm::APSInt EnumVal(IntWidth);
12316   QualType EltTy;
12317 
12318   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12319     Val = 0;
12320 
12321   if (Val)
12322     Val = DefaultLvalueConversion(Val).take();
12323 
12324   if (Val) {
12325     if (Enum->isDependentType() || Val->isTypeDependent())
12326       EltTy = Context.DependentTy;
12327     else {
12328       SourceLocation ExpLoc;
12329       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12330           !getLangOpts().MSVCCompat) {
12331         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12332         // constant-expression in the enumerator-definition shall be a converted
12333         // constant expression of the underlying type.
12334         EltTy = Enum->getIntegerType();
12335         ExprResult Converted =
12336           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12337                                            CCEK_Enumerator);
12338         if (Converted.isInvalid())
12339           Val = 0;
12340         else
12341           Val = Converted.take();
12342       } else if (!Val->isValueDependent() &&
12343                  !(Val = VerifyIntegerConstantExpression(Val,
12344                                                          &EnumVal).take())) {
12345         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12346       } else {
12347         if (Enum->isFixed()) {
12348           EltTy = Enum->getIntegerType();
12349 
12350           // In Obj-C and Microsoft mode, require the enumeration value to be
12351           // representable in the underlying type of the enumeration. In C++11,
12352           // we perform a non-narrowing conversion as part of converted constant
12353           // expression checking.
12354           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12355             if (getLangOpts().MSVCCompat) {
12356               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12357               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12358             } else
12359               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12360           } else
12361             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12362         } else if (getLangOpts().CPlusPlus) {
12363           // C++11 [dcl.enum]p5:
12364           //   If the underlying type is not fixed, the type of each enumerator
12365           //   is the type of its initializing value:
12366           //     - If an initializer is specified for an enumerator, the
12367           //       initializing value has the same type as the expression.
12368           EltTy = Val->getType();
12369         } else {
12370           // C99 6.7.2.2p2:
12371           //   The expression that defines the value of an enumeration constant
12372           //   shall be an integer constant expression that has a value
12373           //   representable as an int.
12374 
12375           // Complain if the value is not representable in an int.
12376           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12377             Diag(IdLoc, diag::ext_enum_value_not_int)
12378               << EnumVal.toString(10) << Val->getSourceRange()
12379               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12380           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12381             // Force the type of the expression to 'int'.
12382             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12383           }
12384           EltTy = Val->getType();
12385         }
12386       }
12387     }
12388   }
12389 
12390   if (!Val) {
12391     if (Enum->isDependentType())
12392       EltTy = Context.DependentTy;
12393     else if (!LastEnumConst) {
12394       // C++0x [dcl.enum]p5:
12395       //   If the underlying type is not fixed, the type of each enumerator
12396       //   is the type of its initializing value:
12397       //     - If no initializer is specified for the first enumerator, the
12398       //       initializing value has an unspecified integral type.
12399       //
12400       // GCC uses 'int' for its unspecified integral type, as does
12401       // C99 6.7.2.2p3.
12402       if (Enum->isFixed()) {
12403         EltTy = Enum->getIntegerType();
12404       }
12405       else {
12406         EltTy = Context.IntTy;
12407       }
12408     } else {
12409       // Assign the last value + 1.
12410       EnumVal = LastEnumConst->getInitVal();
12411       ++EnumVal;
12412       EltTy = LastEnumConst->getType();
12413 
12414       // Check for overflow on increment.
12415       if (EnumVal < LastEnumConst->getInitVal()) {
12416         // C++0x [dcl.enum]p5:
12417         //   If the underlying type is not fixed, the type of each enumerator
12418         //   is the type of its initializing value:
12419         //
12420         //     - Otherwise the type of the initializing value is the same as
12421         //       the type of the initializing value of the preceding enumerator
12422         //       unless the incremented value is not representable in that type,
12423         //       in which case the type is an unspecified integral type
12424         //       sufficient to contain the incremented value. If no such type
12425         //       exists, the program is ill-formed.
12426         QualType T = getNextLargerIntegralType(Context, EltTy);
12427         if (T.isNull() || Enum->isFixed()) {
12428           // There is no integral type larger enough to represent this
12429           // value. Complain, then allow the value to wrap around.
12430           EnumVal = LastEnumConst->getInitVal();
12431           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12432           ++EnumVal;
12433           if (Enum->isFixed())
12434             // When the underlying type is fixed, this is ill-formed.
12435             Diag(IdLoc, diag::err_enumerator_wrapped)
12436               << EnumVal.toString(10)
12437               << EltTy;
12438           else
12439             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
12440               << EnumVal.toString(10);
12441         } else {
12442           EltTy = T;
12443         }
12444 
12445         // Retrieve the last enumerator's value, extent that type to the
12446         // type that is supposed to be large enough to represent the incremented
12447         // value, then increment.
12448         EnumVal = LastEnumConst->getInitVal();
12449         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12450         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12451         ++EnumVal;
12452 
12453         // If we're not in C++, diagnose the overflow of enumerator values,
12454         // which in C99 means that the enumerator value is not representable in
12455         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12456         // permits enumerator values that are representable in some larger
12457         // integral type.
12458         if (!getLangOpts().CPlusPlus && !T.isNull())
12459           Diag(IdLoc, diag::warn_enum_value_overflow);
12460       } else if (!getLangOpts().CPlusPlus &&
12461                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12462         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12463         Diag(IdLoc, diag::ext_enum_value_not_int)
12464           << EnumVal.toString(10) << 1;
12465       }
12466     }
12467   }
12468 
12469   if (!EltTy->isDependentType()) {
12470     // Make the enumerator value match the signedness and size of the
12471     // enumerator's type.
12472     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12473     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12474   }
12475 
12476   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12477                                   Val, EnumVal);
12478 }
12479 
12480 
12481 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12482                               SourceLocation IdLoc, IdentifierInfo *Id,
12483                               AttributeList *Attr,
12484                               SourceLocation EqualLoc, Expr *Val) {
12485   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12486   EnumConstantDecl *LastEnumConst =
12487     cast_or_null<EnumConstantDecl>(lastEnumConst);
12488 
12489   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12490   // we find one that is.
12491   S = getNonFieldDeclScope(S);
12492 
12493   // Verify that there isn't already something declared with this name in this
12494   // scope.
12495   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12496                                          ForRedeclaration);
12497   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12498     // Maybe we will complain about the shadowed template parameter.
12499     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12500     // Just pretend that we didn't see the previous declaration.
12501     PrevDecl = 0;
12502   }
12503 
12504   if (PrevDecl) {
12505     // When in C++, we may get a TagDecl with the same name; in this case the
12506     // enum constant will 'hide' the tag.
12507     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12508            "Received TagDecl when not in C++!");
12509     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12510       if (isa<EnumConstantDecl>(PrevDecl))
12511         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12512       else
12513         Diag(IdLoc, diag::err_redefinition) << Id;
12514       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12515       return 0;
12516     }
12517   }
12518 
12519   // C++ [class.mem]p15:
12520   // If T is the name of a class, then each of the following shall have a name
12521   // different from T:
12522   // - every enumerator of every member of class T that is an unscoped
12523   // enumerated type
12524   if (CXXRecordDecl *Record
12525                       = dyn_cast<CXXRecordDecl>(
12526                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12527     if (!TheEnumDecl->isScoped() &&
12528         Record->getIdentifier() && Record->getIdentifier() == Id)
12529       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12530 
12531   EnumConstantDecl *New =
12532     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12533 
12534   if (New) {
12535     // Process attributes.
12536     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12537 
12538     // Register this decl in the current scope stack.
12539     New->setAccess(TheEnumDecl->getAccess());
12540     PushOnScopeChains(New, S);
12541   }
12542 
12543   ActOnDocumentableDecl(New);
12544 
12545   return New;
12546 }
12547 
12548 // Returns true when the enum initial expression does not trigger the
12549 // duplicate enum warning.  A few common cases are exempted as follows:
12550 // Element2 = Element1
12551 // Element2 = Element1 + 1
12552 // Element2 = Element1 - 1
12553 // Where Element2 and Element1 are from the same enum.
12554 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12555   Expr *InitExpr = ECD->getInitExpr();
12556   if (!InitExpr)
12557     return true;
12558   InitExpr = InitExpr->IgnoreImpCasts();
12559 
12560   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12561     if (!BO->isAdditiveOp())
12562       return true;
12563     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12564     if (!IL)
12565       return true;
12566     if (IL->getValue() != 1)
12567       return true;
12568 
12569     InitExpr = BO->getLHS();
12570   }
12571 
12572   // This checks if the elements are from the same enum.
12573   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12574   if (!DRE)
12575     return true;
12576 
12577   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12578   if (!EnumConstant)
12579     return true;
12580 
12581   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12582       Enum)
12583     return true;
12584 
12585   return false;
12586 }
12587 
12588 struct DupKey {
12589   int64_t val;
12590   bool isTombstoneOrEmptyKey;
12591   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12592     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12593 };
12594 
12595 static DupKey GetDupKey(const llvm::APSInt& Val) {
12596   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12597                 false);
12598 }
12599 
12600 struct DenseMapInfoDupKey {
12601   static DupKey getEmptyKey() { return DupKey(0, true); }
12602   static DupKey getTombstoneKey() { return DupKey(1, true); }
12603   static unsigned getHashValue(const DupKey Key) {
12604     return (unsigned)(Key.val * 37);
12605   }
12606   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12607     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12608            LHS.val == RHS.val;
12609   }
12610 };
12611 
12612 // Emits a warning when an element is implicitly set a value that
12613 // a previous element has already been set to.
12614 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12615                                         EnumDecl *Enum,
12616                                         QualType EnumType) {
12617   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12618                                  Enum->getLocation()) ==
12619       DiagnosticsEngine::Ignored)
12620     return;
12621   // Avoid anonymous enums
12622   if (!Enum->getIdentifier())
12623     return;
12624 
12625   // Only check for small enums.
12626   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12627     return;
12628 
12629   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12630   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12631 
12632   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12633   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12634           ValueToVectorMap;
12635 
12636   DuplicatesVector DupVector;
12637   ValueToVectorMap EnumMap;
12638 
12639   // Populate the EnumMap with all values represented by enum constants without
12640   // an initialier.
12641   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12642     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12643 
12644     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12645     // this constant.  Skip this enum since it may be ill-formed.
12646     if (!ECD) {
12647       return;
12648     }
12649 
12650     if (ECD->getInitExpr())
12651       continue;
12652 
12653     DupKey Key = GetDupKey(ECD->getInitVal());
12654     DeclOrVector &Entry = EnumMap[Key];
12655 
12656     // First time encountering this value.
12657     if (Entry.isNull())
12658       Entry = ECD;
12659   }
12660 
12661   // Create vectors for any values that has duplicates.
12662   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12663     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12664     if (!ValidDuplicateEnum(ECD, Enum))
12665       continue;
12666 
12667     DupKey Key = GetDupKey(ECD->getInitVal());
12668 
12669     DeclOrVector& Entry = EnumMap[Key];
12670     if (Entry.isNull())
12671       continue;
12672 
12673     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12674       // Ensure constants are different.
12675       if (D == ECD)
12676         continue;
12677 
12678       // Create new vector and push values onto it.
12679       ECDVector *Vec = new ECDVector();
12680       Vec->push_back(D);
12681       Vec->push_back(ECD);
12682 
12683       // Update entry to point to the duplicates vector.
12684       Entry = Vec;
12685 
12686       // Store the vector somewhere we can consult later for quick emission of
12687       // diagnostics.
12688       DupVector.push_back(Vec);
12689       continue;
12690     }
12691 
12692     ECDVector *Vec = Entry.get<ECDVector*>();
12693     // Make sure constants are not added more than once.
12694     if (*Vec->begin() == ECD)
12695       continue;
12696 
12697     Vec->push_back(ECD);
12698   }
12699 
12700   // Emit diagnostics.
12701   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12702                                   DupVectorEnd = DupVector.end();
12703        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12704     ECDVector *Vec = *DupVectorIter;
12705     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12706 
12707     // Emit warning for one enum constant.
12708     ECDVector::iterator I = Vec->begin();
12709     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12710       << (*I)->getName() << (*I)->getInitVal().toString(10)
12711       << (*I)->getSourceRange();
12712     ++I;
12713 
12714     // Emit one note for each of the remaining enum constants with
12715     // the same value.
12716     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12717       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12718         << (*I)->getName() << (*I)->getInitVal().toString(10)
12719         << (*I)->getSourceRange();
12720     delete Vec;
12721   }
12722 }
12723 
12724 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12725                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12726                          ArrayRef<Decl *> Elements,
12727                          Scope *S, AttributeList *Attr) {
12728   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12729   QualType EnumType = Context.getTypeDeclType(Enum);
12730 
12731   if (Attr)
12732     ProcessDeclAttributeList(S, Enum, Attr);
12733 
12734   if (Enum->isDependentType()) {
12735     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12736       EnumConstantDecl *ECD =
12737         cast_or_null<EnumConstantDecl>(Elements[i]);
12738       if (!ECD) continue;
12739 
12740       ECD->setType(EnumType);
12741     }
12742 
12743     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12744     return;
12745   }
12746 
12747   // TODO: If the result value doesn't fit in an int, it must be a long or long
12748   // long value.  ISO C does not support this, but GCC does as an extension,
12749   // emit a warning.
12750   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12751   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12752   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12753 
12754   // Verify that all the values are okay, compute the size of the values, and
12755   // reverse the list.
12756   unsigned NumNegativeBits = 0;
12757   unsigned NumPositiveBits = 0;
12758 
12759   // Keep track of whether all elements have type int.
12760   bool AllElementsInt = true;
12761 
12762   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12763     EnumConstantDecl *ECD =
12764       cast_or_null<EnumConstantDecl>(Elements[i]);
12765     if (!ECD) continue;  // Already issued a diagnostic.
12766 
12767     const llvm::APSInt &InitVal = ECD->getInitVal();
12768 
12769     // Keep track of the size of positive and negative values.
12770     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12771       NumPositiveBits = std::max(NumPositiveBits,
12772                                  (unsigned)InitVal.getActiveBits());
12773     else
12774       NumNegativeBits = std::max(NumNegativeBits,
12775                                  (unsigned)InitVal.getMinSignedBits());
12776 
12777     // Keep track of whether every enum element has type int (very commmon).
12778     if (AllElementsInt)
12779       AllElementsInt = ECD->getType() == Context.IntTy;
12780   }
12781 
12782   // Figure out the type that should be used for this enum.
12783   QualType BestType;
12784   unsigned BestWidth;
12785 
12786   // C++0x N3000 [conv.prom]p3:
12787   //   An rvalue of an unscoped enumeration type whose underlying
12788   //   type is not fixed can be converted to an rvalue of the first
12789   //   of the following types that can represent all the values of
12790   //   the enumeration: int, unsigned int, long int, unsigned long
12791   //   int, long long int, or unsigned long long int.
12792   // C99 6.4.4.3p2:
12793   //   An identifier declared as an enumeration constant has type int.
12794   // The C99 rule is modified by a gcc extension
12795   QualType BestPromotionType;
12796 
12797   bool Packed = Enum->hasAttr<PackedAttr>();
12798   // -fshort-enums is the equivalent to specifying the packed attribute on all
12799   // enum definitions.
12800   if (LangOpts.ShortEnums)
12801     Packed = true;
12802 
12803   if (Enum->isFixed()) {
12804     BestType = Enum->getIntegerType();
12805     if (BestType->isPromotableIntegerType())
12806       BestPromotionType = Context.getPromotedIntegerType(BestType);
12807     else
12808       BestPromotionType = BestType;
12809     // We don't need to set BestWidth, because BestType is going to be the type
12810     // of the enumerators, but we do anyway because otherwise some compilers
12811     // warn that it might be used uninitialized.
12812     BestWidth = CharWidth;
12813   }
12814   else if (NumNegativeBits) {
12815     // If there is a negative value, figure out the smallest integer type (of
12816     // int/long/longlong) that fits.
12817     // If it's packed, check also if it fits a char or a short.
12818     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12819       BestType = Context.SignedCharTy;
12820       BestWidth = CharWidth;
12821     } else if (Packed && NumNegativeBits <= ShortWidth &&
12822                NumPositiveBits < ShortWidth) {
12823       BestType = Context.ShortTy;
12824       BestWidth = ShortWidth;
12825     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12826       BestType = Context.IntTy;
12827       BestWidth = IntWidth;
12828     } else {
12829       BestWidth = Context.getTargetInfo().getLongWidth();
12830 
12831       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12832         BestType = Context.LongTy;
12833       } else {
12834         BestWidth = Context.getTargetInfo().getLongLongWidth();
12835 
12836         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12837           Diag(Enum->getLocation(), diag::ext_enum_too_large);
12838         BestType = Context.LongLongTy;
12839       }
12840     }
12841     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12842   } else {
12843     // If there is no negative value, figure out the smallest type that fits
12844     // all of the enumerator values.
12845     // If it's packed, check also if it fits a char or a short.
12846     if (Packed && NumPositiveBits <= CharWidth) {
12847       BestType = Context.UnsignedCharTy;
12848       BestPromotionType = Context.IntTy;
12849       BestWidth = CharWidth;
12850     } else if (Packed && NumPositiveBits <= ShortWidth) {
12851       BestType = Context.UnsignedShortTy;
12852       BestPromotionType = Context.IntTy;
12853       BestWidth = ShortWidth;
12854     } else if (NumPositiveBits <= IntWidth) {
12855       BestType = Context.UnsignedIntTy;
12856       BestWidth = IntWidth;
12857       BestPromotionType
12858         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12859                            ? Context.UnsignedIntTy : Context.IntTy;
12860     } else if (NumPositiveBits <=
12861                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12862       BestType = Context.UnsignedLongTy;
12863       BestPromotionType
12864         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12865                            ? Context.UnsignedLongTy : Context.LongTy;
12866     } else {
12867       BestWidth = Context.getTargetInfo().getLongLongWidth();
12868       assert(NumPositiveBits <= BestWidth &&
12869              "How could an initializer get larger than ULL?");
12870       BestType = Context.UnsignedLongLongTy;
12871       BestPromotionType
12872         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12873                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12874     }
12875   }
12876 
12877   // Loop over all of the enumerator constants, changing their types to match
12878   // the type of the enum if needed.
12879   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12880     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12881     if (!ECD) continue;  // Already issued a diagnostic.
12882 
12883     // Standard C says the enumerators have int type, but we allow, as an
12884     // extension, the enumerators to be larger than int size.  If each
12885     // enumerator value fits in an int, type it as an int, otherwise type it the
12886     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12887     // that X has type 'int', not 'unsigned'.
12888 
12889     // Determine whether the value fits into an int.
12890     llvm::APSInt InitVal = ECD->getInitVal();
12891 
12892     // If it fits into an integer type, force it.  Otherwise force it to match
12893     // the enum decl type.
12894     QualType NewTy;
12895     unsigned NewWidth;
12896     bool NewSign;
12897     if (!getLangOpts().CPlusPlus &&
12898         !Enum->isFixed() &&
12899         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12900       NewTy = Context.IntTy;
12901       NewWidth = IntWidth;
12902       NewSign = true;
12903     } else if (ECD->getType() == BestType) {
12904       // Already the right type!
12905       if (getLangOpts().CPlusPlus)
12906         // C++ [dcl.enum]p4: Following the closing brace of an
12907         // enum-specifier, each enumerator has the type of its
12908         // enumeration.
12909         ECD->setType(EnumType);
12910       continue;
12911     } else {
12912       NewTy = BestType;
12913       NewWidth = BestWidth;
12914       NewSign = BestType->isSignedIntegerOrEnumerationType();
12915     }
12916 
12917     // Adjust the APSInt value.
12918     InitVal = InitVal.extOrTrunc(NewWidth);
12919     InitVal.setIsSigned(NewSign);
12920     ECD->setInitVal(InitVal);
12921 
12922     // Adjust the Expr initializer and type.
12923     if (ECD->getInitExpr() &&
12924         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12925       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12926                                                 CK_IntegralCast,
12927                                                 ECD->getInitExpr(),
12928                                                 /*base paths*/ 0,
12929                                                 VK_RValue));
12930     if (getLangOpts().CPlusPlus)
12931       // C++ [dcl.enum]p4: Following the closing brace of an
12932       // enum-specifier, each enumerator has the type of its
12933       // enumeration.
12934       ECD->setType(EnumType);
12935     else
12936       ECD->setType(NewTy);
12937   }
12938 
12939   Enum->completeDefinition(BestType, BestPromotionType,
12940                            NumPositiveBits, NumNegativeBits);
12941 
12942   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12943 
12944   // Now that the enum type is defined, ensure it's not been underaligned.
12945   if (Enum->hasAttrs())
12946     CheckAlignasUnderalignment(Enum);
12947 }
12948 
12949 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12950                                   SourceLocation StartLoc,
12951                                   SourceLocation EndLoc) {
12952   StringLiteral *AsmString = cast<StringLiteral>(expr);
12953 
12954   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12955                                                    AsmString, StartLoc,
12956                                                    EndLoc);
12957   CurContext->addDecl(New);
12958   return New;
12959 }
12960 
12961 static void checkModuleImportContext(Sema &S, Module *M,
12962                                      SourceLocation ImportLoc,
12963                                      DeclContext *DC) {
12964   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
12965     switch (LSD->getLanguage()) {
12966     case LinkageSpecDecl::lang_c:
12967       if (!M->IsExternC) {
12968         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
12969           << M->getFullModuleName();
12970         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
12971         return;
12972       }
12973       break;
12974     case LinkageSpecDecl::lang_cxx:
12975       break;
12976     }
12977     DC = LSD->getParent();
12978   }
12979 
12980   while (isa<LinkageSpecDecl>(DC))
12981     DC = DC->getParent();
12982   if (!isa<TranslationUnitDecl>(DC)) {
12983     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
12984       << M->getFullModuleName() << DC;
12985     S.Diag(cast<Decl>(DC)->getLocStart(),
12986            diag::note_module_import_not_at_top_level)
12987       << DC;
12988   }
12989 }
12990 
12991 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12992                                    SourceLocation ImportLoc,
12993                                    ModuleIdPath Path) {
12994   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12995                                                 Module::AllVisible,
12996                                                 /*IsIncludeDirective=*/false);
12997   if (!Mod)
12998     return true;
12999 
13000   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13001 
13002   SmallVector<SourceLocation, 2> IdentifierLocs;
13003   Module *ModCheck = Mod;
13004   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13005     // If we've run out of module parents, just drop the remaining identifiers.
13006     // We need the length to be consistent.
13007     if (!ModCheck)
13008       break;
13009     ModCheck = ModCheck->Parent;
13010 
13011     IdentifierLocs.push_back(Path[I].second);
13012   }
13013 
13014   ImportDecl *Import = ImportDecl::Create(Context,
13015                                           Context.getTranslationUnitDecl(),
13016                                           AtLoc.isValid()? AtLoc : ImportLoc,
13017                                           Mod, IdentifierLocs);
13018   Context.getTranslationUnitDecl()->addDecl(Import);
13019   return Import;
13020 }
13021 
13022 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13023   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13024 
13025   // FIXME: Should we synthesize an ImportDecl here?
13026   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13027                                          /*Complain=*/true);
13028 }
13029 
13030 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13031   // Create the implicit import declaration.
13032   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13033   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13034                                                    Loc, Mod, Loc);
13035   TU->addDecl(ImportD);
13036   Consumer.HandleImplicitImportDecl(ImportD);
13037 
13038   // Make the module visible.
13039   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13040                                          /*Complain=*/false);
13041 }
13042 
13043 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13044                                       IdentifierInfo* AliasName,
13045                                       SourceLocation PragmaLoc,
13046                                       SourceLocation NameLoc,
13047                                       SourceLocation AliasNameLoc) {
13048   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13049                                     LookupOrdinaryName);
13050   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13051                                                     AliasName->getName(), 0);
13052 
13053   if (PrevDecl)
13054     PrevDecl->addAttr(Attr);
13055   else
13056     (void)ExtnameUndeclaredIdentifiers.insert(
13057       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13058 }
13059 
13060 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13061                              SourceLocation PragmaLoc,
13062                              SourceLocation NameLoc) {
13063   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13064 
13065   if (PrevDecl) {
13066     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13067   } else {
13068     (void)WeakUndeclaredIdentifiers.insert(
13069       std::pair<IdentifierInfo*,WeakInfo>
13070         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
13071   }
13072 }
13073 
13074 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13075                                 IdentifierInfo* AliasName,
13076                                 SourceLocation PragmaLoc,
13077                                 SourceLocation NameLoc,
13078                                 SourceLocation AliasNameLoc) {
13079   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13080                                     LookupOrdinaryName);
13081   WeakInfo W = WeakInfo(Name, NameLoc);
13082 
13083   if (PrevDecl) {
13084     if (!PrevDecl->hasAttr<AliasAttr>())
13085       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13086         DeclApplyPragmaWeak(TUScope, ND, W);
13087   } else {
13088     (void)WeakUndeclaredIdentifiers.insert(
13089       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13090   }
13091 }
13092 
13093 Decl *Sema::getObjCDeclContext() const {
13094   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13095 }
13096 
13097 AvailabilityResult Sema::getCurContextAvailability() const {
13098   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13099   // If we are within an Objective-C method, we should consult
13100   // both the availability of the method as well as the
13101   // enclosing class.  If the class is (say) deprecated,
13102   // the entire method is considered deprecated from the
13103   // purpose of checking if the current context is deprecated.
13104   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13105     AvailabilityResult R = MD->getAvailability();
13106     if (R != AR_Available)
13107       return R;
13108     D = MD->getClassInterface();
13109   }
13110   // If we are within an Objective-c @implementation, it
13111   // gets the same availability context as the @interface.
13112   else if (const ObjCImplementationDecl *ID =
13113             dyn_cast<ObjCImplementationDecl>(D)) {
13114     D = ID->getClassInterface();
13115   }
13116   return D->getAvailability();
13117 }
13118