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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.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" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
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/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   case tok::kw_char8_t:
152     return getLangOpts().Char8;
153 
154   default:
155     break;
156   }
157 
158   return false;
159 }
160 
161 namespace {
162 enum class UnqualifiedTypeNameLookupResult {
163   NotFound,
164   FoundNonType,
165   FoundType
166 };
167 } // end anonymous namespace
168 
169 /// Tries to perform unqualified lookup of the type decls in bases for
170 /// dependent class.
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175                                 SourceLocation NameLoc,
176                                 const CXXRecordDecl *RD) {
177   if (!RD->hasDefinition())
178     return UnqualifiedTypeNameLookupResult::NotFound;
179   // Look for type decls in base classes.
180   UnqualifiedTypeNameLookupResult FoundTypeDecl =
181       UnqualifiedTypeNameLookupResult::NotFound;
182   for (const auto &Base : RD->bases()) {
183     const CXXRecordDecl *BaseRD = nullptr;
184     if (auto *BaseTT = Base.getType()->getAs<TagType>())
185       BaseRD = BaseTT->getAsCXXRecordDecl();
186     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187       // Look for type decls in dependent base classes that have known primary
188       // templates.
189       if (!TST || !TST->isDependentType())
190         continue;
191       auto *TD = TST->getTemplateName().getAsTemplateDecl();
192       if (!TD)
193         continue;
194       if (auto *BasePrimaryTemplate =
195           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197           BaseRD = BasePrimaryTemplate;
198         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199           if (const ClassTemplatePartialSpecializationDecl *PS =
200                   CTD->findPartialSpecialization(Base.getType()))
201             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
202               BaseRD = PS;
203         }
204       }
205     }
206     if (BaseRD) {
207       for (NamedDecl *ND : BaseRD->lookup(&II)) {
208         if (!isa<TypeDecl>(ND))
209           return UnqualifiedTypeNameLookupResult::FoundNonType;
210         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
211       }
212       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214         case UnqualifiedTypeNameLookupResult::FoundNonType:
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         case UnqualifiedTypeNameLookupResult::FoundType:
217           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218           break;
219         case UnqualifiedTypeNameLookupResult::NotFound:
220           break;
221         }
222       }
223     }
224   }
225 
226   return FoundTypeDecl;
227 }
228 
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230                                                       const IdentifierInfo &II,
231                                                       SourceLocation NameLoc) {
232   // Lookup in the parent class template context, if any.
233   const CXXRecordDecl *RD = nullptr;
234   UnqualifiedTypeNameLookupResult FoundTypeDecl =
235       UnqualifiedTypeNameLookupResult::NotFound;
236   for (DeclContext *DC = S.CurContext;
237        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238        DC = DC->getParent()) {
239     // Look for type decls in dependent base classes that have known primary
240     // templates.
241     RD = dyn_cast<CXXRecordDecl>(DC);
242     if (RD && RD->getDescribedClassTemplate())
243       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
244   }
245   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
246     return nullptr;
247 
248   // We found some types in dependent base classes.  Recover as if the user
249   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
250   // lookup during template instantiation.
251   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
252 
253   ASTContext &Context = S.Context;
254   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255                                           cast<Type>(Context.getRecordType(RD)));
256   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
257 
258   CXXScopeSpec SS;
259   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
260 
261   TypeLocBuilder Builder;
262   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263   DepTL.setNameLoc(NameLoc);
264   DepTL.setElaboratedKeywordLoc(SourceLocation());
265   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
267 }
268 
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
271 ///
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278                              Scope *S, CXXScopeSpec *SS,
279                              bool isClassName, bool HasTrailingDot,
280                              ParsedType ObjectTypePtr,
281                              bool IsCtorOrDtorName,
282                              bool WantNontrivialTypeSourceInfo,
283                              bool IsClassTemplateDeductionContext,
284                              IdentifierInfo **CorrectedII) {
285   // FIXME: Consider allowing this outside C++1z mode as an extension.
286   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288                               !isClassName && !HasTrailingDot;
289 
290   // Determine where we will perform name lookup.
291   DeclContext *LookupCtx = nullptr;
292   if (ObjectTypePtr) {
293     QualType ObjectType = ObjectTypePtr.get();
294     if (ObjectType->isRecordType())
295       LookupCtx = computeDeclContext(ObjectType);
296   } else if (SS && SS->isNotEmpty()) {
297     LookupCtx = computeDeclContext(*SS, false);
298 
299     if (!LookupCtx) {
300       if (isDependentScopeSpecifier(*SS)) {
301         // C++ [temp.res]p3:
302         //   A qualified-id that refers to a type and in which the
303         //   nested-name-specifier depends on a template-parameter (14.6.2)
304         //   shall be prefixed by the keyword typename to indicate that the
305         //   qualified-id denotes a type, forming an
306         //   elaborated-type-specifier (7.1.5.3).
307         //
308         // We therefore do not perform any name lookup if the result would
309         // refer to a member of an unknown specialization.
310         if (!isClassName && !IsCtorOrDtorName)
311           return nullptr;
312 
313         // We know from the grammar that this name refers to a type,
314         // so build a dependent node to describe the type.
315         if (WantNontrivialTypeSourceInfo)
316           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
317 
318         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
320                                        II, NameLoc);
321         return ParsedType::make(T);
322       }
323 
324       return nullptr;
325     }
326 
327     if (!LookupCtx->isDependentContext() &&
328         RequireCompleteDeclContext(*SS, LookupCtx))
329       return nullptr;
330   }
331 
332   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333   // lookup for class-names.
334   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
335                                       LookupOrdinaryName;
336   LookupResult Result(*this, &II, NameLoc, Kind);
337   if (LookupCtx) {
338     // Perform "qualified" name lookup into the declaration context we
339     // computed, which is either the type of the base of a member access
340     // expression or the declaration context associated with a prior
341     // nested-name-specifier.
342     LookupQualifiedName(Result, LookupCtx);
343 
344     if (ObjectTypePtr && Result.empty()) {
345       // C++ [basic.lookup.classref]p3:
346       //   If the unqualified-id is ~type-name, the type-name is looked up
347       //   in the context of the entire postfix-expression. If the type T of
348       //   the object expression is of a class type C, the type-name is also
349       //   looked up in the scope of class C. At least one of the lookups shall
350       //   find a name that refers to (possibly cv-qualified) T.
351       LookupName(Result, S);
352     }
353   } else {
354     // Perform unqualified name lookup.
355     LookupName(Result, S);
356 
357     // For unqualified lookup in a class template in MSVC mode, look into
358     // dependent base classes where the primary class template is known.
359     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360       if (ParsedType TypeInBase =
361               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362         return TypeInBase;
363     }
364   }
365 
366   NamedDecl *IIDecl = nullptr;
367   switch (Result.getResultKind()) {
368   case LookupResult::NotFound:
369   case LookupResult::NotFoundInCurrentInstantiation:
370     if (CorrectedII) {
371       TypoCorrection Correction =
372           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373                       llvm::make_unique<TypeNameValidatorCCC>(
374                           true, isClassName, AllowDeducedTemplate),
375                       CTK_ErrorRecovery);
376       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
377       TemplateTy Template;
378       bool MemberOfUnknownSpecialization;
379       UnqualifiedId TemplateName;
380       TemplateName.setIdentifier(NewII, NameLoc);
381       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382       CXXScopeSpec NewSS, *NewSSPtr = SS;
383       if (SS && NNS) {
384         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
385         NewSSPtr = &NewSS;
386       }
387       if (Correction && (NNS || NewII != &II) &&
388           // Ignore a correction to a template type as the to-be-corrected
389           // identifier is not a template (typo correction for template names
390           // is handled elsewhere).
391           !(getLangOpts().CPlusPlus && NewSSPtr &&
392             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393                            Template, MemberOfUnknownSpecialization))) {
394         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395                                     isClassName, HasTrailingDot, ObjectTypePtr,
396                                     IsCtorOrDtorName,
397                                     WantNontrivialTypeSourceInfo,
398                                     IsClassTemplateDeductionContext);
399         if (Ty) {
400           diagnoseTypo(Correction,
401                        PDiag(diag::err_unknown_type_or_class_name_suggest)
402                          << Result.getLookupName() << isClassName);
403           if (SS && NNS)
404             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405           *CorrectedII = NewII;
406           return Ty;
407         }
408       }
409     }
410     // If typo correction failed or was not performed, fall through
411     LLVM_FALLTHROUGH;
412   case LookupResult::FoundOverloaded:
413   case LookupResult::FoundUnresolvedValue:
414     Result.suppressDiagnostics();
415     return nullptr;
416 
417   case LookupResult::Ambiguous:
418     // Recover from type-hiding ambiguities by hiding the type.  We'll
419     // do the lookup again when looking for an object, and we can
420     // diagnose the error then.  If we don't do this, then the error
421     // about hiding the type will be immediately followed by an error
422     // that only makes sense if the identifier was treated like a type.
423     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424       Result.suppressDiagnostics();
425       return nullptr;
426     }
427 
428     // Look to see if we have a type anywhere in the list of results.
429     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430          Res != ResEnd; ++Res) {
431       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
433         if (!IIDecl ||
434             (*Res)->getLocation().getRawEncoding() <
435               IIDecl->getLocation().getRawEncoding())
436           IIDecl = *Res;
437       }
438     }
439 
440     if (!IIDecl) {
441       // None of the entities we found is a type, so there is no way
442       // to even assume that the result is a type. In this case, don't
443       // complain about the ambiguity. The parser will either try to
444       // perform this lookup again (e.g., as an object name), which
445       // will produce the ambiguity, or will complain that it expected
446       // a type name.
447       Result.suppressDiagnostics();
448       return nullptr;
449     }
450 
451     // We found a type within the ambiguous lookup; diagnose the
452     // ambiguity and then return that type. This might be the right
453     // answer, or it might not be, but it suppresses any attempt to
454     // perform the name lookup again.
455     break;
456 
457   case LookupResult::Found:
458     IIDecl = Result.getFoundDecl();
459     break;
460   }
461 
462   assert(IIDecl && "Didn't find decl");
463 
464   QualType T;
465   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466     // C++ [class.qual]p2: A lookup that would find the injected-class-name
467     // instead names the constructors of the class, except when naming a class.
468     // This is ill-formed when we're not actually forming a ctor or dtor name.
469     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472         FoundRD->isInjectedClassName() &&
473         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
475           << &II << /*Type*/1;
476 
477     DiagnoseUseOfDecl(IIDecl, NameLoc);
478 
479     T = Context.getTypeDeclType(TD);
480     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
483     if (!HasTrailingDot)
484       T = Context.getObjCInterfaceType(IDecl);
485   } else if (AllowDeducedTemplate) {
486     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488                                                        QualType(), false);
489   }
490 
491   if (T.isNull()) {
492     // If it's not plausibly a type, suppress diagnostics.
493     Result.suppressDiagnostics();
494     return nullptr;
495   }
496 
497   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498   // constructor or destructor name (in such a case, the scope specifier
499   // will be attached to the enclosing Expr or Decl node).
500   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501       !isa<ObjCInterfaceDecl>(IIDecl)) {
502     if (WantNontrivialTypeSourceInfo) {
503       // Construct a type with type-source information.
504       TypeLocBuilder Builder;
505       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
506 
507       T = getElaboratedType(ETK_None, *SS, T);
508       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509       ElabTL.setElaboratedKeywordLoc(SourceLocation());
510       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
512     } else {
513       T = getElaboratedType(ETK_None, *SS, T);
514     }
515   }
516 
517   return ParsedType::make(T);
518 }
519 
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523   for (;; DC = DC->getLookupParent()) {
524     DC = DC->getPrimaryContext();
525     auto *ND = dyn_cast<NamespaceDecl>(DC);
526     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527       return NestedNameSpecifier::Create(Context, nullptr, ND);
528     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530                                          RD->getTypeForDecl());
531     else if (isa<TranslationUnitDecl>(DC))
532       return NestedNameSpecifier::GlobalSpecifier(Context);
533   }
534   llvm_unreachable("something isn't in TU scope?");
535 }
536 
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544     DC = DC->getPrimaryContext();
545     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546       if (MD->getParent()->hasAnyDependentBases())
547         return MD->getParent();
548   }
549   return nullptr;
550 }
551 
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553                                           SourceLocation NameLoc,
554                                           bool IsTemplateTypeArg) {
555   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
556 
557   NestedNameSpecifier *NNS = nullptr;
558   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559     // If we weren't able to parse a default template argument, delay lookup
560     // until instantiation time by making a non-dependent DependentTypeName. We
561     // pretend we saw a NestedNameSpecifier referring to the current scope, and
562     // lookup is retried.
563     // FIXME: This hurts our diagnostic quality, since we get errors like "no
564     // type named 'Foo' in 'current_namespace'" when the user didn't write any
565     // name specifiers.
566     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568   } else if (const CXXRecordDecl *RD =
569                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570     // Build a DependentNameType that will perform lookup into RD at
571     // instantiation time.
572     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573                                       RD->getTypeForDecl());
574 
575     // Diagnose that this identifier was undeclared, and retry the lookup during
576     // template instantiation.
577     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
578                                                                       << RD;
579   } else {
580     // This is not a situation that we should recover from.
581     return ParsedType();
582   }
583 
584   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
585 
586   // Build type location information.  We synthesized the qualifier, so we have
587   // to build a fake NestedNameSpecifierLoc.
588   NestedNameSpecifierLocBuilder NNSLocBuilder;
589   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
591 
592   TypeLocBuilder Builder;
593   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594   DepTL.setNameLoc(NameLoc);
595   DepTL.setElaboratedKeywordLoc(SourceLocation());
596   DepTL.setQualifierLoc(QualifierLoc);
597   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
598 }
599 
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo").  If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606   // Do a tag name lookup in this scope.
607   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608   LookupName(R, S, false);
609   R.suppressDiagnostics();
610   if (R.getResultKind() == LookupResult::Found)
611     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612       switch (TD->getTagKind()) {
613       case TTK_Struct: return DeclSpec::TST_struct;
614       case TTK_Interface: return DeclSpec::TST_interface;
615       case TTK_Union:  return DeclSpec::TST_union;
616       case TTK_Class:  return DeclSpec::TST_class;
617       case TTK_Enum:   return DeclSpec::TST_enum;
618       }
619     }
620 
621   return DeclSpec::TST_unspecified;
622 }
623 
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
628 /// @code
629 /// template<class T> class A {
630 /// public:
631 ///   typedef int TYPE;
632 /// };
633 /// template<class T> class B : public A<T> {
634 /// public:
635 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
636 /// };
637 /// @endcode
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639   if (CurContext->isRecord()) {
640     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
641       return true;
642 
643     const Type *Ty = SS->getScopeRep()->getAsType();
644 
645     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646     for (const auto &Base : RD->bases())
647       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
648         return true;
649     return S->isFunctionPrototypeScope();
650   }
651   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
652 }
653 
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655                                    SourceLocation IILoc,
656                                    Scope *S,
657                                    CXXScopeSpec *SS,
658                                    ParsedType &SuggestedType,
659                                    bool IsTemplateName) {
660   // Don't report typename errors for editor placeholders.
661   if (II->isEditorPlaceholder())
662     return;
663   // We don't have anything to suggest (yet).
664   SuggestedType = nullptr;
665 
666   // There may have been a typo in the name of the type. Look up typo
667   // results, in case we have something that we can suggest.
668   if (TypoCorrection Corrected =
669           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670                       llvm::make_unique<TypeNameValidatorCCC>(
671                           false, false, IsTemplateName, !IsTemplateName),
672                       CTK_ErrorRecovery)) {
673     // FIXME: Support error recovery for the template-name case.
674     bool CanRecover = !IsTemplateName;
675     if (Corrected.isKeyword()) {
676       // We corrected to a keyword.
677       diagnoseTypo(Corrected,
678                    PDiag(IsTemplateName ? diag::err_no_template_suggest
679                                         : diag::err_unknown_typename_suggest)
680                        << II);
681       II = Corrected.getCorrectionAsIdentifierInfo();
682     } else {
683       // We found a similarly-named type or interface; suggest that.
684       if (!SS || !SS->isSet()) {
685         diagnoseTypo(Corrected,
686                      PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                           : diag::err_unknown_typename_suggest)
688                          << II, CanRecover);
689       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692                                 II->getName().equals(CorrectedStr);
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName
695                                ? diag::err_no_member_template_suggest
696                                : diag::err_unknown_nested_typename_suggest)
697                          << II << DC << DroppedSpecifier << SS->getRange(),
698                      CanRecover);
699       } else {
700         llvm_unreachable("could not have corrected a typo here");
701       }
702 
703       if (!CanRecover)
704         return;
705 
706       CXXScopeSpec tmpSS;
707       if (Corrected.getCorrectionSpecifier())
708         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
709                           SourceRange(IILoc));
710       // FIXME: Support class template argument deduction here.
711       SuggestedType =
712           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714                       /*IsCtorOrDtorName=*/false,
715                       /*NonTrivialTypeSourceInfo=*/true);
716     }
717     return;
718   }
719 
720   if (getLangOpts().CPlusPlus && !IsTemplateName) {
721     // See if II is a class template that the user forgot to pass arguments to.
722     UnqualifiedId Name;
723     Name.setIdentifier(II, IILoc);
724     CXXScopeSpec EmptySS;
725     TemplateTy TemplateResult;
726     bool MemberOfUnknownSpecialization;
727     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728                        Name, nullptr, true, TemplateResult,
729                        MemberOfUnknownSpecialization) == TNK_Type_template) {
730       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
731       return;
732     }
733   }
734 
735   // FIXME: Should we move the logic that tries to recover from a missing tag
736   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
737 
738   if (!SS || (!SS->isSet() && !SS->isInvalid()))
739     Diag(IILoc, IsTemplateName ? diag::err_no_template
740                                : diag::err_unknown_typename)
741         << II;
742   else if (DeclContext *DC = computeDeclContext(*SS, false))
743     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744                                : diag::err_typename_nested_not_found)
745         << II << DC << SS->getRange();
746   else if (isDependentScopeSpecifier(*SS)) {
747     unsigned DiagID = diag::err_typename_missing;
748     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749       DiagID = diag::ext_typename_missing;
750 
751     Diag(SS->getRange().getBegin(), DiagID)
752       << SS->getScopeRep() << II->getName()
753       << SourceRange(SS->getRange().getBegin(), IILoc)
754       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755     SuggestedType = ActOnTypenameType(S, SourceLocation(),
756                                       *SS, *II, IILoc).get();
757   } else {
758     assert(SS && SS->isInvalid() &&
759            "Invalid scope specifier has already been diagnosed");
760   }
761 }
762 
763 /// Determine whether the given result set contains either a type name
764 /// or
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767                        NextToken.is(tok::less);
768 
769   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
771       return true;
772 
773     if (CheckTemplate && isa<TemplateDecl>(*I))
774       return true;
775   }
776 
777   return false;
778 }
779 
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781                                     Scope *S, CXXScopeSpec &SS,
782                                     IdentifierInfo *&Name,
783                                     SourceLocation NameLoc) {
784   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785   SemaRef.LookupParsedName(R, S, &SS);
786   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787     StringRef FixItTagName;
788     switch (Tag->getTagKind()) {
789       case TTK_Class:
790         FixItTagName = "class ";
791         break;
792 
793       case TTK_Enum:
794         FixItTagName = "enum ";
795         break;
796 
797       case TTK_Struct:
798         FixItTagName = "struct ";
799         break;
800 
801       case TTK_Interface:
802         FixItTagName = "__interface ";
803         break;
804 
805       case TTK_Union:
806         FixItTagName = "union ";
807         break;
808     }
809 
810     StringRef TagName = FixItTagName.drop_back();
811     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
814 
815     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
816          I != IEnd; ++I)
817       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
818         << Name << TagName;
819 
820     // Replace lookup results with just the tag decl.
821     Result.clear(Sema::LookupTagName);
822     SemaRef.LookupParsedName(Result, S, &SS);
823     return true;
824   }
825 
826   return false;
827 }
828 
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831                                   QualType T, SourceLocation NameLoc) {
832   ASTContext &Context = S.Context;
833 
834   TypeLocBuilder Builder;
835   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
836 
837   T = S.getElaboratedType(ETK_None, SS, T);
838   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839   ElabTL.setElaboratedKeywordLoc(SourceLocation());
840   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
842 }
843 
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846                    SourceLocation NameLoc, const Token &NextToken,
847                    bool IsAddressOfOperand,
848                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
849   DeclarationNameInfo NameInfo(Name, NameLoc);
850   ObjCMethodDecl *CurMethod = getCurMethodDecl();
851 
852   if (NextToken.is(tok::coloncolon)) {
853     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856              isCurrentClassName(*Name, S, &SS)) {
857     // Per [class.qual]p2, this names the constructors of SS, not the
858     // injected-class-name. We don't have a classification for that.
859     // There's not much point caching this result, since the parser
860     // will reject it later.
861     return NameClassification::Unknown();
862   }
863 
864   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865   LookupParsedName(Result, S, &SS, !CurMethod);
866 
867   // For unqualified lookup in a class template in MSVC mode, look into
868   // dependent base classes where the primary class template is known.
869   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870     if (ParsedType TypeInBase =
871             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
872       return TypeInBase;
873   }
874 
875   // Perform lookup for Objective-C instance variables (including automatically
876   // synthesized instance variables), if we're in an Objective-C method.
877   // FIXME: This lookup really, really needs to be folded in to the normal
878   // unqualified lookup mechanism.
879   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881     if (E.get() || E.isInvalid())
882       return E;
883   }
884 
885   bool SecondTry = false;
886   bool IsFilteredTemplateName = false;
887 
888 Corrected:
889   switch (Result.getResultKind()) {
890   case LookupResult::NotFound:
891     // If an unqualified-id is followed by a '(', then we have a function
892     // call.
893     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894       // In C++, this is an ADL-only call.
895       // FIXME: Reference?
896       if (getLangOpts().CPlusPlus)
897         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
898 
899       // C90 6.3.2.2:
900       //   If the expression that precedes the parenthesized argument list in a
901       //   function call consists solely of an identifier, and if no
902       //   declaration is visible for this identifier, the identifier is
903       //   implicitly declared exactly as if, in the innermost block containing
904       //   the function call, the declaration
905       //
906       //     extern int identifier ();
907       //
908       //   appeared.
909       //
910       // We also allow this in C99 as an extension.
911       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
912         Result.addDecl(D);
913         Result.resolveKind();
914         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
915       }
916     }
917 
918     // In C, we first see whether there is a tag type by the same name, in
919     // which case it's likely that the user just forgot to write "enum",
920     // "struct", or "union".
921     if (!getLangOpts().CPlusPlus && !SecondTry &&
922         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
923       break;
924     }
925 
926     // Perform typo correction to determine if there is another name that is
927     // close to this name.
928     if (!SecondTry && CCC) {
929       SecondTry = true;
930       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931                                                  Result.getLookupKind(), S,
932                                                  &SS, std::move(CCC),
933                                                  CTK_ErrorRecovery)) {
934         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935         unsigned QualifiedDiag = diag::err_no_member_suggest;
936 
937         NamedDecl *FirstDecl = Corrected.getFoundDecl();
938         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941           UnqualifiedDiag = diag::err_no_template_suggest;
942           QualifiedDiag = diag::err_no_member_template_suggest;
943         } else if (UnderlyingFirstDecl &&
944                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947           UnqualifiedDiag = diag::err_unknown_typename_suggest;
948           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
949         }
950 
951         if (SS.isEmpty()) {
952           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953         } else {// FIXME: is this even reachable? Test it.
954           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956                                   Name->getName().equals(CorrectedStr);
957           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958                                     << Name << computeDeclContext(SS, false)
959                                     << DroppedSpecifier << SS.getRange());
960         }
961 
962         // Update the name, so that the caller has the new name.
963         Name = Corrected.getCorrectionAsIdentifierInfo();
964 
965         // Typo correction corrected to a keyword.
966         if (Corrected.isKeyword())
967           return Name;
968 
969         // Also update the LookupResult...
970         // FIXME: This should probably go away at some point
971         Result.clear();
972         Result.setLookupName(Corrected.getCorrection());
973         if (FirstDecl)
974           Result.addDecl(FirstDecl);
975 
976         // If we found an Objective-C instance variable, let
977         // LookupInObjCMethod build the appropriate expression to
978         // reference the ivar.
979         // FIXME: This is a gross hack.
980         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
981           Result.clear();
982           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
983           return E;
984         }
985 
986         goto Corrected;
987       }
988     }
989 
990     // We failed to correct; just fall through and let the parser deal with it.
991     Result.suppressDiagnostics();
992     return NameClassification::Unknown();
993 
994   case LookupResult::NotFoundInCurrentInstantiation: {
995     // We performed name lookup into the current instantiation, and there were
996     // dependent bases, so we treat this result the same way as any other
997     // dependent nested-name-specifier.
998 
999     // C++ [temp.res]p2:
1000     //   A name used in a template declaration or definition and that is
1001     //   dependent on a template-parameter is assumed not to name a type
1002     //   unless the applicable name lookup finds a type name or the name is
1003     //   qualified by the keyword typename.
1004     //
1005     // FIXME: If the next token is '<', we might want to ask the parser to
1006     // perform some heroics to see if we actually have a
1007     // template-argument-list, which would indicate a missing 'template'
1008     // keyword here.
1009     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010                                       NameInfo, IsAddressOfOperand,
1011                                       /*TemplateArgs=*/nullptr);
1012   }
1013 
1014   case LookupResult::Found:
1015   case LookupResult::FoundOverloaded:
1016   case LookupResult::FoundUnresolvedValue:
1017     break;
1018 
1019   case LookupResult::Ambiguous:
1020     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021         hasAnyAcceptableTemplateNames(Result)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039 
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043 
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1046     // C++ [temp.names]p3:
1047     //   After name lookup (3.4) finds that a name is a template-name or that
1048     //   an operator-function-id or a literal- operator-id refers to a set of
1049     //   overloaded functions any member of which is a function template if
1050     //   this is followed by a <, the < is always taken as the delimiter of a
1051     //   template-argument-list and never as the less-than operator.
1052     if (!IsFilteredTemplateName)
1053       FilterAcceptableTemplateNames(Result);
1054 
1055     if (!Result.empty()) {
1056       bool IsFunctionTemplate;
1057       bool IsVarTemplate;
1058       TemplateName Template;
1059       if (Result.end() - Result.begin() > 1) {
1060         IsFunctionTemplate = true;
1061         Template = Context.getOverloadedTemplateName(Result.begin(),
1062                                                      Result.end());
1063       } else {
1064         TemplateDecl *TD
1065           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067         IsVarTemplate = isa<VarTemplateDecl>(TD);
1068 
1069         if (SS.isSet() && !SS.isInvalid())
1070           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071                                                     /*TemplateKeyword=*/false,
1072                                                       TD);
1073         else
1074           Template = TemplateName(TD);
1075       }
1076 
1077       if (IsFunctionTemplate) {
1078         // Function templates always go through overload resolution, at which
1079         // point we'll perform the various checks (e.g., accessibility) we need
1080         // to based on which function we selected.
1081         Result.suppressDiagnostics();
1082 
1083         return NameClassification::FunctionTemplate(Template);
1084       }
1085 
1086       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087                            : NameClassification::TypeTemplate(Template);
1088     }
1089   }
1090 
1091   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093     DiagnoseUseOfDecl(Type, NameLoc);
1094     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095     QualType T = Context.getTypeDeclType(Type);
1096     if (SS.isNotEmpty())
1097       return buildNestedType(*this, SS, T, NameLoc);
1098     return ParsedType::make(T);
1099   }
1100 
1101   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1102   if (!Class) {
1103     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104     if (ObjCCompatibleAliasDecl *Alias =
1105             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106       Class = Alias->getClassInterface();
1107   }
1108 
1109   if (Class) {
1110     DiagnoseUseOfDecl(Class, NameLoc);
1111 
1112     if (NextToken.is(tok::period)) {
1113       // Interface. <something> is parsed as a property reference expression.
1114       // Just return "unknown" as a fall-through for now.
1115       Result.suppressDiagnostics();
1116       return NameClassification::Unknown();
1117     }
1118 
1119     QualType T = Context.getObjCInterfaceType(Class);
1120     return ParsedType::make(T);
1121   }
1122 
1123   // We can have a type template here if we're classifying a template argument.
1124   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125       !isa<VarTemplateDecl>(FirstDecl))
1126     return NameClassification::TypeTemplate(
1127         TemplateName(cast<TemplateDecl>(FirstDecl)));
1128 
1129   // Check for a tag type hidden by a non-type decl in a few cases where it
1130   // seems likely a type is wanted instead of the non-type that was found.
1131   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132   if ((NextToken.is(tok::identifier) ||
1133        (NextIsOp &&
1134         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137     DiagnoseUseOfDecl(Type, NameLoc);
1138     QualType T = Context.getTypeDeclType(Type);
1139     if (SS.isNotEmpty())
1140       return buildNestedType(*this, SS, T, NameLoc);
1141     return ParsedType::make(T);
1142   }
1143 
1144   if (FirstDecl->isCXXClassMember())
1145     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1146                                            nullptr, S);
1147 
1148   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149   return BuildDeclarationNameExpr(SS, Result, ADL);
1150 }
1151 
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154   auto *TD = Name.getAsTemplateDecl();
1155   if (!TD)
1156     return TemplateNameKindForDiagnostics::DependentTemplate;
1157   if (isa<ClassTemplateDecl>(TD))
1158     return TemplateNameKindForDiagnostics::ClassTemplate;
1159   if (isa<FunctionTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::FunctionTemplate;
1161   if (isa<VarTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::VarTemplate;
1163   if (isa<TypeAliasTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::AliasTemplate;
1165   if (isa<TemplateTemplateParmDecl>(TD))
1166     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167   return TemplateNameKindForDiagnostics::DependentTemplate;
1168 }
1169 
1170 // Determines the context to return to after temporarily entering a
1171 // context.  This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1174 
1175   // Functions defined inline within classes aren't parsed until we've
1176   // finished parsing the top-level class, so the top-level class is
1177   // the context we'll need to return to.
1178   // A Lambda call operator whose parent is a class must not be treated
1179   // as an inline member function.  A Lambda can be used legally
1180   // either as an in-class member initializer or a default argument.  These
1181   // are parsed once the class has been marked complete and so the containing
1182   // context would be the nested class (when the lambda is defined in one);
1183   // If the class is not complete, then the lambda is being used in an
1184   // ill-formed fashion (such as to specify the width of a bit-field, or
1185   // in an array-bound) - in which case we still want to return the
1186   // lexically containing DC (which could be a nested class).
1187   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188     DC = DC->getLexicalParent();
1189 
1190     // A function not defined within a class will always return to its
1191     // lexical context.
1192     if (!isa<CXXRecordDecl>(DC))
1193       return DC;
1194 
1195     // A C++ inline method/friend is parsed *after* the topmost class
1196     // it was declared in is fully parsed ("complete");  the topmost
1197     // class is the context we need to return to.
1198     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1199       DC = RD;
1200 
1201     // Return the declaration context of the topmost class the inline method is
1202     // declared in.
1203     return DC;
1204   }
1205 
1206   return DC->getLexicalParent();
1207 }
1208 
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210   assert(getContainingDC(DC) == CurContext &&
1211       "The next DeclContext should be lexically contained in the current one.");
1212   CurContext = DC;
1213   S->setEntity(DC);
1214 }
1215 
1216 void Sema::PopDeclContext() {
1217   assert(CurContext && "DeclContext imbalance!");
1218 
1219   CurContext = getContainingDC(CurContext);
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222 
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1224                                                                     Decl *D) {
1225   // Unlike PushDeclContext, the context to which we return is not necessarily
1226   // the containing DC of TD, because the new context will be some pre-existing
1227   // TagDecl definition instead of a fresh one.
1228   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229   CurContext = cast<TagDecl>(D)->getDefinition();
1230   assert(CurContext && "skipping definition of undefined tag");
1231   // Start lookups from the parent of the current context; we don't want to look
1232   // into the pre-existing complete definition.
1233   S->setEntity(CurContext->getLookupParent());
1234   return Result;
1235 }
1236 
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238   CurContext = static_cast<decltype(CurContext)>(Context);
1239 }
1240 
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1243 ///
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245   // C++0x [basic.lookup.unqual]p13:
1246   //   A name used in the definition of a static data member of class
1247   //   X (after the qualified-id of the static member) is looked up as
1248   //   if the name was used in a member function of X.
1249   // C++0x [basic.lookup.unqual]p14:
1250   //   If a variable member of a namespace is defined outside of the
1251   //   scope of its namespace then any name used in the definition of
1252   //   the variable member (after the declarator-id) is looked up as
1253   //   if the definition of the variable member occurred in its
1254   //   namespace.
1255   // Both of these imply that we should push a scope whose context
1256   // is the semantic context of the declaration.  We can't use
1257   // PushDeclContext here because that context is not necessarily
1258   // lexically contained in the current context.  Fortunately,
1259   // the containing scope should have the appropriate information.
1260 
1261   assert(!S->getEntity() && "scope already has entity");
1262 
1263 #ifndef NDEBUG
1264   Scope *Ancestor = S->getParent();
1265   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1267 #endif
1268 
1269   CurContext = DC;
1270   S->setEntity(DC);
1271 }
1272 
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274   assert(S->getEntity() == CurContext && "Context imbalance!");
1275 
1276   // Switch back to the lexical context.  The safety of this is
1277   // enforced by an assert in EnterDeclaratorContext.
1278   Scope *Ancestor = S->getParent();
1279   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280   CurContext = Ancestor->getEntity();
1281 
1282   // We don't need to do anything with the scope, which is going to
1283   // disappear.
1284 }
1285 
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287   // We assume that the caller has already called
1288   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289   FunctionDecl *FD = D->getAsFunction();
1290   if (!FD)
1291     return;
1292 
1293   // Same implementation as PushDeclContext, but enters the context
1294   // from the lexical parent, rather than the top-level class.
1295   assert(CurContext == FD->getLexicalParent() &&
1296     "The next DeclContext should be lexically contained in the current one.");
1297   CurContext = FD;
1298   S->setEntity(CurContext);
1299 
1300   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301     ParmVarDecl *Param = FD->getParamDecl(P);
1302     // If the parameter has an identifier, then add it to the scope
1303     if (Param->getIdentifier()) {
1304       S->AddDecl(Param);
1305       IdResolver.AddDecl(Param);
1306     }
1307   }
1308 }
1309 
1310 void Sema::ActOnExitFunctionContext() {
1311   // Same implementation as PopDeclContext, but returns to the lexical parent,
1312   // rather than the top-level class.
1313   assert(CurContext && "DeclContext imbalance!");
1314   CurContext = CurContext->getLexicalParent();
1315   assert(CurContext && "Popped translation unit!");
1316 }
1317 
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1320 ///
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1326 /// attribute.
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328                                        ASTContext &Context,
1329                                        const FunctionDecl *New) {
1330   if (Context.getLangOpts().CPlusPlus)
1331     return true;
1332 
1333   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1334     return true;
1335 
1336   return Previous.getResultKind() == LookupResult::Found &&
1337          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338           New->hasAttr<OverloadableAttr>());
1339 }
1340 
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348 
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354 
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362 
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367 
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375 
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380 
1381   S->AddDecl(D);
1382 
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395 
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401 
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461 
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464   if (NewM == OldM)
1465     return false;
1466 
1467   // FIXME: Check proclaimed-ownership-declarations here too.
1468   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470   if (NewIsModuleInterface || OldIsModuleInterface) {
1471     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472     //   if a declaration of D [...] appears in the purview of a module, all
1473     //   other such declarations shall appear in the purview of the same module
1474     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1475       << New
1476       << NewIsModuleInterface
1477       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478       << OldIsModuleInterface
1479       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480     Diag(Old->getLocation(), diag::note_previous_declaration);
1481     New->setInvalidDecl();
1482     return true;
1483   }
1484 
1485   return false;
1486 }
1487 
1488 static bool isUsingDecl(NamedDecl *D) {
1489   return isa<UsingShadowDecl>(D) ||
1490          isa<UnresolvedUsingTypenameDecl>(D) ||
1491          isa<UnresolvedUsingValueDecl>(D);
1492 }
1493 
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496   LookupResult::Filter F = R.makeFilter();
1497   while (F.hasNext())
1498     if (isUsingDecl(F.next()))
1499       F.erase();
1500 
1501   F.done();
1502 }
1503 
1504 /// Check for this common pattern:
1505 /// @code
1506 /// class S {
1507 ///   S(const S&); // DO NOT IMPLEMENT
1508 ///   void operator=(const S&); // DO NOT IMPLEMENT
1509 /// };
1510 /// @endcode
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512   // FIXME: Should check for private access too but access is set after we get
1513   // the decl here.
1514   if (D->doesThisDeclarationHaveABody())
1515     return false;
1516 
1517   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518     return CD->isCopyConstructor();
1519   return D->isCopyAssignmentOperator();
1520 }
1521 
1522 // We need this to handle
1523 //
1524 // typedef struct {
1525 //   void *foo() { return 0; }
1526 // } A;
1527 //
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1533 // not.
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535   const DeclContext *DC = D->getDeclContext();
1536   while (!DC->isTranslationUnit()) {
1537     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538       if (!RD->hasNameForLinkage())
1539         return true;
1540     }
1541     DC = DC->getParent();
1542   }
1543 
1544   return !D->isExternallyVisible();
1545 }
1546 
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1548 // these semantics.
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550   if (S.TUKind != TU_Complete)
1551     return false;
1552   return S.SourceMgr.isInMainFile(Loc);
1553 }
1554 
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1556   assert(D);
1557 
1558   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1559     return false;
1560 
1561   // Ignore all entities declared within templates, and out-of-line definitions
1562   // of members of class templates.
1563   if (D->getDeclContext()->isDependentContext() ||
1564       D->getLexicalDeclContext()->isDependentContext())
1565     return false;
1566 
1567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1569       return false;
1570     // A non-out-of-line declaration of a member specialization was implicitly
1571     // instantiated; it's the out-of-line declaration that we're interested in.
1572     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1574       return false;
1575 
1576     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1578         return false;
1579     } else {
1580       // 'static inline' functions are defined in headers; don't warn.
1581       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1582         return false;
1583     }
1584 
1585     if (FD->doesThisDeclarationHaveABody() &&
1586         Context.DeclMustBeEmitted(FD))
1587       return false;
1588   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589     // Constants and utility variables are defined in headers with internal
1590     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1591     // like "inline".)
1592     if (!isMainFileLoc(*this, VD->getLocation()))
1593       return false;
1594 
1595     if (Context.DeclMustBeEmitted(VD))
1596       return false;
1597 
1598     if (VD->isStaticDataMember() &&
1599         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1600       return false;
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1604       return false;
1605 
1606     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1607       return false;
1608   } else {
1609     return false;
1610   }
1611 
1612   // Only warn for unused decls internal to the translation unit.
1613   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614   // for inline functions defined in the main source file, for instance.
1615   return mightHaveNonExternalLinkage(D);
1616 }
1617 
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1619   if (!D)
1620     return;
1621 
1622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623     const FunctionDecl *First = FD->getFirstDecl();
1624     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625       return; // First should already be in the vector.
1626   }
1627 
1628   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629     const VarDecl *First = VD->getFirstDecl();
1630     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631       return; // First should already be in the vector.
1632   }
1633 
1634   if (ShouldWarnIfUnusedFileScopedDecl(D))
1635     UnusedFileScopedDecls.push_back(D);
1636 }
1637 
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639   if (D->isInvalidDecl())
1640     return false;
1641 
1642   bool Referenced = false;
1643   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644     // For a decomposition declaration, warn if none of the bindings are
1645     // referenced, instead of if the variable itself is referenced (which
1646     // it is, by the bindings' expressions).
1647     for (auto *BD : DD->bindings()) {
1648       if (BD->isReferenced()) {
1649         Referenced = true;
1650         break;
1651       }
1652     }
1653   } else if (!D->getDeclName()) {
1654     return false;
1655   } else if (D->isReferenced() || D->isUsed()) {
1656     Referenced = true;
1657   }
1658 
1659   if (Referenced || D->hasAttr<UnusedAttr>() ||
1660       D->hasAttr<ObjCPreciseLifetimeAttr>())
1661     return false;
1662 
1663   if (isa<LabelDecl>(D))
1664     return true;
1665 
1666   // Except for labels, we only care about unused decls that are local to
1667   // functions.
1668   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670     // For dependent types, the diagnostic is deferred.
1671     WithinFunction =
1672         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673   if (!WithinFunction)
1674     return false;
1675 
1676   if (isa<TypedefNameDecl>(D))
1677     return true;
1678 
1679   // White-list anything that isn't a local variable.
1680   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1681     return false;
1682 
1683   // Types of valid local variables should be complete, so this should succeed.
1684   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1685 
1686     // White-list anything with an __attribute__((unused)) type.
1687     const auto *Ty = VD->getType().getTypePtr();
1688 
1689     // Only look at the outermost level of typedef.
1690     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691       if (TT->getDecl()->hasAttr<UnusedAttr>())
1692         return false;
1693     }
1694 
1695     // If we failed to complete the type for some reason, or if the type is
1696     // dependent, don't diagnose the variable.
1697     if (Ty->isIncompleteType() || Ty->isDependentType())
1698       return false;
1699 
1700     // Look at the element type to ensure that the warning behaviour is
1701     // consistent for both scalars and arrays.
1702     Ty = Ty->getBaseElementTypeUnsafe();
1703 
1704     if (const TagType *TT = Ty->getAs<TagType>()) {
1705       const TagDecl *Tag = TT->getDecl();
1706       if (Tag->hasAttr<UnusedAttr>())
1707         return false;
1708 
1709       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1711           return false;
1712 
1713         if (const Expr *Init = VD->getInit()) {
1714           if (const ExprWithCleanups *Cleanups =
1715                   dyn_cast<ExprWithCleanups>(Init))
1716             Init = Cleanups->getSubExpr();
1717           const CXXConstructExpr *Construct =
1718             dyn_cast<CXXConstructExpr>(Init);
1719           if (Construct && !Construct->isElidable()) {
1720             CXXConstructorDecl *CD = Construct->getConstructor();
1721             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1723               return false;
1724           }
1725         }
1726       }
1727     }
1728 
1729     // TODO: __attribute__((unused)) templates?
1730   }
1731 
1732   return true;
1733 }
1734 
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1736                                      FixItHint &Hint) {
1737   if (isa<LabelDecl>(D)) {
1738     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1739         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1740         true);
1741     if (AfterColon.isInvalid())
1742       return;
1743     Hint = FixItHint::CreateRemoval(
1744         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1745   }
1746 }
1747 
1748 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1749   if (D->getTypeForDecl()->isDependentType())
1750     return;
1751 
1752   for (auto *TmpD : D->decls()) {
1753     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1754       DiagnoseUnusedDecl(T);
1755     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1756       DiagnoseUnusedNestedTypedefs(R);
1757   }
1758 }
1759 
1760 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1761 /// unless they are marked attr(unused).
1762 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1763   if (!ShouldDiagnoseUnusedDecl(D))
1764     return;
1765 
1766   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1767     // typedefs can be referenced later on, so the diagnostics are emitted
1768     // at end-of-translation-unit.
1769     UnusedLocalTypedefNameCandidates.insert(TD);
1770     return;
1771   }
1772 
1773   FixItHint Hint;
1774   GenerateFixForUnusedDecl(D, Context, Hint);
1775 
1776   unsigned DiagID;
1777   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1778     DiagID = diag::warn_unused_exception_param;
1779   else if (isa<LabelDecl>(D))
1780     DiagID = diag::warn_unused_label;
1781   else
1782     DiagID = diag::warn_unused_variable;
1783 
1784   Diag(D->getLocation(), DiagID) << D << Hint;
1785 }
1786 
1787 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1788   // Verify that we have no forward references left.  If so, there was a goto
1789   // or address of a label taken, but no definition of it.  Label fwd
1790   // definitions are indicated with a null substmt which is also not a resolved
1791   // MS inline assembly label name.
1792   bool Diagnose = false;
1793   if (L->isMSAsmLabel())
1794     Diagnose = !L->isResolvedMSAsmLabel();
1795   else
1796     Diagnose = L->getStmt() == nullptr;
1797   if (Diagnose)
1798     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1799 }
1800 
1801 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1802   S->mergeNRVOIntoParent();
1803 
1804   if (S->decl_empty()) return;
1805   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1806          "Scope shouldn't contain decls!");
1807 
1808   for (auto *TmpD : S->decls()) {
1809     assert(TmpD && "This decl didn't get pushed??");
1810 
1811     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1812     NamedDecl *D = cast<NamedDecl>(TmpD);
1813 
1814     // Diagnose unused variables in this scope.
1815     if (!S->hasUnrecoverableErrorOccurred()) {
1816       DiagnoseUnusedDecl(D);
1817       if (const auto *RD = dyn_cast<RecordDecl>(D))
1818         DiagnoseUnusedNestedTypedefs(RD);
1819     }
1820 
1821     if (!D->getDeclName()) continue;
1822 
1823     // If this was a forward reference to a label, verify it was defined.
1824     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1825       CheckPoppedLabel(LD, *this);
1826 
1827     // Remove this name from our lexical scope, and warn on it if we haven't
1828     // already.
1829     IdResolver.RemoveDecl(D);
1830     auto ShadowI = ShadowingDecls.find(D);
1831     if (ShadowI != ShadowingDecls.end()) {
1832       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1833         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1834             << D << FD << FD->getParent();
1835         Diag(FD->getLocation(), diag::note_previous_declaration);
1836       }
1837       ShadowingDecls.erase(ShadowI);
1838     }
1839   }
1840 }
1841 
1842 /// Look for an Objective-C class in the translation unit.
1843 ///
1844 /// \param Id The name of the Objective-C class we're looking for. If
1845 /// typo-correction fixes this name, the Id will be updated
1846 /// to the fixed name.
1847 ///
1848 /// \param IdLoc The location of the name in the translation unit.
1849 ///
1850 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1851 /// if there is no class with the given name.
1852 ///
1853 /// \returns The declaration of the named Objective-C class, or NULL if the
1854 /// class could not be found.
1855 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1856                                               SourceLocation IdLoc,
1857                                               bool DoTypoCorrection) {
1858   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1859   // creation from this context.
1860   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1861 
1862   if (!IDecl && DoTypoCorrection) {
1863     // Perform typo correction at the given location, but only if we
1864     // find an Objective-C class name.
1865     if (TypoCorrection C = CorrectTypo(
1866             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1867             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1868             CTK_ErrorRecovery)) {
1869       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1870       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1871       Id = IDecl->getIdentifier();
1872     }
1873   }
1874   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1875   // This routine must always return a class definition, if any.
1876   if (Def && Def->getDefinition())
1877       Def = Def->getDefinition();
1878   return Def;
1879 }
1880 
1881 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1882 /// from S, where a non-field would be declared. This routine copes
1883 /// with the difference between C and C++ scoping rules in structs and
1884 /// unions. For example, the following code is well-formed in C but
1885 /// ill-formed in C++:
1886 /// @code
1887 /// struct S6 {
1888 ///   enum { BAR } e;
1889 /// };
1890 ///
1891 /// void test_S6() {
1892 ///   struct S6 a;
1893 ///   a.e = BAR;
1894 /// }
1895 /// @endcode
1896 /// For the declaration of BAR, this routine will return a different
1897 /// scope. The scope S will be the scope of the unnamed enumeration
1898 /// within S6. In C++, this routine will return the scope associated
1899 /// with S6, because the enumeration's scope is a transparent
1900 /// context but structures can contain non-field names. In C, this
1901 /// routine will return the translation unit scope, since the
1902 /// enumeration's scope is a transparent context and structures cannot
1903 /// contain non-field names.
1904 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1905   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1906          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1907          (S->isClassScope() && !getLangOpts().CPlusPlus))
1908     S = S->getParent();
1909   return S;
1910 }
1911 
1912 /// Looks up the declaration of "struct objc_super" and
1913 /// saves it for later use in building builtin declaration of
1914 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1915 /// pre-existing declaration exists no action takes place.
1916 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1917                                         IdentifierInfo *II) {
1918   if (!II->isStr("objc_msgSendSuper"))
1919     return;
1920   ASTContext &Context = ThisSema.Context;
1921 
1922   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1923                       SourceLocation(), Sema::LookupTagName);
1924   ThisSema.LookupName(Result, S);
1925   if (Result.getResultKind() == LookupResult::Found)
1926     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1927       Context.setObjCSuperType(Context.getTagDeclType(TD));
1928 }
1929 
1930 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1931   switch (Error) {
1932   case ASTContext::GE_None:
1933     return "";
1934   case ASTContext::GE_Missing_stdio:
1935     return "stdio.h";
1936   case ASTContext::GE_Missing_setjmp:
1937     return "setjmp.h";
1938   case ASTContext::GE_Missing_ucontext:
1939     return "ucontext.h";
1940   }
1941   llvm_unreachable("unhandled error kind");
1942 }
1943 
1944 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1945 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1946 /// if we're creating this built-in in anticipation of redeclaring the
1947 /// built-in.
1948 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1949                                      Scope *S, bool ForRedeclaration,
1950                                      SourceLocation Loc) {
1951   LookupPredefedObjCSuperType(*this, S, II);
1952 
1953   ASTContext::GetBuiltinTypeError Error;
1954   QualType R = Context.GetBuiltinType(ID, Error);
1955   if (Error) {
1956     if (ForRedeclaration)
1957       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1958           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1959     return nullptr;
1960   }
1961 
1962   if (!ForRedeclaration &&
1963       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1964        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1965     Diag(Loc, diag::ext_implicit_lib_function_decl)
1966         << Context.BuiltinInfo.getName(ID) << R;
1967     if (Context.BuiltinInfo.getHeaderName(ID) &&
1968         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1969       Diag(Loc, diag::note_include_header_or_declare)
1970           << Context.BuiltinInfo.getHeaderName(ID)
1971           << Context.BuiltinInfo.getName(ID);
1972   }
1973 
1974   if (R.isNull())
1975     return nullptr;
1976 
1977   DeclContext *Parent = Context.getTranslationUnitDecl();
1978   if (getLangOpts().CPlusPlus) {
1979     LinkageSpecDecl *CLinkageDecl =
1980         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1981                                 LinkageSpecDecl::lang_c, false);
1982     CLinkageDecl->setImplicit();
1983     Parent->addDecl(CLinkageDecl);
1984     Parent = CLinkageDecl;
1985   }
1986 
1987   FunctionDecl *New = FunctionDecl::Create(Context,
1988                                            Parent,
1989                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1990                                            SC_Extern,
1991                                            false,
1992                                            R->isFunctionProtoType());
1993   New->setImplicit();
1994 
1995   // Create Decl objects for each parameter, adding them to the
1996   // FunctionDecl.
1997   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1998     SmallVector<ParmVarDecl*, 16> Params;
1999     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2000       ParmVarDecl *parm =
2001           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2002                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2003                               SC_None, nullptr);
2004       parm->setScopeInfo(0, i);
2005       Params.push_back(parm);
2006     }
2007     New->setParams(Params);
2008   }
2009 
2010   AddKnownFunctionAttributes(New);
2011   RegisterLocallyScopedExternCDecl(New, S);
2012 
2013   // TUScope is the translation-unit scope to insert this function into.
2014   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2015   // relate Scopes to DeclContexts, and probably eliminate CurContext
2016   // entirely, but we're not there yet.
2017   DeclContext *SavedContext = CurContext;
2018   CurContext = Parent;
2019   PushOnScopeChains(New, TUScope);
2020   CurContext = SavedContext;
2021   return New;
2022 }
2023 
2024 /// Typedef declarations don't have linkage, but they still denote the same
2025 /// entity if their types are the same.
2026 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2027 /// isSameEntity.
2028 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2029                                                      TypedefNameDecl *Decl,
2030                                                      LookupResult &Previous) {
2031   // This is only interesting when modules are enabled.
2032   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2033     return;
2034 
2035   // Empty sets are uninteresting.
2036   if (Previous.empty())
2037     return;
2038 
2039   LookupResult::Filter Filter = Previous.makeFilter();
2040   while (Filter.hasNext()) {
2041     NamedDecl *Old = Filter.next();
2042 
2043     // Non-hidden declarations are never ignored.
2044     if (S.isVisible(Old))
2045       continue;
2046 
2047     // Declarations of the same entity are not ignored, even if they have
2048     // different linkages.
2049     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2050       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2051                                 Decl->getUnderlyingType()))
2052         continue;
2053 
2054       // If both declarations give a tag declaration a typedef name for linkage
2055       // purposes, then they declare the same entity.
2056       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2057           Decl->getAnonDeclWithTypedefName())
2058         continue;
2059     }
2060 
2061     Filter.erase();
2062   }
2063 
2064   Filter.done();
2065 }
2066 
2067 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2068   QualType OldType;
2069   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2070     OldType = OldTypedef->getUnderlyingType();
2071   else
2072     OldType = Context.getTypeDeclType(Old);
2073   QualType NewType = New->getUnderlyingType();
2074 
2075   if (NewType->isVariablyModifiedType()) {
2076     // Must not redefine a typedef with a variably-modified type.
2077     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2078     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2079       << Kind << NewType;
2080     if (Old->getLocation().isValid())
2081       notePreviousDefinition(Old, New->getLocation());
2082     New->setInvalidDecl();
2083     return true;
2084   }
2085 
2086   if (OldType != NewType &&
2087       !OldType->isDependentType() &&
2088       !NewType->isDependentType() &&
2089       !Context.hasSameType(OldType, NewType)) {
2090     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2091     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2092       << Kind << NewType << OldType;
2093     if (Old->getLocation().isValid())
2094       notePreviousDefinition(Old, New->getLocation());
2095     New->setInvalidDecl();
2096     return true;
2097   }
2098   return false;
2099 }
2100 
2101 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2102 /// same name and scope as a previous declaration 'Old'.  Figure out
2103 /// how to resolve this situation, merging decls or emitting
2104 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2105 ///
2106 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2107                                 LookupResult &OldDecls) {
2108   // If the new decl is known invalid already, don't bother doing any
2109   // merging checks.
2110   if (New->isInvalidDecl()) return;
2111 
2112   // Allow multiple definitions for ObjC built-in typedefs.
2113   // FIXME: Verify the underlying types are equivalent!
2114   if (getLangOpts().ObjC) {
2115     const IdentifierInfo *TypeID = New->getIdentifier();
2116     switch (TypeID->getLength()) {
2117     default: break;
2118     case 2:
2119       {
2120         if (!TypeID->isStr("id"))
2121           break;
2122         QualType T = New->getUnderlyingType();
2123         if (!T->isPointerType())
2124           break;
2125         if (!T->isVoidPointerType()) {
2126           QualType PT = T->getAs<PointerType>()->getPointeeType();
2127           if (!PT->isStructureType())
2128             break;
2129         }
2130         Context.setObjCIdRedefinitionType(T);
2131         // Install the built-in type for 'id', ignoring the current definition.
2132         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2133         return;
2134       }
2135     case 5:
2136       if (!TypeID->isStr("Class"))
2137         break;
2138       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2139       // Install the built-in type for 'Class', ignoring the current definition.
2140       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2141       return;
2142     case 3:
2143       if (!TypeID->isStr("SEL"))
2144         break;
2145       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2146       // Install the built-in type for 'SEL', ignoring the current definition.
2147       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2148       return;
2149     }
2150     // Fall through - the typedef name was not a builtin type.
2151   }
2152 
2153   // Verify the old decl was also a type.
2154   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2155   if (!Old) {
2156     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2157       << New->getDeclName();
2158 
2159     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2160     if (OldD->getLocation().isValid())
2161       notePreviousDefinition(OldD, New->getLocation());
2162 
2163     return New->setInvalidDecl();
2164   }
2165 
2166   // If the old declaration is invalid, just give up here.
2167   if (Old->isInvalidDecl())
2168     return New->setInvalidDecl();
2169 
2170   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2171     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2172     auto *NewTag = New->getAnonDeclWithTypedefName();
2173     NamedDecl *Hidden = nullptr;
2174     if (OldTag && NewTag &&
2175         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2176         !hasVisibleDefinition(OldTag, &Hidden)) {
2177       // There is a definition of this tag, but it is not visible. Use it
2178       // instead of our tag.
2179       New->setTypeForDecl(OldTD->getTypeForDecl());
2180       if (OldTD->isModed())
2181         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2182                                     OldTD->getUnderlyingType());
2183       else
2184         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2185 
2186       // Make the old tag definition visible.
2187       makeMergedDefinitionVisible(Hidden);
2188 
2189       // If this was an unscoped enumeration, yank all of its enumerators
2190       // out of the scope.
2191       if (isa<EnumDecl>(NewTag)) {
2192         Scope *EnumScope = getNonFieldDeclScope(S);
2193         for (auto *D : NewTag->decls()) {
2194           auto *ED = cast<EnumConstantDecl>(D);
2195           assert(EnumScope->isDeclScope(ED));
2196           EnumScope->RemoveDecl(ED);
2197           IdResolver.RemoveDecl(ED);
2198           ED->getLexicalDeclContext()->removeDecl(ED);
2199         }
2200       }
2201     }
2202   }
2203 
2204   // If the typedef types are not identical, reject them in all languages and
2205   // with any extensions enabled.
2206   if (isIncompatibleTypedef(Old, New))
2207     return;
2208 
2209   // The types match.  Link up the redeclaration chain and merge attributes if
2210   // the old declaration was a typedef.
2211   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2212     New->setPreviousDecl(Typedef);
2213     mergeDeclAttributes(New, Old);
2214   }
2215 
2216   if (getLangOpts().MicrosoftExt)
2217     return;
2218 
2219   if (getLangOpts().CPlusPlus) {
2220     // C++ [dcl.typedef]p2:
2221     //   In a given non-class scope, a typedef specifier can be used to
2222     //   redefine the name of any type declared in that scope to refer
2223     //   to the type to which it already refers.
2224     if (!isa<CXXRecordDecl>(CurContext))
2225       return;
2226 
2227     // C++0x [dcl.typedef]p4:
2228     //   In a given class scope, a typedef specifier can be used to redefine
2229     //   any class-name declared in that scope that is not also a typedef-name
2230     //   to refer to the type to which it already refers.
2231     //
2232     // This wording came in via DR424, which was a correction to the
2233     // wording in DR56, which accidentally banned code like:
2234     //
2235     //   struct S {
2236     //     typedef struct A { } A;
2237     //   };
2238     //
2239     // in the C++03 standard. We implement the C++0x semantics, which
2240     // allow the above but disallow
2241     //
2242     //   struct S {
2243     //     typedef int I;
2244     //     typedef int I;
2245     //   };
2246     //
2247     // since that was the intent of DR56.
2248     if (!isa<TypedefNameDecl>(Old))
2249       return;
2250 
2251     Diag(New->getLocation(), diag::err_redefinition)
2252       << New->getDeclName();
2253     notePreviousDefinition(Old, New->getLocation());
2254     return New->setInvalidDecl();
2255   }
2256 
2257   // Modules always permit redefinition of typedefs, as does C11.
2258   if (getLangOpts().Modules || getLangOpts().C11)
2259     return;
2260 
2261   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2262   // is normally mapped to an error, but can be controlled with
2263   // -Wtypedef-redefinition.  If either the original or the redefinition is
2264   // in a system header, don't emit this for compatibility with GCC.
2265   if (getDiagnostics().getSuppressSystemWarnings() &&
2266       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2267       (Old->isImplicit() ||
2268        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2269        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2270     return;
2271 
2272   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2273     << New->getDeclName();
2274   notePreviousDefinition(Old, New->getLocation());
2275 }
2276 
2277 /// DeclhasAttr - returns true if decl Declaration already has the target
2278 /// attribute.
2279 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2280   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2281   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2282   for (const auto *i : D->attrs())
2283     if (i->getKind() == A->getKind()) {
2284       if (Ann) {
2285         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2286           return true;
2287         continue;
2288       }
2289       // FIXME: Don't hardcode this check
2290       if (OA && isa<OwnershipAttr>(i))
2291         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2292       return true;
2293     }
2294 
2295   return false;
2296 }
2297 
2298 static bool isAttributeTargetADefinition(Decl *D) {
2299   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2300     return VD->isThisDeclarationADefinition();
2301   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2302     return TD->isCompleteDefinition() || TD->isBeingDefined();
2303   return true;
2304 }
2305 
2306 /// Merge alignment attributes from \p Old to \p New, taking into account the
2307 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2308 ///
2309 /// \return \c true if any attributes were added to \p New.
2310 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2311   // Look for alignas attributes on Old, and pick out whichever attribute
2312   // specifies the strictest alignment requirement.
2313   AlignedAttr *OldAlignasAttr = nullptr;
2314   AlignedAttr *OldStrictestAlignAttr = nullptr;
2315   unsigned OldAlign = 0;
2316   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2317     // FIXME: We have no way of representing inherited dependent alignments
2318     // in a case like:
2319     //   template<int A, int B> struct alignas(A) X;
2320     //   template<int A, int B> struct alignas(B) X {};
2321     // For now, we just ignore any alignas attributes which are not on the
2322     // definition in such a case.
2323     if (I->isAlignmentDependent())
2324       return false;
2325 
2326     if (I->isAlignas())
2327       OldAlignasAttr = I;
2328 
2329     unsigned Align = I->getAlignment(S.Context);
2330     if (Align > OldAlign) {
2331       OldAlign = Align;
2332       OldStrictestAlignAttr = I;
2333     }
2334   }
2335 
2336   // Look for alignas attributes on New.
2337   AlignedAttr *NewAlignasAttr = nullptr;
2338   unsigned NewAlign = 0;
2339   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2340     if (I->isAlignmentDependent())
2341       return false;
2342 
2343     if (I->isAlignas())
2344       NewAlignasAttr = I;
2345 
2346     unsigned Align = I->getAlignment(S.Context);
2347     if (Align > NewAlign)
2348       NewAlign = Align;
2349   }
2350 
2351   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2352     // Both declarations have 'alignas' attributes. We require them to match.
2353     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2354     // fall short. (If two declarations both have alignas, they must both match
2355     // every definition, and so must match each other if there is a definition.)
2356 
2357     // If either declaration only contains 'alignas(0)' specifiers, then it
2358     // specifies the natural alignment for the type.
2359     if (OldAlign == 0 || NewAlign == 0) {
2360       QualType Ty;
2361       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2362         Ty = VD->getType();
2363       else
2364         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2365 
2366       if (OldAlign == 0)
2367         OldAlign = S.Context.getTypeAlign(Ty);
2368       if (NewAlign == 0)
2369         NewAlign = S.Context.getTypeAlign(Ty);
2370     }
2371 
2372     if (OldAlign != NewAlign) {
2373       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2374         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2375         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2376       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2377     }
2378   }
2379 
2380   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2381     // C++11 [dcl.align]p6:
2382     //   if any declaration of an entity has an alignment-specifier,
2383     //   every defining declaration of that entity shall specify an
2384     //   equivalent alignment.
2385     // C11 6.7.5/7:
2386     //   If the definition of an object does not have an alignment
2387     //   specifier, any other declaration of that object shall also
2388     //   have no alignment specifier.
2389     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2390       << OldAlignasAttr;
2391     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2392       << OldAlignasAttr;
2393   }
2394 
2395   bool AnyAdded = false;
2396 
2397   // Ensure we have an attribute representing the strictest alignment.
2398   if (OldAlign > NewAlign) {
2399     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2400     Clone->setInherited(true);
2401     New->addAttr(Clone);
2402     AnyAdded = true;
2403   }
2404 
2405   // Ensure we have an alignas attribute if the old declaration had one.
2406   if (OldAlignasAttr && !NewAlignasAttr &&
2407       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2408     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2409     Clone->setInherited(true);
2410     New->addAttr(Clone);
2411     AnyAdded = true;
2412   }
2413 
2414   return AnyAdded;
2415 }
2416 
2417 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2418                                const InheritableAttr *Attr,
2419                                Sema::AvailabilityMergeKind AMK) {
2420   // This function copies an attribute Attr from a previous declaration to the
2421   // new declaration D if the new declaration doesn't itself have that attribute
2422   // yet or if that attribute allows duplicates.
2423   // If you're adding a new attribute that requires logic different from
2424   // "use explicit attribute on decl if present, else use attribute from
2425   // previous decl", for example if the attribute needs to be consistent
2426   // between redeclarations, you need to call a custom merge function here.
2427   InheritableAttr *NewAttr = nullptr;
2428   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2429   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2430     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2431                                       AA->isImplicit(), AA->getIntroduced(),
2432                                       AA->getDeprecated(),
2433                                       AA->getObsoleted(), AA->getUnavailable(),
2434                                       AA->getMessage(), AA->getStrict(),
2435                                       AA->getReplacement(), AMK,
2436                                       AttrSpellingListIndex);
2437   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2438     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2439                                     AttrSpellingListIndex);
2440   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2441     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2442                                         AttrSpellingListIndex);
2443   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2444     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2445                                    AttrSpellingListIndex);
2446   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2447     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2448                                    AttrSpellingListIndex);
2449   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2450     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2451                                 FA->getFormatIdx(), FA->getFirstArg(),
2452                                 AttrSpellingListIndex);
2453   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2454     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2455                                  AttrSpellingListIndex);
2456   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2457     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2458                                  AttrSpellingListIndex);
2459   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2460     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2461                                        AttrSpellingListIndex,
2462                                        IA->getSemanticSpelling());
2463   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2464     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2465                                       &S.Context.Idents.get(AA->getSpelling()),
2466                                       AttrSpellingListIndex);
2467   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2468            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2469             isa<CUDAGlobalAttr>(Attr))) {
2470     // CUDA target attributes are part of function signature for
2471     // overloading purposes and must not be merged.
2472     return false;
2473   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2474     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2475   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2476     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2477   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2478     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2479   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2480     NewAttr = S.mergeCommonAttr(D, *CommonA);
2481   else if (isa<AlignedAttr>(Attr))
2482     // AlignedAttrs are handled separately, because we need to handle all
2483     // such attributes on a declaration at the same time.
2484     NewAttr = nullptr;
2485   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2486            (AMK == Sema::AMK_Override ||
2487             AMK == Sema::AMK_ProtocolImplementation))
2488     NewAttr = nullptr;
2489   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2490     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2491                               UA->getGuid());
2492   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2493     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2494 
2495   if (NewAttr) {
2496     NewAttr->setInherited(true);
2497     D->addAttr(NewAttr);
2498     if (isa<MSInheritanceAttr>(NewAttr))
2499       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2500     return true;
2501   }
2502 
2503   return false;
2504 }
2505 
2506 static const NamedDecl *getDefinition(const Decl *D) {
2507   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2508     return TD->getDefinition();
2509   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2510     const VarDecl *Def = VD->getDefinition();
2511     if (Def)
2512       return Def;
2513     return VD->getActingDefinition();
2514   }
2515   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2516     return FD->getDefinition();
2517   return nullptr;
2518 }
2519 
2520 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2521   for (const auto *Attribute : D->attrs())
2522     if (Attribute->getKind() == Kind)
2523       return true;
2524   return false;
2525 }
2526 
2527 /// checkNewAttributesAfterDef - If we already have a definition, check that
2528 /// there are no new attributes in this declaration.
2529 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2530   if (!New->hasAttrs())
2531     return;
2532 
2533   const NamedDecl *Def = getDefinition(Old);
2534   if (!Def || Def == New)
2535     return;
2536 
2537   AttrVec &NewAttributes = New->getAttrs();
2538   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2539     const Attr *NewAttribute = NewAttributes[I];
2540 
2541     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2542       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2543         Sema::SkipBodyInfo SkipBody;
2544         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2545 
2546         // If we're skipping this definition, drop the "alias" attribute.
2547         if (SkipBody.ShouldSkip) {
2548           NewAttributes.erase(NewAttributes.begin() + I);
2549           --E;
2550           continue;
2551         }
2552       } else {
2553         VarDecl *VD = cast<VarDecl>(New);
2554         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2555                                 VarDecl::TentativeDefinition
2556                             ? diag::err_alias_after_tentative
2557                             : diag::err_redefinition;
2558         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2559         if (Diag == diag::err_redefinition)
2560           S.notePreviousDefinition(Def, VD->getLocation());
2561         else
2562           S.Diag(Def->getLocation(), diag::note_previous_definition);
2563         VD->setInvalidDecl();
2564       }
2565       ++I;
2566       continue;
2567     }
2568 
2569     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2570       // Tentative definitions are only interesting for the alias check above.
2571       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2572         ++I;
2573         continue;
2574       }
2575     }
2576 
2577     if (hasAttribute(Def, NewAttribute->getKind())) {
2578       ++I;
2579       continue; // regular attr merging will take care of validating this.
2580     }
2581 
2582     if (isa<C11NoReturnAttr>(NewAttribute)) {
2583       // C's _Noreturn is allowed to be added to a function after it is defined.
2584       ++I;
2585       continue;
2586     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2587       if (AA->isAlignas()) {
2588         // C++11 [dcl.align]p6:
2589         //   if any declaration of an entity has an alignment-specifier,
2590         //   every defining declaration of that entity shall specify an
2591         //   equivalent alignment.
2592         // C11 6.7.5/7:
2593         //   If the definition of an object does not have an alignment
2594         //   specifier, any other declaration of that object shall also
2595         //   have no alignment specifier.
2596         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2597           << AA;
2598         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2599           << AA;
2600         NewAttributes.erase(NewAttributes.begin() + I);
2601         --E;
2602         continue;
2603       }
2604     }
2605 
2606     S.Diag(NewAttribute->getLocation(),
2607            diag::warn_attribute_precede_definition);
2608     S.Diag(Def->getLocation(), diag::note_previous_definition);
2609     NewAttributes.erase(NewAttributes.begin() + I);
2610     --E;
2611   }
2612 }
2613 
2614 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2615 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2616                                AvailabilityMergeKind AMK) {
2617   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2618     UsedAttr *NewAttr = OldAttr->clone(Context);
2619     NewAttr->setInherited(true);
2620     New->addAttr(NewAttr);
2621   }
2622 
2623   if (!Old->hasAttrs() && !New->hasAttrs())
2624     return;
2625 
2626   // Attributes declared post-definition are currently ignored.
2627   checkNewAttributesAfterDef(*this, New, Old);
2628 
2629   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2630     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2631       if (OldA->getLabel() != NewA->getLabel()) {
2632         // This redeclaration changes __asm__ label.
2633         Diag(New->getLocation(), diag::err_different_asm_label);
2634         Diag(OldA->getLocation(), diag::note_previous_declaration);
2635       }
2636     } else if (Old->isUsed()) {
2637       // This redeclaration adds an __asm__ label to a declaration that has
2638       // already been ODR-used.
2639       Diag(New->getLocation(), diag::err_late_asm_label_name)
2640         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2641     }
2642   }
2643 
2644   // Re-declaration cannot add abi_tag's.
2645   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2646     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2647       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2648         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2649                       NewTag) == OldAbiTagAttr->tags_end()) {
2650           Diag(NewAbiTagAttr->getLocation(),
2651                diag::err_new_abi_tag_on_redeclaration)
2652               << NewTag;
2653           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2654         }
2655       }
2656     } else {
2657       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2658       Diag(Old->getLocation(), diag::note_previous_declaration);
2659     }
2660   }
2661 
2662   // This redeclaration adds a section attribute.
2663   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2664     if (auto *VD = dyn_cast<VarDecl>(New)) {
2665       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2666         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2667         Diag(Old->getLocation(), diag::note_previous_declaration);
2668       }
2669     }
2670   }
2671 
2672   // Redeclaration adds code-seg attribute.
2673   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2674   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2675       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2676     Diag(New->getLocation(), diag::warn_mismatched_section)
2677          << 0 /*codeseg*/;
2678     Diag(Old->getLocation(), diag::note_previous_declaration);
2679   }
2680 
2681   if (!Old->hasAttrs())
2682     return;
2683 
2684   bool foundAny = New->hasAttrs();
2685 
2686   // Ensure that any moving of objects within the allocated map is done before
2687   // we process them.
2688   if (!foundAny) New->setAttrs(AttrVec());
2689 
2690   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2691     // Ignore deprecated/unavailable/availability attributes if requested.
2692     AvailabilityMergeKind LocalAMK = AMK_None;
2693     if (isa<DeprecatedAttr>(I) ||
2694         isa<UnavailableAttr>(I) ||
2695         isa<AvailabilityAttr>(I)) {
2696       switch (AMK) {
2697       case AMK_None:
2698         continue;
2699 
2700       case AMK_Redeclaration:
2701       case AMK_Override:
2702       case AMK_ProtocolImplementation:
2703         LocalAMK = AMK;
2704         break;
2705       }
2706     }
2707 
2708     // Already handled.
2709     if (isa<UsedAttr>(I))
2710       continue;
2711 
2712     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2713       foundAny = true;
2714   }
2715 
2716   if (mergeAlignedAttrs(*this, New, Old))
2717     foundAny = true;
2718 
2719   if (!foundAny) New->dropAttrs();
2720 }
2721 
2722 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2723 /// to the new one.
2724 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2725                                      const ParmVarDecl *oldDecl,
2726                                      Sema &S) {
2727   // C++11 [dcl.attr.depend]p2:
2728   //   The first declaration of a function shall specify the
2729   //   carries_dependency attribute for its declarator-id if any declaration
2730   //   of the function specifies the carries_dependency attribute.
2731   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2732   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2733     S.Diag(CDA->getLocation(),
2734            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2735     // Find the first declaration of the parameter.
2736     // FIXME: Should we build redeclaration chains for function parameters?
2737     const FunctionDecl *FirstFD =
2738       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2739     const ParmVarDecl *FirstVD =
2740       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2741     S.Diag(FirstVD->getLocation(),
2742            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2743   }
2744 
2745   if (!oldDecl->hasAttrs())
2746     return;
2747 
2748   bool foundAny = newDecl->hasAttrs();
2749 
2750   // Ensure that any moving of objects within the allocated map is
2751   // done before we process them.
2752   if (!foundAny) newDecl->setAttrs(AttrVec());
2753 
2754   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2755     if (!DeclHasAttr(newDecl, I)) {
2756       InheritableAttr *newAttr =
2757         cast<InheritableParamAttr>(I->clone(S.Context));
2758       newAttr->setInherited(true);
2759       newDecl->addAttr(newAttr);
2760       foundAny = true;
2761     }
2762   }
2763 
2764   if (!foundAny) newDecl->dropAttrs();
2765 }
2766 
2767 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2768                                 const ParmVarDecl *OldParam,
2769                                 Sema &S) {
2770   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2771     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2772       if (*Oldnullability != *Newnullability) {
2773         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2774           << DiagNullabilityKind(
2775                *Newnullability,
2776                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2777                 != 0))
2778           << DiagNullabilityKind(
2779                *Oldnullability,
2780                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2781                 != 0));
2782         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2783       }
2784     } else {
2785       QualType NewT = NewParam->getType();
2786       NewT = S.Context.getAttributedType(
2787                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2788                          NewT, NewT);
2789       NewParam->setType(NewT);
2790     }
2791   }
2792 }
2793 
2794 namespace {
2795 
2796 /// Used in MergeFunctionDecl to keep track of function parameters in
2797 /// C.
2798 struct GNUCompatibleParamWarning {
2799   ParmVarDecl *OldParm;
2800   ParmVarDecl *NewParm;
2801   QualType PromotedType;
2802 };
2803 
2804 } // end anonymous namespace
2805 
2806 /// getSpecialMember - get the special member enum for a method.
2807 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2808   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2809     if (Ctor->isDefaultConstructor())
2810       return Sema::CXXDefaultConstructor;
2811 
2812     if (Ctor->isCopyConstructor())
2813       return Sema::CXXCopyConstructor;
2814 
2815     if (Ctor->isMoveConstructor())
2816       return Sema::CXXMoveConstructor;
2817   } else if (isa<CXXDestructorDecl>(MD)) {
2818     return Sema::CXXDestructor;
2819   } else if (MD->isCopyAssignmentOperator()) {
2820     return Sema::CXXCopyAssignment;
2821   } else if (MD->isMoveAssignmentOperator()) {
2822     return Sema::CXXMoveAssignment;
2823   }
2824 
2825   return Sema::CXXInvalid;
2826 }
2827 
2828 // Determine whether the previous declaration was a definition, implicit
2829 // declaration, or a declaration.
2830 template <typename T>
2831 static std::pair<diag::kind, SourceLocation>
2832 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2833   diag::kind PrevDiag;
2834   SourceLocation OldLocation = Old->getLocation();
2835   if (Old->isThisDeclarationADefinition())
2836     PrevDiag = diag::note_previous_definition;
2837   else if (Old->isImplicit()) {
2838     PrevDiag = diag::note_previous_implicit_declaration;
2839     if (OldLocation.isInvalid())
2840       OldLocation = New->getLocation();
2841   } else
2842     PrevDiag = diag::note_previous_declaration;
2843   return std::make_pair(PrevDiag, OldLocation);
2844 }
2845 
2846 /// canRedefineFunction - checks if a function can be redefined. Currently,
2847 /// only extern inline functions can be redefined, and even then only in
2848 /// GNU89 mode.
2849 static bool canRedefineFunction(const FunctionDecl *FD,
2850                                 const LangOptions& LangOpts) {
2851   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2852           !LangOpts.CPlusPlus &&
2853           FD->isInlineSpecified() &&
2854           FD->getStorageClass() == SC_Extern);
2855 }
2856 
2857 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2858   const AttributedType *AT = T->getAs<AttributedType>();
2859   while (AT && !AT->isCallingConv())
2860     AT = AT->getModifiedType()->getAs<AttributedType>();
2861   return AT;
2862 }
2863 
2864 template <typename T>
2865 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2866   const DeclContext *DC = Old->getDeclContext();
2867   if (DC->isRecord())
2868     return false;
2869 
2870   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2871   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2872     return true;
2873   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2874     return true;
2875   return false;
2876 }
2877 
2878 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2879 static bool isExternC(VarTemplateDecl *) { return false; }
2880 
2881 /// Check whether a redeclaration of an entity introduced by a
2882 /// using-declaration is valid, given that we know it's not an overload
2883 /// (nor a hidden tag declaration).
2884 template<typename ExpectedDecl>
2885 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2886                                    ExpectedDecl *New) {
2887   // C++11 [basic.scope.declarative]p4:
2888   //   Given a set of declarations in a single declarative region, each of
2889   //   which specifies the same unqualified name,
2890   //   -- they shall all refer to the same entity, or all refer to functions
2891   //      and function templates; or
2892   //   -- exactly one declaration shall declare a class name or enumeration
2893   //      name that is not a typedef name and the other declarations shall all
2894   //      refer to the same variable or enumerator, or all refer to functions
2895   //      and function templates; in this case the class name or enumeration
2896   //      name is hidden (3.3.10).
2897 
2898   // C++11 [namespace.udecl]p14:
2899   //   If a function declaration in namespace scope or block scope has the
2900   //   same name and the same parameter-type-list as a function introduced
2901   //   by a using-declaration, and the declarations do not declare the same
2902   //   function, the program is ill-formed.
2903 
2904   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2905   if (Old &&
2906       !Old->getDeclContext()->getRedeclContext()->Equals(
2907           New->getDeclContext()->getRedeclContext()) &&
2908       !(isExternC(Old) && isExternC(New)))
2909     Old = nullptr;
2910 
2911   if (!Old) {
2912     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2913     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2914     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2915     return true;
2916   }
2917   return false;
2918 }
2919 
2920 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2921                                             const FunctionDecl *B) {
2922   assert(A->getNumParams() == B->getNumParams());
2923 
2924   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2925     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2926     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2927     if (AttrA == AttrB)
2928       return true;
2929     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2930   };
2931 
2932   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2933 }
2934 
2935 /// If necessary, adjust the semantic declaration context for a qualified
2936 /// declaration to name the correct inline namespace within the qualifier.
2937 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2938                                                DeclaratorDecl *OldD) {
2939   // The only case where we need to update the DeclContext is when
2940   // redeclaration lookup for a qualified name finds a declaration
2941   // in an inline namespace within the context named by the qualifier:
2942   //
2943   //   inline namespace N { int f(); }
2944   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2945   //
2946   // For unqualified declarations, the semantic context *can* change
2947   // along the redeclaration chain (for local extern declarations,
2948   // extern "C" declarations, and friend declarations in particular).
2949   if (!NewD->getQualifier())
2950     return;
2951 
2952   // NewD is probably already in the right context.
2953   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2954   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2955   if (NamedDC->Equals(SemaDC))
2956     return;
2957 
2958   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2959           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2960          "unexpected context for redeclaration");
2961 
2962   auto *LexDC = NewD->getLexicalDeclContext();
2963   auto FixSemaDC = [=](NamedDecl *D) {
2964     if (!D)
2965       return;
2966     D->setDeclContext(SemaDC);
2967     D->setLexicalDeclContext(LexDC);
2968   };
2969 
2970   FixSemaDC(NewD);
2971   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2972     FixSemaDC(FD->getDescribedFunctionTemplate());
2973   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2974     FixSemaDC(VD->getDescribedVarTemplate());
2975 }
2976 
2977 /// MergeFunctionDecl - We just parsed a function 'New' from
2978 /// declarator D which has the same name and scope as a previous
2979 /// declaration 'Old'.  Figure out how to resolve this situation,
2980 /// merging decls or emitting diagnostics as appropriate.
2981 ///
2982 /// In C++, New and Old must be declarations that are not
2983 /// overloaded. Use IsOverload to determine whether New and Old are
2984 /// overloaded, and to select the Old declaration that New should be
2985 /// merged with.
2986 ///
2987 /// Returns true if there was an error, false otherwise.
2988 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2989                              Scope *S, bool MergeTypeWithOld) {
2990   // Verify the old decl was also a function.
2991   FunctionDecl *Old = OldD->getAsFunction();
2992   if (!Old) {
2993     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2994       if (New->getFriendObjectKind()) {
2995         Diag(New->getLocation(), diag::err_using_decl_friend);
2996         Diag(Shadow->getTargetDecl()->getLocation(),
2997              diag::note_using_decl_target);
2998         Diag(Shadow->getUsingDecl()->getLocation(),
2999              diag::note_using_decl) << 0;
3000         return true;
3001       }
3002 
3003       // Check whether the two declarations might declare the same function.
3004       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3005         return true;
3006       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3007     } else {
3008       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3009         << New->getDeclName();
3010       notePreviousDefinition(OldD, New->getLocation());
3011       return true;
3012     }
3013   }
3014 
3015   // If the old declaration is invalid, just give up here.
3016   if (Old->isInvalidDecl())
3017     return true;
3018 
3019   // Disallow redeclaration of some builtins.
3020   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3021     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3022     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3023         << Old << Old->getType();
3024     return true;
3025   }
3026 
3027   diag::kind PrevDiag;
3028   SourceLocation OldLocation;
3029   std::tie(PrevDiag, OldLocation) =
3030       getNoteDiagForInvalidRedeclaration(Old, New);
3031 
3032   // Don't complain about this if we're in GNU89 mode and the old function
3033   // is an extern inline function.
3034   // Don't complain about specializations. They are not supposed to have
3035   // storage classes.
3036   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3037       New->getStorageClass() == SC_Static &&
3038       Old->hasExternalFormalLinkage() &&
3039       !New->getTemplateSpecializationInfo() &&
3040       !canRedefineFunction(Old, getLangOpts())) {
3041     if (getLangOpts().MicrosoftExt) {
3042       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3043       Diag(OldLocation, PrevDiag);
3044     } else {
3045       Diag(New->getLocation(), diag::err_static_non_static) << New;
3046       Diag(OldLocation, PrevDiag);
3047       return true;
3048     }
3049   }
3050 
3051   if (New->hasAttr<InternalLinkageAttr>() &&
3052       !Old->hasAttr<InternalLinkageAttr>()) {
3053     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3054         << New->getDeclName();
3055     notePreviousDefinition(Old, New->getLocation());
3056     New->dropAttr<InternalLinkageAttr>();
3057   }
3058 
3059   if (CheckRedeclarationModuleOwnership(New, Old))
3060     return true;
3061 
3062   if (!getLangOpts().CPlusPlus) {
3063     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3064     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3065       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3066         << New << OldOvl;
3067 
3068       // Try our best to find a decl that actually has the overloadable
3069       // attribute for the note. In most cases (e.g. programs with only one
3070       // broken declaration/definition), this won't matter.
3071       //
3072       // FIXME: We could do this if we juggled some extra state in
3073       // OverloadableAttr, rather than just removing it.
3074       const Decl *DiagOld = Old;
3075       if (OldOvl) {
3076         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3077           const auto *A = D->getAttr<OverloadableAttr>();
3078           return A && !A->isImplicit();
3079         });
3080         // If we've implicitly added *all* of the overloadable attrs to this
3081         // chain, emitting a "previous redecl" note is pointless.
3082         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3083       }
3084 
3085       if (DiagOld)
3086         Diag(DiagOld->getLocation(),
3087              diag::note_attribute_overloadable_prev_overload)
3088           << OldOvl;
3089 
3090       if (OldOvl)
3091         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3092       else
3093         New->dropAttr<OverloadableAttr>();
3094     }
3095   }
3096 
3097   // If a function is first declared with a calling convention, but is later
3098   // declared or defined without one, all following decls assume the calling
3099   // convention of the first.
3100   //
3101   // It's OK if a function is first declared without a calling convention,
3102   // but is later declared or defined with the default calling convention.
3103   //
3104   // To test if either decl has an explicit calling convention, we look for
3105   // AttributedType sugar nodes on the type as written.  If they are missing or
3106   // were canonicalized away, we assume the calling convention was implicit.
3107   //
3108   // Note also that we DO NOT return at this point, because we still have
3109   // other tests to run.
3110   QualType OldQType = Context.getCanonicalType(Old->getType());
3111   QualType NewQType = Context.getCanonicalType(New->getType());
3112   const FunctionType *OldType = cast<FunctionType>(OldQType);
3113   const FunctionType *NewType = cast<FunctionType>(NewQType);
3114   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3115   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3116   bool RequiresAdjustment = false;
3117 
3118   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3119     FunctionDecl *First = Old->getFirstDecl();
3120     const FunctionType *FT =
3121         First->getType().getCanonicalType()->castAs<FunctionType>();
3122     FunctionType::ExtInfo FI = FT->getExtInfo();
3123     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3124     if (!NewCCExplicit) {
3125       // Inherit the CC from the previous declaration if it was specified
3126       // there but not here.
3127       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3128       RequiresAdjustment = true;
3129     } else {
3130       // Calling conventions aren't compatible, so complain.
3131       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3132       Diag(New->getLocation(), diag::err_cconv_change)
3133         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3134         << !FirstCCExplicit
3135         << (!FirstCCExplicit ? "" :
3136             FunctionType::getNameForCallConv(FI.getCC()));
3137 
3138       // Put the note on the first decl, since it is the one that matters.
3139       Diag(First->getLocation(), diag::note_previous_declaration);
3140       return true;
3141     }
3142   }
3143 
3144   // FIXME: diagnose the other way around?
3145   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3146     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3147     RequiresAdjustment = true;
3148   }
3149 
3150   // Merge regparm attribute.
3151   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3152       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3153     if (NewTypeInfo.getHasRegParm()) {
3154       Diag(New->getLocation(), diag::err_regparm_mismatch)
3155         << NewType->getRegParmType()
3156         << OldType->getRegParmType();
3157       Diag(OldLocation, diag::note_previous_declaration);
3158       return true;
3159     }
3160 
3161     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3162     RequiresAdjustment = true;
3163   }
3164 
3165   // Merge ns_returns_retained attribute.
3166   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3167     if (NewTypeInfo.getProducesResult()) {
3168       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3169           << "'ns_returns_retained'";
3170       Diag(OldLocation, diag::note_previous_declaration);
3171       return true;
3172     }
3173 
3174     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3175     RequiresAdjustment = true;
3176   }
3177 
3178   if (OldTypeInfo.getNoCallerSavedRegs() !=
3179       NewTypeInfo.getNoCallerSavedRegs()) {
3180     if (NewTypeInfo.getNoCallerSavedRegs()) {
3181       AnyX86NoCallerSavedRegistersAttr *Attr =
3182         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3183       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3184       Diag(OldLocation, diag::note_previous_declaration);
3185       return true;
3186     }
3187 
3188     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3189     RequiresAdjustment = true;
3190   }
3191 
3192   if (RequiresAdjustment) {
3193     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3194     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3195     New->setType(QualType(AdjustedType, 0));
3196     NewQType = Context.getCanonicalType(New->getType());
3197     NewType = cast<FunctionType>(NewQType);
3198   }
3199 
3200   // If this redeclaration makes the function inline, we may need to add it to
3201   // UndefinedButUsed.
3202   if (!Old->isInlined() && New->isInlined() &&
3203       !New->hasAttr<GNUInlineAttr>() &&
3204       !getLangOpts().GNUInline &&
3205       Old->isUsed(false) &&
3206       !Old->isDefined() && !New->isThisDeclarationADefinition())
3207     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3208                                            SourceLocation()));
3209 
3210   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3211   // about it.
3212   if (New->hasAttr<GNUInlineAttr>() &&
3213       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3214     UndefinedButUsed.erase(Old->getCanonicalDecl());
3215   }
3216 
3217   // If pass_object_size params don't match up perfectly, this isn't a valid
3218   // redeclaration.
3219   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3220       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3221     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3222         << New->getDeclName();
3223     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3224     return true;
3225   }
3226 
3227   if (getLangOpts().CPlusPlus) {
3228     // C++1z [over.load]p2
3229     //   Certain function declarations cannot be overloaded:
3230     //     -- Function declarations that differ only in the return type,
3231     //        the exception specification, or both cannot be overloaded.
3232 
3233     // Check the exception specifications match. This may recompute the type of
3234     // both Old and New if it resolved exception specifications, so grab the
3235     // types again after this. Because this updates the type, we do this before
3236     // any of the other checks below, which may update the "de facto" NewQType
3237     // but do not necessarily update the type of New.
3238     if (CheckEquivalentExceptionSpec(Old, New))
3239       return true;
3240     OldQType = Context.getCanonicalType(Old->getType());
3241     NewQType = Context.getCanonicalType(New->getType());
3242 
3243     // Go back to the type source info to compare the declared return types,
3244     // per C++1y [dcl.type.auto]p13:
3245     //   Redeclarations or specializations of a function or function template
3246     //   with a declared return type that uses a placeholder type shall also
3247     //   use that placeholder, not a deduced type.
3248     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3249     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3250     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3251         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3252                                        OldDeclaredReturnType)) {
3253       QualType ResQT;
3254       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3255           OldDeclaredReturnType->isObjCObjectPointerType())
3256         // FIXME: This does the wrong thing for a deduced return type.
3257         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3258       if (ResQT.isNull()) {
3259         if (New->isCXXClassMember() && New->isOutOfLine())
3260           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3261               << New << New->getReturnTypeSourceRange();
3262         else
3263           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3264               << New->getReturnTypeSourceRange();
3265         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3266                                     << Old->getReturnTypeSourceRange();
3267         return true;
3268       }
3269       else
3270         NewQType = ResQT;
3271     }
3272 
3273     QualType OldReturnType = OldType->getReturnType();
3274     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3275     if (OldReturnType != NewReturnType) {
3276       // If this function has a deduced return type and has already been
3277       // defined, copy the deduced value from the old declaration.
3278       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3279       if (OldAT && OldAT->isDeduced()) {
3280         New->setType(
3281             SubstAutoType(New->getType(),
3282                           OldAT->isDependentType() ? Context.DependentTy
3283                                                    : OldAT->getDeducedType()));
3284         NewQType = Context.getCanonicalType(
3285             SubstAutoType(NewQType,
3286                           OldAT->isDependentType() ? Context.DependentTy
3287                                                    : OldAT->getDeducedType()));
3288       }
3289     }
3290 
3291     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3292     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3293     if (OldMethod && NewMethod) {
3294       // Preserve triviality.
3295       NewMethod->setTrivial(OldMethod->isTrivial());
3296 
3297       // MSVC allows explicit template specialization at class scope:
3298       // 2 CXXMethodDecls referring to the same function will be injected.
3299       // We don't want a redeclaration error.
3300       bool IsClassScopeExplicitSpecialization =
3301                               OldMethod->isFunctionTemplateSpecialization() &&
3302                               NewMethod->isFunctionTemplateSpecialization();
3303       bool isFriend = NewMethod->getFriendObjectKind();
3304 
3305       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3306           !IsClassScopeExplicitSpecialization) {
3307         //    -- Member function declarations with the same name and the
3308         //       same parameter types cannot be overloaded if any of them
3309         //       is a static member function declaration.
3310         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3311           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3312           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3313           return true;
3314         }
3315 
3316         // C++ [class.mem]p1:
3317         //   [...] A member shall not be declared twice in the
3318         //   member-specification, except that a nested class or member
3319         //   class template can be declared and then later defined.
3320         if (!inTemplateInstantiation()) {
3321           unsigned NewDiag;
3322           if (isa<CXXConstructorDecl>(OldMethod))
3323             NewDiag = diag::err_constructor_redeclared;
3324           else if (isa<CXXDestructorDecl>(NewMethod))
3325             NewDiag = diag::err_destructor_redeclared;
3326           else if (isa<CXXConversionDecl>(NewMethod))
3327             NewDiag = diag::err_conv_function_redeclared;
3328           else
3329             NewDiag = diag::err_member_redeclared;
3330 
3331           Diag(New->getLocation(), NewDiag);
3332         } else {
3333           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3334             << New << New->getType();
3335         }
3336         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3337         return true;
3338 
3339       // Complain if this is an explicit declaration of a special
3340       // member that was initially declared implicitly.
3341       //
3342       // As an exception, it's okay to befriend such methods in order
3343       // to permit the implicit constructor/destructor/operator calls.
3344       } else if (OldMethod->isImplicit()) {
3345         if (isFriend) {
3346           NewMethod->setImplicit();
3347         } else {
3348           Diag(NewMethod->getLocation(),
3349                diag::err_definition_of_implicitly_declared_member)
3350             << New << getSpecialMember(OldMethod);
3351           return true;
3352         }
3353       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3354         Diag(NewMethod->getLocation(),
3355              diag::err_definition_of_explicitly_defaulted_member)
3356           << getSpecialMember(OldMethod);
3357         return true;
3358       }
3359     }
3360 
3361     // C++11 [dcl.attr.noreturn]p1:
3362     //   The first declaration of a function shall specify the noreturn
3363     //   attribute if any declaration of that function specifies the noreturn
3364     //   attribute.
3365     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3366     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3367       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3368       Diag(Old->getFirstDecl()->getLocation(),
3369            diag::note_noreturn_missing_first_decl);
3370     }
3371 
3372     // C++11 [dcl.attr.depend]p2:
3373     //   The first declaration of a function shall specify the
3374     //   carries_dependency attribute for its declarator-id if any declaration
3375     //   of the function specifies the carries_dependency attribute.
3376     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3377     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3378       Diag(CDA->getLocation(),
3379            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3380       Diag(Old->getFirstDecl()->getLocation(),
3381            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3382     }
3383 
3384     // (C++98 8.3.5p3):
3385     //   All declarations for a function shall agree exactly in both the
3386     //   return type and the parameter-type-list.
3387     // We also want to respect all the extended bits except noreturn.
3388 
3389     // noreturn should now match unless the old type info didn't have it.
3390     QualType OldQTypeForComparison = OldQType;
3391     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3392       auto *OldType = OldQType->castAs<FunctionProtoType>();
3393       const FunctionType *OldTypeForComparison
3394         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3395       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3396       assert(OldQTypeForComparison.isCanonical());
3397     }
3398 
3399     if (haveIncompatibleLanguageLinkages(Old, New)) {
3400       // As a special case, retain the language linkage from previous
3401       // declarations of a friend function as an extension.
3402       //
3403       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3404       // and is useful because there's otherwise no way to specify language
3405       // linkage within class scope.
3406       //
3407       // Check cautiously as the friend object kind isn't yet complete.
3408       if (New->getFriendObjectKind() != Decl::FOK_None) {
3409         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3410         Diag(OldLocation, PrevDiag);
3411       } else {
3412         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3413         Diag(OldLocation, PrevDiag);
3414         return true;
3415       }
3416     }
3417 
3418     if (OldQTypeForComparison == NewQType)
3419       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3420 
3421     // If the types are imprecise (due to dependent constructs in friends or
3422     // local extern declarations), it's OK if they differ. We'll check again
3423     // during instantiation.
3424     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3425       return false;
3426 
3427     // Fall through for conflicting redeclarations and redefinitions.
3428   }
3429 
3430   // C: Function types need to be compatible, not identical. This handles
3431   // duplicate function decls like "void f(int); void f(enum X);" properly.
3432   if (!getLangOpts().CPlusPlus &&
3433       Context.typesAreCompatible(OldQType, NewQType)) {
3434     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3435     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3436     const FunctionProtoType *OldProto = nullptr;
3437     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3438         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3439       // The old declaration provided a function prototype, but the
3440       // new declaration does not. Merge in the prototype.
3441       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3442       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3443       NewQType =
3444           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3445                                   OldProto->getExtProtoInfo());
3446       New->setType(NewQType);
3447       New->setHasInheritedPrototype();
3448 
3449       // Synthesize parameters with the same types.
3450       SmallVector<ParmVarDecl*, 16> Params;
3451       for (const auto &ParamType : OldProto->param_types()) {
3452         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3453                                                  SourceLocation(), nullptr,
3454                                                  ParamType, /*TInfo=*/nullptr,
3455                                                  SC_None, nullptr);
3456         Param->setScopeInfo(0, Params.size());
3457         Param->setImplicit();
3458         Params.push_back(Param);
3459       }
3460 
3461       New->setParams(Params);
3462     }
3463 
3464     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3465   }
3466 
3467   // GNU C permits a K&R definition to follow a prototype declaration
3468   // if the declared types of the parameters in the K&R definition
3469   // match the types in the prototype declaration, even when the
3470   // promoted types of the parameters from the K&R definition differ
3471   // from the types in the prototype. GCC then keeps the types from
3472   // the prototype.
3473   //
3474   // If a variadic prototype is followed by a non-variadic K&R definition,
3475   // the K&R definition becomes variadic.  This is sort of an edge case, but
3476   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3477   // C99 6.9.1p8.
3478   if (!getLangOpts().CPlusPlus &&
3479       Old->hasPrototype() && !New->hasPrototype() &&
3480       New->getType()->getAs<FunctionProtoType>() &&
3481       Old->getNumParams() == New->getNumParams()) {
3482     SmallVector<QualType, 16> ArgTypes;
3483     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3484     const FunctionProtoType *OldProto
3485       = Old->getType()->getAs<FunctionProtoType>();
3486     const FunctionProtoType *NewProto
3487       = New->getType()->getAs<FunctionProtoType>();
3488 
3489     // Determine whether this is the GNU C extension.
3490     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3491                                                NewProto->getReturnType());
3492     bool LooseCompatible = !MergedReturn.isNull();
3493     for (unsigned Idx = 0, End = Old->getNumParams();
3494          LooseCompatible && Idx != End; ++Idx) {
3495       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3496       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3497       if (Context.typesAreCompatible(OldParm->getType(),
3498                                      NewProto->getParamType(Idx))) {
3499         ArgTypes.push_back(NewParm->getType());
3500       } else if (Context.typesAreCompatible(OldParm->getType(),
3501                                             NewParm->getType(),
3502                                             /*CompareUnqualified=*/true)) {
3503         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3504                                            NewProto->getParamType(Idx) };
3505         Warnings.push_back(Warn);
3506         ArgTypes.push_back(NewParm->getType());
3507       } else
3508         LooseCompatible = false;
3509     }
3510 
3511     if (LooseCompatible) {
3512       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3513         Diag(Warnings[Warn].NewParm->getLocation(),
3514              diag::ext_param_promoted_not_compatible_with_prototype)
3515           << Warnings[Warn].PromotedType
3516           << Warnings[Warn].OldParm->getType();
3517         if (Warnings[Warn].OldParm->getLocation().isValid())
3518           Diag(Warnings[Warn].OldParm->getLocation(),
3519                diag::note_previous_declaration);
3520       }
3521 
3522       if (MergeTypeWithOld)
3523         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3524                                              OldProto->getExtProtoInfo()));
3525       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3526     }
3527 
3528     // Fall through to diagnose conflicting types.
3529   }
3530 
3531   // A function that has already been declared has been redeclared or
3532   // defined with a different type; show an appropriate diagnostic.
3533 
3534   // If the previous declaration was an implicitly-generated builtin
3535   // declaration, then at the very least we should use a specialized note.
3536   unsigned BuiltinID;
3537   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3538     // If it's actually a library-defined builtin function like 'malloc'
3539     // or 'printf', just warn about the incompatible redeclaration.
3540     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3541       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3542       Diag(OldLocation, diag::note_previous_builtin_declaration)
3543         << Old << Old->getType();
3544 
3545       // If this is a global redeclaration, just forget hereafter
3546       // about the "builtin-ness" of the function.
3547       //
3548       // Doing this for local extern declarations is problematic.  If
3549       // the builtin declaration remains visible, a second invalid
3550       // local declaration will produce a hard error; if it doesn't
3551       // remain visible, a single bogus local redeclaration (which is
3552       // actually only a warning) could break all the downstream code.
3553       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3554         New->getIdentifier()->revertBuiltin();
3555 
3556       return false;
3557     }
3558 
3559     PrevDiag = diag::note_previous_builtin_declaration;
3560   }
3561 
3562   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3563   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3564   return true;
3565 }
3566 
3567 /// Completes the merge of two function declarations that are
3568 /// known to be compatible.
3569 ///
3570 /// This routine handles the merging of attributes and other
3571 /// properties of function declarations from the old declaration to
3572 /// the new declaration, once we know that New is in fact a
3573 /// redeclaration of Old.
3574 ///
3575 /// \returns false
3576 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3577                                         Scope *S, bool MergeTypeWithOld) {
3578   // Merge the attributes
3579   mergeDeclAttributes(New, Old);
3580 
3581   // Merge "pure" flag.
3582   if (Old->isPure())
3583     New->setPure();
3584 
3585   // Merge "used" flag.
3586   if (Old->getMostRecentDecl()->isUsed(false))
3587     New->setIsUsed();
3588 
3589   // Merge attributes from the parameters.  These can mismatch with K&R
3590   // declarations.
3591   if (New->getNumParams() == Old->getNumParams())
3592       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3593         ParmVarDecl *NewParam = New->getParamDecl(i);
3594         ParmVarDecl *OldParam = Old->getParamDecl(i);
3595         mergeParamDeclAttributes(NewParam, OldParam, *this);
3596         mergeParamDeclTypes(NewParam, OldParam, *this);
3597       }
3598 
3599   if (getLangOpts().CPlusPlus)
3600     return MergeCXXFunctionDecl(New, Old, S);
3601 
3602   // Merge the function types so the we get the composite types for the return
3603   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3604   // was visible.
3605   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3606   if (!Merged.isNull() && MergeTypeWithOld)
3607     New->setType(Merged);
3608 
3609   return false;
3610 }
3611 
3612 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3613                                 ObjCMethodDecl *oldMethod) {
3614   // Merge the attributes, including deprecated/unavailable
3615   AvailabilityMergeKind MergeKind =
3616     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3617       ? AMK_ProtocolImplementation
3618       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3619                                                        : AMK_Override;
3620 
3621   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3622 
3623   // Merge attributes from the parameters.
3624   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3625                                        oe = oldMethod->param_end();
3626   for (ObjCMethodDecl::param_iterator
3627          ni = newMethod->param_begin(), ne = newMethod->param_end();
3628        ni != ne && oi != oe; ++ni, ++oi)
3629     mergeParamDeclAttributes(*ni, *oi, *this);
3630 
3631   CheckObjCMethodOverride(newMethod, oldMethod);
3632 }
3633 
3634 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3635   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3636 
3637   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3638          ? diag::err_redefinition_different_type
3639          : diag::err_redeclaration_different_type)
3640     << New->getDeclName() << New->getType() << Old->getType();
3641 
3642   diag::kind PrevDiag;
3643   SourceLocation OldLocation;
3644   std::tie(PrevDiag, OldLocation)
3645     = getNoteDiagForInvalidRedeclaration(Old, New);
3646   S.Diag(OldLocation, PrevDiag);
3647   New->setInvalidDecl();
3648 }
3649 
3650 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3651 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3652 /// emitting diagnostics as appropriate.
3653 ///
3654 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3655 /// to here in AddInitializerToDecl. We can't check them before the initializer
3656 /// is attached.
3657 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3658                              bool MergeTypeWithOld) {
3659   if (New->isInvalidDecl() || Old->isInvalidDecl())
3660     return;
3661 
3662   QualType MergedT;
3663   if (getLangOpts().CPlusPlus) {
3664     if (New->getType()->isUndeducedType()) {
3665       // We don't know what the new type is until the initializer is attached.
3666       return;
3667     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3668       // These could still be something that needs exception specs checked.
3669       return MergeVarDeclExceptionSpecs(New, Old);
3670     }
3671     // C++ [basic.link]p10:
3672     //   [...] the types specified by all declarations referring to a given
3673     //   object or function shall be identical, except that declarations for an
3674     //   array object can specify array types that differ by the presence or
3675     //   absence of a major array bound (8.3.4).
3676     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3677       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3678       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3679 
3680       // We are merging a variable declaration New into Old. If it has an array
3681       // bound, and that bound differs from Old's bound, we should diagnose the
3682       // mismatch.
3683       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3684         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3685              PrevVD = PrevVD->getPreviousDecl()) {
3686           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3687           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3688             continue;
3689 
3690           if (!Context.hasSameType(NewArray, PrevVDTy))
3691             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3692         }
3693       }
3694 
3695       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3696         if (Context.hasSameType(OldArray->getElementType(),
3697                                 NewArray->getElementType()))
3698           MergedT = New->getType();
3699       }
3700       // FIXME: Check visibility. New is hidden but has a complete type. If New
3701       // has no array bound, it should not inherit one from Old, if Old is not
3702       // visible.
3703       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3704         if (Context.hasSameType(OldArray->getElementType(),
3705                                 NewArray->getElementType()))
3706           MergedT = Old->getType();
3707       }
3708     }
3709     else if (New->getType()->isObjCObjectPointerType() &&
3710                Old->getType()->isObjCObjectPointerType()) {
3711       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3712                                               Old->getType());
3713     }
3714   } else {
3715     // C 6.2.7p2:
3716     //   All declarations that refer to the same object or function shall have
3717     //   compatible type.
3718     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3719   }
3720   if (MergedT.isNull()) {
3721     // It's OK if we couldn't merge types if either type is dependent, for a
3722     // block-scope variable. In other cases (static data members of class
3723     // templates, variable templates, ...), we require the types to be
3724     // equivalent.
3725     // FIXME: The C++ standard doesn't say anything about this.
3726     if ((New->getType()->isDependentType() ||
3727          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3728       // If the old type was dependent, we can't merge with it, so the new type
3729       // becomes dependent for now. We'll reproduce the original type when we
3730       // instantiate the TypeSourceInfo for the variable.
3731       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3732         New->setType(Context.DependentTy);
3733       return;
3734     }
3735     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3736   }
3737 
3738   // Don't actually update the type on the new declaration if the old
3739   // declaration was an extern declaration in a different scope.
3740   if (MergeTypeWithOld)
3741     New->setType(MergedT);
3742 }
3743 
3744 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3745                                   LookupResult &Previous) {
3746   // C11 6.2.7p4:
3747   //   For an identifier with internal or external linkage declared
3748   //   in a scope in which a prior declaration of that identifier is
3749   //   visible, if the prior declaration specifies internal or
3750   //   external linkage, the type of the identifier at the later
3751   //   declaration becomes the composite type.
3752   //
3753   // If the variable isn't visible, we do not merge with its type.
3754   if (Previous.isShadowed())
3755     return false;
3756 
3757   if (S.getLangOpts().CPlusPlus) {
3758     // C++11 [dcl.array]p3:
3759     //   If there is a preceding declaration of the entity in the same
3760     //   scope in which the bound was specified, an omitted array bound
3761     //   is taken to be the same as in that earlier declaration.
3762     return NewVD->isPreviousDeclInSameBlockScope() ||
3763            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3764             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3765   } else {
3766     // If the old declaration was function-local, don't merge with its
3767     // type unless we're in the same function.
3768     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3769            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3770   }
3771 }
3772 
3773 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3774 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3775 /// situation, merging decls or emitting diagnostics as appropriate.
3776 ///
3777 /// Tentative definition rules (C99 6.9.2p2) are checked by
3778 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3779 /// definitions here, since the initializer hasn't been attached.
3780 ///
3781 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3782   // If the new decl is already invalid, don't do any other checking.
3783   if (New->isInvalidDecl())
3784     return;
3785 
3786   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3787     return;
3788 
3789   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3790 
3791   // Verify the old decl was also a variable or variable template.
3792   VarDecl *Old = nullptr;
3793   VarTemplateDecl *OldTemplate = nullptr;
3794   if (Previous.isSingleResult()) {
3795     if (NewTemplate) {
3796       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3797       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3798 
3799       if (auto *Shadow =
3800               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3801         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3802           return New->setInvalidDecl();
3803     } else {
3804       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3805 
3806       if (auto *Shadow =
3807               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3808         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3809           return New->setInvalidDecl();
3810     }
3811   }
3812   if (!Old) {
3813     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3814         << New->getDeclName();
3815     notePreviousDefinition(Previous.getRepresentativeDecl(),
3816                            New->getLocation());
3817     return New->setInvalidDecl();
3818   }
3819 
3820   // Ensure the template parameters are compatible.
3821   if (NewTemplate &&
3822       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3823                                       OldTemplate->getTemplateParameters(),
3824                                       /*Complain=*/true, TPL_TemplateMatch))
3825     return New->setInvalidDecl();
3826 
3827   // C++ [class.mem]p1:
3828   //   A member shall not be declared twice in the member-specification [...]
3829   //
3830   // Here, we need only consider static data members.
3831   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3832     Diag(New->getLocation(), diag::err_duplicate_member)
3833       << New->getIdentifier();
3834     Diag(Old->getLocation(), diag::note_previous_declaration);
3835     New->setInvalidDecl();
3836   }
3837 
3838   mergeDeclAttributes(New, Old);
3839   // Warn if an already-declared variable is made a weak_import in a subsequent
3840   // declaration
3841   if (New->hasAttr<WeakImportAttr>() &&
3842       Old->getStorageClass() == SC_None &&
3843       !Old->hasAttr<WeakImportAttr>()) {
3844     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3845     notePreviousDefinition(Old, New->getLocation());
3846     // Remove weak_import attribute on new declaration.
3847     New->dropAttr<WeakImportAttr>();
3848   }
3849 
3850   if (New->hasAttr<InternalLinkageAttr>() &&
3851       !Old->hasAttr<InternalLinkageAttr>()) {
3852     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3853         << New->getDeclName();
3854     notePreviousDefinition(Old, New->getLocation());
3855     New->dropAttr<InternalLinkageAttr>();
3856   }
3857 
3858   // Merge the types.
3859   VarDecl *MostRecent = Old->getMostRecentDecl();
3860   if (MostRecent != Old) {
3861     MergeVarDeclTypes(New, MostRecent,
3862                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3863     if (New->isInvalidDecl())
3864       return;
3865   }
3866 
3867   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3868   if (New->isInvalidDecl())
3869     return;
3870 
3871   diag::kind PrevDiag;
3872   SourceLocation OldLocation;
3873   std::tie(PrevDiag, OldLocation) =
3874       getNoteDiagForInvalidRedeclaration(Old, New);
3875 
3876   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3877   if (New->getStorageClass() == SC_Static &&
3878       !New->isStaticDataMember() &&
3879       Old->hasExternalFormalLinkage()) {
3880     if (getLangOpts().MicrosoftExt) {
3881       Diag(New->getLocation(), diag::ext_static_non_static)
3882           << New->getDeclName();
3883       Diag(OldLocation, PrevDiag);
3884     } else {
3885       Diag(New->getLocation(), diag::err_static_non_static)
3886           << New->getDeclName();
3887       Diag(OldLocation, PrevDiag);
3888       return New->setInvalidDecl();
3889     }
3890   }
3891   // C99 6.2.2p4:
3892   //   For an identifier declared with the storage-class specifier
3893   //   extern in a scope in which a prior declaration of that
3894   //   identifier is visible,23) if the prior declaration specifies
3895   //   internal or external linkage, the linkage of the identifier at
3896   //   the later declaration is the same as the linkage specified at
3897   //   the prior declaration. If no prior declaration is visible, or
3898   //   if the prior declaration specifies no linkage, then the
3899   //   identifier has external linkage.
3900   if (New->hasExternalStorage() && Old->hasLinkage())
3901     /* Okay */;
3902   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3903            !New->isStaticDataMember() &&
3904            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3905     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3906     Diag(OldLocation, PrevDiag);
3907     return New->setInvalidDecl();
3908   }
3909 
3910   // Check if extern is followed by non-extern and vice-versa.
3911   if (New->hasExternalStorage() &&
3912       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3913     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3914     Diag(OldLocation, PrevDiag);
3915     return New->setInvalidDecl();
3916   }
3917   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3918       !New->hasExternalStorage()) {
3919     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3920     Diag(OldLocation, PrevDiag);
3921     return New->setInvalidDecl();
3922   }
3923 
3924   if (CheckRedeclarationModuleOwnership(New, Old))
3925     return;
3926 
3927   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3928 
3929   // FIXME: The test for external storage here seems wrong? We still
3930   // need to check for mismatches.
3931   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3932       // Don't complain about out-of-line definitions of static members.
3933       !(Old->getLexicalDeclContext()->isRecord() &&
3934         !New->getLexicalDeclContext()->isRecord())) {
3935     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3936     Diag(OldLocation, PrevDiag);
3937     return New->setInvalidDecl();
3938   }
3939 
3940   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3941     if (VarDecl *Def = Old->getDefinition()) {
3942       // C++1z [dcl.fcn.spec]p4:
3943       //   If the definition of a variable appears in a translation unit before
3944       //   its first declaration as inline, the program is ill-formed.
3945       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3946       Diag(Def->getLocation(), diag::note_previous_definition);
3947     }
3948   }
3949 
3950   // If this redeclaration makes the variable inline, we may need to add it to
3951   // UndefinedButUsed.
3952   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3953       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3954     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3955                                            SourceLocation()));
3956 
3957   if (New->getTLSKind() != Old->getTLSKind()) {
3958     if (!Old->getTLSKind()) {
3959       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3960       Diag(OldLocation, PrevDiag);
3961     } else if (!New->getTLSKind()) {
3962       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3963       Diag(OldLocation, PrevDiag);
3964     } else {
3965       // Do not allow redeclaration to change the variable between requiring
3966       // static and dynamic initialization.
3967       // FIXME: GCC allows this, but uses the TLS keyword on the first
3968       // declaration to determine the kind. Do we need to be compatible here?
3969       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3970         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3971       Diag(OldLocation, PrevDiag);
3972     }
3973   }
3974 
3975   // C++ doesn't have tentative definitions, so go right ahead and check here.
3976   if (getLangOpts().CPlusPlus &&
3977       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3978     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3979         Old->getCanonicalDecl()->isConstexpr()) {
3980       // This definition won't be a definition any more once it's been merged.
3981       Diag(New->getLocation(),
3982            diag::warn_deprecated_redundant_constexpr_static_def);
3983     } else if (VarDecl *Def = Old->getDefinition()) {
3984       if (checkVarDeclRedefinition(Def, New))
3985         return;
3986     }
3987   }
3988 
3989   if (haveIncompatibleLanguageLinkages(Old, New)) {
3990     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3991     Diag(OldLocation, PrevDiag);
3992     New->setInvalidDecl();
3993     return;
3994   }
3995 
3996   // Merge "used" flag.
3997   if (Old->getMostRecentDecl()->isUsed(false))
3998     New->setIsUsed();
3999 
4000   // Keep a chain of previous declarations.
4001   New->setPreviousDecl(Old);
4002   if (NewTemplate)
4003     NewTemplate->setPreviousDecl(OldTemplate);
4004   adjustDeclContextForDeclaratorDecl(New, Old);
4005 
4006   // Inherit access appropriately.
4007   New->setAccess(Old->getAccess());
4008   if (NewTemplate)
4009     NewTemplate->setAccess(New->getAccess());
4010 
4011   if (Old->isInline())
4012     New->setImplicitlyInline();
4013 }
4014 
4015 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4016   SourceManager &SrcMgr = getSourceManager();
4017   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4018   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4019   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4020   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4021   auto &HSI = PP.getHeaderSearchInfo();
4022   StringRef HdrFilename =
4023       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4024 
4025   auto noteFromModuleOrInclude = [&](Module *Mod,
4026                                      SourceLocation IncLoc) -> bool {
4027     // Redefinition errors with modules are common with non modular mapped
4028     // headers, example: a non-modular header H in module A that also gets
4029     // included directly in a TU. Pointing twice to the same header/definition
4030     // is confusing, try to get better diagnostics when modules is on.
4031     if (IncLoc.isValid()) {
4032       if (Mod) {
4033         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4034             << HdrFilename.str() << Mod->getFullModuleName();
4035         if (!Mod->DefinitionLoc.isInvalid())
4036           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4037               << Mod->getFullModuleName();
4038       } else {
4039         Diag(IncLoc, diag::note_redefinition_include_same_file)
4040             << HdrFilename.str();
4041       }
4042       return true;
4043     }
4044 
4045     return false;
4046   };
4047 
4048   // Is it the same file and same offset? Provide more information on why
4049   // this leads to a redefinition error.
4050   bool EmittedDiag = false;
4051   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4052     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4053     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4054     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4055     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4056 
4057     // If the header has no guards, emit a note suggesting one.
4058     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4059       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4060 
4061     if (EmittedDiag)
4062       return;
4063   }
4064 
4065   // Redefinition coming from different files or couldn't do better above.
4066   if (Old->getLocation().isValid())
4067     Diag(Old->getLocation(), diag::note_previous_definition);
4068 }
4069 
4070 /// We've just determined that \p Old and \p New both appear to be definitions
4071 /// of the same variable. Either diagnose or fix the problem.
4072 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4073   if (!hasVisibleDefinition(Old) &&
4074       (New->getFormalLinkage() == InternalLinkage ||
4075        New->isInline() ||
4076        New->getDescribedVarTemplate() ||
4077        New->getNumTemplateParameterLists() ||
4078        New->getDeclContext()->isDependentContext())) {
4079     // The previous definition is hidden, and multiple definitions are
4080     // permitted (in separate TUs). Demote this to a declaration.
4081     New->demoteThisDefinitionToDeclaration();
4082 
4083     // Make the canonical definition visible.
4084     if (auto *OldTD = Old->getDescribedVarTemplate())
4085       makeMergedDefinitionVisible(OldTD);
4086     makeMergedDefinitionVisible(Old);
4087     return false;
4088   } else {
4089     Diag(New->getLocation(), diag::err_redefinition) << New;
4090     notePreviousDefinition(Old, New->getLocation());
4091     New->setInvalidDecl();
4092     return true;
4093   }
4094 }
4095 
4096 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4097 /// no declarator (e.g. "struct foo;") is parsed.
4098 Decl *
4099 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4100                                  RecordDecl *&AnonRecord) {
4101   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4102                                     AnonRecord);
4103 }
4104 
4105 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4106 // disambiguate entities defined in different scopes.
4107 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4108 // compatibility.
4109 // We will pick our mangling number depending on which version of MSVC is being
4110 // targeted.
4111 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4112   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4113              ? S->getMSCurManglingNumber()
4114              : S->getMSLastManglingNumber();
4115 }
4116 
4117 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4118   if (!Context.getLangOpts().CPlusPlus)
4119     return;
4120 
4121   if (isa<CXXRecordDecl>(Tag->getParent())) {
4122     // If this tag is the direct child of a class, number it if
4123     // it is anonymous.
4124     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4125       return;
4126     MangleNumberingContext &MCtx =
4127         Context.getManglingNumberContext(Tag->getParent());
4128     Context.setManglingNumber(
4129         Tag, MCtx.getManglingNumber(
4130                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4131     return;
4132   }
4133 
4134   // If this tag isn't a direct child of a class, number it if it is local.
4135   Decl *ManglingContextDecl;
4136   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4137           Tag->getDeclContext(), ManglingContextDecl)) {
4138     Context.setManglingNumber(
4139         Tag, MCtx->getManglingNumber(
4140                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4141   }
4142 }
4143 
4144 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4145                                         TypedefNameDecl *NewTD) {
4146   if (TagFromDeclSpec->isInvalidDecl())
4147     return;
4148 
4149   // Do nothing if the tag already has a name for linkage purposes.
4150   if (TagFromDeclSpec->hasNameForLinkage())
4151     return;
4152 
4153   // A well-formed anonymous tag must always be a TUK_Definition.
4154   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4155 
4156   // The type must match the tag exactly;  no qualifiers allowed.
4157   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4158                            Context.getTagDeclType(TagFromDeclSpec))) {
4159     if (getLangOpts().CPlusPlus)
4160       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4161     return;
4162   }
4163 
4164   // If we've already computed linkage for the anonymous tag, then
4165   // adding a typedef name for the anonymous decl can change that
4166   // linkage, which might be a serious problem.  Diagnose this as
4167   // unsupported and ignore the typedef name.  TODO: we should
4168   // pursue this as a language defect and establish a formal rule
4169   // for how to handle it.
4170   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4171     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4172 
4173     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4174     tagLoc = getLocForEndOfToken(tagLoc);
4175 
4176     llvm::SmallString<40> textToInsert;
4177     textToInsert += ' ';
4178     textToInsert += NewTD->getIdentifier()->getName();
4179     Diag(tagLoc, diag::note_typedef_changes_linkage)
4180         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4181     return;
4182   }
4183 
4184   // Otherwise, set this is the anon-decl typedef for the tag.
4185   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4186 }
4187 
4188 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4189   switch (T) {
4190   case DeclSpec::TST_class:
4191     return 0;
4192   case DeclSpec::TST_struct:
4193     return 1;
4194   case DeclSpec::TST_interface:
4195     return 2;
4196   case DeclSpec::TST_union:
4197     return 3;
4198   case DeclSpec::TST_enum:
4199     return 4;
4200   default:
4201     llvm_unreachable("unexpected type specifier");
4202   }
4203 }
4204 
4205 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4206 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4207 /// parameters to cope with template friend declarations.
4208 Decl *
4209 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4210                                  MultiTemplateParamsArg TemplateParams,
4211                                  bool IsExplicitInstantiation,
4212                                  RecordDecl *&AnonRecord) {
4213   Decl *TagD = nullptr;
4214   TagDecl *Tag = nullptr;
4215   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4216       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4217       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4218       DS.getTypeSpecType() == DeclSpec::TST_union ||
4219       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4220     TagD = DS.getRepAsDecl();
4221 
4222     if (!TagD) // We probably had an error
4223       return nullptr;
4224 
4225     // Note that the above type specs guarantee that the
4226     // type rep is a Decl, whereas in many of the others
4227     // it's a Type.
4228     if (isa<TagDecl>(TagD))
4229       Tag = cast<TagDecl>(TagD);
4230     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4231       Tag = CTD->getTemplatedDecl();
4232   }
4233 
4234   if (Tag) {
4235     handleTagNumbering(Tag, S);
4236     Tag->setFreeStanding();
4237     if (Tag->isInvalidDecl())
4238       return Tag;
4239   }
4240 
4241   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4242     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4243     // or incomplete types shall not be restrict-qualified."
4244     if (TypeQuals & DeclSpec::TQ_restrict)
4245       Diag(DS.getRestrictSpecLoc(),
4246            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4247            << DS.getSourceRange();
4248   }
4249 
4250   if (DS.isInlineSpecified())
4251     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4252         << getLangOpts().CPlusPlus17;
4253 
4254   if (DS.isConstexprSpecified()) {
4255     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4256     // and definitions of functions and variables.
4257     if (Tag)
4258       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4259           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4260     else
4261       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4262     // Don't emit warnings after this error.
4263     return TagD;
4264   }
4265 
4266   DiagnoseFunctionSpecifiers(DS);
4267 
4268   if (DS.isFriendSpecified()) {
4269     // If we're dealing with a decl but not a TagDecl, assume that
4270     // whatever routines created it handled the friendship aspect.
4271     if (TagD && !Tag)
4272       return nullptr;
4273     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4274   }
4275 
4276   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4277   bool IsExplicitSpecialization =
4278     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4279   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4280       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4281       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4282     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4283     // nested-name-specifier unless it is an explicit instantiation
4284     // or an explicit specialization.
4285     //
4286     // FIXME: We allow class template partial specializations here too, per the
4287     // obvious intent of DR1819.
4288     //
4289     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4290     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4291         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4292     return nullptr;
4293   }
4294 
4295   // Track whether this decl-specifier declares anything.
4296   bool DeclaresAnything = true;
4297 
4298   // Handle anonymous struct definitions.
4299   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4300     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4301         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4302       if (getLangOpts().CPlusPlus ||
4303           Record->getDeclContext()->isRecord()) {
4304         // If CurContext is a DeclContext that can contain statements,
4305         // RecursiveASTVisitor won't visit the decls that
4306         // BuildAnonymousStructOrUnion() will put into CurContext.
4307         // Also store them here so that they can be part of the
4308         // DeclStmt that gets created in this case.
4309         // FIXME: Also return the IndirectFieldDecls created by
4310         // BuildAnonymousStructOr union, for the same reason?
4311         if (CurContext->isFunctionOrMethod())
4312           AnonRecord = Record;
4313         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4314                                            Context.getPrintingPolicy());
4315       }
4316 
4317       DeclaresAnything = false;
4318     }
4319   }
4320 
4321   // C11 6.7.2.1p2:
4322   //   A struct-declaration that does not declare an anonymous structure or
4323   //   anonymous union shall contain a struct-declarator-list.
4324   //
4325   // This rule also existed in C89 and C99; the grammar for struct-declaration
4326   // did not permit a struct-declaration without a struct-declarator-list.
4327   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4328       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4329     // Check for Microsoft C extension: anonymous struct/union member.
4330     // Handle 2 kinds of anonymous struct/union:
4331     //   struct STRUCT;
4332     //   union UNION;
4333     // and
4334     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4335     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4336     if ((Tag && Tag->getDeclName()) ||
4337         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4338       RecordDecl *Record = nullptr;
4339       if (Tag)
4340         Record = dyn_cast<RecordDecl>(Tag);
4341       else if (const RecordType *RT =
4342                    DS.getRepAsType().get()->getAsStructureType())
4343         Record = RT->getDecl();
4344       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4345         Record = UT->getDecl();
4346 
4347       if (Record && getLangOpts().MicrosoftExt) {
4348         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4349             << Record->isUnion() << DS.getSourceRange();
4350         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4351       }
4352 
4353       DeclaresAnything = false;
4354     }
4355   }
4356 
4357   // Skip all the checks below if we have a type error.
4358   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4359       (TagD && TagD->isInvalidDecl()))
4360     return TagD;
4361 
4362   if (getLangOpts().CPlusPlus &&
4363       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4364     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4365       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4366           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4367         DeclaresAnything = false;
4368 
4369   if (!DS.isMissingDeclaratorOk()) {
4370     // Customize diagnostic for a typedef missing a name.
4371     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4372       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4373           << DS.getSourceRange();
4374     else
4375       DeclaresAnything = false;
4376   }
4377 
4378   if (DS.isModulePrivateSpecified() &&
4379       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4380     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4381       << Tag->getTagKind()
4382       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4383 
4384   ActOnDocumentableDecl(TagD);
4385 
4386   // C 6.7/2:
4387   //   A declaration [...] shall declare at least a declarator [...], a tag,
4388   //   or the members of an enumeration.
4389   // C++ [dcl.dcl]p3:
4390   //   [If there are no declarators], and except for the declaration of an
4391   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4392   //   names into the program, or shall redeclare a name introduced by a
4393   //   previous declaration.
4394   if (!DeclaresAnything) {
4395     // In C, we allow this as a (popular) extension / bug. Don't bother
4396     // producing further diagnostics for redundant qualifiers after this.
4397     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4398     return TagD;
4399   }
4400 
4401   // C++ [dcl.stc]p1:
4402   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4403   //   init-declarator-list of the declaration shall not be empty.
4404   // C++ [dcl.fct.spec]p1:
4405   //   If a cv-qualifier appears in a decl-specifier-seq, the
4406   //   init-declarator-list of the declaration shall not be empty.
4407   //
4408   // Spurious qualifiers here appear to be valid in C.
4409   unsigned DiagID = diag::warn_standalone_specifier;
4410   if (getLangOpts().CPlusPlus)
4411     DiagID = diag::ext_standalone_specifier;
4412 
4413   // Note that a linkage-specification sets a storage class, but
4414   // 'extern "C" struct foo;' is actually valid and not theoretically
4415   // useless.
4416   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4417     if (SCS == DeclSpec::SCS_mutable)
4418       // Since mutable is not a viable storage class specifier in C, there is
4419       // no reason to treat it as an extension. Instead, diagnose as an error.
4420       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4421     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4422       Diag(DS.getStorageClassSpecLoc(), DiagID)
4423         << DeclSpec::getSpecifierName(SCS);
4424   }
4425 
4426   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4427     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4428       << DeclSpec::getSpecifierName(TSCS);
4429   if (DS.getTypeQualifiers()) {
4430     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4431       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4432     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4433       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4434     // Restrict is covered above.
4435     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4436       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4437     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4438       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4439   }
4440 
4441   // Warn about ignored type attributes, for example:
4442   // __attribute__((aligned)) struct A;
4443   // Attributes should be placed after tag to apply to type declaration.
4444   if (!DS.getAttributes().empty()) {
4445     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4446     if (TypeSpecType == DeclSpec::TST_class ||
4447         TypeSpecType == DeclSpec::TST_struct ||
4448         TypeSpecType == DeclSpec::TST_interface ||
4449         TypeSpecType == DeclSpec::TST_union ||
4450         TypeSpecType == DeclSpec::TST_enum) {
4451       for (const ParsedAttr &AL : DS.getAttributes())
4452         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4453             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4454     }
4455   }
4456 
4457   return TagD;
4458 }
4459 
4460 /// We are trying to inject an anonymous member into the given scope;
4461 /// check if there's an existing declaration that can't be overloaded.
4462 ///
4463 /// \return true if this is a forbidden redeclaration
4464 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4465                                          Scope *S,
4466                                          DeclContext *Owner,
4467                                          DeclarationName Name,
4468                                          SourceLocation NameLoc,
4469                                          bool IsUnion) {
4470   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4471                  Sema::ForVisibleRedeclaration);
4472   if (!SemaRef.LookupName(R, S)) return false;
4473 
4474   // Pick a representative declaration.
4475   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4476   assert(PrevDecl && "Expected a non-null Decl");
4477 
4478   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4479     return false;
4480 
4481   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4482     << IsUnion << Name;
4483   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4484 
4485   return true;
4486 }
4487 
4488 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4489 /// anonymous struct or union AnonRecord into the owning context Owner
4490 /// and scope S. This routine will be invoked just after we realize
4491 /// that an unnamed union or struct is actually an anonymous union or
4492 /// struct, e.g.,
4493 ///
4494 /// @code
4495 /// union {
4496 ///   int i;
4497 ///   float f;
4498 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4499 ///    // f into the surrounding scope.x
4500 /// @endcode
4501 ///
4502 /// This routine is recursive, injecting the names of nested anonymous
4503 /// structs/unions into the owning context and scope as well.
4504 static bool
4505 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4506                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4507                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4508   bool Invalid = false;
4509 
4510   // Look every FieldDecl and IndirectFieldDecl with a name.
4511   for (auto *D : AnonRecord->decls()) {
4512     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4513         cast<NamedDecl>(D)->getDeclName()) {
4514       ValueDecl *VD = cast<ValueDecl>(D);
4515       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4516                                        VD->getLocation(),
4517                                        AnonRecord->isUnion())) {
4518         // C++ [class.union]p2:
4519         //   The names of the members of an anonymous union shall be
4520         //   distinct from the names of any other entity in the
4521         //   scope in which the anonymous union is declared.
4522         Invalid = true;
4523       } else {
4524         // C++ [class.union]p2:
4525         //   For the purpose of name lookup, after the anonymous union
4526         //   definition, the members of the anonymous union are
4527         //   considered to have been defined in the scope in which the
4528         //   anonymous union is declared.
4529         unsigned OldChainingSize = Chaining.size();
4530         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4531           Chaining.append(IF->chain_begin(), IF->chain_end());
4532         else
4533           Chaining.push_back(VD);
4534 
4535         assert(Chaining.size() >= 2);
4536         NamedDecl **NamedChain =
4537           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4538         for (unsigned i = 0; i < Chaining.size(); i++)
4539           NamedChain[i] = Chaining[i];
4540 
4541         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4542             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4543             VD->getType(), {NamedChain, Chaining.size()});
4544 
4545         for (const auto *Attr : VD->attrs())
4546           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4547 
4548         IndirectField->setAccess(AS);
4549         IndirectField->setImplicit();
4550         SemaRef.PushOnScopeChains(IndirectField, S);
4551 
4552         // That includes picking up the appropriate access specifier.
4553         if (AS != AS_none) IndirectField->setAccess(AS);
4554 
4555         Chaining.resize(OldChainingSize);
4556       }
4557     }
4558   }
4559 
4560   return Invalid;
4561 }
4562 
4563 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4564 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4565 /// illegal input values are mapped to SC_None.
4566 static StorageClass
4567 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4568   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4569   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4570          "Parser allowed 'typedef' as storage class VarDecl.");
4571   switch (StorageClassSpec) {
4572   case DeclSpec::SCS_unspecified:    return SC_None;
4573   case DeclSpec::SCS_extern:
4574     if (DS.isExternInLinkageSpec())
4575       return SC_None;
4576     return SC_Extern;
4577   case DeclSpec::SCS_static:         return SC_Static;
4578   case DeclSpec::SCS_auto:           return SC_Auto;
4579   case DeclSpec::SCS_register:       return SC_Register;
4580   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4581     // Illegal SCSs map to None: error reporting is up to the caller.
4582   case DeclSpec::SCS_mutable:        // Fall through.
4583   case DeclSpec::SCS_typedef:        return SC_None;
4584   }
4585   llvm_unreachable("unknown storage class specifier");
4586 }
4587 
4588 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4589   assert(Record->hasInClassInitializer());
4590 
4591   for (const auto *I : Record->decls()) {
4592     const auto *FD = dyn_cast<FieldDecl>(I);
4593     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4594       FD = IFD->getAnonField();
4595     if (FD && FD->hasInClassInitializer())
4596       return FD->getLocation();
4597   }
4598 
4599   llvm_unreachable("couldn't find in-class initializer");
4600 }
4601 
4602 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4603                                       SourceLocation DefaultInitLoc) {
4604   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4605     return;
4606 
4607   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4608   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4609 }
4610 
4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4612                                       CXXRecordDecl *AnonUnion) {
4613   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4614     return;
4615 
4616   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4617 }
4618 
4619 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4620 /// anonymous structure or union. Anonymous unions are a C++ feature
4621 /// (C++ [class.union]) and a C11 feature; anonymous structures
4622 /// are a C11 feature and GNU C++ extension.
4623 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4624                                         AccessSpecifier AS,
4625                                         RecordDecl *Record,
4626                                         const PrintingPolicy &Policy) {
4627   DeclContext *Owner = Record->getDeclContext();
4628 
4629   // Diagnose whether this anonymous struct/union is an extension.
4630   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4631     Diag(Record->getLocation(), diag::ext_anonymous_union);
4632   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4633     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4634   else if (!Record->isUnion() && !getLangOpts().C11)
4635     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4636 
4637   // C and C++ require different kinds of checks for anonymous
4638   // structs/unions.
4639   bool Invalid = false;
4640   if (getLangOpts().CPlusPlus) {
4641     const char *PrevSpec = nullptr;
4642     unsigned DiagID;
4643     if (Record->isUnion()) {
4644       // C++ [class.union]p6:
4645       // C++17 [class.union.anon]p2:
4646       //   Anonymous unions declared in a named namespace or in the
4647       //   global namespace shall be declared static.
4648       DeclContext *OwnerScope = Owner->getRedeclContext();
4649       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4650           (OwnerScope->isTranslationUnit() ||
4651            (OwnerScope->isNamespace() &&
4652             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4653         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4654           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4655 
4656         // Recover by adding 'static'.
4657         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4658                                PrevSpec, DiagID, Policy);
4659       }
4660       // C++ [class.union]p6:
4661       //   A storage class is not allowed in a declaration of an
4662       //   anonymous union in a class scope.
4663       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4664                isa<RecordDecl>(Owner)) {
4665         Diag(DS.getStorageClassSpecLoc(),
4666              diag::err_anonymous_union_with_storage_spec)
4667           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4668 
4669         // Recover by removing the storage specifier.
4670         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4671                                SourceLocation(),
4672                                PrevSpec, DiagID, Context.getPrintingPolicy());
4673       }
4674     }
4675 
4676     // Ignore const/volatile/restrict qualifiers.
4677     if (DS.getTypeQualifiers()) {
4678       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4679         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4680           << Record->isUnion() << "const"
4681           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4682       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4683         Diag(DS.getVolatileSpecLoc(),
4684              diag::ext_anonymous_struct_union_qualified)
4685           << Record->isUnion() << "volatile"
4686           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4687       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4688         Diag(DS.getRestrictSpecLoc(),
4689              diag::ext_anonymous_struct_union_qualified)
4690           << Record->isUnion() << "restrict"
4691           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4692       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4693         Diag(DS.getAtomicSpecLoc(),
4694              diag::ext_anonymous_struct_union_qualified)
4695           << Record->isUnion() << "_Atomic"
4696           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4697       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4698         Diag(DS.getUnalignedSpecLoc(),
4699              diag::ext_anonymous_struct_union_qualified)
4700           << Record->isUnion() << "__unaligned"
4701           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4702 
4703       DS.ClearTypeQualifiers();
4704     }
4705 
4706     // C++ [class.union]p2:
4707     //   The member-specification of an anonymous union shall only
4708     //   define non-static data members. [Note: nested types and
4709     //   functions cannot be declared within an anonymous union. ]
4710     for (auto *Mem : Record->decls()) {
4711       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4712         // C++ [class.union]p3:
4713         //   An anonymous union shall not have private or protected
4714         //   members (clause 11).
4715         assert(FD->getAccess() != AS_none);
4716         if (FD->getAccess() != AS_public) {
4717           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4718             << Record->isUnion() << (FD->getAccess() == AS_protected);
4719           Invalid = true;
4720         }
4721 
4722         // C++ [class.union]p1
4723         //   An object of a class with a non-trivial constructor, a non-trivial
4724         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4725         //   assignment operator cannot be a member of a union, nor can an
4726         //   array of such objects.
4727         if (CheckNontrivialField(FD))
4728           Invalid = true;
4729       } else if (Mem->isImplicit()) {
4730         // Any implicit members are fine.
4731       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4732         // This is a type that showed up in an
4733         // elaborated-type-specifier inside the anonymous struct or
4734         // union, but which actually declares a type outside of the
4735         // anonymous struct or union. It's okay.
4736       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4737         if (!MemRecord->isAnonymousStructOrUnion() &&
4738             MemRecord->getDeclName()) {
4739           // Visual C++ allows type definition in anonymous struct or union.
4740           if (getLangOpts().MicrosoftExt)
4741             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4742               << Record->isUnion();
4743           else {
4744             // This is a nested type declaration.
4745             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4746               << Record->isUnion();
4747             Invalid = true;
4748           }
4749         } else {
4750           // This is an anonymous type definition within another anonymous type.
4751           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4752           // not part of standard C++.
4753           Diag(MemRecord->getLocation(),
4754                diag::ext_anonymous_record_with_anonymous_type)
4755             << Record->isUnion();
4756         }
4757       } else if (isa<AccessSpecDecl>(Mem)) {
4758         // Any access specifier is fine.
4759       } else if (isa<StaticAssertDecl>(Mem)) {
4760         // In C++1z, static_assert declarations are also fine.
4761       } else {
4762         // We have something that isn't a non-static data
4763         // member. Complain about it.
4764         unsigned DK = diag::err_anonymous_record_bad_member;
4765         if (isa<TypeDecl>(Mem))
4766           DK = diag::err_anonymous_record_with_type;
4767         else if (isa<FunctionDecl>(Mem))
4768           DK = diag::err_anonymous_record_with_function;
4769         else if (isa<VarDecl>(Mem))
4770           DK = diag::err_anonymous_record_with_static;
4771 
4772         // Visual C++ allows type definition in anonymous struct or union.
4773         if (getLangOpts().MicrosoftExt &&
4774             DK == diag::err_anonymous_record_with_type)
4775           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4776             << Record->isUnion();
4777         else {
4778           Diag(Mem->getLocation(), DK) << Record->isUnion();
4779           Invalid = true;
4780         }
4781       }
4782     }
4783 
4784     // C++11 [class.union]p8 (DR1460):
4785     //   At most one variant member of a union may have a
4786     //   brace-or-equal-initializer.
4787     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4788         Owner->isRecord())
4789       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4790                                 cast<CXXRecordDecl>(Record));
4791   }
4792 
4793   if (!Record->isUnion() && !Owner->isRecord()) {
4794     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4795       << getLangOpts().CPlusPlus;
4796     Invalid = true;
4797   }
4798 
4799   // Mock up a declarator.
4800   Declarator Dc(DS, DeclaratorContext::MemberContext);
4801   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4802   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4803 
4804   // Create a declaration for this anonymous struct/union.
4805   NamedDecl *Anon = nullptr;
4806   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4807     Anon = FieldDecl::Create(
4808         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4809         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4810         /*BitWidth=*/nullptr, /*Mutable=*/false,
4811         /*InitStyle=*/ICIS_NoInit);
4812     Anon->setAccess(AS);
4813     if (getLangOpts().CPlusPlus)
4814       FieldCollector->Add(cast<FieldDecl>(Anon));
4815   } else {
4816     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4817     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4818     if (SCSpec == DeclSpec::SCS_mutable) {
4819       // mutable can only appear on non-static class members, so it's always
4820       // an error here
4821       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4822       Invalid = true;
4823       SC = SC_None;
4824     }
4825 
4826     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4827                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4828                            Context.getTypeDeclType(Record), TInfo, SC);
4829 
4830     // Default-initialize the implicit variable. This initialization will be
4831     // trivial in almost all cases, except if a union member has an in-class
4832     // initializer:
4833     //   union { int n = 0; };
4834     ActOnUninitializedDecl(Anon);
4835   }
4836   Anon->setImplicit();
4837 
4838   // Mark this as an anonymous struct/union type.
4839   Record->setAnonymousStructOrUnion(true);
4840 
4841   // Add the anonymous struct/union object to the current
4842   // context. We'll be referencing this object when we refer to one of
4843   // its members.
4844   Owner->addDecl(Anon);
4845 
4846   // Inject the members of the anonymous struct/union into the owning
4847   // context and into the identifier resolver chain for name lookup
4848   // purposes.
4849   SmallVector<NamedDecl*, 2> Chain;
4850   Chain.push_back(Anon);
4851 
4852   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4853     Invalid = true;
4854 
4855   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4856     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4857       Decl *ManglingContextDecl;
4858       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4859               NewVD->getDeclContext(), ManglingContextDecl)) {
4860         Context.setManglingNumber(
4861             NewVD, MCtx->getManglingNumber(
4862                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4863         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4864       }
4865     }
4866   }
4867 
4868   if (Invalid)
4869     Anon->setInvalidDecl();
4870 
4871   return Anon;
4872 }
4873 
4874 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4875 /// Microsoft C anonymous structure.
4876 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4877 /// Example:
4878 ///
4879 /// struct A { int a; };
4880 /// struct B { struct A; int b; };
4881 ///
4882 /// void foo() {
4883 ///   B var;
4884 ///   var.a = 3;
4885 /// }
4886 ///
4887 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4888                                            RecordDecl *Record) {
4889   assert(Record && "expected a record!");
4890 
4891   // Mock up a declarator.
4892   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4893   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4894   assert(TInfo && "couldn't build declarator info for anonymous struct");
4895 
4896   auto *ParentDecl = cast<RecordDecl>(CurContext);
4897   QualType RecTy = Context.getTypeDeclType(Record);
4898 
4899   // Create a declaration for this anonymous struct.
4900   NamedDecl *Anon =
4901       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4902                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4903                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4904                         /*InitStyle=*/ICIS_NoInit);
4905   Anon->setImplicit();
4906 
4907   // Add the anonymous struct object to the current context.
4908   CurContext->addDecl(Anon);
4909 
4910   // Inject the members of the anonymous struct into the current
4911   // context and into the identifier resolver chain for name lookup
4912   // purposes.
4913   SmallVector<NamedDecl*, 2> Chain;
4914   Chain.push_back(Anon);
4915 
4916   RecordDecl *RecordDef = Record->getDefinition();
4917   if (RequireCompleteType(Anon->getLocation(), RecTy,
4918                           diag::err_field_incomplete) ||
4919       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4920                                           AS_none, Chain)) {
4921     Anon->setInvalidDecl();
4922     ParentDecl->setInvalidDecl();
4923   }
4924 
4925   return Anon;
4926 }
4927 
4928 /// GetNameForDeclarator - Determine the full declaration name for the
4929 /// given Declarator.
4930 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4931   return GetNameFromUnqualifiedId(D.getName());
4932 }
4933 
4934 /// Retrieves the declaration name from a parsed unqualified-id.
4935 DeclarationNameInfo
4936 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4937   DeclarationNameInfo NameInfo;
4938   NameInfo.setLoc(Name.StartLocation);
4939 
4940   switch (Name.getKind()) {
4941 
4942   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4943   case UnqualifiedIdKind::IK_Identifier:
4944     NameInfo.setName(Name.Identifier);
4945     return NameInfo;
4946 
4947   case UnqualifiedIdKind::IK_DeductionGuideName: {
4948     // C++ [temp.deduct.guide]p3:
4949     //   The simple-template-id shall name a class template specialization.
4950     //   The template-name shall be the same identifier as the template-name
4951     //   of the simple-template-id.
4952     // These together intend to imply that the template-name shall name a
4953     // class template.
4954     // FIXME: template<typename T> struct X {};
4955     //        template<typename T> using Y = X<T>;
4956     //        Y(int) -> Y<int>;
4957     //   satisfies these rules but does not name a class template.
4958     TemplateName TN = Name.TemplateName.get().get();
4959     auto *Template = TN.getAsTemplateDecl();
4960     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4961       Diag(Name.StartLocation,
4962            diag::err_deduction_guide_name_not_class_template)
4963         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4964       if (Template)
4965         Diag(Template->getLocation(), diag::note_template_decl_here);
4966       return DeclarationNameInfo();
4967     }
4968 
4969     NameInfo.setName(
4970         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4971     return NameInfo;
4972   }
4973 
4974   case UnqualifiedIdKind::IK_OperatorFunctionId:
4975     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4976                                            Name.OperatorFunctionId.Operator));
4977     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4978       = Name.OperatorFunctionId.SymbolLocations[0];
4979     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4980       = Name.EndLocation.getRawEncoding();
4981     return NameInfo;
4982 
4983   case UnqualifiedIdKind::IK_LiteralOperatorId:
4984     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4985                                                            Name.Identifier));
4986     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4987     return NameInfo;
4988 
4989   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4990     TypeSourceInfo *TInfo;
4991     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4992     if (Ty.isNull())
4993       return DeclarationNameInfo();
4994     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4995                                                Context.getCanonicalType(Ty)));
4996     NameInfo.setNamedTypeInfo(TInfo);
4997     return NameInfo;
4998   }
4999 
5000   case UnqualifiedIdKind::IK_ConstructorName: {
5001     TypeSourceInfo *TInfo;
5002     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5003     if (Ty.isNull())
5004       return DeclarationNameInfo();
5005     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5006                                               Context.getCanonicalType(Ty)));
5007     NameInfo.setNamedTypeInfo(TInfo);
5008     return NameInfo;
5009   }
5010 
5011   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5012     // In well-formed code, we can only have a constructor
5013     // template-id that refers to the current context, so go there
5014     // to find the actual type being constructed.
5015     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5016     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5017       return DeclarationNameInfo();
5018 
5019     // Determine the type of the class being constructed.
5020     QualType CurClassType = Context.getTypeDeclType(CurClass);
5021 
5022     // FIXME: Check two things: that the template-id names the same type as
5023     // CurClassType, and that the template-id does not occur when the name
5024     // was qualified.
5025 
5026     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5027                                     Context.getCanonicalType(CurClassType)));
5028     // FIXME: should we retrieve TypeSourceInfo?
5029     NameInfo.setNamedTypeInfo(nullptr);
5030     return NameInfo;
5031   }
5032 
5033   case UnqualifiedIdKind::IK_DestructorName: {
5034     TypeSourceInfo *TInfo;
5035     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5036     if (Ty.isNull())
5037       return DeclarationNameInfo();
5038     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5039                                               Context.getCanonicalType(Ty)));
5040     NameInfo.setNamedTypeInfo(TInfo);
5041     return NameInfo;
5042   }
5043 
5044   case UnqualifiedIdKind::IK_TemplateId: {
5045     TemplateName TName = Name.TemplateId->Template.get();
5046     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5047     return Context.getNameForTemplate(TName, TNameLoc);
5048   }
5049 
5050   } // switch (Name.getKind())
5051 
5052   llvm_unreachable("Unknown name kind");
5053 }
5054 
5055 static QualType getCoreType(QualType Ty) {
5056   do {
5057     if (Ty->isPointerType() || Ty->isReferenceType())
5058       Ty = Ty->getPointeeType();
5059     else if (Ty->isArrayType())
5060       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5061     else
5062       return Ty.withoutLocalFastQualifiers();
5063   } while (true);
5064 }
5065 
5066 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5067 /// and Definition have "nearly" matching parameters. This heuristic is
5068 /// used to improve diagnostics in the case where an out-of-line function
5069 /// definition doesn't match any declaration within the class or namespace.
5070 /// Also sets Params to the list of indices to the parameters that differ
5071 /// between the declaration and the definition. If hasSimilarParameters
5072 /// returns true and Params is empty, then all of the parameters match.
5073 static bool hasSimilarParameters(ASTContext &Context,
5074                                      FunctionDecl *Declaration,
5075                                      FunctionDecl *Definition,
5076                                      SmallVectorImpl<unsigned> &Params) {
5077   Params.clear();
5078   if (Declaration->param_size() != Definition->param_size())
5079     return false;
5080   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5081     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5082     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5083 
5084     // The parameter types are identical
5085     if (Context.hasSameType(DefParamTy, DeclParamTy))
5086       continue;
5087 
5088     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5089     QualType DefParamBaseTy = getCoreType(DefParamTy);
5090     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5091     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5092 
5093     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5094         (DeclTyName && DeclTyName == DefTyName))
5095       Params.push_back(Idx);
5096     else  // The two parameters aren't even close
5097       return false;
5098   }
5099 
5100   return true;
5101 }
5102 
5103 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5104 /// declarator needs to be rebuilt in the current instantiation.
5105 /// Any bits of declarator which appear before the name are valid for
5106 /// consideration here.  That's specifically the type in the decl spec
5107 /// and the base type in any member-pointer chunks.
5108 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5109                                                     DeclarationName Name) {
5110   // The types we specifically need to rebuild are:
5111   //   - typenames, typeofs, and decltypes
5112   //   - types which will become injected class names
5113   // Of course, we also need to rebuild any type referencing such a
5114   // type.  It's safest to just say "dependent", but we call out a
5115   // few cases here.
5116 
5117   DeclSpec &DS = D.getMutableDeclSpec();
5118   switch (DS.getTypeSpecType()) {
5119   case DeclSpec::TST_typename:
5120   case DeclSpec::TST_typeofType:
5121   case DeclSpec::TST_underlyingType:
5122   case DeclSpec::TST_atomic: {
5123     // Grab the type from the parser.
5124     TypeSourceInfo *TSI = nullptr;
5125     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5126     if (T.isNull() || !T->isDependentType()) break;
5127 
5128     // Make sure there's a type source info.  This isn't really much
5129     // of a waste; most dependent types should have type source info
5130     // attached already.
5131     if (!TSI)
5132       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5133 
5134     // Rebuild the type in the current instantiation.
5135     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5136     if (!TSI) return true;
5137 
5138     // Store the new type back in the decl spec.
5139     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5140     DS.UpdateTypeRep(LocType);
5141     break;
5142   }
5143 
5144   case DeclSpec::TST_decltype:
5145   case DeclSpec::TST_typeofExpr: {
5146     Expr *E = DS.getRepAsExpr();
5147     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5148     if (Result.isInvalid()) return true;
5149     DS.UpdateExprRep(Result.get());
5150     break;
5151   }
5152 
5153   default:
5154     // Nothing to do for these decl specs.
5155     break;
5156   }
5157 
5158   // It doesn't matter what order we do this in.
5159   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5160     DeclaratorChunk &Chunk = D.getTypeObject(I);
5161 
5162     // The only type information in the declarator which can come
5163     // before the declaration name is the base type of a member
5164     // pointer.
5165     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5166       continue;
5167 
5168     // Rebuild the scope specifier in-place.
5169     CXXScopeSpec &SS = Chunk.Mem.Scope();
5170     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5171       return true;
5172   }
5173 
5174   return false;
5175 }
5176 
5177 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5178   D.setFunctionDefinitionKind(FDK_Declaration);
5179   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5180 
5181   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5182       Dcl && Dcl->getDeclContext()->isFileContext())
5183     Dcl->setTopLevelDeclInObjCContainer();
5184 
5185   if (getLangOpts().OpenCL)
5186     setCurrentOpenCLExtensionForDecl(Dcl);
5187 
5188   return Dcl;
5189 }
5190 
5191 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5192 ///   If T is the name of a class, then each of the following shall have a
5193 ///   name different from T:
5194 ///     - every static data member of class T;
5195 ///     - every member function of class T
5196 ///     - every member of class T that is itself a type;
5197 /// \returns true if the declaration name violates these rules.
5198 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5199                                    DeclarationNameInfo NameInfo) {
5200   DeclarationName Name = NameInfo.getName();
5201 
5202   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5203   while (Record && Record->isAnonymousStructOrUnion())
5204     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5205   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5206     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5207     return true;
5208   }
5209 
5210   return false;
5211 }
5212 
5213 /// Diagnose a declaration whose declarator-id has the given
5214 /// nested-name-specifier.
5215 ///
5216 /// \param SS The nested-name-specifier of the declarator-id.
5217 ///
5218 /// \param DC The declaration context to which the nested-name-specifier
5219 /// resolves.
5220 ///
5221 /// \param Name The name of the entity being declared.
5222 ///
5223 /// \param Loc The location of the name of the entity being declared.
5224 ///
5225 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5226 /// we're declaring an explicit / partial specialization / instantiation.
5227 ///
5228 /// \returns true if we cannot safely recover from this error, false otherwise.
5229 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5230                                         DeclarationName Name,
5231                                         SourceLocation Loc, bool IsTemplateId) {
5232   DeclContext *Cur = CurContext;
5233   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5234     Cur = Cur->getParent();
5235 
5236   // If the user provided a superfluous scope specifier that refers back to the
5237   // class in which the entity is already declared, diagnose and ignore it.
5238   //
5239   // class X {
5240   //   void X::f();
5241   // };
5242   //
5243   // Note, it was once ill-formed to give redundant qualification in all
5244   // contexts, but that rule was removed by DR482.
5245   if (Cur->Equals(DC)) {
5246     if (Cur->isRecord()) {
5247       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5248                                       : diag::err_member_extra_qualification)
5249         << Name << FixItHint::CreateRemoval(SS.getRange());
5250       SS.clear();
5251     } else {
5252       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5253     }
5254     return false;
5255   }
5256 
5257   // Check whether the qualifying scope encloses the scope of the original
5258   // declaration. For a template-id, we perform the checks in
5259   // CheckTemplateSpecializationScope.
5260   if (!Cur->Encloses(DC) && !IsTemplateId) {
5261     if (Cur->isRecord())
5262       Diag(Loc, diag::err_member_qualification)
5263         << Name << SS.getRange();
5264     else if (isa<TranslationUnitDecl>(DC))
5265       Diag(Loc, diag::err_invalid_declarator_global_scope)
5266         << Name << SS.getRange();
5267     else if (isa<FunctionDecl>(Cur))
5268       Diag(Loc, diag::err_invalid_declarator_in_function)
5269         << Name << SS.getRange();
5270     else if (isa<BlockDecl>(Cur))
5271       Diag(Loc, diag::err_invalid_declarator_in_block)
5272         << Name << SS.getRange();
5273     else
5274       Diag(Loc, diag::err_invalid_declarator_scope)
5275       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5276 
5277     return true;
5278   }
5279 
5280   if (Cur->isRecord()) {
5281     // Cannot qualify members within a class.
5282     Diag(Loc, diag::err_member_qualification)
5283       << Name << SS.getRange();
5284     SS.clear();
5285 
5286     // C++ constructors and destructors with incorrect scopes can break
5287     // our AST invariants by having the wrong underlying types. If
5288     // that's the case, then drop this declaration entirely.
5289     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5290          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5291         !Context.hasSameType(Name.getCXXNameType(),
5292                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5293       return true;
5294 
5295     return false;
5296   }
5297 
5298   // C++11 [dcl.meaning]p1:
5299   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5300   //   not begin with a decltype-specifer"
5301   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5302   while (SpecLoc.getPrefix())
5303     SpecLoc = SpecLoc.getPrefix();
5304   if (dyn_cast_or_null<DecltypeType>(
5305         SpecLoc.getNestedNameSpecifier()->getAsType()))
5306     Diag(Loc, diag::err_decltype_in_declarator)
5307       << SpecLoc.getTypeLoc().getSourceRange();
5308 
5309   return false;
5310 }
5311 
5312 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5313                                   MultiTemplateParamsArg TemplateParamLists) {
5314   // TODO: consider using NameInfo for diagnostic.
5315   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5316   DeclarationName Name = NameInfo.getName();
5317 
5318   // All of these full declarators require an identifier.  If it doesn't have
5319   // one, the ParsedFreeStandingDeclSpec action should be used.
5320   if (D.isDecompositionDeclarator()) {
5321     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5322   } else if (!Name) {
5323     if (!D.isInvalidType())  // Reject this if we think it is valid.
5324       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5325           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5326     return nullptr;
5327   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5328     return nullptr;
5329 
5330   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5331   // we find one that is.
5332   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5333          (S->getFlags() & Scope::TemplateParamScope) != 0)
5334     S = S->getParent();
5335 
5336   DeclContext *DC = CurContext;
5337   if (D.getCXXScopeSpec().isInvalid())
5338     D.setInvalidType();
5339   else if (D.getCXXScopeSpec().isSet()) {
5340     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5341                                         UPPC_DeclarationQualifier))
5342       return nullptr;
5343 
5344     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5345     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5346     if (!DC || isa<EnumDecl>(DC)) {
5347       // If we could not compute the declaration context, it's because the
5348       // declaration context is dependent but does not refer to a class,
5349       // class template, or class template partial specialization. Complain
5350       // and return early, to avoid the coming semantic disaster.
5351       Diag(D.getIdentifierLoc(),
5352            diag::err_template_qualified_declarator_no_match)
5353         << D.getCXXScopeSpec().getScopeRep()
5354         << D.getCXXScopeSpec().getRange();
5355       return nullptr;
5356     }
5357     bool IsDependentContext = DC->isDependentContext();
5358 
5359     if (!IsDependentContext &&
5360         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5361       return nullptr;
5362 
5363     // If a class is incomplete, do not parse entities inside it.
5364     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5365       Diag(D.getIdentifierLoc(),
5366            diag::err_member_def_undefined_record)
5367         << Name << DC << D.getCXXScopeSpec().getRange();
5368       return nullptr;
5369     }
5370     if (!D.getDeclSpec().isFriendSpecified()) {
5371       if (diagnoseQualifiedDeclaration(
5372               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5373               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5374         if (DC->isRecord())
5375           return nullptr;
5376 
5377         D.setInvalidType();
5378       }
5379     }
5380 
5381     // Check whether we need to rebuild the type of the given
5382     // declaration in the current instantiation.
5383     if (EnteringContext && IsDependentContext &&
5384         TemplateParamLists.size() != 0) {
5385       ContextRAII SavedContext(*this, DC);
5386       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5387         D.setInvalidType();
5388     }
5389   }
5390 
5391   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5392   QualType R = TInfo->getType();
5393 
5394   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5395                                       UPPC_DeclarationType))
5396     D.setInvalidType();
5397 
5398   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5399                         forRedeclarationInCurContext());
5400 
5401   // See if this is a redefinition of a variable in the same scope.
5402   if (!D.getCXXScopeSpec().isSet()) {
5403     bool IsLinkageLookup = false;
5404     bool CreateBuiltins = false;
5405 
5406     // If the declaration we're planning to build will be a function
5407     // or object with linkage, then look for another declaration with
5408     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5409     //
5410     // If the declaration we're planning to build will be declared with
5411     // external linkage in the translation unit, create any builtin with
5412     // the same name.
5413     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5414       /* Do nothing*/;
5415     else if (CurContext->isFunctionOrMethod() &&
5416              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5417               R->isFunctionType())) {
5418       IsLinkageLookup = true;
5419       CreateBuiltins =
5420           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5421     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5422                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5423       CreateBuiltins = true;
5424 
5425     if (IsLinkageLookup) {
5426       Previous.clear(LookupRedeclarationWithLinkage);
5427       Previous.setRedeclarationKind(ForExternalRedeclaration);
5428     }
5429 
5430     LookupName(Previous, S, CreateBuiltins);
5431   } else { // Something like "int foo::x;"
5432     LookupQualifiedName(Previous, DC);
5433 
5434     // C++ [dcl.meaning]p1:
5435     //   When the declarator-id is qualified, the declaration shall refer to a
5436     //  previously declared member of the class or namespace to which the
5437     //  qualifier refers (or, in the case of a namespace, of an element of the
5438     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5439     //  thereof; [...]
5440     //
5441     // Note that we already checked the context above, and that we do not have
5442     // enough information to make sure that Previous contains the declaration
5443     // we want to match. For example, given:
5444     //
5445     //   class X {
5446     //     void f();
5447     //     void f(float);
5448     //   };
5449     //
5450     //   void X::f(int) { } // ill-formed
5451     //
5452     // In this case, Previous will point to the overload set
5453     // containing the two f's declared in X, but neither of them
5454     // matches.
5455 
5456     // C++ [dcl.meaning]p1:
5457     //   [...] the member shall not merely have been introduced by a
5458     //   using-declaration in the scope of the class or namespace nominated by
5459     //   the nested-name-specifier of the declarator-id.
5460     RemoveUsingDecls(Previous);
5461   }
5462 
5463   if (Previous.isSingleResult() &&
5464       Previous.getFoundDecl()->isTemplateParameter()) {
5465     // Maybe we will complain about the shadowed template parameter.
5466     if (!D.isInvalidType())
5467       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5468                                       Previous.getFoundDecl());
5469 
5470     // Just pretend that we didn't see the previous declaration.
5471     Previous.clear();
5472   }
5473 
5474   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5475     // Forget that the previous declaration is the injected-class-name.
5476     Previous.clear();
5477 
5478   // In C++, the previous declaration we find might be a tag type
5479   // (class or enum). In this case, the new declaration will hide the
5480   // tag type. Note that this applies to functions, function templates, and
5481   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5482   if (Previous.isSingleTagDecl() &&
5483       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5484       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5485     Previous.clear();
5486 
5487   // Check that there are no default arguments other than in the parameters
5488   // of a function declaration (C++ only).
5489   if (getLangOpts().CPlusPlus)
5490     CheckExtraCXXDefaultArguments(D);
5491 
5492   NamedDecl *New;
5493 
5494   bool AddToScope = true;
5495   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5496     if (TemplateParamLists.size()) {
5497       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5498       return nullptr;
5499     }
5500 
5501     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5502   } else if (R->isFunctionType()) {
5503     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5504                                   TemplateParamLists,
5505                                   AddToScope);
5506   } else {
5507     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5508                                   AddToScope);
5509   }
5510 
5511   if (!New)
5512     return nullptr;
5513 
5514   // If this has an identifier and is not a function template specialization,
5515   // add it to the scope stack.
5516   if (New->getDeclName() && AddToScope) {
5517     // Only make a locally-scoped extern declaration visible if it is the first
5518     // declaration of this entity. Qualified lookup for such an entity should
5519     // only find this declaration if there is no visible declaration of it.
5520     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5521     PushOnScopeChains(New, S, AddToContext);
5522     if (!AddToContext)
5523       CurContext->addHiddenDecl(New);
5524   }
5525 
5526   if (isInOpenMPDeclareTargetContext())
5527     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5528 
5529   return New;
5530 }
5531 
5532 /// Helper method to turn variable array types into constant array
5533 /// types in certain situations which would otherwise be errors (for
5534 /// GCC compatibility).
5535 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5536                                                     ASTContext &Context,
5537                                                     bool &SizeIsNegative,
5538                                                     llvm::APSInt &Oversized) {
5539   // This method tries to turn a variable array into a constant
5540   // array even when the size isn't an ICE.  This is necessary
5541   // for compatibility with code that depends on gcc's buggy
5542   // constant expression folding, like struct {char x[(int)(char*)2];}
5543   SizeIsNegative = false;
5544   Oversized = 0;
5545 
5546   if (T->isDependentType())
5547     return QualType();
5548 
5549   QualifierCollector Qs;
5550   const Type *Ty = Qs.strip(T);
5551 
5552   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5553     QualType Pointee = PTy->getPointeeType();
5554     QualType FixedType =
5555         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5556                                             Oversized);
5557     if (FixedType.isNull()) return FixedType;
5558     FixedType = Context.getPointerType(FixedType);
5559     return Qs.apply(Context, FixedType);
5560   }
5561   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5562     QualType Inner = PTy->getInnerType();
5563     QualType FixedType =
5564         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5565                                             Oversized);
5566     if (FixedType.isNull()) return FixedType;
5567     FixedType = Context.getParenType(FixedType);
5568     return Qs.apply(Context, FixedType);
5569   }
5570 
5571   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5572   if (!VLATy)
5573     return QualType();
5574   // FIXME: We should probably handle this case
5575   if (VLATy->getElementType()->isVariablyModifiedType())
5576     return QualType();
5577 
5578   llvm::APSInt Res;
5579   if (!VLATy->getSizeExpr() ||
5580       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5581     return QualType();
5582 
5583   // Check whether the array size is negative.
5584   if (Res.isSigned() && Res.isNegative()) {
5585     SizeIsNegative = true;
5586     return QualType();
5587   }
5588 
5589   // Check whether the array is too large to be addressed.
5590   unsigned ActiveSizeBits
5591     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5592                                               Res);
5593   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5594     Oversized = Res;
5595     return QualType();
5596   }
5597 
5598   return Context.getConstantArrayType(VLATy->getElementType(),
5599                                       Res, ArrayType::Normal, 0);
5600 }
5601 
5602 static void
5603 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5604   SrcTL = SrcTL.getUnqualifiedLoc();
5605   DstTL = DstTL.getUnqualifiedLoc();
5606   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5607     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5608     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5609                                       DstPTL.getPointeeLoc());
5610     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5611     return;
5612   }
5613   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5614     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5615     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5616                                       DstPTL.getInnerLoc());
5617     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5618     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5619     return;
5620   }
5621   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5622   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5623   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5624   TypeLoc DstElemTL = DstATL.getElementLoc();
5625   DstElemTL.initializeFullCopy(SrcElemTL);
5626   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5627   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5628   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5629 }
5630 
5631 /// Helper method to turn variable array types into constant array
5632 /// types in certain situations which would otherwise be errors (for
5633 /// GCC compatibility).
5634 static TypeSourceInfo*
5635 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5636                                               ASTContext &Context,
5637                                               bool &SizeIsNegative,
5638                                               llvm::APSInt &Oversized) {
5639   QualType FixedTy
5640     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5641                                           SizeIsNegative, Oversized);
5642   if (FixedTy.isNull())
5643     return nullptr;
5644   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5645   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5646                                     FixedTInfo->getTypeLoc());
5647   return FixedTInfo;
5648 }
5649 
5650 /// Register the given locally-scoped extern "C" declaration so
5651 /// that it can be found later for redeclarations. We include any extern "C"
5652 /// declaration that is not visible in the translation unit here, not just
5653 /// function-scope declarations.
5654 void
5655 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5656   if (!getLangOpts().CPlusPlus &&
5657       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5658     // Don't need to track declarations in the TU in C.
5659     return;
5660 
5661   // Note that we have a locally-scoped external with this name.
5662   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5663 }
5664 
5665 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5666   // FIXME: We can have multiple results via __attribute__((overloadable)).
5667   auto Result = Context.getExternCContextDecl()->lookup(Name);
5668   return Result.empty() ? nullptr : *Result.begin();
5669 }
5670 
5671 /// Diagnose function specifiers on a declaration of an identifier that
5672 /// does not identify a function.
5673 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5674   // FIXME: We should probably indicate the identifier in question to avoid
5675   // confusion for constructs like "virtual int a(), b;"
5676   if (DS.isVirtualSpecified())
5677     Diag(DS.getVirtualSpecLoc(),
5678          diag::err_virtual_non_function);
5679 
5680   if (DS.isExplicitSpecified())
5681     Diag(DS.getExplicitSpecLoc(),
5682          diag::err_explicit_non_function);
5683 
5684   if (DS.isNoreturnSpecified())
5685     Diag(DS.getNoreturnSpecLoc(),
5686          diag::err_noreturn_non_function);
5687 }
5688 
5689 NamedDecl*
5690 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5691                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5692   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5693   if (D.getCXXScopeSpec().isSet()) {
5694     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5695       << D.getCXXScopeSpec().getRange();
5696     D.setInvalidType();
5697     // Pretend we didn't see the scope specifier.
5698     DC = CurContext;
5699     Previous.clear();
5700   }
5701 
5702   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5703 
5704   if (D.getDeclSpec().isInlineSpecified())
5705     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5706         << getLangOpts().CPlusPlus17;
5707   if (D.getDeclSpec().isConstexprSpecified())
5708     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5709       << 1;
5710 
5711   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5712     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5713       Diag(D.getName().StartLocation,
5714            diag::err_deduction_guide_invalid_specifier)
5715           << "typedef";
5716     else
5717       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5718           << D.getName().getSourceRange();
5719     return nullptr;
5720   }
5721 
5722   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5723   if (!NewTD) return nullptr;
5724 
5725   // Handle attributes prior to checking for duplicates in MergeVarDecl
5726   ProcessDeclAttributes(S, NewTD, D);
5727 
5728   CheckTypedefForVariablyModifiedType(S, NewTD);
5729 
5730   bool Redeclaration = D.isRedeclaration();
5731   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5732   D.setRedeclaration(Redeclaration);
5733   return ND;
5734 }
5735 
5736 void
5737 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5738   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5739   // then it shall have block scope.
5740   // Note that variably modified types must be fixed before merging the decl so
5741   // that redeclarations will match.
5742   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5743   QualType T = TInfo->getType();
5744   if (T->isVariablyModifiedType()) {
5745     setFunctionHasBranchProtectedScope();
5746 
5747     if (S->getFnParent() == nullptr) {
5748       bool SizeIsNegative;
5749       llvm::APSInt Oversized;
5750       TypeSourceInfo *FixedTInfo =
5751         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5752                                                       SizeIsNegative,
5753                                                       Oversized);
5754       if (FixedTInfo) {
5755         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5756         NewTD->setTypeSourceInfo(FixedTInfo);
5757       } else {
5758         if (SizeIsNegative)
5759           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5760         else if (T->isVariableArrayType())
5761           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5762         else if (Oversized.getBoolValue())
5763           Diag(NewTD->getLocation(), diag::err_array_too_large)
5764             << Oversized.toString(10);
5765         else
5766           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5767         NewTD->setInvalidDecl();
5768       }
5769     }
5770   }
5771 }
5772 
5773 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5774 /// declares a typedef-name, either using the 'typedef' type specifier or via
5775 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5776 NamedDecl*
5777 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5778                            LookupResult &Previous, bool &Redeclaration) {
5779 
5780   // Find the shadowed declaration before filtering for scope.
5781   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5782 
5783   // Merge the decl with the existing one if appropriate. If the decl is
5784   // in an outer scope, it isn't the same thing.
5785   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5786                        /*AllowInlineNamespace*/false);
5787   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5788   if (!Previous.empty()) {
5789     Redeclaration = true;
5790     MergeTypedefNameDecl(S, NewTD, Previous);
5791   }
5792 
5793   if (ShadowedDecl && !Redeclaration)
5794     CheckShadow(NewTD, ShadowedDecl, Previous);
5795 
5796   // If this is the C FILE type, notify the AST context.
5797   if (IdentifierInfo *II = NewTD->getIdentifier())
5798     if (!NewTD->isInvalidDecl() &&
5799         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5800       if (II->isStr("FILE"))
5801         Context.setFILEDecl(NewTD);
5802       else if (II->isStr("jmp_buf"))
5803         Context.setjmp_bufDecl(NewTD);
5804       else if (II->isStr("sigjmp_buf"))
5805         Context.setsigjmp_bufDecl(NewTD);
5806       else if (II->isStr("ucontext_t"))
5807         Context.setucontext_tDecl(NewTD);
5808     }
5809 
5810   return NewTD;
5811 }
5812 
5813 /// Determines whether the given declaration is an out-of-scope
5814 /// previous declaration.
5815 ///
5816 /// This routine should be invoked when name lookup has found a
5817 /// previous declaration (PrevDecl) that is not in the scope where a
5818 /// new declaration by the same name is being introduced. If the new
5819 /// declaration occurs in a local scope, previous declarations with
5820 /// linkage may still be considered previous declarations (C99
5821 /// 6.2.2p4-5, C++ [basic.link]p6).
5822 ///
5823 /// \param PrevDecl the previous declaration found by name
5824 /// lookup
5825 ///
5826 /// \param DC the context in which the new declaration is being
5827 /// declared.
5828 ///
5829 /// \returns true if PrevDecl is an out-of-scope previous declaration
5830 /// for a new delcaration with the same name.
5831 static bool
5832 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5833                                 ASTContext &Context) {
5834   if (!PrevDecl)
5835     return false;
5836 
5837   if (!PrevDecl->hasLinkage())
5838     return false;
5839 
5840   if (Context.getLangOpts().CPlusPlus) {
5841     // C++ [basic.link]p6:
5842     //   If there is a visible declaration of an entity with linkage
5843     //   having the same name and type, ignoring entities declared
5844     //   outside the innermost enclosing namespace scope, the block
5845     //   scope declaration declares that same entity and receives the
5846     //   linkage of the previous declaration.
5847     DeclContext *OuterContext = DC->getRedeclContext();
5848     if (!OuterContext->isFunctionOrMethod())
5849       // This rule only applies to block-scope declarations.
5850       return false;
5851 
5852     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5853     if (PrevOuterContext->isRecord())
5854       // We found a member function: ignore it.
5855       return false;
5856 
5857     // Find the innermost enclosing namespace for the new and
5858     // previous declarations.
5859     OuterContext = OuterContext->getEnclosingNamespaceContext();
5860     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5861 
5862     // The previous declaration is in a different namespace, so it
5863     // isn't the same function.
5864     if (!OuterContext->Equals(PrevOuterContext))
5865       return false;
5866   }
5867 
5868   return true;
5869 }
5870 
5871 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5872   CXXScopeSpec &SS = D.getCXXScopeSpec();
5873   if (!SS.isSet()) return;
5874   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5875 }
5876 
5877 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5878   QualType type = decl->getType();
5879   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5880   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5881     // Various kinds of declaration aren't allowed to be __autoreleasing.
5882     unsigned kind = -1U;
5883     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5884       if (var->hasAttr<BlocksAttr>())
5885         kind = 0; // __block
5886       else if (!var->hasLocalStorage())
5887         kind = 1; // global
5888     } else if (isa<ObjCIvarDecl>(decl)) {
5889       kind = 3; // ivar
5890     } else if (isa<FieldDecl>(decl)) {
5891       kind = 2; // field
5892     }
5893 
5894     if (kind != -1U) {
5895       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5896         << kind;
5897     }
5898   } else if (lifetime == Qualifiers::OCL_None) {
5899     // Try to infer lifetime.
5900     if (!type->isObjCLifetimeType())
5901       return false;
5902 
5903     lifetime = type->getObjCARCImplicitLifetime();
5904     type = Context.getLifetimeQualifiedType(type, lifetime);
5905     decl->setType(type);
5906   }
5907 
5908   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5909     // Thread-local variables cannot have lifetime.
5910     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5911         var->getTLSKind()) {
5912       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5913         << var->getType();
5914       return true;
5915     }
5916   }
5917 
5918   return false;
5919 }
5920 
5921 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5922   // Ensure that an auto decl is deduced otherwise the checks below might cache
5923   // the wrong linkage.
5924   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5925 
5926   // 'weak' only applies to declarations with external linkage.
5927   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5928     if (!ND.isExternallyVisible()) {
5929       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5930       ND.dropAttr<WeakAttr>();
5931     }
5932   }
5933   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5934     if (ND.isExternallyVisible()) {
5935       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5936       ND.dropAttr<WeakRefAttr>();
5937       ND.dropAttr<AliasAttr>();
5938     }
5939   }
5940 
5941   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5942     if (VD->hasInit()) {
5943       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5944         assert(VD->isThisDeclarationADefinition() &&
5945                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5946         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5947         VD->dropAttr<AliasAttr>();
5948       }
5949     }
5950   }
5951 
5952   // 'selectany' only applies to externally visible variable declarations.
5953   // It does not apply to functions.
5954   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5955     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5956       S.Diag(Attr->getLocation(),
5957              diag::err_attribute_selectany_non_extern_data);
5958       ND.dropAttr<SelectAnyAttr>();
5959     }
5960   }
5961 
5962   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5963     // dll attributes require external linkage. Static locals may have external
5964     // linkage but still cannot be explicitly imported or exported.
5965     auto *VD = dyn_cast<VarDecl>(&ND);
5966     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5967       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5968         << &ND << Attr;
5969       ND.setInvalidDecl();
5970     }
5971   }
5972 
5973   // Virtual functions cannot be marked as 'notail'.
5974   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5975     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5976       if (MD->isVirtual()) {
5977         S.Diag(ND.getLocation(),
5978                diag::err_invalid_attribute_on_virtual_function)
5979             << Attr;
5980         ND.dropAttr<NotTailCalledAttr>();
5981       }
5982 
5983   // Check the attributes on the function type, if any.
5984   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
5985     // Don't declare this variable in the second operand of the for-statement;
5986     // GCC miscompiles that by ending its lifetime before evaluating the
5987     // third operand. See gcc.gnu.org/PR86769.
5988     AttributedTypeLoc ATL;
5989     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
5990          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
5991          TL = ATL.getModifiedLoc()) {
5992       // The [[lifetimebound]] attribute can be applied to the implicit object
5993       // parameter of a non-static member function (other than a ctor or dtor)
5994       // by applying it to the function type.
5995       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
5996         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
5997         if (!MD || MD->isStatic()) {
5998           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
5999               << !MD << A->getRange();
6000         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6001           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6002               << isa<CXXDestructorDecl>(MD) << A->getRange();
6003         }
6004       }
6005     }
6006   }
6007 }
6008 
6009 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6010                                            NamedDecl *NewDecl,
6011                                            bool IsSpecialization,
6012                                            bool IsDefinition) {
6013   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6014     return;
6015 
6016   bool IsTemplate = false;
6017   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6018     OldDecl = OldTD->getTemplatedDecl();
6019     IsTemplate = true;
6020     if (!IsSpecialization)
6021       IsDefinition = false;
6022   }
6023   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6024     NewDecl = NewTD->getTemplatedDecl();
6025     IsTemplate = true;
6026   }
6027 
6028   if (!OldDecl || !NewDecl)
6029     return;
6030 
6031   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6032   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6033   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6034   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6035 
6036   // dllimport and dllexport are inheritable attributes so we have to exclude
6037   // inherited attribute instances.
6038   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6039                     (NewExportAttr && !NewExportAttr->isInherited());
6040 
6041   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6042   // the only exception being explicit specializations.
6043   // Implicitly generated declarations are also excluded for now because there
6044   // is no other way to switch these to use dllimport or dllexport.
6045   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6046 
6047   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6048     // Allow with a warning for free functions and global variables.
6049     bool JustWarn = false;
6050     if (!OldDecl->isCXXClassMember()) {
6051       auto *VD = dyn_cast<VarDecl>(OldDecl);
6052       if (VD && !VD->getDescribedVarTemplate())
6053         JustWarn = true;
6054       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6055       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6056         JustWarn = true;
6057     }
6058 
6059     // We cannot change a declaration that's been used because IR has already
6060     // been emitted. Dllimported functions will still work though (modulo
6061     // address equality) as they can use the thunk.
6062     if (OldDecl->isUsed())
6063       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6064         JustWarn = false;
6065 
6066     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6067                                : diag::err_attribute_dll_redeclaration;
6068     S.Diag(NewDecl->getLocation(), DiagID)
6069         << NewDecl
6070         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6071     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6072     if (!JustWarn) {
6073       NewDecl->setInvalidDecl();
6074       return;
6075     }
6076   }
6077 
6078   // A redeclaration is not allowed to drop a dllimport attribute, the only
6079   // exceptions being inline function definitions (except for function
6080   // templates), local extern declarations, qualified friend declarations or
6081   // special MSVC extension: in the last case, the declaration is treated as if
6082   // it were marked dllexport.
6083   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6084   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6085   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6086     // Ignore static data because out-of-line definitions are diagnosed
6087     // separately.
6088     IsStaticDataMember = VD->isStaticDataMember();
6089     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6090                    VarDecl::DeclarationOnly;
6091   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6092     IsInline = FD->isInlined();
6093     IsQualifiedFriend = FD->getQualifier() &&
6094                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6095   }
6096 
6097   if (OldImportAttr && !HasNewAttr &&
6098       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6099       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6100     if (IsMicrosoft && IsDefinition) {
6101       S.Diag(NewDecl->getLocation(),
6102              diag::warn_redeclaration_without_import_attribute)
6103           << NewDecl;
6104       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6105       NewDecl->dropAttr<DLLImportAttr>();
6106       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6107           NewImportAttr->getRange(), S.Context,
6108           NewImportAttr->getSpellingListIndex()));
6109     } else {
6110       S.Diag(NewDecl->getLocation(),
6111              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6112           << NewDecl << OldImportAttr;
6113       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6114       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6115       OldDecl->dropAttr<DLLImportAttr>();
6116       NewDecl->dropAttr<DLLImportAttr>();
6117     }
6118   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6119     // In MinGW, seeing a function declared inline drops the dllimport
6120     // attribute.
6121     OldDecl->dropAttr<DLLImportAttr>();
6122     NewDecl->dropAttr<DLLImportAttr>();
6123     S.Diag(NewDecl->getLocation(),
6124            diag::warn_dllimport_dropped_from_inline_function)
6125         << NewDecl << OldImportAttr;
6126   }
6127 
6128   // A specialization of a class template member function is processed here
6129   // since it's a redeclaration. If the parent class is dllexport, the
6130   // specialization inherits that attribute. This doesn't happen automatically
6131   // since the parent class isn't instantiated until later.
6132   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6133     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6134         !NewImportAttr && !NewExportAttr) {
6135       if (const DLLExportAttr *ParentExportAttr =
6136               MD->getParent()->getAttr<DLLExportAttr>()) {
6137         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6138         NewAttr->setInherited(true);
6139         NewDecl->addAttr(NewAttr);
6140       }
6141     }
6142   }
6143 }
6144 
6145 /// Given that we are within the definition of the given function,
6146 /// will that definition behave like C99's 'inline', where the
6147 /// definition is discarded except for optimization purposes?
6148 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6149   // Try to avoid calling GetGVALinkageForFunction.
6150 
6151   // All cases of this require the 'inline' keyword.
6152   if (!FD->isInlined()) return false;
6153 
6154   // This is only possible in C++ with the gnu_inline attribute.
6155   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6156     return false;
6157 
6158   // Okay, go ahead and call the relatively-more-expensive function.
6159   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6160 }
6161 
6162 /// Determine whether a variable is extern "C" prior to attaching
6163 /// an initializer. We can't just call isExternC() here, because that
6164 /// will also compute and cache whether the declaration is externally
6165 /// visible, which might change when we attach the initializer.
6166 ///
6167 /// This can only be used if the declaration is known to not be a
6168 /// redeclaration of an internal linkage declaration.
6169 ///
6170 /// For instance:
6171 ///
6172 ///   auto x = []{};
6173 ///
6174 /// Attaching the initializer here makes this declaration not externally
6175 /// visible, because its type has internal linkage.
6176 ///
6177 /// FIXME: This is a hack.
6178 template<typename T>
6179 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6180   if (S.getLangOpts().CPlusPlus) {
6181     // In C++, the overloadable attribute negates the effects of extern "C".
6182     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6183       return false;
6184 
6185     // So do CUDA's host/device attributes.
6186     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6187                                  D->template hasAttr<CUDAHostAttr>()))
6188       return false;
6189   }
6190   return D->isExternC();
6191 }
6192 
6193 static bool shouldConsiderLinkage(const VarDecl *VD) {
6194   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6195   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6196     return VD->hasExternalStorage();
6197   if (DC->isFileContext())
6198     return true;
6199   if (DC->isRecord())
6200     return false;
6201   llvm_unreachable("Unexpected context");
6202 }
6203 
6204 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6205   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6206   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6207       isa<OMPDeclareReductionDecl>(DC))
6208     return true;
6209   if (DC->isRecord())
6210     return false;
6211   llvm_unreachable("Unexpected context");
6212 }
6213 
6214 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6215                           ParsedAttr::Kind Kind) {
6216   // Check decl attributes on the DeclSpec.
6217   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6218     return true;
6219 
6220   // Walk the declarator structure, checking decl attributes that were in a type
6221   // position to the decl itself.
6222   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6223     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6224       return true;
6225   }
6226 
6227   // Finally, check attributes on the decl itself.
6228   return PD.getAttributes().hasAttribute(Kind);
6229 }
6230 
6231 /// Adjust the \c DeclContext for a function or variable that might be a
6232 /// function-local external declaration.
6233 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6234   if (!DC->isFunctionOrMethod())
6235     return false;
6236 
6237   // If this is a local extern function or variable declared within a function
6238   // template, don't add it into the enclosing namespace scope until it is
6239   // instantiated; it might have a dependent type right now.
6240   if (DC->isDependentContext())
6241     return true;
6242 
6243   // C++11 [basic.link]p7:
6244   //   When a block scope declaration of an entity with linkage is not found to
6245   //   refer to some other declaration, then that entity is a member of the
6246   //   innermost enclosing namespace.
6247   //
6248   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6249   // semantically-enclosing namespace, not a lexically-enclosing one.
6250   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6251     DC = DC->getParent();
6252   return true;
6253 }
6254 
6255 /// Returns true if given declaration has external C language linkage.
6256 static bool isDeclExternC(const Decl *D) {
6257   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6258     return FD->isExternC();
6259   if (const auto *VD = dyn_cast<VarDecl>(D))
6260     return VD->isExternC();
6261 
6262   llvm_unreachable("Unknown type of decl!");
6263 }
6264 
6265 NamedDecl *Sema::ActOnVariableDeclarator(
6266     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6267     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6268     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6269   QualType R = TInfo->getType();
6270   DeclarationName Name = GetNameForDeclarator(D).getName();
6271 
6272   IdentifierInfo *II = Name.getAsIdentifierInfo();
6273 
6274   if (D.isDecompositionDeclarator()) {
6275     // Take the name of the first declarator as our name for diagnostic
6276     // purposes.
6277     auto &Decomp = D.getDecompositionDeclarator();
6278     if (!Decomp.bindings().empty()) {
6279       II = Decomp.bindings()[0].Name;
6280       Name = II;
6281     }
6282   } else if (!II) {
6283     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6284     return nullptr;
6285   }
6286 
6287   if (getLangOpts().OpenCL) {
6288     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6289     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6290     // argument.
6291     if (R->isImageType() || R->isPipeType()) {
6292       Diag(D.getIdentifierLoc(),
6293            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6294           << R;
6295       D.setInvalidType();
6296       return nullptr;
6297     }
6298 
6299     // OpenCL v1.2 s6.9.r:
6300     // The event type cannot be used to declare a program scope variable.
6301     // OpenCL v2.0 s6.9.q:
6302     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6303     if (NULL == S->getParent()) {
6304       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6305         Diag(D.getIdentifierLoc(),
6306              diag::err_invalid_type_for_program_scope_var) << R;
6307         D.setInvalidType();
6308         return nullptr;
6309       }
6310     }
6311 
6312     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6313     QualType NR = R;
6314     while (NR->isPointerType()) {
6315       if (NR->isFunctionPointerType()) {
6316         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6317         D.setInvalidType();
6318         break;
6319       }
6320       NR = NR->getPointeeType();
6321     }
6322 
6323     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6324       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6325       // half array type (unless the cl_khr_fp16 extension is enabled).
6326       if (Context.getBaseElementType(R)->isHalfType()) {
6327         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6328         D.setInvalidType();
6329       }
6330     }
6331 
6332     if (R->isSamplerT()) {
6333       // OpenCL v1.2 s6.9.b p4:
6334       // The sampler type cannot be used with the __local and __global address
6335       // space qualifiers.
6336       if (R.getAddressSpace() == LangAS::opencl_local ||
6337           R.getAddressSpace() == LangAS::opencl_global) {
6338         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6339       }
6340 
6341       // OpenCL v1.2 s6.12.14.1:
6342       // A global sampler must be declared with either the constant address
6343       // space qualifier or with the const qualifier.
6344       if (DC->isTranslationUnit() &&
6345           !(R.getAddressSpace() == LangAS::opencl_constant ||
6346           R.isConstQualified())) {
6347         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6348         D.setInvalidType();
6349       }
6350     }
6351 
6352     // OpenCL v1.2 s6.9.r:
6353     // The event type cannot be used with the __local, __constant and __global
6354     // address space qualifiers.
6355     if (R->isEventT()) {
6356       if (R.getAddressSpace() != LangAS::opencl_private) {
6357         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6358         D.setInvalidType();
6359       }
6360     }
6361 
6362     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6363     // supported.  OpenCL C does not support thread_local either, and
6364     // also reject all other thread storage class specifiers.
6365     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6366     if (TSC != TSCS_unspecified) {
6367       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6368       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6369            diag::err_opencl_unknown_type_specifier)
6370           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6371           << DeclSpec::getSpecifierName(TSC) << 1;
6372       D.setInvalidType();
6373       return nullptr;
6374     }
6375   }
6376 
6377   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6378   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6379 
6380   // dllimport globals without explicit storage class are treated as extern. We
6381   // have to change the storage class this early to get the right DeclContext.
6382   if (SC == SC_None && !DC->isRecord() &&
6383       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6384       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6385     SC = SC_Extern;
6386 
6387   DeclContext *OriginalDC = DC;
6388   bool IsLocalExternDecl = SC == SC_Extern &&
6389                            adjustContextForLocalExternDecl(DC);
6390 
6391   if (SCSpec == DeclSpec::SCS_mutable) {
6392     // mutable can only appear on non-static class members, so it's always
6393     // an error here
6394     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6395     D.setInvalidType();
6396     SC = SC_None;
6397   }
6398 
6399   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6400       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6401                               D.getDeclSpec().getStorageClassSpecLoc())) {
6402     // In C++11, the 'register' storage class specifier is deprecated.
6403     // Suppress the warning in system macros, it's used in macros in some
6404     // popular C system headers, such as in glibc's htonl() macro.
6405     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6406          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6407                                    : diag::warn_deprecated_register)
6408       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6409   }
6410 
6411   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6412 
6413   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6414     // C99 6.9p2: The storage-class specifiers auto and register shall not
6415     // appear in the declaration specifiers in an external declaration.
6416     // Global Register+Asm is a GNU extension we support.
6417     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6418       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6419       D.setInvalidType();
6420     }
6421   }
6422 
6423   bool IsMemberSpecialization = false;
6424   bool IsVariableTemplateSpecialization = false;
6425   bool IsPartialSpecialization = false;
6426   bool IsVariableTemplate = false;
6427   VarDecl *NewVD = nullptr;
6428   VarTemplateDecl *NewTemplate = nullptr;
6429   TemplateParameterList *TemplateParams = nullptr;
6430   if (!getLangOpts().CPlusPlus) {
6431     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6432                             II, R, TInfo, SC);
6433 
6434     if (R->getContainedDeducedType())
6435       ParsingInitForAutoVars.insert(NewVD);
6436 
6437     if (D.isInvalidType())
6438       NewVD->setInvalidDecl();
6439   } else {
6440     bool Invalid = false;
6441 
6442     if (DC->isRecord() && !CurContext->isRecord()) {
6443       // This is an out-of-line definition of a static data member.
6444       switch (SC) {
6445       case SC_None:
6446         break;
6447       case SC_Static:
6448         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6449              diag::err_static_out_of_line)
6450           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6451         break;
6452       case SC_Auto:
6453       case SC_Register:
6454       case SC_Extern:
6455         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6456         // to names of variables declared in a block or to function parameters.
6457         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6458         // of class members
6459 
6460         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6461              diag::err_storage_class_for_static_member)
6462           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6463         break;
6464       case SC_PrivateExtern:
6465         llvm_unreachable("C storage class in c++!");
6466       }
6467     }
6468 
6469     if (SC == SC_Static && CurContext->isRecord()) {
6470       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6471         if (RD->isLocalClass())
6472           Diag(D.getIdentifierLoc(),
6473                diag::err_static_data_member_not_allowed_in_local_class)
6474             << Name << RD->getDeclName();
6475 
6476         // C++98 [class.union]p1: If a union contains a static data member,
6477         // the program is ill-formed. C++11 drops this restriction.
6478         if (RD->isUnion())
6479           Diag(D.getIdentifierLoc(),
6480                getLangOpts().CPlusPlus11
6481                  ? diag::warn_cxx98_compat_static_data_member_in_union
6482                  : diag::ext_static_data_member_in_union) << Name;
6483         // We conservatively disallow static data members in anonymous structs.
6484         else if (!RD->getDeclName())
6485           Diag(D.getIdentifierLoc(),
6486                diag::err_static_data_member_not_allowed_in_anon_struct)
6487             << Name << RD->isUnion();
6488       }
6489     }
6490 
6491     // Match up the template parameter lists with the scope specifier, then
6492     // determine whether we have a template or a template specialization.
6493     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6494         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6495         D.getCXXScopeSpec(),
6496         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6497             ? D.getName().TemplateId
6498             : nullptr,
6499         TemplateParamLists,
6500         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6501 
6502     if (TemplateParams) {
6503       if (!TemplateParams->size() &&
6504           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6505         // There is an extraneous 'template<>' for this variable. Complain
6506         // about it, but allow the declaration of the variable.
6507         Diag(TemplateParams->getTemplateLoc(),
6508              diag::err_template_variable_noparams)
6509           << II
6510           << SourceRange(TemplateParams->getTemplateLoc(),
6511                          TemplateParams->getRAngleLoc());
6512         TemplateParams = nullptr;
6513       } else {
6514         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6515           // This is an explicit specialization or a partial specialization.
6516           // FIXME: Check that we can declare a specialization here.
6517           IsVariableTemplateSpecialization = true;
6518           IsPartialSpecialization = TemplateParams->size() > 0;
6519         } else { // if (TemplateParams->size() > 0)
6520           // This is a template declaration.
6521           IsVariableTemplate = true;
6522 
6523           // Check that we can declare a template here.
6524           if (CheckTemplateDeclScope(S, TemplateParams))
6525             return nullptr;
6526 
6527           // Only C++1y supports variable templates (N3651).
6528           Diag(D.getIdentifierLoc(),
6529                getLangOpts().CPlusPlus14
6530                    ? diag::warn_cxx11_compat_variable_template
6531                    : diag::ext_variable_template);
6532         }
6533       }
6534     } else {
6535       assert((Invalid ||
6536               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6537              "should have a 'template<>' for this decl");
6538     }
6539 
6540     if (IsVariableTemplateSpecialization) {
6541       SourceLocation TemplateKWLoc =
6542           TemplateParamLists.size() > 0
6543               ? TemplateParamLists[0]->getTemplateLoc()
6544               : SourceLocation();
6545       DeclResult Res = ActOnVarTemplateSpecialization(
6546           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6547           IsPartialSpecialization);
6548       if (Res.isInvalid())
6549         return nullptr;
6550       NewVD = cast<VarDecl>(Res.get());
6551       AddToScope = false;
6552     } else if (D.isDecompositionDeclarator()) {
6553       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6554                                         D.getIdentifierLoc(), R, TInfo, SC,
6555                                         Bindings);
6556     } else
6557       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6558                               D.getIdentifierLoc(), II, R, TInfo, SC);
6559 
6560     // If this is supposed to be a variable template, create it as such.
6561     if (IsVariableTemplate) {
6562       NewTemplate =
6563           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6564                                   TemplateParams, NewVD);
6565       NewVD->setDescribedVarTemplate(NewTemplate);
6566     }
6567 
6568     // If this decl has an auto type in need of deduction, make a note of the
6569     // Decl so we can diagnose uses of it in its own initializer.
6570     if (R->getContainedDeducedType())
6571       ParsingInitForAutoVars.insert(NewVD);
6572 
6573     if (D.isInvalidType() || Invalid) {
6574       NewVD->setInvalidDecl();
6575       if (NewTemplate)
6576         NewTemplate->setInvalidDecl();
6577     }
6578 
6579     SetNestedNameSpecifier(NewVD, D);
6580 
6581     // If we have any template parameter lists that don't directly belong to
6582     // the variable (matching the scope specifier), store them.
6583     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6584     if (TemplateParamLists.size() > VDTemplateParamLists)
6585       NewVD->setTemplateParameterListsInfo(
6586           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6587 
6588     if (D.getDeclSpec().isConstexprSpecified()) {
6589       NewVD->setConstexpr(true);
6590       // C++1z [dcl.spec.constexpr]p1:
6591       //   A static data member declared with the constexpr specifier is
6592       //   implicitly an inline variable.
6593       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6594         NewVD->setImplicitlyInline();
6595     }
6596   }
6597 
6598   if (D.getDeclSpec().isInlineSpecified()) {
6599     if (!getLangOpts().CPlusPlus) {
6600       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6601           << 0;
6602     } else if (CurContext->isFunctionOrMethod()) {
6603       // 'inline' is not allowed on block scope variable declaration.
6604       Diag(D.getDeclSpec().getInlineSpecLoc(),
6605            diag::err_inline_declaration_block_scope) << Name
6606         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6607     } else {
6608       Diag(D.getDeclSpec().getInlineSpecLoc(),
6609            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6610                                      : diag::ext_inline_variable);
6611       NewVD->setInlineSpecified();
6612     }
6613   }
6614 
6615   // Set the lexical context. If the declarator has a C++ scope specifier, the
6616   // lexical context will be different from the semantic context.
6617   NewVD->setLexicalDeclContext(CurContext);
6618   if (NewTemplate)
6619     NewTemplate->setLexicalDeclContext(CurContext);
6620 
6621   if (IsLocalExternDecl) {
6622     if (D.isDecompositionDeclarator())
6623       for (auto *B : Bindings)
6624         B->setLocalExternDecl();
6625     else
6626       NewVD->setLocalExternDecl();
6627   }
6628 
6629   bool EmitTLSUnsupportedError = false;
6630   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6631     // C++11 [dcl.stc]p4:
6632     //   When thread_local is applied to a variable of block scope the
6633     //   storage-class-specifier static is implied if it does not appear
6634     //   explicitly.
6635     // Core issue: 'static' is not implied if the variable is declared
6636     //   'extern'.
6637     if (NewVD->hasLocalStorage() &&
6638         (SCSpec != DeclSpec::SCS_unspecified ||
6639          TSCS != DeclSpec::TSCS_thread_local ||
6640          !DC->isFunctionOrMethod()))
6641       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6642            diag::err_thread_non_global)
6643         << DeclSpec::getSpecifierName(TSCS);
6644     else if (!Context.getTargetInfo().isTLSSupported()) {
6645       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6646         // Postpone error emission until we've collected attributes required to
6647         // figure out whether it's a host or device variable and whether the
6648         // error should be ignored.
6649         EmitTLSUnsupportedError = true;
6650         // We still need to mark the variable as TLS so it shows up in AST with
6651         // proper storage class for other tools to use even if we're not going
6652         // to emit any code for it.
6653         NewVD->setTSCSpec(TSCS);
6654       } else
6655         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6656              diag::err_thread_unsupported);
6657     } else
6658       NewVD->setTSCSpec(TSCS);
6659   }
6660 
6661   // C99 6.7.4p3
6662   //   An inline definition of a function with external linkage shall
6663   //   not contain a definition of a modifiable object with static or
6664   //   thread storage duration...
6665   // We only apply this when the function is required to be defined
6666   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6667   // that a local variable with thread storage duration still has to
6668   // be marked 'static'.  Also note that it's possible to get these
6669   // semantics in C++ using __attribute__((gnu_inline)).
6670   if (SC == SC_Static && S->getFnParent() != nullptr &&
6671       !NewVD->getType().isConstQualified()) {
6672     FunctionDecl *CurFD = getCurFunctionDecl();
6673     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6674       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6675            diag::warn_static_local_in_extern_inline);
6676       MaybeSuggestAddingStaticToDecl(CurFD);
6677     }
6678   }
6679 
6680   if (D.getDeclSpec().isModulePrivateSpecified()) {
6681     if (IsVariableTemplateSpecialization)
6682       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6683           << (IsPartialSpecialization ? 1 : 0)
6684           << FixItHint::CreateRemoval(
6685                  D.getDeclSpec().getModulePrivateSpecLoc());
6686     else if (IsMemberSpecialization)
6687       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6688         << 2
6689         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6690     else if (NewVD->hasLocalStorage())
6691       Diag(NewVD->getLocation(), diag::err_module_private_local)
6692         << 0 << NewVD->getDeclName()
6693         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6694         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6695     else {
6696       NewVD->setModulePrivate();
6697       if (NewTemplate)
6698         NewTemplate->setModulePrivate();
6699       for (auto *B : Bindings)
6700         B->setModulePrivate();
6701     }
6702   }
6703 
6704   // Handle attributes prior to checking for duplicates in MergeVarDecl
6705   ProcessDeclAttributes(S, NewVD, D);
6706 
6707   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6708     if (EmitTLSUnsupportedError &&
6709         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6710          (getLangOpts().OpenMPIsDevice &&
6711           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6712       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6713            diag::err_thread_unsupported);
6714     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6715     // storage [duration]."
6716     if (SC == SC_None && S->getFnParent() != nullptr &&
6717         (NewVD->hasAttr<CUDASharedAttr>() ||
6718          NewVD->hasAttr<CUDAConstantAttr>())) {
6719       NewVD->setStorageClass(SC_Static);
6720     }
6721   }
6722 
6723   // Ensure that dllimport globals without explicit storage class are treated as
6724   // extern. The storage class is set above using parsed attributes. Now we can
6725   // check the VarDecl itself.
6726   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6727          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6728          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6729 
6730   // In auto-retain/release, infer strong retension for variables of
6731   // retainable type.
6732   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6733     NewVD->setInvalidDecl();
6734 
6735   // Handle GNU asm-label extension (encoded as an attribute).
6736   if (Expr *E = (Expr*)D.getAsmLabel()) {
6737     // The parser guarantees this is a string.
6738     StringLiteral *SE = cast<StringLiteral>(E);
6739     StringRef Label = SE->getString();
6740     if (S->getFnParent() != nullptr) {
6741       switch (SC) {
6742       case SC_None:
6743       case SC_Auto:
6744         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6745         break;
6746       case SC_Register:
6747         // Local Named register
6748         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6749             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6750           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6751         break;
6752       case SC_Static:
6753       case SC_Extern:
6754       case SC_PrivateExtern:
6755         break;
6756       }
6757     } else if (SC == SC_Register) {
6758       // Global Named register
6759       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6760         const auto &TI = Context.getTargetInfo();
6761         bool HasSizeMismatch;
6762 
6763         if (!TI.isValidGCCRegisterName(Label))
6764           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6765         else if (!TI.validateGlobalRegisterVariable(Label,
6766                                                     Context.getTypeSize(R),
6767                                                     HasSizeMismatch))
6768           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6769         else if (HasSizeMismatch)
6770           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6771       }
6772 
6773       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6774         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6775         NewVD->setInvalidDecl(true);
6776       }
6777     }
6778 
6779     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6780                                                 Context, Label, 0));
6781   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6782     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6783       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6784     if (I != ExtnameUndeclaredIdentifiers.end()) {
6785       if (isDeclExternC(NewVD)) {
6786         NewVD->addAttr(I->second);
6787         ExtnameUndeclaredIdentifiers.erase(I);
6788       } else
6789         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6790             << /*Variable*/1 << NewVD;
6791     }
6792   }
6793 
6794   // Find the shadowed declaration before filtering for scope.
6795   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6796                                 ? getShadowedDeclaration(NewVD, Previous)
6797                                 : nullptr;
6798 
6799   // Don't consider existing declarations that are in a different
6800   // scope and are out-of-semantic-context declarations (if the new
6801   // declaration has linkage).
6802   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6803                        D.getCXXScopeSpec().isNotEmpty() ||
6804                        IsMemberSpecialization ||
6805                        IsVariableTemplateSpecialization);
6806 
6807   // Check whether the previous declaration is in the same block scope. This
6808   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6809   if (getLangOpts().CPlusPlus &&
6810       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6811     NewVD->setPreviousDeclInSameBlockScope(
6812         Previous.isSingleResult() && !Previous.isShadowed() &&
6813         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6814 
6815   if (!getLangOpts().CPlusPlus) {
6816     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6817   } else {
6818     // If this is an explicit specialization of a static data member, check it.
6819     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6820         CheckMemberSpecialization(NewVD, Previous))
6821       NewVD->setInvalidDecl();
6822 
6823     // Merge the decl with the existing one if appropriate.
6824     if (!Previous.empty()) {
6825       if (Previous.isSingleResult() &&
6826           isa<FieldDecl>(Previous.getFoundDecl()) &&
6827           D.getCXXScopeSpec().isSet()) {
6828         // The user tried to define a non-static data member
6829         // out-of-line (C++ [dcl.meaning]p1).
6830         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6831           << D.getCXXScopeSpec().getRange();
6832         Previous.clear();
6833         NewVD->setInvalidDecl();
6834       }
6835     } else if (D.getCXXScopeSpec().isSet()) {
6836       // No previous declaration in the qualifying scope.
6837       Diag(D.getIdentifierLoc(), diag::err_no_member)
6838         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6839         << D.getCXXScopeSpec().getRange();
6840       NewVD->setInvalidDecl();
6841     }
6842 
6843     if (!IsVariableTemplateSpecialization)
6844       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6845 
6846     if (NewTemplate) {
6847       VarTemplateDecl *PrevVarTemplate =
6848           NewVD->getPreviousDecl()
6849               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6850               : nullptr;
6851 
6852       // Check the template parameter list of this declaration, possibly
6853       // merging in the template parameter list from the previous variable
6854       // template declaration.
6855       if (CheckTemplateParameterList(
6856               TemplateParams,
6857               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6858                               : nullptr,
6859               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6860                DC->isDependentContext())
6861                   ? TPC_ClassTemplateMember
6862                   : TPC_VarTemplate))
6863         NewVD->setInvalidDecl();
6864 
6865       // If we are providing an explicit specialization of a static variable
6866       // template, make a note of that.
6867       if (PrevVarTemplate &&
6868           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6869         PrevVarTemplate->setMemberSpecialization();
6870     }
6871   }
6872 
6873   // Diagnose shadowed variables iff this isn't a redeclaration.
6874   if (ShadowedDecl && !D.isRedeclaration())
6875     CheckShadow(NewVD, ShadowedDecl, Previous);
6876 
6877   ProcessPragmaWeak(S, NewVD);
6878 
6879   // If this is the first declaration of an extern C variable, update
6880   // the map of such variables.
6881   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6882       isIncompleteDeclExternC(*this, NewVD))
6883     RegisterLocallyScopedExternCDecl(NewVD, S);
6884 
6885   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6886     Decl *ManglingContextDecl;
6887     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6888             NewVD->getDeclContext(), ManglingContextDecl)) {
6889       Context.setManglingNumber(
6890           NewVD, MCtx->getManglingNumber(
6891                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6892       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6893     }
6894   }
6895 
6896   // Special handling of variable named 'main'.
6897   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6898       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6899       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6900 
6901     // C++ [basic.start.main]p3
6902     // A program that declares a variable main at global scope is ill-formed.
6903     if (getLangOpts().CPlusPlus)
6904       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6905 
6906     // In C, and external-linkage variable named main results in undefined
6907     // behavior.
6908     else if (NewVD->hasExternalFormalLinkage())
6909       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6910   }
6911 
6912   if (D.isRedeclaration() && !Previous.empty()) {
6913     NamedDecl *Prev = Previous.getRepresentativeDecl();
6914     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6915                                    D.isFunctionDefinition());
6916   }
6917 
6918   if (NewTemplate) {
6919     if (NewVD->isInvalidDecl())
6920       NewTemplate->setInvalidDecl();
6921     ActOnDocumentableDecl(NewTemplate);
6922     return NewTemplate;
6923   }
6924 
6925   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6926     CompleteMemberSpecialization(NewVD, Previous);
6927 
6928   return NewVD;
6929 }
6930 
6931 /// Enum describing the %select options in diag::warn_decl_shadow.
6932 enum ShadowedDeclKind {
6933   SDK_Local,
6934   SDK_Global,
6935   SDK_StaticMember,
6936   SDK_Field,
6937   SDK_Typedef,
6938   SDK_Using
6939 };
6940 
6941 /// Determine what kind of declaration we're shadowing.
6942 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6943                                                 const DeclContext *OldDC) {
6944   if (isa<TypeAliasDecl>(ShadowedDecl))
6945     return SDK_Using;
6946   else if (isa<TypedefDecl>(ShadowedDecl))
6947     return SDK_Typedef;
6948   else if (isa<RecordDecl>(OldDC))
6949     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6950 
6951   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6952 }
6953 
6954 /// Return the location of the capture if the given lambda captures the given
6955 /// variable \p VD, or an invalid source location otherwise.
6956 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6957                                          const VarDecl *VD) {
6958   for (const Capture &Capture : LSI->Captures) {
6959     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6960       return Capture.getLocation();
6961   }
6962   return SourceLocation();
6963 }
6964 
6965 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6966                                      const LookupResult &R) {
6967   // Only diagnose if we're shadowing an unambiguous field or variable.
6968   if (R.getResultKind() != LookupResult::Found)
6969     return false;
6970 
6971   // Return false if warning is ignored.
6972   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6973 }
6974 
6975 /// Return the declaration shadowed by the given variable \p D, or null
6976 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6977 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6978                                         const LookupResult &R) {
6979   if (!shouldWarnIfShadowedDecl(Diags, R))
6980     return nullptr;
6981 
6982   // Don't diagnose declarations at file scope.
6983   if (D->hasGlobalStorage())
6984     return nullptr;
6985 
6986   NamedDecl *ShadowedDecl = R.getFoundDecl();
6987   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6988              ? ShadowedDecl
6989              : nullptr;
6990 }
6991 
6992 /// Return the declaration shadowed by the given typedef \p D, or null
6993 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6994 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6995                                         const LookupResult &R) {
6996   // Don't warn if typedef declaration is part of a class
6997   if (D->getDeclContext()->isRecord())
6998     return nullptr;
6999 
7000   if (!shouldWarnIfShadowedDecl(Diags, R))
7001     return nullptr;
7002 
7003   NamedDecl *ShadowedDecl = R.getFoundDecl();
7004   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7005 }
7006 
7007 /// Diagnose variable or built-in function shadowing.  Implements
7008 /// -Wshadow.
7009 ///
7010 /// This method is called whenever a VarDecl is added to a "useful"
7011 /// scope.
7012 ///
7013 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7014 /// \param R the lookup of the name
7015 ///
7016 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7017                        const LookupResult &R) {
7018   DeclContext *NewDC = D->getDeclContext();
7019 
7020   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7021     // Fields are not shadowed by variables in C++ static methods.
7022     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7023       if (MD->isStatic())
7024         return;
7025 
7026     // Fields shadowed by constructor parameters are a special case. Usually
7027     // the constructor initializes the field with the parameter.
7028     if (isa<CXXConstructorDecl>(NewDC))
7029       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7030         // Remember that this was shadowed so we can either warn about its
7031         // modification or its existence depending on warning settings.
7032         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7033         return;
7034       }
7035   }
7036 
7037   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7038     if (shadowedVar->isExternC()) {
7039       // For shadowing external vars, make sure that we point to the global
7040       // declaration, not a locally scoped extern declaration.
7041       for (auto I : shadowedVar->redecls())
7042         if (I->isFileVarDecl()) {
7043           ShadowedDecl = I;
7044           break;
7045         }
7046     }
7047 
7048   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7049 
7050   unsigned WarningDiag = diag::warn_decl_shadow;
7051   SourceLocation CaptureLoc;
7052   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7053       isa<CXXMethodDecl>(NewDC)) {
7054     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7055       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7056         if (RD->getLambdaCaptureDefault() == LCD_None) {
7057           // Try to avoid warnings for lambdas with an explicit capture list.
7058           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7059           // Warn only when the lambda captures the shadowed decl explicitly.
7060           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7061           if (CaptureLoc.isInvalid())
7062             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7063         } else {
7064           // Remember that this was shadowed so we can avoid the warning if the
7065           // shadowed decl isn't captured and the warning settings allow it.
7066           cast<LambdaScopeInfo>(getCurFunction())
7067               ->ShadowingDecls.push_back(
7068                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7069           return;
7070         }
7071       }
7072 
7073       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7074         // A variable can't shadow a local variable in an enclosing scope, if
7075         // they are separated by a non-capturing declaration context.
7076         for (DeclContext *ParentDC = NewDC;
7077              ParentDC && !ParentDC->Equals(OldDC);
7078              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7079           // Only block literals, captured statements, and lambda expressions
7080           // can capture; other scopes don't.
7081           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7082               !isLambdaCallOperator(ParentDC)) {
7083             return;
7084           }
7085         }
7086       }
7087     }
7088   }
7089 
7090   // Only warn about certain kinds of shadowing for class members.
7091   if (NewDC && NewDC->isRecord()) {
7092     // In particular, don't warn about shadowing non-class members.
7093     if (!OldDC->isRecord())
7094       return;
7095 
7096     // TODO: should we warn about static data members shadowing
7097     // static data members from base classes?
7098 
7099     // TODO: don't diagnose for inaccessible shadowed members.
7100     // This is hard to do perfectly because we might friend the
7101     // shadowing context, but that's just a false negative.
7102   }
7103 
7104 
7105   DeclarationName Name = R.getLookupName();
7106 
7107   // Emit warning and note.
7108   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7109     return;
7110   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7111   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7112   if (!CaptureLoc.isInvalid())
7113     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7114         << Name << /*explicitly*/ 1;
7115   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7116 }
7117 
7118 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7119 /// when these variables are captured by the lambda.
7120 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7121   for (const auto &Shadow : LSI->ShadowingDecls) {
7122     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7123     // Try to avoid the warning when the shadowed decl isn't captured.
7124     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7125     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7126     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7127                                        ? diag::warn_decl_shadow_uncaptured_local
7128                                        : diag::warn_decl_shadow)
7129         << Shadow.VD->getDeclName()
7130         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7131     if (!CaptureLoc.isInvalid())
7132       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7133           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7134     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7135   }
7136 }
7137 
7138 /// Check -Wshadow without the advantage of a previous lookup.
7139 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7140   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7141     return;
7142 
7143   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7144                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7145   LookupName(R, S);
7146   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7147     CheckShadow(D, ShadowedDecl, R);
7148 }
7149 
7150 /// Check if 'E', which is an expression that is about to be modified, refers
7151 /// to a constructor parameter that shadows a field.
7152 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7153   // Quickly ignore expressions that can't be shadowing ctor parameters.
7154   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7155     return;
7156   E = E->IgnoreParenImpCasts();
7157   auto *DRE = dyn_cast<DeclRefExpr>(E);
7158   if (!DRE)
7159     return;
7160   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7161   auto I = ShadowingDecls.find(D);
7162   if (I == ShadowingDecls.end())
7163     return;
7164   const NamedDecl *ShadowedDecl = I->second;
7165   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7166   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7167   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7168   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7169 
7170   // Avoid issuing multiple warnings about the same decl.
7171   ShadowingDecls.erase(I);
7172 }
7173 
7174 /// Check for conflict between this global or extern "C" declaration and
7175 /// previous global or extern "C" declarations. This is only used in C++.
7176 template<typename T>
7177 static bool checkGlobalOrExternCConflict(
7178     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7179   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7180   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7181 
7182   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7183     // The common case: this global doesn't conflict with any extern "C"
7184     // declaration.
7185     return false;
7186   }
7187 
7188   if (Prev) {
7189     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7190       // Both the old and new declarations have C language linkage. This is a
7191       // redeclaration.
7192       Previous.clear();
7193       Previous.addDecl(Prev);
7194       return true;
7195     }
7196 
7197     // This is a global, non-extern "C" declaration, and there is a previous
7198     // non-global extern "C" declaration. Diagnose if this is a variable
7199     // declaration.
7200     if (!isa<VarDecl>(ND))
7201       return false;
7202   } else {
7203     // The declaration is extern "C". Check for any declaration in the
7204     // translation unit which might conflict.
7205     if (IsGlobal) {
7206       // We have already performed the lookup into the translation unit.
7207       IsGlobal = false;
7208       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7209            I != E; ++I) {
7210         if (isa<VarDecl>(*I)) {
7211           Prev = *I;
7212           break;
7213         }
7214       }
7215     } else {
7216       DeclContext::lookup_result R =
7217           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7218       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7219            I != E; ++I) {
7220         if (isa<VarDecl>(*I)) {
7221           Prev = *I;
7222           break;
7223         }
7224         // FIXME: If we have any other entity with this name in global scope,
7225         // the declaration is ill-formed, but that is a defect: it breaks the
7226         // 'stat' hack, for instance. Only variables can have mangled name
7227         // clashes with extern "C" declarations, so only they deserve a
7228         // diagnostic.
7229       }
7230     }
7231 
7232     if (!Prev)
7233       return false;
7234   }
7235 
7236   // Use the first declaration's location to ensure we point at something which
7237   // is lexically inside an extern "C" linkage-spec.
7238   assert(Prev && "should have found a previous declaration to diagnose");
7239   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7240     Prev = FD->getFirstDecl();
7241   else
7242     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7243 
7244   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7245     << IsGlobal << ND;
7246   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7247     << IsGlobal;
7248   return false;
7249 }
7250 
7251 /// Apply special rules for handling extern "C" declarations. Returns \c true
7252 /// if we have found that this is a redeclaration of some prior entity.
7253 ///
7254 /// Per C++ [dcl.link]p6:
7255 ///   Two declarations [for a function or variable] with C language linkage
7256 ///   with the same name that appear in different scopes refer to the same
7257 ///   [entity]. An entity with C language linkage shall not be declared with
7258 ///   the same name as an entity in global scope.
7259 template<typename T>
7260 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7261                                                   LookupResult &Previous) {
7262   if (!S.getLangOpts().CPlusPlus) {
7263     // In C, when declaring a global variable, look for a corresponding 'extern'
7264     // variable declared in function scope. We don't need this in C++, because
7265     // we find local extern decls in the surrounding file-scope DeclContext.
7266     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7267       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7268         Previous.clear();
7269         Previous.addDecl(Prev);
7270         return true;
7271       }
7272     }
7273     return false;
7274   }
7275 
7276   // A declaration in the translation unit can conflict with an extern "C"
7277   // declaration.
7278   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7279     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7280 
7281   // An extern "C" declaration can conflict with a declaration in the
7282   // translation unit or can be a redeclaration of an extern "C" declaration
7283   // in another scope.
7284   if (isIncompleteDeclExternC(S,ND))
7285     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7286 
7287   // Neither global nor extern "C": nothing to do.
7288   return false;
7289 }
7290 
7291 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7292   // If the decl is already known invalid, don't check it.
7293   if (NewVD->isInvalidDecl())
7294     return;
7295 
7296   QualType T = NewVD->getType();
7297 
7298   // Defer checking an 'auto' type until its initializer is attached.
7299   if (T->isUndeducedType())
7300     return;
7301 
7302   if (NewVD->hasAttrs())
7303     CheckAlignasUnderalignment(NewVD);
7304 
7305   if (T->isObjCObjectType()) {
7306     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7307       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7308     T = Context.getObjCObjectPointerType(T);
7309     NewVD->setType(T);
7310   }
7311 
7312   // Emit an error if an address space was applied to decl with local storage.
7313   // This includes arrays of objects with address space qualifiers, but not
7314   // automatic variables that point to other address spaces.
7315   // ISO/IEC TR 18037 S5.1.2
7316   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7317       T.getAddressSpace() != LangAS::Default) {
7318     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7319     NewVD->setInvalidDecl();
7320     return;
7321   }
7322 
7323   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7324   // scope.
7325   if (getLangOpts().OpenCLVersion == 120 &&
7326       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7327       NewVD->isStaticLocal()) {
7328     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7329     NewVD->setInvalidDecl();
7330     return;
7331   }
7332 
7333   if (getLangOpts().OpenCL) {
7334     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7335     if (NewVD->hasAttr<BlocksAttr>()) {
7336       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7337       return;
7338     }
7339 
7340     if (T->isBlockPointerType()) {
7341       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7342       // can't use 'extern' storage class.
7343       if (!T.isConstQualified()) {
7344         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7345             << 0 /*const*/;
7346         NewVD->setInvalidDecl();
7347         return;
7348       }
7349       if (NewVD->hasExternalStorage()) {
7350         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7351         NewVD->setInvalidDecl();
7352         return;
7353       }
7354     }
7355     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7356     // __constant address space.
7357     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7358     // variables inside a function can also be declared in the global
7359     // address space.
7360     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7361         NewVD->hasExternalStorage()) {
7362       if (!T->isSamplerT() &&
7363           !(T.getAddressSpace() == LangAS::opencl_constant ||
7364             (T.getAddressSpace() == LangAS::opencl_global &&
7365              getLangOpts().OpenCLVersion == 200))) {
7366         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7367         if (getLangOpts().OpenCLVersion == 200)
7368           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7369               << Scope << "global or constant";
7370         else
7371           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7372               << Scope << "constant";
7373         NewVD->setInvalidDecl();
7374         return;
7375       }
7376     } else {
7377       if (T.getAddressSpace() == LangAS::opencl_global) {
7378         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7379             << 1 /*is any function*/ << "global";
7380         NewVD->setInvalidDecl();
7381         return;
7382       }
7383       if (T.getAddressSpace() == LangAS::opencl_constant ||
7384           T.getAddressSpace() == LangAS::opencl_local) {
7385         FunctionDecl *FD = getCurFunctionDecl();
7386         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7387         // in functions.
7388         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7389           if (T.getAddressSpace() == LangAS::opencl_constant)
7390             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7391                 << 0 /*non-kernel only*/ << "constant";
7392           else
7393             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7394                 << 0 /*non-kernel only*/ << "local";
7395           NewVD->setInvalidDecl();
7396           return;
7397         }
7398         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7399         // in the outermost scope of a kernel function.
7400         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7401           if (!getCurScope()->isFunctionScope()) {
7402             if (T.getAddressSpace() == LangAS::opencl_constant)
7403               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7404                   << "constant";
7405             else
7406               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7407                   << "local";
7408             NewVD->setInvalidDecl();
7409             return;
7410           }
7411         }
7412       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7413         // Do not allow other address spaces on automatic variable.
7414         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7415         NewVD->setInvalidDecl();
7416         return;
7417       }
7418     }
7419   }
7420 
7421   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7422       && !NewVD->hasAttr<BlocksAttr>()) {
7423     if (getLangOpts().getGC() != LangOptions::NonGC)
7424       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7425     else {
7426       assert(!getLangOpts().ObjCAutoRefCount);
7427       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7428     }
7429   }
7430 
7431   bool isVM = T->isVariablyModifiedType();
7432   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7433       NewVD->hasAttr<BlocksAttr>())
7434     setFunctionHasBranchProtectedScope();
7435 
7436   if ((isVM && NewVD->hasLinkage()) ||
7437       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7438     bool SizeIsNegative;
7439     llvm::APSInt Oversized;
7440     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7441         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7442     QualType FixedT;
7443     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7444       FixedT = FixedTInfo->getType();
7445     else if (FixedTInfo) {
7446       // Type and type-as-written are canonically different. We need to fix up
7447       // both types separately.
7448       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7449                                                    Oversized);
7450     }
7451     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7452       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7453       // FIXME: This won't give the correct result for
7454       // int a[10][n];
7455       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7456 
7457       if (NewVD->isFileVarDecl())
7458         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7459         << SizeRange;
7460       else if (NewVD->isStaticLocal())
7461         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7462         << SizeRange;
7463       else
7464         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7465         << SizeRange;
7466       NewVD->setInvalidDecl();
7467       return;
7468     }
7469 
7470     if (!FixedTInfo) {
7471       if (NewVD->isFileVarDecl())
7472         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7473       else
7474         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7475       NewVD->setInvalidDecl();
7476       return;
7477     }
7478 
7479     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7480     NewVD->setType(FixedT);
7481     NewVD->setTypeSourceInfo(FixedTInfo);
7482   }
7483 
7484   if (T->isVoidType()) {
7485     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7486     //                    of objects and functions.
7487     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7488       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7489         << T;
7490       NewVD->setInvalidDecl();
7491       return;
7492     }
7493   }
7494 
7495   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7496     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7497     NewVD->setInvalidDecl();
7498     return;
7499   }
7500 
7501   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7502     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7503     NewVD->setInvalidDecl();
7504     return;
7505   }
7506 
7507   if (NewVD->isConstexpr() && !T->isDependentType() &&
7508       RequireLiteralType(NewVD->getLocation(), T,
7509                          diag::err_constexpr_var_non_literal)) {
7510     NewVD->setInvalidDecl();
7511     return;
7512   }
7513 }
7514 
7515 /// Perform semantic checking on a newly-created variable
7516 /// declaration.
7517 ///
7518 /// This routine performs all of the type-checking required for a
7519 /// variable declaration once it has been built. It is used both to
7520 /// check variables after they have been parsed and their declarators
7521 /// have been translated into a declaration, and to check variables
7522 /// that have been instantiated from a template.
7523 ///
7524 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7525 ///
7526 /// Returns true if the variable declaration is a redeclaration.
7527 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7528   CheckVariableDeclarationType(NewVD);
7529 
7530   // If the decl is already known invalid, don't check it.
7531   if (NewVD->isInvalidDecl())
7532     return false;
7533 
7534   // If we did not find anything by this name, look for a non-visible
7535   // extern "C" declaration with the same name.
7536   if (Previous.empty() &&
7537       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7538     Previous.setShadowed();
7539 
7540   if (!Previous.empty()) {
7541     MergeVarDecl(NewVD, Previous);
7542     return true;
7543   }
7544   return false;
7545 }
7546 
7547 namespace {
7548 struct FindOverriddenMethod {
7549   Sema *S;
7550   CXXMethodDecl *Method;
7551 
7552   /// Member lookup function that determines whether a given C++
7553   /// method overrides a method in a base class, to be used with
7554   /// CXXRecordDecl::lookupInBases().
7555   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7556     RecordDecl *BaseRecord =
7557         Specifier->getType()->getAs<RecordType>()->getDecl();
7558 
7559     DeclarationName Name = Method->getDeclName();
7560 
7561     // FIXME: Do we care about other names here too?
7562     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7563       // We really want to find the base class destructor here.
7564       QualType T = S->Context.getTypeDeclType(BaseRecord);
7565       CanQualType CT = S->Context.getCanonicalType(T);
7566 
7567       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7568     }
7569 
7570     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7571          Path.Decls = Path.Decls.slice(1)) {
7572       NamedDecl *D = Path.Decls.front();
7573       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7574         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7575           return true;
7576       }
7577     }
7578 
7579     return false;
7580   }
7581 };
7582 
7583 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7584 } // end anonymous namespace
7585 
7586 /// Report an error regarding overriding, along with any relevant
7587 /// overridden methods.
7588 ///
7589 /// \param DiagID the primary error to report.
7590 /// \param MD the overriding method.
7591 /// \param OEK which overrides to include as notes.
7592 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7593                             OverrideErrorKind OEK = OEK_All) {
7594   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7595   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7596     // This check (& the OEK parameter) could be replaced by a predicate, but
7597     // without lambdas that would be overkill. This is still nicer than writing
7598     // out the diag loop 3 times.
7599     if ((OEK == OEK_All) ||
7600         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7601         (OEK == OEK_Deleted && O->isDeleted()))
7602       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7603   }
7604 }
7605 
7606 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7607 /// and if so, check that it's a valid override and remember it.
7608 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7609   // Look for methods in base classes that this method might override.
7610   CXXBasePaths Paths;
7611   FindOverriddenMethod FOM;
7612   FOM.Method = MD;
7613   FOM.S = this;
7614   bool hasDeletedOverridenMethods = false;
7615   bool hasNonDeletedOverridenMethods = false;
7616   bool AddedAny = false;
7617   if (DC->lookupInBases(FOM, Paths)) {
7618     for (auto *I : Paths.found_decls()) {
7619       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7620         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7621         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7622             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7623             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7624             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7625           hasDeletedOverridenMethods |= OldMD->isDeleted();
7626           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7627           AddedAny = true;
7628         }
7629       }
7630     }
7631   }
7632 
7633   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7634     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7635   }
7636   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7637     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7638   }
7639 
7640   return AddedAny;
7641 }
7642 
7643 namespace {
7644   // Struct for holding all of the extra arguments needed by
7645   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7646   struct ActOnFDArgs {
7647     Scope *S;
7648     Declarator &D;
7649     MultiTemplateParamsArg TemplateParamLists;
7650     bool AddToScope;
7651   };
7652 } // end anonymous namespace
7653 
7654 namespace {
7655 
7656 // Callback to only accept typo corrections that have a non-zero edit distance.
7657 // Also only accept corrections that have the same parent decl.
7658 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7659  public:
7660   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7661                             CXXRecordDecl *Parent)
7662       : Context(Context), OriginalFD(TypoFD),
7663         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7664 
7665   bool ValidateCandidate(const TypoCorrection &candidate) override {
7666     if (candidate.getEditDistance() == 0)
7667       return false;
7668 
7669     SmallVector<unsigned, 1> MismatchedParams;
7670     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7671                                           CDeclEnd = candidate.end();
7672          CDecl != CDeclEnd; ++CDecl) {
7673       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7674 
7675       if (FD && !FD->hasBody() &&
7676           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7677         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7678           CXXRecordDecl *Parent = MD->getParent();
7679           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7680             return true;
7681         } else if (!ExpectedParent) {
7682           return true;
7683         }
7684       }
7685     }
7686 
7687     return false;
7688   }
7689 
7690  private:
7691   ASTContext &Context;
7692   FunctionDecl *OriginalFD;
7693   CXXRecordDecl *ExpectedParent;
7694 };
7695 
7696 } // end anonymous namespace
7697 
7698 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7699   TypoCorrectedFunctionDefinitions.insert(F);
7700 }
7701 
7702 /// Generate diagnostics for an invalid function redeclaration.
7703 ///
7704 /// This routine handles generating the diagnostic messages for an invalid
7705 /// function redeclaration, including finding possible similar declarations
7706 /// or performing typo correction if there are no previous declarations with
7707 /// the same name.
7708 ///
7709 /// Returns a NamedDecl iff typo correction was performed and substituting in
7710 /// the new declaration name does not cause new errors.
7711 static NamedDecl *DiagnoseInvalidRedeclaration(
7712     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7713     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7714   DeclarationName Name = NewFD->getDeclName();
7715   DeclContext *NewDC = NewFD->getDeclContext();
7716   SmallVector<unsigned, 1> MismatchedParams;
7717   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7718   TypoCorrection Correction;
7719   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7720   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7721                                    : diag::err_member_decl_does_not_match;
7722   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7723                     IsLocalFriend ? Sema::LookupLocalFriendName
7724                                   : Sema::LookupOrdinaryName,
7725                     Sema::ForVisibleRedeclaration);
7726 
7727   NewFD->setInvalidDecl();
7728   if (IsLocalFriend)
7729     SemaRef.LookupName(Prev, S);
7730   else
7731     SemaRef.LookupQualifiedName(Prev, NewDC);
7732   assert(!Prev.isAmbiguous() &&
7733          "Cannot have an ambiguity in previous-declaration lookup");
7734   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7735   if (!Prev.empty()) {
7736     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7737          Func != FuncEnd; ++Func) {
7738       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7739       if (FD &&
7740           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7741         // Add 1 to the index so that 0 can mean the mismatch didn't
7742         // involve a parameter
7743         unsigned ParamNum =
7744             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7745         NearMatches.push_back(std::make_pair(FD, ParamNum));
7746       }
7747     }
7748   // If the qualified name lookup yielded nothing, try typo correction
7749   } else if ((Correction = SemaRef.CorrectTypo(
7750                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7751                   &ExtraArgs.D.getCXXScopeSpec(),
7752                   llvm::make_unique<DifferentNameValidatorCCC>(
7753                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7754                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7755     // Set up everything for the call to ActOnFunctionDeclarator
7756     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7757                               ExtraArgs.D.getIdentifierLoc());
7758     Previous.clear();
7759     Previous.setLookupName(Correction.getCorrection());
7760     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7761                                     CDeclEnd = Correction.end();
7762          CDecl != CDeclEnd; ++CDecl) {
7763       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7764       if (FD && !FD->hasBody() &&
7765           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7766         Previous.addDecl(FD);
7767       }
7768     }
7769     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7770 
7771     NamedDecl *Result;
7772     // Retry building the function declaration with the new previous
7773     // declarations, and with errors suppressed.
7774     {
7775       // Trap errors.
7776       Sema::SFINAETrap Trap(SemaRef);
7777 
7778       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7779       // pieces need to verify the typo-corrected C++ declaration and hopefully
7780       // eliminate the need for the parameter pack ExtraArgs.
7781       Result = SemaRef.ActOnFunctionDeclarator(
7782           ExtraArgs.S, ExtraArgs.D,
7783           Correction.getCorrectionDecl()->getDeclContext(),
7784           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7785           ExtraArgs.AddToScope);
7786 
7787       if (Trap.hasErrorOccurred())
7788         Result = nullptr;
7789     }
7790 
7791     if (Result) {
7792       // Determine which correction we picked.
7793       Decl *Canonical = Result->getCanonicalDecl();
7794       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7795            I != E; ++I)
7796         if ((*I)->getCanonicalDecl() == Canonical)
7797           Correction.setCorrectionDecl(*I);
7798 
7799       // Let Sema know about the correction.
7800       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7801       SemaRef.diagnoseTypo(
7802           Correction,
7803           SemaRef.PDiag(IsLocalFriend
7804                           ? diag::err_no_matching_local_friend_suggest
7805                           : diag::err_member_decl_does_not_match_suggest)
7806             << Name << NewDC << IsDefinition);
7807       return Result;
7808     }
7809 
7810     // Pretend the typo correction never occurred
7811     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7812                               ExtraArgs.D.getIdentifierLoc());
7813     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7814     Previous.clear();
7815     Previous.setLookupName(Name);
7816   }
7817 
7818   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7819       << Name << NewDC << IsDefinition << NewFD->getLocation();
7820 
7821   bool NewFDisConst = false;
7822   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7823     NewFDisConst = NewMD->isConst();
7824 
7825   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7826        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7827        NearMatch != NearMatchEnd; ++NearMatch) {
7828     FunctionDecl *FD = NearMatch->first;
7829     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7830     bool FDisConst = MD && MD->isConst();
7831     bool IsMember = MD || !IsLocalFriend;
7832 
7833     // FIXME: These notes are poorly worded for the local friend case.
7834     if (unsigned Idx = NearMatch->second) {
7835       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7836       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7837       if (Loc.isInvalid()) Loc = FD->getLocation();
7838       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7839                                  : diag::note_local_decl_close_param_match)
7840         << Idx << FDParam->getType()
7841         << NewFD->getParamDecl(Idx - 1)->getType();
7842     } else if (FDisConst != NewFDisConst) {
7843       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7844           << NewFDisConst << FD->getSourceRange().getEnd();
7845     } else
7846       SemaRef.Diag(FD->getLocation(),
7847                    IsMember ? diag::note_member_def_close_match
7848                             : diag::note_local_decl_close_match);
7849   }
7850   return nullptr;
7851 }
7852 
7853 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7854   switch (D.getDeclSpec().getStorageClassSpec()) {
7855   default: llvm_unreachable("Unknown storage class!");
7856   case DeclSpec::SCS_auto:
7857   case DeclSpec::SCS_register:
7858   case DeclSpec::SCS_mutable:
7859     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7860                  diag::err_typecheck_sclass_func);
7861     D.getMutableDeclSpec().ClearStorageClassSpecs();
7862     D.setInvalidType();
7863     break;
7864   case DeclSpec::SCS_unspecified: break;
7865   case DeclSpec::SCS_extern:
7866     if (D.getDeclSpec().isExternInLinkageSpec())
7867       return SC_None;
7868     return SC_Extern;
7869   case DeclSpec::SCS_static: {
7870     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7871       // C99 6.7.1p5:
7872       //   The declaration of an identifier for a function that has
7873       //   block scope shall have no explicit storage-class specifier
7874       //   other than extern
7875       // See also (C++ [dcl.stc]p4).
7876       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7877                    diag::err_static_block_func);
7878       break;
7879     } else
7880       return SC_Static;
7881   }
7882   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7883   }
7884 
7885   // No explicit storage class has already been returned
7886   return SC_None;
7887 }
7888 
7889 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7890                                            DeclContext *DC, QualType &R,
7891                                            TypeSourceInfo *TInfo,
7892                                            StorageClass SC,
7893                                            bool &IsVirtualOkay) {
7894   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7895   DeclarationName Name = NameInfo.getName();
7896 
7897   FunctionDecl *NewFD = nullptr;
7898   bool isInline = D.getDeclSpec().isInlineSpecified();
7899 
7900   if (!SemaRef.getLangOpts().CPlusPlus) {
7901     // Determine whether the function was written with a
7902     // prototype. This true when:
7903     //   - there is a prototype in the declarator, or
7904     //   - the type R of the function is some kind of typedef or other non-
7905     //     attributed reference to a type name (which eventually refers to a
7906     //     function type).
7907     bool HasPrototype =
7908       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7909       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7910 
7911     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7912                                  R, TInfo, SC, isInline, HasPrototype, false);
7913     if (D.isInvalidType())
7914       NewFD->setInvalidDecl();
7915 
7916     return NewFD;
7917   }
7918 
7919   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7920   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7921 
7922   // Check that the return type is not an abstract class type.
7923   // For record types, this is done by the AbstractClassUsageDiagnoser once
7924   // the class has been completely parsed.
7925   if (!DC->isRecord() &&
7926       SemaRef.RequireNonAbstractType(
7927           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7928           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7929     D.setInvalidType();
7930 
7931   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7932     // This is a C++ constructor declaration.
7933     assert(DC->isRecord() &&
7934            "Constructors can only be declared in a member context");
7935 
7936     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7937     return CXXConstructorDecl::Create(
7938         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7939         TInfo, isExplicit, isInline,
7940         /*isImplicitlyDeclared=*/false, isConstexpr);
7941 
7942   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7943     // This is a C++ destructor declaration.
7944     if (DC->isRecord()) {
7945       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7946       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7947       CXXDestructorDecl *NewDD =
7948           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7949                                     NameInfo, R, TInfo, isInline,
7950                                     /*isImplicitlyDeclared=*/false);
7951 
7952       // If the destructor needs an implicit exception specification, set it
7953       // now. FIXME: It'd be nice to be able to create the right type to start
7954       // with, but the type needs to reference the destructor declaration.
7955       if (SemaRef.getLangOpts().CPlusPlus11)
7956         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7957 
7958       IsVirtualOkay = true;
7959       return NewDD;
7960 
7961     } else {
7962       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7963       D.setInvalidType();
7964 
7965       // Create a FunctionDecl to satisfy the function definition parsing
7966       // code path.
7967       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7968                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7969                                   isInline,
7970                                   /*hasPrototype=*/true, isConstexpr);
7971     }
7972 
7973   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7974     if (!DC->isRecord()) {
7975       SemaRef.Diag(D.getIdentifierLoc(),
7976            diag::err_conv_function_not_member);
7977       return nullptr;
7978     }
7979 
7980     SemaRef.CheckConversionDeclarator(D, R, SC);
7981     IsVirtualOkay = true;
7982     return CXXConversionDecl::Create(
7983         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7984         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
7985 
7986   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7987     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7988 
7989     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7990                                          isExplicit, NameInfo, R, TInfo,
7991                                          D.getEndLoc());
7992   } else if (DC->isRecord()) {
7993     // If the name of the function is the same as the name of the record,
7994     // then this must be an invalid constructor that has a return type.
7995     // (The parser checks for a return type and makes the declarator a
7996     // constructor if it has no return type).
7997     if (Name.getAsIdentifierInfo() &&
7998         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7999       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8000         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8001         << SourceRange(D.getIdentifierLoc());
8002       return nullptr;
8003     }
8004 
8005     // This is a C++ method declaration.
8006     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8007         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8008         TInfo, SC, isInline, isConstexpr, SourceLocation());
8009     IsVirtualOkay = !Ret->isStatic();
8010     return Ret;
8011   } else {
8012     bool isFriend =
8013         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8014     if (!isFriend && SemaRef.CurContext->isRecord())
8015       return nullptr;
8016 
8017     // Determine whether the function was written with a
8018     // prototype. This true when:
8019     //   - we're in C++ (where every function has a prototype),
8020     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8021                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8022                                 isConstexpr);
8023   }
8024 }
8025 
8026 enum OpenCLParamType {
8027   ValidKernelParam,
8028   PtrPtrKernelParam,
8029   PtrKernelParam,
8030   InvalidAddrSpacePtrKernelParam,
8031   InvalidKernelParam,
8032   RecordKernelParam
8033 };
8034 
8035 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8036   // Size dependent types are just typedefs to normal integer types
8037   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8038   // integers other than by their names.
8039   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8040 
8041   // Remove typedefs one by one until we reach a typedef
8042   // for a size dependent type.
8043   QualType DesugaredTy = Ty;
8044   do {
8045     ArrayRef<StringRef> Names(SizeTypeNames);
8046     auto Match =
8047         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8048     if (Names.end() != Match)
8049       return true;
8050 
8051     Ty = DesugaredTy;
8052     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8053   } while (DesugaredTy != Ty);
8054 
8055   return false;
8056 }
8057 
8058 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8059   if (PT->isPointerType()) {
8060     QualType PointeeType = PT->getPointeeType();
8061     if (PointeeType->isPointerType())
8062       return PtrPtrKernelParam;
8063     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8064         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8065         PointeeType.getAddressSpace() == LangAS::Default)
8066       return InvalidAddrSpacePtrKernelParam;
8067     return PtrKernelParam;
8068   }
8069 
8070   // OpenCL v1.2 s6.9.k:
8071   // Arguments to kernel functions in a program cannot be declared with the
8072   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8073   // uintptr_t or a struct and/or union that contain fields declared to be one
8074   // of these built-in scalar types.
8075   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8076     return InvalidKernelParam;
8077 
8078   if (PT->isImageType())
8079     return PtrKernelParam;
8080 
8081   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8082     return InvalidKernelParam;
8083 
8084   // OpenCL extension spec v1.2 s9.5:
8085   // This extension adds support for half scalar and vector types as built-in
8086   // types that can be used for arithmetic operations, conversions etc.
8087   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8088     return InvalidKernelParam;
8089 
8090   if (PT->isRecordType())
8091     return RecordKernelParam;
8092 
8093   // Look into an array argument to check if it has a forbidden type.
8094   if (PT->isArrayType()) {
8095     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8096     // Call ourself to check an underlying type of an array. Since the
8097     // getPointeeOrArrayElementType returns an innermost type which is not an
8098     // array, this recusive call only happens once.
8099     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8100   }
8101 
8102   return ValidKernelParam;
8103 }
8104 
8105 static void checkIsValidOpenCLKernelParameter(
8106   Sema &S,
8107   Declarator &D,
8108   ParmVarDecl *Param,
8109   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8110   QualType PT = Param->getType();
8111 
8112   // Cache the valid types we encounter to avoid rechecking structs that are
8113   // used again
8114   if (ValidTypes.count(PT.getTypePtr()))
8115     return;
8116 
8117   switch (getOpenCLKernelParameterType(S, PT)) {
8118   case PtrPtrKernelParam:
8119     // OpenCL v1.2 s6.9.a:
8120     // A kernel function argument cannot be declared as a
8121     // pointer to a pointer type.
8122     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8123     D.setInvalidType();
8124     return;
8125 
8126   case InvalidAddrSpacePtrKernelParam:
8127     // OpenCL v1.0 s6.5:
8128     // __kernel function arguments declared to be a pointer of a type can point
8129     // to one of the following address spaces only : __global, __local or
8130     // __constant.
8131     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8132     D.setInvalidType();
8133     return;
8134 
8135     // OpenCL v1.2 s6.9.k:
8136     // Arguments to kernel functions in a program cannot be declared with the
8137     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8138     // uintptr_t or a struct and/or union that contain fields declared to be
8139     // one of these built-in scalar types.
8140 
8141   case InvalidKernelParam:
8142     // OpenCL v1.2 s6.8 n:
8143     // A kernel function argument cannot be declared
8144     // of event_t type.
8145     // Do not diagnose half type since it is diagnosed as invalid argument
8146     // type for any function elsewhere.
8147     if (!PT->isHalfType()) {
8148       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8149 
8150       // Explain what typedefs are involved.
8151       const TypedefType *Typedef = nullptr;
8152       while ((Typedef = PT->getAs<TypedefType>())) {
8153         SourceLocation Loc = Typedef->getDecl()->getLocation();
8154         // SourceLocation may be invalid for a built-in type.
8155         if (Loc.isValid())
8156           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8157         PT = Typedef->desugar();
8158       }
8159     }
8160 
8161     D.setInvalidType();
8162     return;
8163 
8164   case PtrKernelParam:
8165   case ValidKernelParam:
8166     ValidTypes.insert(PT.getTypePtr());
8167     return;
8168 
8169   case RecordKernelParam:
8170     break;
8171   }
8172 
8173   // Track nested structs we will inspect
8174   SmallVector<const Decl *, 4> VisitStack;
8175 
8176   // Track where we are in the nested structs. Items will migrate from
8177   // VisitStack to HistoryStack as we do the DFS for bad field.
8178   SmallVector<const FieldDecl *, 4> HistoryStack;
8179   HistoryStack.push_back(nullptr);
8180 
8181   // At this point we already handled everything except of a RecordType or
8182   // an ArrayType of a RecordType.
8183   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8184   const RecordType *RecTy =
8185       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8186   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8187 
8188   VisitStack.push_back(RecTy->getDecl());
8189   assert(VisitStack.back() && "First decl null?");
8190 
8191   do {
8192     const Decl *Next = VisitStack.pop_back_val();
8193     if (!Next) {
8194       assert(!HistoryStack.empty());
8195       // Found a marker, we have gone up a level
8196       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8197         ValidTypes.insert(Hist->getType().getTypePtr());
8198 
8199       continue;
8200     }
8201 
8202     // Adds everything except the original parameter declaration (which is not a
8203     // field itself) to the history stack.
8204     const RecordDecl *RD;
8205     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8206       HistoryStack.push_back(Field);
8207 
8208       QualType FieldTy = Field->getType();
8209       // Other field types (known to be valid or invalid) are handled while we
8210       // walk around RecordDecl::fields().
8211       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8212              "Unexpected type.");
8213       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8214 
8215       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8216     } else {
8217       RD = cast<RecordDecl>(Next);
8218     }
8219 
8220     // Add a null marker so we know when we've gone back up a level
8221     VisitStack.push_back(nullptr);
8222 
8223     for (const auto *FD : RD->fields()) {
8224       QualType QT = FD->getType();
8225 
8226       if (ValidTypes.count(QT.getTypePtr()))
8227         continue;
8228 
8229       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8230       if (ParamType == ValidKernelParam)
8231         continue;
8232 
8233       if (ParamType == RecordKernelParam) {
8234         VisitStack.push_back(FD);
8235         continue;
8236       }
8237 
8238       // OpenCL v1.2 s6.9.p:
8239       // Arguments to kernel functions that are declared to be a struct or union
8240       // do not allow OpenCL objects to be passed as elements of the struct or
8241       // union.
8242       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8243           ParamType == InvalidAddrSpacePtrKernelParam) {
8244         S.Diag(Param->getLocation(),
8245                diag::err_record_with_pointers_kernel_param)
8246           << PT->isUnionType()
8247           << PT;
8248       } else {
8249         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8250       }
8251 
8252       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8253           << OrigRecDecl->getDeclName();
8254 
8255       // We have an error, now let's go back up through history and show where
8256       // the offending field came from
8257       for (ArrayRef<const FieldDecl *>::const_iterator
8258                I = HistoryStack.begin() + 1,
8259                E = HistoryStack.end();
8260            I != E; ++I) {
8261         const FieldDecl *OuterField = *I;
8262         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8263           << OuterField->getType();
8264       }
8265 
8266       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8267         << QT->isPointerType()
8268         << QT;
8269       D.setInvalidType();
8270       return;
8271     }
8272   } while (!VisitStack.empty());
8273 }
8274 
8275 /// Find the DeclContext in which a tag is implicitly declared if we see an
8276 /// elaborated type specifier in the specified context, and lookup finds
8277 /// nothing.
8278 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8279   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8280     DC = DC->getParent();
8281   return DC;
8282 }
8283 
8284 /// Find the Scope in which a tag is implicitly declared if we see an
8285 /// elaborated type specifier in the specified context, and lookup finds
8286 /// nothing.
8287 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8288   while (S->isClassScope() ||
8289          (LangOpts.CPlusPlus &&
8290           S->isFunctionPrototypeScope()) ||
8291          ((S->getFlags() & Scope::DeclScope) == 0) ||
8292          (S->getEntity() && S->getEntity()->isTransparentContext()))
8293     S = S->getParent();
8294   return S;
8295 }
8296 
8297 NamedDecl*
8298 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8299                               TypeSourceInfo *TInfo, LookupResult &Previous,
8300                               MultiTemplateParamsArg TemplateParamLists,
8301                               bool &AddToScope) {
8302   QualType R = TInfo->getType();
8303 
8304   assert(R->isFunctionType());
8305 
8306   // TODO: consider using NameInfo for diagnostic.
8307   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8308   DeclarationName Name = NameInfo.getName();
8309   StorageClass SC = getFunctionStorageClass(*this, D);
8310 
8311   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8312     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8313          diag::err_invalid_thread)
8314       << DeclSpec::getSpecifierName(TSCS);
8315 
8316   if (D.isFirstDeclarationOfMember())
8317     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8318                            D.getIdentifierLoc());
8319 
8320   bool isFriend = false;
8321   FunctionTemplateDecl *FunctionTemplate = nullptr;
8322   bool isMemberSpecialization = false;
8323   bool isFunctionTemplateSpecialization = false;
8324 
8325   bool isDependentClassScopeExplicitSpecialization = false;
8326   bool HasExplicitTemplateArgs = false;
8327   TemplateArgumentListInfo TemplateArgs;
8328 
8329   bool isVirtualOkay = false;
8330 
8331   DeclContext *OriginalDC = DC;
8332   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8333 
8334   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8335                                               isVirtualOkay);
8336   if (!NewFD) return nullptr;
8337 
8338   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8339     NewFD->setTopLevelDeclInObjCContainer();
8340 
8341   // Set the lexical context. If this is a function-scope declaration, or has a
8342   // C++ scope specifier, or is the object of a friend declaration, the lexical
8343   // context will be different from the semantic context.
8344   NewFD->setLexicalDeclContext(CurContext);
8345 
8346   if (IsLocalExternDecl)
8347     NewFD->setLocalExternDecl();
8348 
8349   if (getLangOpts().CPlusPlus) {
8350     bool isInline = D.getDeclSpec().isInlineSpecified();
8351     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8352     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8353     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8354     isFriend = D.getDeclSpec().isFriendSpecified();
8355     if (isFriend && !isInline && D.isFunctionDefinition()) {
8356       // C++ [class.friend]p5
8357       //   A function can be defined in a friend declaration of a
8358       //   class . . . . Such a function is implicitly inline.
8359       NewFD->setImplicitlyInline();
8360     }
8361 
8362     // If this is a method defined in an __interface, and is not a constructor
8363     // or an overloaded operator, then set the pure flag (isVirtual will already
8364     // return true).
8365     if (const CXXRecordDecl *Parent =
8366           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8367       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8368         NewFD->setPure(true);
8369 
8370       // C++ [class.union]p2
8371       //   A union can have member functions, but not virtual functions.
8372       if (isVirtual && Parent->isUnion())
8373         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8374     }
8375 
8376     SetNestedNameSpecifier(NewFD, D);
8377     isMemberSpecialization = false;
8378     isFunctionTemplateSpecialization = false;
8379     if (D.isInvalidType())
8380       NewFD->setInvalidDecl();
8381 
8382     // Match up the template parameter lists with the scope specifier, then
8383     // determine whether we have a template or a template specialization.
8384     bool Invalid = false;
8385     if (TemplateParameterList *TemplateParams =
8386             MatchTemplateParametersToScopeSpecifier(
8387                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8388                 D.getCXXScopeSpec(),
8389                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8390                     ? D.getName().TemplateId
8391                     : nullptr,
8392                 TemplateParamLists, isFriend, isMemberSpecialization,
8393                 Invalid)) {
8394       if (TemplateParams->size() > 0) {
8395         // This is a function template
8396 
8397         // Check that we can declare a template here.
8398         if (CheckTemplateDeclScope(S, TemplateParams))
8399           NewFD->setInvalidDecl();
8400 
8401         // A destructor cannot be a template.
8402         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8403           Diag(NewFD->getLocation(), diag::err_destructor_template);
8404           NewFD->setInvalidDecl();
8405         }
8406 
8407         // If we're adding a template to a dependent context, we may need to
8408         // rebuilding some of the types used within the template parameter list,
8409         // now that we know what the current instantiation is.
8410         if (DC->isDependentContext()) {
8411           ContextRAII SavedContext(*this, DC);
8412           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8413             Invalid = true;
8414         }
8415 
8416         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8417                                                         NewFD->getLocation(),
8418                                                         Name, TemplateParams,
8419                                                         NewFD);
8420         FunctionTemplate->setLexicalDeclContext(CurContext);
8421         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8422 
8423         // For source fidelity, store the other template param lists.
8424         if (TemplateParamLists.size() > 1) {
8425           NewFD->setTemplateParameterListsInfo(Context,
8426                                                TemplateParamLists.drop_back(1));
8427         }
8428       } else {
8429         // This is a function template specialization.
8430         isFunctionTemplateSpecialization = true;
8431         // For source fidelity, store all the template param lists.
8432         if (TemplateParamLists.size() > 0)
8433           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8434 
8435         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8436         if (isFriend) {
8437           // We want to remove the "template<>", found here.
8438           SourceRange RemoveRange = TemplateParams->getSourceRange();
8439 
8440           // If we remove the template<> and the name is not a
8441           // template-id, we're actually silently creating a problem:
8442           // the friend declaration will refer to an untemplated decl,
8443           // and clearly the user wants a template specialization.  So
8444           // we need to insert '<>' after the name.
8445           SourceLocation InsertLoc;
8446           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8447             InsertLoc = D.getName().getSourceRange().getEnd();
8448             InsertLoc = getLocForEndOfToken(InsertLoc);
8449           }
8450 
8451           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8452             << Name << RemoveRange
8453             << FixItHint::CreateRemoval(RemoveRange)
8454             << FixItHint::CreateInsertion(InsertLoc, "<>");
8455         }
8456       }
8457     } else {
8458       // All template param lists were matched against the scope specifier:
8459       // this is NOT (an explicit specialization of) a template.
8460       if (TemplateParamLists.size() > 0)
8461         // For source fidelity, store all the template param lists.
8462         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8463     }
8464 
8465     if (Invalid) {
8466       NewFD->setInvalidDecl();
8467       if (FunctionTemplate)
8468         FunctionTemplate->setInvalidDecl();
8469     }
8470 
8471     // C++ [dcl.fct.spec]p5:
8472     //   The virtual specifier shall only be used in declarations of
8473     //   nonstatic class member functions that appear within a
8474     //   member-specification of a class declaration; see 10.3.
8475     //
8476     if (isVirtual && !NewFD->isInvalidDecl()) {
8477       if (!isVirtualOkay) {
8478         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8479              diag::err_virtual_non_function);
8480       } else if (!CurContext->isRecord()) {
8481         // 'virtual' was specified outside of the class.
8482         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8483              diag::err_virtual_out_of_class)
8484           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8485       } else if (NewFD->getDescribedFunctionTemplate()) {
8486         // C++ [temp.mem]p3:
8487         //  A member function template shall not be virtual.
8488         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8489              diag::err_virtual_member_function_template)
8490           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8491       } else {
8492         // Okay: Add virtual to the method.
8493         NewFD->setVirtualAsWritten(true);
8494       }
8495 
8496       if (getLangOpts().CPlusPlus14 &&
8497           NewFD->getReturnType()->isUndeducedType())
8498         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8499     }
8500 
8501     if (getLangOpts().CPlusPlus14 &&
8502         (NewFD->isDependentContext() ||
8503          (isFriend && CurContext->isDependentContext())) &&
8504         NewFD->getReturnType()->isUndeducedType()) {
8505       // If the function template is referenced directly (for instance, as a
8506       // member of the current instantiation), pretend it has a dependent type.
8507       // This is not really justified by the standard, but is the only sane
8508       // thing to do.
8509       // FIXME: For a friend function, we have not marked the function as being
8510       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8511       const FunctionProtoType *FPT =
8512           NewFD->getType()->castAs<FunctionProtoType>();
8513       QualType Result =
8514           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8515       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8516                                              FPT->getExtProtoInfo()));
8517     }
8518 
8519     // C++ [dcl.fct.spec]p3:
8520     //  The inline specifier shall not appear on a block scope function
8521     //  declaration.
8522     if (isInline && !NewFD->isInvalidDecl()) {
8523       if (CurContext->isFunctionOrMethod()) {
8524         // 'inline' is not allowed on block scope function declaration.
8525         Diag(D.getDeclSpec().getInlineSpecLoc(),
8526              diag::err_inline_declaration_block_scope) << Name
8527           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8528       }
8529     }
8530 
8531     // C++ [dcl.fct.spec]p6:
8532     //  The explicit specifier shall be used only in the declaration of a
8533     //  constructor or conversion function within its class definition;
8534     //  see 12.3.1 and 12.3.2.
8535     if (isExplicit && !NewFD->isInvalidDecl() &&
8536         !isa<CXXDeductionGuideDecl>(NewFD)) {
8537       if (!CurContext->isRecord()) {
8538         // 'explicit' was specified outside of the class.
8539         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8540              diag::err_explicit_out_of_class)
8541           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8542       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8543                  !isa<CXXConversionDecl>(NewFD)) {
8544         // 'explicit' was specified on a function that wasn't a constructor
8545         // or conversion function.
8546         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8547              diag::err_explicit_non_ctor_or_conv_function)
8548           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8549       }
8550     }
8551 
8552     if (isConstexpr) {
8553       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8554       // are implicitly inline.
8555       NewFD->setImplicitlyInline();
8556 
8557       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8558       // be either constructors or to return a literal type. Therefore,
8559       // destructors cannot be declared constexpr.
8560       if (isa<CXXDestructorDecl>(NewFD))
8561         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8562     }
8563 
8564     // If __module_private__ was specified, mark the function accordingly.
8565     if (D.getDeclSpec().isModulePrivateSpecified()) {
8566       if (isFunctionTemplateSpecialization) {
8567         SourceLocation ModulePrivateLoc
8568           = D.getDeclSpec().getModulePrivateSpecLoc();
8569         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8570           << 0
8571           << FixItHint::CreateRemoval(ModulePrivateLoc);
8572       } else {
8573         NewFD->setModulePrivate();
8574         if (FunctionTemplate)
8575           FunctionTemplate->setModulePrivate();
8576       }
8577     }
8578 
8579     if (isFriend) {
8580       if (FunctionTemplate) {
8581         FunctionTemplate->setObjectOfFriendDecl();
8582         FunctionTemplate->setAccess(AS_public);
8583       }
8584       NewFD->setObjectOfFriendDecl();
8585       NewFD->setAccess(AS_public);
8586     }
8587 
8588     // If a function is defined as defaulted or deleted, mark it as such now.
8589     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8590     // definition kind to FDK_Definition.
8591     switch (D.getFunctionDefinitionKind()) {
8592       case FDK_Declaration:
8593       case FDK_Definition:
8594         break;
8595 
8596       case FDK_Defaulted:
8597         NewFD->setDefaulted();
8598         break;
8599 
8600       case FDK_Deleted:
8601         NewFD->setDeletedAsWritten();
8602         break;
8603     }
8604 
8605     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8606         D.isFunctionDefinition()) {
8607       // C++ [class.mfct]p2:
8608       //   A member function may be defined (8.4) in its class definition, in
8609       //   which case it is an inline member function (7.1.2)
8610       NewFD->setImplicitlyInline();
8611     }
8612 
8613     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8614         !CurContext->isRecord()) {
8615       // C++ [class.static]p1:
8616       //   A data or function member of a class may be declared static
8617       //   in a class definition, in which case it is a static member of
8618       //   the class.
8619 
8620       // Complain about the 'static' specifier if it's on an out-of-line
8621       // member function definition.
8622       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8623            diag::err_static_out_of_line)
8624         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8625     }
8626 
8627     // C++11 [except.spec]p15:
8628     //   A deallocation function with no exception-specification is treated
8629     //   as if it were specified with noexcept(true).
8630     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8631     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8632          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8633         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8634       NewFD->setType(Context.getFunctionType(
8635           FPT->getReturnType(), FPT->getParamTypes(),
8636           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8637   }
8638 
8639   // Filter out previous declarations that don't match the scope.
8640   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8641                        D.getCXXScopeSpec().isNotEmpty() ||
8642                        isMemberSpecialization ||
8643                        isFunctionTemplateSpecialization);
8644 
8645   // Handle GNU asm-label extension (encoded as an attribute).
8646   if (Expr *E = (Expr*) D.getAsmLabel()) {
8647     // The parser guarantees this is a string.
8648     StringLiteral *SE = cast<StringLiteral>(E);
8649     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8650                                                 SE->getString(), 0));
8651   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8652     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8653       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8654     if (I != ExtnameUndeclaredIdentifiers.end()) {
8655       if (isDeclExternC(NewFD)) {
8656         NewFD->addAttr(I->second);
8657         ExtnameUndeclaredIdentifiers.erase(I);
8658       } else
8659         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8660             << /*Variable*/0 << NewFD;
8661     }
8662   }
8663 
8664   // Copy the parameter declarations from the declarator D to the function
8665   // declaration NewFD, if they are available.  First scavenge them into Params.
8666   SmallVector<ParmVarDecl*, 16> Params;
8667   unsigned FTIIdx;
8668   if (D.isFunctionDeclarator(FTIIdx)) {
8669     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8670 
8671     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8672     // function that takes no arguments, not a function that takes a
8673     // single void argument.
8674     // We let through "const void" here because Sema::GetTypeForDeclarator
8675     // already checks for that case.
8676     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8677       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8678         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8679         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8680         Param->setDeclContext(NewFD);
8681         Params.push_back(Param);
8682 
8683         if (Param->isInvalidDecl())
8684           NewFD->setInvalidDecl();
8685       }
8686     }
8687 
8688     if (!getLangOpts().CPlusPlus) {
8689       // In C, find all the tag declarations from the prototype and move them
8690       // into the function DeclContext. Remove them from the surrounding tag
8691       // injection context of the function, which is typically but not always
8692       // the TU.
8693       DeclContext *PrototypeTagContext =
8694           getTagInjectionContext(NewFD->getLexicalDeclContext());
8695       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8696         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8697 
8698         // We don't want to reparent enumerators. Look at their parent enum
8699         // instead.
8700         if (!TD) {
8701           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8702             TD = cast<EnumDecl>(ECD->getDeclContext());
8703         }
8704         if (!TD)
8705           continue;
8706         DeclContext *TagDC = TD->getLexicalDeclContext();
8707         if (!TagDC->containsDecl(TD))
8708           continue;
8709         TagDC->removeDecl(TD);
8710         TD->setDeclContext(NewFD);
8711         NewFD->addDecl(TD);
8712 
8713         // Preserve the lexical DeclContext if it is not the surrounding tag
8714         // injection context of the FD. In this example, the semantic context of
8715         // E will be f and the lexical context will be S, while both the
8716         // semantic and lexical contexts of S will be f:
8717         //   void f(struct S { enum E { a } f; } s);
8718         if (TagDC != PrototypeTagContext)
8719           TD->setLexicalDeclContext(TagDC);
8720       }
8721     }
8722   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8723     // When we're declaring a function with a typedef, typeof, etc as in the
8724     // following example, we'll need to synthesize (unnamed)
8725     // parameters for use in the declaration.
8726     //
8727     // @code
8728     // typedef void fn(int);
8729     // fn f;
8730     // @endcode
8731 
8732     // Synthesize a parameter for each argument type.
8733     for (const auto &AI : FT->param_types()) {
8734       ParmVarDecl *Param =
8735           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8736       Param->setScopeInfo(0, Params.size());
8737       Params.push_back(Param);
8738     }
8739   } else {
8740     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8741            "Should not need args for typedef of non-prototype fn");
8742   }
8743 
8744   // Finally, we know we have the right number of parameters, install them.
8745   NewFD->setParams(Params);
8746 
8747   if (D.getDeclSpec().isNoreturnSpecified())
8748     NewFD->addAttr(
8749         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8750                                        Context, 0));
8751 
8752   // Functions returning a variably modified type violate C99 6.7.5.2p2
8753   // because all functions have linkage.
8754   if (!NewFD->isInvalidDecl() &&
8755       NewFD->getReturnType()->isVariablyModifiedType()) {
8756     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8757     NewFD->setInvalidDecl();
8758   }
8759 
8760   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8761   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8762       !NewFD->hasAttr<SectionAttr>()) {
8763     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8764                                                  PragmaClangTextSection.SectionName,
8765                                                  PragmaClangTextSection.PragmaLocation));
8766   }
8767 
8768   // Apply an implicit SectionAttr if #pragma code_seg is active.
8769   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8770       !NewFD->hasAttr<SectionAttr>()) {
8771     NewFD->addAttr(
8772         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8773                                     CodeSegStack.CurrentValue->getString(),
8774                                     CodeSegStack.CurrentPragmaLocation));
8775     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8776                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8777                          ASTContext::PSF_Read,
8778                      NewFD))
8779       NewFD->dropAttr<SectionAttr>();
8780   }
8781 
8782   // Apply an implicit CodeSegAttr from class declspec or
8783   // apply an implicit SectionAttr from #pragma code_seg if active.
8784   if (!NewFD->hasAttr<CodeSegAttr>()) {
8785     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8786                                                                  D.isFunctionDefinition())) {
8787       NewFD->addAttr(SAttr);
8788     }
8789   }
8790 
8791   // Handle attributes.
8792   ProcessDeclAttributes(S, NewFD, D);
8793 
8794   if (getLangOpts().OpenCL) {
8795     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8796     // type declaration will generate a compilation error.
8797     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8798     if (AddressSpace != LangAS::Default) {
8799       Diag(NewFD->getLocation(),
8800            diag::err_opencl_return_value_with_address_space);
8801       NewFD->setInvalidDecl();
8802     }
8803   }
8804 
8805   if (!getLangOpts().CPlusPlus) {
8806     // Perform semantic checking on the function declaration.
8807     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8808       CheckMain(NewFD, D.getDeclSpec());
8809 
8810     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8811       CheckMSVCRTEntryPoint(NewFD);
8812 
8813     if (!NewFD->isInvalidDecl())
8814       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8815                                                   isMemberSpecialization));
8816     else if (!Previous.empty())
8817       // Recover gracefully from an invalid redeclaration.
8818       D.setRedeclaration(true);
8819     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8820             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8821            "previous declaration set still overloaded");
8822 
8823     // Diagnose no-prototype function declarations with calling conventions that
8824     // don't support variadic calls. Only do this in C and do it after merging
8825     // possibly prototyped redeclarations.
8826     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8827     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8828       CallingConv CC = FT->getExtInfo().getCC();
8829       if (!supportsVariadicCall(CC)) {
8830         // Windows system headers sometimes accidentally use stdcall without
8831         // (void) parameters, so we relax this to a warning.
8832         int DiagID =
8833             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8834         Diag(NewFD->getLocation(), DiagID)
8835             << FunctionType::getNameForCallConv(CC);
8836       }
8837     }
8838   } else {
8839     // C++11 [replacement.functions]p3:
8840     //  The program's definitions shall not be specified as inline.
8841     //
8842     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8843     //
8844     // Suppress the diagnostic if the function is __attribute__((used)), since
8845     // that forces an external definition to be emitted.
8846     if (D.getDeclSpec().isInlineSpecified() &&
8847         NewFD->isReplaceableGlobalAllocationFunction() &&
8848         !NewFD->hasAttr<UsedAttr>())
8849       Diag(D.getDeclSpec().getInlineSpecLoc(),
8850            diag::ext_operator_new_delete_declared_inline)
8851         << NewFD->getDeclName();
8852 
8853     // If the declarator is a template-id, translate the parser's template
8854     // argument list into our AST format.
8855     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8856       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8857       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8858       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8859       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8860                                          TemplateId->NumArgs);
8861       translateTemplateArguments(TemplateArgsPtr,
8862                                  TemplateArgs);
8863 
8864       HasExplicitTemplateArgs = true;
8865 
8866       if (NewFD->isInvalidDecl()) {
8867         HasExplicitTemplateArgs = false;
8868       } else if (FunctionTemplate) {
8869         // Function template with explicit template arguments.
8870         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8871           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8872 
8873         HasExplicitTemplateArgs = false;
8874       } else {
8875         assert((isFunctionTemplateSpecialization ||
8876                 D.getDeclSpec().isFriendSpecified()) &&
8877                "should have a 'template<>' for this decl");
8878         // "friend void foo<>(int);" is an implicit specialization decl.
8879         isFunctionTemplateSpecialization = true;
8880       }
8881     } else if (isFriend && isFunctionTemplateSpecialization) {
8882       // This combination is only possible in a recovery case;  the user
8883       // wrote something like:
8884       //   template <> friend void foo(int);
8885       // which we're recovering from as if the user had written:
8886       //   friend void foo<>(int);
8887       // Go ahead and fake up a template id.
8888       HasExplicitTemplateArgs = true;
8889       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8890       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8891     }
8892 
8893     // We do not add HD attributes to specializations here because
8894     // they may have different constexpr-ness compared to their
8895     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8896     // may end up with different effective targets. Instead, a
8897     // specialization inherits its target attributes from its template
8898     // in the CheckFunctionTemplateSpecialization() call below.
8899     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8900       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8901 
8902     // If it's a friend (and only if it's a friend), it's possible
8903     // that either the specialized function type or the specialized
8904     // template is dependent, and therefore matching will fail.  In
8905     // this case, don't check the specialization yet.
8906     bool InstantiationDependent = false;
8907     if (isFunctionTemplateSpecialization && isFriend &&
8908         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8909          TemplateSpecializationType::anyDependentTemplateArguments(
8910             TemplateArgs,
8911             InstantiationDependent))) {
8912       assert(HasExplicitTemplateArgs &&
8913              "friend function specialization without template args");
8914       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8915                                                        Previous))
8916         NewFD->setInvalidDecl();
8917     } else if (isFunctionTemplateSpecialization) {
8918       if (CurContext->isDependentContext() && CurContext->isRecord()
8919           && !isFriend) {
8920         isDependentClassScopeExplicitSpecialization = true;
8921       } else if (!NewFD->isInvalidDecl() &&
8922                  CheckFunctionTemplateSpecialization(
8923                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8924                      Previous))
8925         NewFD->setInvalidDecl();
8926 
8927       // C++ [dcl.stc]p1:
8928       //   A storage-class-specifier shall not be specified in an explicit
8929       //   specialization (14.7.3)
8930       FunctionTemplateSpecializationInfo *Info =
8931           NewFD->getTemplateSpecializationInfo();
8932       if (Info && SC != SC_None) {
8933         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8934           Diag(NewFD->getLocation(),
8935                diag::err_explicit_specialization_inconsistent_storage_class)
8936             << SC
8937             << FixItHint::CreateRemoval(
8938                                       D.getDeclSpec().getStorageClassSpecLoc());
8939 
8940         else
8941           Diag(NewFD->getLocation(),
8942                diag::ext_explicit_specialization_storage_class)
8943             << FixItHint::CreateRemoval(
8944                                       D.getDeclSpec().getStorageClassSpecLoc());
8945       }
8946     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8947       if (CheckMemberSpecialization(NewFD, Previous))
8948           NewFD->setInvalidDecl();
8949     }
8950 
8951     // Perform semantic checking on the function declaration.
8952     if (!isDependentClassScopeExplicitSpecialization) {
8953       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8954         CheckMain(NewFD, D.getDeclSpec());
8955 
8956       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8957         CheckMSVCRTEntryPoint(NewFD);
8958 
8959       if (!NewFD->isInvalidDecl())
8960         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8961                                                     isMemberSpecialization));
8962       else if (!Previous.empty())
8963         // Recover gracefully from an invalid redeclaration.
8964         D.setRedeclaration(true);
8965     }
8966 
8967     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8968             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8969            "previous declaration set still overloaded");
8970 
8971     NamedDecl *PrincipalDecl = (FunctionTemplate
8972                                 ? cast<NamedDecl>(FunctionTemplate)
8973                                 : NewFD);
8974 
8975     if (isFriend && NewFD->getPreviousDecl()) {
8976       AccessSpecifier Access = AS_public;
8977       if (!NewFD->isInvalidDecl())
8978         Access = NewFD->getPreviousDecl()->getAccess();
8979 
8980       NewFD->setAccess(Access);
8981       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8982     }
8983 
8984     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8985         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8986       PrincipalDecl->setNonMemberOperator();
8987 
8988     // If we have a function template, check the template parameter
8989     // list. This will check and merge default template arguments.
8990     if (FunctionTemplate) {
8991       FunctionTemplateDecl *PrevTemplate =
8992                                      FunctionTemplate->getPreviousDecl();
8993       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8994                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8995                                     : nullptr,
8996                             D.getDeclSpec().isFriendSpecified()
8997                               ? (D.isFunctionDefinition()
8998                                    ? TPC_FriendFunctionTemplateDefinition
8999                                    : TPC_FriendFunctionTemplate)
9000                               : (D.getCXXScopeSpec().isSet() &&
9001                                  DC && DC->isRecord() &&
9002                                  DC->isDependentContext())
9003                                   ? TPC_ClassTemplateMember
9004                                   : TPC_FunctionTemplate);
9005     }
9006 
9007     if (NewFD->isInvalidDecl()) {
9008       // Ignore all the rest of this.
9009     } else if (!D.isRedeclaration()) {
9010       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9011                                        AddToScope };
9012       // Fake up an access specifier if it's supposed to be a class member.
9013       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9014         NewFD->setAccess(AS_public);
9015 
9016       // Qualified decls generally require a previous declaration.
9017       if (D.getCXXScopeSpec().isSet()) {
9018         // ...with the major exception of templated-scope or
9019         // dependent-scope friend declarations.
9020 
9021         // TODO: we currently also suppress this check in dependent
9022         // contexts because (1) the parameter depth will be off when
9023         // matching friend templates and (2) we might actually be
9024         // selecting a friend based on a dependent factor.  But there
9025         // are situations where these conditions don't apply and we
9026         // can actually do this check immediately.
9027         if (isFriend &&
9028             (TemplateParamLists.size() ||
9029              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9030              CurContext->isDependentContext())) {
9031           // ignore these
9032         } else {
9033           // The user tried to provide an out-of-line definition for a
9034           // function that is a member of a class or namespace, but there
9035           // was no such member function declared (C++ [class.mfct]p2,
9036           // C++ [namespace.memdef]p2). For example:
9037           //
9038           // class X {
9039           //   void f() const;
9040           // };
9041           //
9042           // void X::f() { } // ill-formed
9043           //
9044           // Complain about this problem, and attempt to suggest close
9045           // matches (e.g., those that differ only in cv-qualifiers and
9046           // whether the parameter types are references).
9047 
9048           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9049                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9050             AddToScope = ExtraArgs.AddToScope;
9051             return Result;
9052           }
9053         }
9054 
9055         // Unqualified local friend declarations are required to resolve
9056         // to something.
9057       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9058         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9059                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9060           AddToScope = ExtraArgs.AddToScope;
9061           return Result;
9062         }
9063       }
9064     } else if (!D.isFunctionDefinition() &&
9065                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9066                !isFriend && !isFunctionTemplateSpecialization &&
9067                !isMemberSpecialization) {
9068       // An out-of-line member function declaration must also be a
9069       // definition (C++ [class.mfct]p2).
9070       // Note that this is not the case for explicit specializations of
9071       // function templates or member functions of class templates, per
9072       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9073       // extension for compatibility with old SWIG code which likes to
9074       // generate them.
9075       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9076         << D.getCXXScopeSpec().getRange();
9077     }
9078   }
9079 
9080   ProcessPragmaWeak(S, NewFD);
9081   checkAttributesAfterMerging(*this, *NewFD);
9082 
9083   AddKnownFunctionAttributes(NewFD);
9084 
9085   if (NewFD->hasAttr<OverloadableAttr>() &&
9086       !NewFD->getType()->getAs<FunctionProtoType>()) {
9087     Diag(NewFD->getLocation(),
9088          diag::err_attribute_overloadable_no_prototype)
9089       << NewFD;
9090 
9091     // Turn this into a variadic function with no parameters.
9092     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9093     FunctionProtoType::ExtProtoInfo EPI(
9094         Context.getDefaultCallingConvention(true, false));
9095     EPI.Variadic = true;
9096     EPI.ExtInfo = FT->getExtInfo();
9097 
9098     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9099     NewFD->setType(R);
9100   }
9101 
9102   // If there's a #pragma GCC visibility in scope, and this isn't a class
9103   // member, set the visibility of this function.
9104   if (!DC->isRecord() && NewFD->isExternallyVisible())
9105     AddPushedVisibilityAttribute(NewFD);
9106 
9107   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9108   // marking the function.
9109   AddCFAuditedAttribute(NewFD);
9110 
9111   // If this is a function definition, check if we have to apply optnone due to
9112   // a pragma.
9113   if(D.isFunctionDefinition())
9114     AddRangeBasedOptnone(NewFD);
9115 
9116   // If this is the first declaration of an extern C variable, update
9117   // the map of such variables.
9118   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9119       isIncompleteDeclExternC(*this, NewFD))
9120     RegisterLocallyScopedExternCDecl(NewFD, S);
9121 
9122   // Set this FunctionDecl's range up to the right paren.
9123   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9124 
9125   if (D.isRedeclaration() && !Previous.empty()) {
9126     NamedDecl *Prev = Previous.getRepresentativeDecl();
9127     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9128                                    isMemberSpecialization ||
9129                                        isFunctionTemplateSpecialization,
9130                                    D.isFunctionDefinition());
9131   }
9132 
9133   if (getLangOpts().CUDA) {
9134     IdentifierInfo *II = NewFD->getIdentifier();
9135     if (II &&
9136         II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9137                                     : "cudaConfigureCall") &&
9138         !NewFD->isInvalidDecl() &&
9139         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9140       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9141         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9142       Context.setcudaConfigureCallDecl(NewFD);
9143     }
9144 
9145     // Variadic functions, other than a *declaration* of printf, are not allowed
9146     // in device-side CUDA code, unless someone passed
9147     // -fcuda-allow-variadic-functions.
9148     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9149         (NewFD->hasAttr<CUDADeviceAttr>() ||
9150          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9151         !(II && II->isStr("printf") && NewFD->isExternC() &&
9152           !D.isFunctionDefinition())) {
9153       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9154     }
9155   }
9156 
9157   MarkUnusedFileScopedDecl(NewFD);
9158 
9159   if (getLangOpts().CPlusPlus) {
9160     if (FunctionTemplate) {
9161       if (NewFD->isInvalidDecl())
9162         FunctionTemplate->setInvalidDecl();
9163       return FunctionTemplate;
9164     }
9165 
9166     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9167       CompleteMemberSpecialization(NewFD, Previous);
9168   }
9169 
9170   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9171     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9172     if ((getLangOpts().OpenCLVersion >= 120)
9173         && (SC == SC_Static)) {
9174       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9175       D.setInvalidType();
9176     }
9177 
9178     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9179     if (!NewFD->getReturnType()->isVoidType()) {
9180       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9181       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9182           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9183                                 : FixItHint());
9184       D.setInvalidType();
9185     }
9186 
9187     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9188     for (auto Param : NewFD->parameters())
9189       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9190   }
9191   for (const ParmVarDecl *Param : NewFD->parameters()) {
9192     QualType PT = Param->getType();
9193 
9194     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9195     // types.
9196     if (getLangOpts().OpenCLVersion >= 200) {
9197       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9198         QualType ElemTy = PipeTy->getElementType();
9199           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9200             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9201             D.setInvalidType();
9202           }
9203       }
9204     }
9205   }
9206 
9207   // Here we have an function template explicit specialization at class scope.
9208   // The actual specialization will be postponed to template instatiation
9209   // time via the ClassScopeFunctionSpecializationDecl node.
9210   if (isDependentClassScopeExplicitSpecialization) {
9211     ClassScopeFunctionSpecializationDecl *NewSpec =
9212                          ClassScopeFunctionSpecializationDecl::Create(
9213                                 Context, CurContext, NewFD->getLocation(),
9214                                 cast<CXXMethodDecl>(NewFD),
9215                                 HasExplicitTemplateArgs, TemplateArgs);
9216     CurContext->addDecl(NewSpec);
9217     AddToScope = false;
9218   }
9219 
9220   // Diagnose availability attributes. Availability cannot be used on functions
9221   // that are run during load/unload.
9222   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9223     if (NewFD->hasAttr<ConstructorAttr>()) {
9224       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9225           << 1;
9226       NewFD->dropAttr<AvailabilityAttr>();
9227     }
9228     if (NewFD->hasAttr<DestructorAttr>()) {
9229       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9230           << 2;
9231       NewFD->dropAttr<AvailabilityAttr>();
9232     }
9233   }
9234 
9235   return NewFD;
9236 }
9237 
9238 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9239 /// when __declspec(code_seg) "is applied to a class, all member functions of
9240 /// the class and nested classes -- this includes compiler-generated special
9241 /// member functions -- are put in the specified segment."
9242 /// The actual behavior is a little more complicated. The Microsoft compiler
9243 /// won't check outer classes if there is an active value from #pragma code_seg.
9244 /// The CodeSeg is always applied from the direct parent but only from outer
9245 /// classes when the #pragma code_seg stack is empty. See:
9246 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9247 /// available since MS has removed the page.
9248 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9249   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9250   if (!Method)
9251     return nullptr;
9252   const CXXRecordDecl *Parent = Method->getParent();
9253   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9254     Attr *NewAttr = SAttr->clone(S.getASTContext());
9255     NewAttr->setImplicit(true);
9256     return NewAttr;
9257   }
9258 
9259   // The Microsoft compiler won't check outer classes for the CodeSeg
9260   // when the #pragma code_seg stack is active.
9261   if (S.CodeSegStack.CurrentValue)
9262    return nullptr;
9263 
9264   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9265     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9266       Attr *NewAttr = SAttr->clone(S.getASTContext());
9267       NewAttr->setImplicit(true);
9268       return NewAttr;
9269     }
9270   }
9271   return nullptr;
9272 }
9273 
9274 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9275 /// containing class. Otherwise it will return implicit SectionAttr if the
9276 /// function is a definition and there is an active value on CodeSegStack
9277 /// (from the current #pragma code-seg value).
9278 ///
9279 /// \param FD Function being declared.
9280 /// \param IsDefinition Whether it is a definition or just a declarartion.
9281 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9282 ///          nullptr if no attribute should be added.
9283 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9284                                                        bool IsDefinition) {
9285   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9286     return A;
9287   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9288       CodeSegStack.CurrentValue) {
9289     return SectionAttr::CreateImplicit(getASTContext(),
9290                                        SectionAttr::Declspec_allocate,
9291                                        CodeSegStack.CurrentValue->getString(),
9292                                        CodeSegStack.CurrentPragmaLocation);
9293   }
9294   return nullptr;
9295 }
9296 
9297 /// Determines if we can perform a correct type check for \p D as a
9298 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9299 /// best-effort check.
9300 ///
9301 /// \param NewD The new declaration.
9302 /// \param OldD The old declaration.
9303 /// \param NewT The portion of the type of the new declaration to check.
9304 /// \param OldT The portion of the type of the old declaration to check.
9305 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9306                                           QualType NewT, QualType OldT) {
9307   if (!NewD->getLexicalDeclContext()->isDependentContext())
9308     return true;
9309 
9310   // For dependently-typed local extern declarations and friends, we can't
9311   // perform a correct type check in general until instantiation:
9312   //
9313   //   int f();
9314   //   template<typename T> void g() { T f(); }
9315   //
9316   // (valid if g() is only instantiated with T = int).
9317   if (NewT->isDependentType() &&
9318       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9319     return false;
9320 
9321   // Similarly, if the previous declaration was a dependent local extern
9322   // declaration, we don't really know its type yet.
9323   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9324     return false;
9325 
9326   return true;
9327 }
9328 
9329 /// Checks if the new declaration declared in dependent context must be
9330 /// put in the same redeclaration chain as the specified declaration.
9331 ///
9332 /// \param D Declaration that is checked.
9333 /// \param PrevDecl Previous declaration found with proper lookup method for the
9334 ///                 same declaration name.
9335 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9336 ///          belongs to.
9337 ///
9338 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9339   if (!D->getLexicalDeclContext()->isDependentContext())
9340     return true;
9341 
9342   // Don't chain dependent friend function definitions until instantiation, to
9343   // permit cases like
9344   //
9345   //   void func();
9346   //   template<typename T> class C1 { friend void func() {} };
9347   //   template<typename T> class C2 { friend void func() {} };
9348   //
9349   // ... which is valid if only one of C1 and C2 is ever instantiated.
9350   //
9351   // FIXME: This need only apply to function definitions. For now, we proxy
9352   // this by checking for a file-scope function. We do not want this to apply
9353   // to friend declarations nominating member functions, because that gets in
9354   // the way of access checks.
9355   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9356     return false;
9357 
9358   auto *VD = dyn_cast<ValueDecl>(D);
9359   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9360   return !VD || !PrevVD ||
9361          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9362                                         PrevVD->getType());
9363 }
9364 
9365 namespace MultiVersioning {
9366 enum Type { None, Target, CPUSpecific, CPUDispatch};
9367 } // MultiVersionType
9368 
9369 static MultiVersioning::Type
9370 getMultiVersionType(const FunctionDecl *FD) {
9371   if (FD->hasAttr<TargetAttr>())
9372     return MultiVersioning::Target;
9373   if (FD->hasAttr<CPUDispatchAttr>())
9374     return MultiVersioning::CPUDispatch;
9375   if (FD->hasAttr<CPUSpecificAttr>())
9376     return MultiVersioning::CPUSpecific;
9377   return MultiVersioning::None;
9378 }
9379 /// Check the target attribute of the function for MultiVersion
9380 /// validity.
9381 ///
9382 /// Returns true if there was an error, false otherwise.
9383 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9384   const auto *TA = FD->getAttr<TargetAttr>();
9385   assert(TA && "MultiVersion Candidate requires a target attribute");
9386   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9387   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9388   enum ErrType { Feature = 0, Architecture = 1 };
9389 
9390   if (!ParseInfo.Architecture.empty() &&
9391       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9392     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9393         << Architecture << ParseInfo.Architecture;
9394     return true;
9395   }
9396 
9397   for (const auto &Feat : ParseInfo.Features) {
9398     auto BareFeat = StringRef{Feat}.substr(1);
9399     if (Feat[0] == '-') {
9400       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9401           << Feature << ("no-" + BareFeat).str();
9402       return true;
9403     }
9404 
9405     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9406         !TargetInfo.isValidFeatureName(BareFeat)) {
9407       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9408           << Feature << BareFeat;
9409       return true;
9410     }
9411   }
9412   return false;
9413 }
9414 
9415 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9416                                              const FunctionDecl *NewFD,
9417                                              bool CausesMV,
9418                                              MultiVersioning::Type MVType) {
9419   enum DoesntSupport {
9420     FuncTemplates = 0,
9421     VirtFuncs = 1,
9422     DeducedReturn = 2,
9423     Constructors = 3,
9424     Destructors = 4,
9425     DeletedFuncs = 5,
9426     DefaultedFuncs = 6,
9427     ConstexprFuncs = 7,
9428   };
9429   enum Different {
9430     CallingConv = 0,
9431     ReturnType = 1,
9432     ConstexprSpec = 2,
9433     InlineSpec = 3,
9434     StorageClass = 4,
9435     Linkage = 5
9436   };
9437 
9438   bool IsCPUSpecificCPUDispatchMVType =
9439       MVType == MultiVersioning::CPUDispatch ||
9440       MVType == MultiVersioning::CPUSpecific;
9441 
9442   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9443     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9444     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9445     return true;
9446   }
9447 
9448   if (!NewFD->getType()->getAs<FunctionProtoType>())
9449     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9450 
9451   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9452     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9453     if (OldFD)
9454       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9455     return true;
9456   }
9457 
9458   // For now, disallow all other attributes.  These should be opt-in, but
9459   // an analysis of all of them is a future FIXME.
9460   if (CausesMV && OldFD &&
9461       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9462     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9463         << IsCPUSpecificCPUDispatchMVType;
9464     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9465     return true;
9466   }
9467 
9468   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9469     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9470            << IsCPUSpecificCPUDispatchMVType;
9471 
9472   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9473     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9474            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9475 
9476   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9477     if (NewCXXFD->isVirtual())
9478       return S.Diag(NewCXXFD->getLocation(),
9479                     diag::err_multiversion_doesnt_support)
9480              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9481 
9482     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9483       return S.Diag(NewCXXCtor->getLocation(),
9484                     diag::err_multiversion_doesnt_support)
9485              << IsCPUSpecificCPUDispatchMVType << Constructors;
9486 
9487     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9488       return S.Diag(NewCXXDtor->getLocation(),
9489                     diag::err_multiversion_doesnt_support)
9490              << IsCPUSpecificCPUDispatchMVType << Destructors;
9491   }
9492 
9493   if (NewFD->isDeleted())
9494     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9495            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9496 
9497   if (NewFD->isDefaulted())
9498     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9499            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9500 
9501   if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch ||
9502                                MVType == MultiVersioning::CPUSpecific))
9503     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9504            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9505 
9506   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9507   const auto *NewType = cast<FunctionType>(NewQType);
9508   QualType NewReturnType = NewType->getReturnType();
9509 
9510   if (NewReturnType->isUndeducedType())
9511     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9512            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9513 
9514   // Only allow transition to MultiVersion if it hasn't been used.
9515   if (OldFD && CausesMV && OldFD->isUsed(false))
9516     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9517 
9518   // Ensure the return type is identical.
9519   if (OldFD) {
9520     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9521     const auto *OldType = cast<FunctionType>(OldQType);
9522     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9523     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9524 
9525     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9526       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9527              << CallingConv;
9528 
9529     QualType OldReturnType = OldType->getReturnType();
9530 
9531     if (OldReturnType != NewReturnType)
9532       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9533              << ReturnType;
9534 
9535     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9536       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9537              << ConstexprSpec;
9538 
9539     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9540       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9541              << InlineSpec;
9542 
9543     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9544       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9545              << StorageClass;
9546 
9547     if (OldFD->isExternC() != NewFD->isExternC())
9548       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9549              << Linkage;
9550 
9551     if (S.CheckEquivalentExceptionSpec(
9552             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9553             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9554       return true;
9555   }
9556   return false;
9557 }
9558 
9559 /// Check the validity of a multiversion function declaration that is the
9560 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9561 ///
9562 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9563 ///
9564 /// Returns true if there was an error, false otherwise.
9565 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9566                                            MultiVersioning::Type MVType,
9567                                            const TargetAttr *TA,
9568                                            const CPUDispatchAttr *CPUDisp,
9569                                            const CPUSpecificAttr *CPUSpec) {
9570   assert(MVType != MultiVersioning::None &&
9571          "Function lacks multiversion attribute");
9572 
9573   // Target only causes MV if it is default, otherwise this is a normal
9574   // function.
9575   if (MVType == MultiVersioning::Target && !TA->isDefaultVersion())
9576     return false;
9577 
9578   if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) {
9579     FD->setInvalidDecl();
9580     return true;
9581   }
9582 
9583   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9584     FD->setInvalidDecl();
9585     return true;
9586   }
9587 
9588   FD->setIsMultiVersion();
9589   return false;
9590 }
9591 
9592 static bool CheckTargetCausesMultiVersioning(
9593     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9594     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9595     LookupResult &Previous) {
9596   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9597   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9598   // Sort order doesn't matter, it just needs to be consistent.
9599   llvm::sort(NewParsed.Features);
9600 
9601   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9602   // to change, this is a simple redeclaration.
9603   if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9604     return false;
9605 
9606   // Otherwise, this decl causes MultiVersioning.
9607   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9608     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9609     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9610     NewFD->setInvalidDecl();
9611     return true;
9612   }
9613 
9614   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9615                                        MultiVersioning::Target)) {
9616     NewFD->setInvalidDecl();
9617     return true;
9618   }
9619 
9620   if (CheckMultiVersionValue(S, NewFD)) {
9621     NewFD->setInvalidDecl();
9622     return true;
9623   }
9624 
9625   if (CheckMultiVersionValue(S, OldFD)) {
9626     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9627     NewFD->setInvalidDecl();
9628     return true;
9629   }
9630 
9631   TargetAttr::ParsedTargetAttr OldParsed =
9632       OldTA->parse(std::less<std::string>());
9633 
9634   if (OldParsed == NewParsed) {
9635     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9636     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9637     NewFD->setInvalidDecl();
9638     return true;
9639   }
9640 
9641   for (const auto *FD : OldFD->redecls()) {
9642     const auto *CurTA = FD->getAttr<TargetAttr>();
9643     if (!CurTA || CurTA->isInherited()) {
9644       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9645           << 0;
9646       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9647       NewFD->setInvalidDecl();
9648       return true;
9649     }
9650   }
9651 
9652   OldFD->setIsMultiVersion();
9653   NewFD->setIsMultiVersion();
9654   Redeclaration = false;
9655   MergeTypeWithPrevious = false;
9656   OldDecl = nullptr;
9657   Previous.clear();
9658   return false;
9659 }
9660 
9661 /// Check the validity of a new function declaration being added to an existing
9662 /// multiversioned declaration collection.
9663 static bool CheckMultiVersionAdditionalDecl(
9664     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9665     MultiVersioning::Type NewMVType, const TargetAttr *NewTA,
9666     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9667     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9668     LookupResult &Previous) {
9669 
9670   MultiVersioning::Type OldMVType = getMultiVersionType(OldFD);
9671   // Disallow mixing of multiversioning types.
9672   if ((OldMVType == MultiVersioning::Target &&
9673        NewMVType != MultiVersioning::Target) ||
9674       (NewMVType == MultiVersioning::Target &&
9675        OldMVType != MultiVersioning::Target)) {
9676     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9677     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9678     NewFD->setInvalidDecl();
9679     return true;
9680   }
9681 
9682   TargetAttr::ParsedTargetAttr NewParsed;
9683   if (NewTA) {
9684     NewParsed = NewTA->parse();
9685     llvm::sort(NewParsed.Features);
9686   }
9687 
9688   bool UseMemberUsingDeclRules =
9689       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9690 
9691   // Next, check ALL non-overloads to see if this is a redeclaration of a
9692   // previous member of the MultiVersion set.
9693   for (NamedDecl *ND : Previous) {
9694     FunctionDecl *CurFD = ND->getAsFunction();
9695     if (!CurFD)
9696       continue;
9697     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9698       continue;
9699 
9700     if (NewMVType == MultiVersioning::Target) {
9701       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9702       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9703         NewFD->setIsMultiVersion();
9704         Redeclaration = true;
9705         OldDecl = ND;
9706         return false;
9707       }
9708 
9709       TargetAttr::ParsedTargetAttr CurParsed =
9710           CurTA->parse(std::less<std::string>());
9711       if (CurParsed == NewParsed) {
9712         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9713         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9714         NewFD->setInvalidDecl();
9715         return true;
9716       }
9717     } else {
9718       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9719       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9720       // Handle CPUDispatch/CPUSpecific versions.
9721       // Only 1 CPUDispatch function is allowed, this will make it go through
9722       // the redeclaration errors.
9723       if (NewMVType == MultiVersioning::CPUDispatch &&
9724           CurFD->hasAttr<CPUDispatchAttr>()) {
9725         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9726             std::equal(
9727                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9728                 NewCPUDisp->cpus_begin(),
9729                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9730                   return Cur->getName() == New->getName();
9731                 })) {
9732           NewFD->setIsMultiVersion();
9733           Redeclaration = true;
9734           OldDecl = ND;
9735           return false;
9736         }
9737 
9738         // If the declarations don't match, this is an error condition.
9739         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9740         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9741         NewFD->setInvalidDecl();
9742         return true;
9743       }
9744       if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) {
9745 
9746         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9747             std::equal(
9748                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9749                 NewCPUSpec->cpus_begin(),
9750                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9751                   return Cur->getName() == New->getName();
9752                 })) {
9753           NewFD->setIsMultiVersion();
9754           Redeclaration = true;
9755           OldDecl = ND;
9756           return false;
9757         }
9758 
9759         // Only 1 version of CPUSpecific is allowed for each CPU.
9760         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9761           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9762             if (CurII == NewII) {
9763               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9764                   << NewII;
9765               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9766               NewFD->setInvalidDecl();
9767               return true;
9768             }
9769           }
9770         }
9771       }
9772       // If the two decls aren't the same MVType, there is no possible error
9773       // condition.
9774     }
9775   }
9776 
9777   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9778   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9779   // handled in the attribute adding step.
9780   if (NewMVType == MultiVersioning::Target &&
9781       CheckMultiVersionValue(S, NewFD)) {
9782     NewFD->setInvalidDecl();
9783     return true;
9784   }
9785 
9786   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) {
9787     NewFD->setInvalidDecl();
9788     return true;
9789   }
9790 
9791   NewFD->setIsMultiVersion();
9792   Redeclaration = false;
9793   MergeTypeWithPrevious = false;
9794   OldDecl = nullptr;
9795   Previous.clear();
9796   return false;
9797 }
9798 
9799 
9800 /// Check the validity of a mulitversion function declaration.
9801 /// Also sets the multiversion'ness' of the function itself.
9802 ///
9803 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9804 ///
9805 /// Returns true if there was an error, false otherwise.
9806 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9807                                       bool &Redeclaration, NamedDecl *&OldDecl,
9808                                       bool &MergeTypeWithPrevious,
9809                                       LookupResult &Previous) {
9810   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9811   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9812   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9813 
9814   // Mixing Multiversioning types is prohibited.
9815   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9816       (NewCPUDisp && NewCPUSpec)) {
9817     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9818     NewFD->setInvalidDecl();
9819     return true;
9820   }
9821 
9822   MultiVersioning::Type MVType = getMultiVersionType(NewFD);
9823 
9824   // Main isn't allowed to become a multiversion function, however it IS
9825   // permitted to have 'main' be marked with the 'target' optimization hint.
9826   if (NewFD->isMain()) {
9827     if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) ||
9828         MVType == MultiVersioning::CPUDispatch ||
9829         MVType == MultiVersioning::CPUSpecific) {
9830       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9831       NewFD->setInvalidDecl();
9832       return true;
9833     }
9834     return false;
9835   }
9836 
9837   if (!OldDecl || !OldDecl->getAsFunction() ||
9838       OldDecl->getDeclContext()->getRedeclContext() !=
9839           NewFD->getDeclContext()->getRedeclContext()) {
9840     // If there's no previous declaration, AND this isn't attempting to cause
9841     // multiversioning, this isn't an error condition.
9842     if (MVType == MultiVersioning::None)
9843       return false;
9844     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9845                                           NewCPUSpec);
9846   }
9847 
9848   FunctionDecl *OldFD = OldDecl->getAsFunction();
9849 
9850   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None)
9851     return false;
9852 
9853   if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) {
9854     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9855         << (getMultiVersionType(OldFD) != MultiVersioning::Target);
9856     NewFD->setInvalidDecl();
9857     return true;
9858   }
9859 
9860   // Handle the target potentially causes multiversioning case.
9861   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target)
9862     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9863                                             Redeclaration, OldDecl,
9864                                             MergeTypeWithPrevious, Previous);
9865   // Previous declarations lack CPUDispatch/CPUSpecific.
9866   if (!OldFD->isMultiVersion()) {
9867     S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl)
9868         << 1;
9869     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9870     NewFD->setInvalidDecl();
9871     return true;
9872   }
9873 
9874   // At this point, we have a multiversion function decl (in OldFD) AND an
9875   // appropriate attribute in the current function decl.  Resolve that these are
9876   // still compatible with previous declarations.
9877   return CheckMultiVersionAdditionalDecl(
9878       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9879       OldDecl, MergeTypeWithPrevious, Previous);
9880 }
9881 
9882 /// Perform semantic checking of a new function declaration.
9883 ///
9884 /// Performs semantic analysis of the new function declaration
9885 /// NewFD. This routine performs all semantic checking that does not
9886 /// require the actual declarator involved in the declaration, and is
9887 /// used both for the declaration of functions as they are parsed
9888 /// (called via ActOnDeclarator) and for the declaration of functions
9889 /// that have been instantiated via C++ template instantiation (called
9890 /// via InstantiateDecl).
9891 ///
9892 /// \param IsMemberSpecialization whether this new function declaration is
9893 /// a member specialization (that replaces any definition provided by the
9894 /// previous declaration).
9895 ///
9896 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9897 ///
9898 /// \returns true if the function declaration is a redeclaration.
9899 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9900                                     LookupResult &Previous,
9901                                     bool IsMemberSpecialization) {
9902   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9903          "Variably modified return types are not handled here");
9904 
9905   // Determine whether the type of this function should be merged with
9906   // a previous visible declaration. This never happens for functions in C++,
9907   // and always happens in C if the previous declaration was visible.
9908   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9909                                !Previous.isShadowed();
9910 
9911   bool Redeclaration = false;
9912   NamedDecl *OldDecl = nullptr;
9913   bool MayNeedOverloadableChecks = false;
9914 
9915   // Merge or overload the declaration with an existing declaration of
9916   // the same name, if appropriate.
9917   if (!Previous.empty()) {
9918     // Determine whether NewFD is an overload of PrevDecl or
9919     // a declaration that requires merging. If it's an overload,
9920     // there's no more work to do here; we'll just add the new
9921     // function to the scope.
9922     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9923       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9924       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9925         Redeclaration = true;
9926         OldDecl = Candidate;
9927       }
9928     } else {
9929       MayNeedOverloadableChecks = true;
9930       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9931                             /*NewIsUsingDecl*/ false)) {
9932       case Ovl_Match:
9933         Redeclaration = true;
9934         break;
9935 
9936       case Ovl_NonFunction:
9937         Redeclaration = true;
9938         break;
9939 
9940       case Ovl_Overload:
9941         Redeclaration = false;
9942         break;
9943       }
9944     }
9945   }
9946 
9947   // Check for a previous extern "C" declaration with this name.
9948   if (!Redeclaration &&
9949       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9950     if (!Previous.empty()) {
9951       // This is an extern "C" declaration with the same name as a previous
9952       // declaration, and thus redeclares that entity...
9953       Redeclaration = true;
9954       OldDecl = Previous.getFoundDecl();
9955       MergeTypeWithPrevious = false;
9956 
9957       // ... except in the presence of __attribute__((overloadable)).
9958       if (OldDecl->hasAttr<OverloadableAttr>() ||
9959           NewFD->hasAttr<OverloadableAttr>()) {
9960         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9961           MayNeedOverloadableChecks = true;
9962           Redeclaration = false;
9963           OldDecl = nullptr;
9964         }
9965       }
9966     }
9967   }
9968 
9969   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9970                                 MergeTypeWithPrevious, Previous))
9971     return Redeclaration;
9972 
9973   // C++11 [dcl.constexpr]p8:
9974   //   A constexpr specifier for a non-static member function that is not
9975   //   a constructor declares that member function to be const.
9976   //
9977   // This needs to be delayed until we know whether this is an out-of-line
9978   // definition of a static member function.
9979   //
9980   // This rule is not present in C++1y, so we produce a backwards
9981   // compatibility warning whenever it happens in C++11.
9982   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9983   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9984       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9985       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9986     CXXMethodDecl *OldMD = nullptr;
9987     if (OldDecl)
9988       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9989     if (!OldMD || !OldMD->isStatic()) {
9990       const FunctionProtoType *FPT =
9991         MD->getType()->castAs<FunctionProtoType>();
9992       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9993       EPI.TypeQuals |= Qualifiers::Const;
9994       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9995                                           FPT->getParamTypes(), EPI));
9996 
9997       // Warn that we did this, if we're not performing template instantiation.
9998       // In that case, we'll have warned already when the template was defined.
9999       if (!inTemplateInstantiation()) {
10000         SourceLocation AddConstLoc;
10001         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10002                 .IgnoreParens().getAs<FunctionTypeLoc>())
10003           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10004 
10005         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10006           << FixItHint::CreateInsertion(AddConstLoc, " const");
10007       }
10008     }
10009   }
10010 
10011   if (Redeclaration) {
10012     // NewFD and OldDecl represent declarations that need to be
10013     // merged.
10014     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10015       NewFD->setInvalidDecl();
10016       return Redeclaration;
10017     }
10018 
10019     Previous.clear();
10020     Previous.addDecl(OldDecl);
10021 
10022     if (FunctionTemplateDecl *OldTemplateDecl =
10023             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10024       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10025       FunctionTemplateDecl *NewTemplateDecl
10026         = NewFD->getDescribedFunctionTemplate();
10027       assert(NewTemplateDecl && "Template/non-template mismatch");
10028 
10029       // The call to MergeFunctionDecl above may have created some state in
10030       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10031       // can add it as a redeclaration.
10032       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10033 
10034       NewFD->setPreviousDeclaration(OldFD);
10035       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10036       if (NewFD->isCXXClassMember()) {
10037         NewFD->setAccess(OldTemplateDecl->getAccess());
10038         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10039       }
10040 
10041       // If this is an explicit specialization of a member that is a function
10042       // template, mark it as a member specialization.
10043       if (IsMemberSpecialization &&
10044           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10045         NewTemplateDecl->setMemberSpecialization();
10046         assert(OldTemplateDecl->isMemberSpecialization());
10047         // Explicit specializations of a member template do not inherit deleted
10048         // status from the parent member template that they are specializing.
10049         if (OldFD->isDeleted()) {
10050           // FIXME: This assert will not hold in the presence of modules.
10051           assert(OldFD->getCanonicalDecl() == OldFD);
10052           // FIXME: We need an update record for this AST mutation.
10053           OldFD->setDeletedAsWritten(false);
10054         }
10055       }
10056 
10057     } else {
10058       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10059         auto *OldFD = cast<FunctionDecl>(OldDecl);
10060         // This needs to happen first so that 'inline' propagates.
10061         NewFD->setPreviousDeclaration(OldFD);
10062         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10063         if (NewFD->isCXXClassMember())
10064           NewFD->setAccess(OldFD->getAccess());
10065       }
10066     }
10067   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10068              !NewFD->getAttr<OverloadableAttr>()) {
10069     assert((Previous.empty() ||
10070             llvm::any_of(Previous,
10071                          [](const NamedDecl *ND) {
10072                            return ND->hasAttr<OverloadableAttr>();
10073                          })) &&
10074            "Non-redecls shouldn't happen without overloadable present");
10075 
10076     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10077       const auto *FD = dyn_cast<FunctionDecl>(ND);
10078       return FD && !FD->hasAttr<OverloadableAttr>();
10079     });
10080 
10081     if (OtherUnmarkedIter != Previous.end()) {
10082       Diag(NewFD->getLocation(),
10083            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10084       Diag((*OtherUnmarkedIter)->getLocation(),
10085            diag::note_attribute_overloadable_prev_overload)
10086           << false;
10087 
10088       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10089     }
10090   }
10091 
10092   // Semantic checking for this function declaration (in isolation).
10093 
10094   if (getLangOpts().CPlusPlus) {
10095     // C++-specific checks.
10096     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10097       CheckConstructor(Constructor);
10098     } else if (CXXDestructorDecl *Destructor =
10099                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10100       CXXRecordDecl *Record = Destructor->getParent();
10101       QualType ClassType = Context.getTypeDeclType(Record);
10102 
10103       // FIXME: Shouldn't we be able to perform this check even when the class
10104       // type is dependent? Both gcc and edg can handle that.
10105       if (!ClassType->isDependentType()) {
10106         DeclarationName Name
10107           = Context.DeclarationNames.getCXXDestructorName(
10108                                         Context.getCanonicalType(ClassType));
10109         if (NewFD->getDeclName() != Name) {
10110           Diag(NewFD->getLocation(), diag::err_destructor_name);
10111           NewFD->setInvalidDecl();
10112           return Redeclaration;
10113         }
10114       }
10115     } else if (CXXConversionDecl *Conversion
10116                = dyn_cast<CXXConversionDecl>(NewFD)) {
10117       ActOnConversionDeclarator(Conversion);
10118     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10119       if (auto *TD = Guide->getDescribedFunctionTemplate())
10120         CheckDeductionGuideTemplate(TD);
10121 
10122       // A deduction guide is not on the list of entities that can be
10123       // explicitly specialized.
10124       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10125         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10126             << /*explicit specialization*/ 1;
10127     }
10128 
10129     // Find any virtual functions that this function overrides.
10130     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10131       if (!Method->isFunctionTemplateSpecialization() &&
10132           !Method->getDescribedFunctionTemplate() &&
10133           Method->isCanonicalDecl()) {
10134         if (AddOverriddenMethods(Method->getParent(), Method)) {
10135           // If the function was marked as "static", we have a problem.
10136           if (NewFD->getStorageClass() == SC_Static) {
10137             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10138           }
10139         }
10140       }
10141 
10142       if (Method->isStatic())
10143         checkThisInStaticMemberFunctionType(Method);
10144     }
10145 
10146     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10147     if (NewFD->isOverloadedOperator() &&
10148         CheckOverloadedOperatorDeclaration(NewFD)) {
10149       NewFD->setInvalidDecl();
10150       return Redeclaration;
10151     }
10152 
10153     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10154     if (NewFD->getLiteralIdentifier() &&
10155         CheckLiteralOperatorDeclaration(NewFD)) {
10156       NewFD->setInvalidDecl();
10157       return Redeclaration;
10158     }
10159 
10160     // In C++, check default arguments now that we have merged decls. Unless
10161     // the lexical context is the class, because in this case this is done
10162     // during delayed parsing anyway.
10163     if (!CurContext->isRecord())
10164       CheckCXXDefaultArguments(NewFD);
10165 
10166     // If this function declares a builtin function, check the type of this
10167     // declaration against the expected type for the builtin.
10168     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10169       ASTContext::GetBuiltinTypeError Error;
10170       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10171       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10172       // If the type of the builtin differs only in its exception
10173       // specification, that's OK.
10174       // FIXME: If the types do differ in this way, it would be better to
10175       // retain the 'noexcept' form of the type.
10176       if (!T.isNull() &&
10177           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10178                                                             NewFD->getType()))
10179         // The type of this function differs from the type of the builtin,
10180         // so forget about the builtin entirely.
10181         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10182     }
10183 
10184     // If this function is declared as being extern "C", then check to see if
10185     // the function returns a UDT (class, struct, or union type) that is not C
10186     // compatible, and if it does, warn the user.
10187     // But, issue any diagnostic on the first declaration only.
10188     if (Previous.empty() && NewFD->isExternC()) {
10189       QualType R = NewFD->getReturnType();
10190       if (R->isIncompleteType() && !R->isVoidType())
10191         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10192             << NewFD << R;
10193       else if (!R.isPODType(Context) && !R->isVoidType() &&
10194                !R->isObjCObjectPointerType())
10195         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10196     }
10197 
10198     // C++1z [dcl.fct]p6:
10199     //   [...] whether the function has a non-throwing exception-specification
10200     //   [is] part of the function type
10201     //
10202     // This results in an ABI break between C++14 and C++17 for functions whose
10203     // declared type includes an exception-specification in a parameter or
10204     // return type. (Exception specifications on the function itself are OK in
10205     // most cases, and exception specifications are not permitted in most other
10206     // contexts where they could make it into a mangling.)
10207     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10208       auto HasNoexcept = [&](QualType T) -> bool {
10209         // Strip off declarator chunks that could be between us and a function
10210         // type. We don't need to look far, exception specifications are very
10211         // restricted prior to C++17.
10212         if (auto *RT = T->getAs<ReferenceType>())
10213           T = RT->getPointeeType();
10214         else if (T->isAnyPointerType())
10215           T = T->getPointeeType();
10216         else if (auto *MPT = T->getAs<MemberPointerType>())
10217           T = MPT->getPointeeType();
10218         if (auto *FPT = T->getAs<FunctionProtoType>())
10219           if (FPT->isNothrow())
10220             return true;
10221         return false;
10222       };
10223 
10224       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10225       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10226       for (QualType T : FPT->param_types())
10227         AnyNoexcept |= HasNoexcept(T);
10228       if (AnyNoexcept)
10229         Diag(NewFD->getLocation(),
10230              diag::warn_cxx17_compat_exception_spec_in_signature)
10231             << NewFD;
10232     }
10233 
10234     if (!Redeclaration && LangOpts.CUDA)
10235       checkCUDATargetOverload(NewFD, Previous);
10236   }
10237   return Redeclaration;
10238 }
10239 
10240 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10241   // C++11 [basic.start.main]p3:
10242   //   A program that [...] declares main to be inline, static or
10243   //   constexpr is ill-formed.
10244   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10245   //   appear in a declaration of main.
10246   // static main is not an error under C99, but we should warn about it.
10247   // We accept _Noreturn main as an extension.
10248   if (FD->getStorageClass() == SC_Static)
10249     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10250          ? diag::err_static_main : diag::warn_static_main)
10251       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10252   if (FD->isInlineSpecified())
10253     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10254       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10255   if (DS.isNoreturnSpecified()) {
10256     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10257     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10258     Diag(NoreturnLoc, diag::ext_noreturn_main);
10259     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10260       << FixItHint::CreateRemoval(NoreturnRange);
10261   }
10262   if (FD->isConstexpr()) {
10263     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10264       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10265     FD->setConstexpr(false);
10266   }
10267 
10268   if (getLangOpts().OpenCL) {
10269     Diag(FD->getLocation(), diag::err_opencl_no_main)
10270         << FD->hasAttr<OpenCLKernelAttr>();
10271     FD->setInvalidDecl();
10272     return;
10273   }
10274 
10275   QualType T = FD->getType();
10276   assert(T->isFunctionType() && "function decl is not of function type");
10277   const FunctionType* FT = T->castAs<FunctionType>();
10278 
10279   // Set default calling convention for main()
10280   if (FT->getCallConv() != CC_C) {
10281     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10282     FD->setType(QualType(FT, 0));
10283     T = Context.getCanonicalType(FD->getType());
10284   }
10285 
10286   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10287     // In C with GNU extensions we allow main() to have non-integer return
10288     // type, but we should warn about the extension, and we disable the
10289     // implicit-return-zero rule.
10290 
10291     // GCC in C mode accepts qualified 'int'.
10292     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10293       FD->setHasImplicitReturnZero(true);
10294     else {
10295       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10296       SourceRange RTRange = FD->getReturnTypeSourceRange();
10297       if (RTRange.isValid())
10298         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10299             << FixItHint::CreateReplacement(RTRange, "int");
10300     }
10301   } else {
10302     // In C and C++, main magically returns 0 if you fall off the end;
10303     // set the flag which tells us that.
10304     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10305 
10306     // All the standards say that main() should return 'int'.
10307     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10308       FD->setHasImplicitReturnZero(true);
10309     else {
10310       // Otherwise, this is just a flat-out error.
10311       SourceRange RTRange = FD->getReturnTypeSourceRange();
10312       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10313           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10314                                 : FixItHint());
10315       FD->setInvalidDecl(true);
10316     }
10317   }
10318 
10319   // Treat protoless main() as nullary.
10320   if (isa<FunctionNoProtoType>(FT)) return;
10321 
10322   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10323   unsigned nparams = FTP->getNumParams();
10324   assert(FD->getNumParams() == nparams);
10325 
10326   bool HasExtraParameters = (nparams > 3);
10327 
10328   if (FTP->isVariadic()) {
10329     Diag(FD->getLocation(), diag::ext_variadic_main);
10330     // FIXME: if we had information about the location of the ellipsis, we
10331     // could add a FixIt hint to remove it as a parameter.
10332   }
10333 
10334   // Darwin passes an undocumented fourth argument of type char**.  If
10335   // other platforms start sprouting these, the logic below will start
10336   // getting shifty.
10337   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10338     HasExtraParameters = false;
10339 
10340   if (HasExtraParameters) {
10341     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10342     FD->setInvalidDecl(true);
10343     nparams = 3;
10344   }
10345 
10346   // FIXME: a lot of the following diagnostics would be improved
10347   // if we had some location information about types.
10348 
10349   QualType CharPP =
10350     Context.getPointerType(Context.getPointerType(Context.CharTy));
10351   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10352 
10353   for (unsigned i = 0; i < nparams; ++i) {
10354     QualType AT = FTP->getParamType(i);
10355 
10356     bool mismatch = true;
10357 
10358     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10359       mismatch = false;
10360     else if (Expected[i] == CharPP) {
10361       // As an extension, the following forms are okay:
10362       //   char const **
10363       //   char const * const *
10364       //   char * const *
10365 
10366       QualifierCollector qs;
10367       const PointerType* PT;
10368       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10369           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10370           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10371                               Context.CharTy)) {
10372         qs.removeConst();
10373         mismatch = !qs.empty();
10374       }
10375     }
10376 
10377     if (mismatch) {
10378       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10379       // TODO: suggest replacing given type with expected type
10380       FD->setInvalidDecl(true);
10381     }
10382   }
10383 
10384   if (nparams == 1 && !FD->isInvalidDecl()) {
10385     Diag(FD->getLocation(), diag::warn_main_one_arg);
10386   }
10387 
10388   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10389     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10390     FD->setInvalidDecl();
10391   }
10392 }
10393 
10394 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10395   QualType T = FD->getType();
10396   assert(T->isFunctionType() && "function decl is not of function type");
10397   const FunctionType *FT = T->castAs<FunctionType>();
10398 
10399   // Set an implicit return of 'zero' if the function can return some integral,
10400   // enumeration, pointer or nullptr type.
10401   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10402       FT->getReturnType()->isAnyPointerType() ||
10403       FT->getReturnType()->isNullPtrType())
10404     // DllMain is exempt because a return value of zero means it failed.
10405     if (FD->getName() != "DllMain")
10406       FD->setHasImplicitReturnZero(true);
10407 
10408   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10409     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10410     FD->setInvalidDecl();
10411   }
10412 }
10413 
10414 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10415   // FIXME: Need strict checking.  In C89, we need to check for
10416   // any assignment, increment, decrement, function-calls, or
10417   // commas outside of a sizeof.  In C99, it's the same list,
10418   // except that the aforementioned are allowed in unevaluated
10419   // expressions.  Everything else falls under the
10420   // "may accept other forms of constant expressions" exception.
10421   // (We never end up here for C++, so the constant expression
10422   // rules there don't matter.)
10423   const Expr *Culprit;
10424   if (Init->isConstantInitializer(Context, false, &Culprit))
10425     return false;
10426   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10427     << Culprit->getSourceRange();
10428   return true;
10429 }
10430 
10431 namespace {
10432   // Visits an initialization expression to see if OrigDecl is evaluated in
10433   // its own initialization and throws a warning if it does.
10434   class SelfReferenceChecker
10435       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10436     Sema &S;
10437     Decl *OrigDecl;
10438     bool isRecordType;
10439     bool isPODType;
10440     bool isReferenceType;
10441 
10442     bool isInitList;
10443     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10444 
10445   public:
10446     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10447 
10448     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10449                                                     S(S), OrigDecl(OrigDecl) {
10450       isPODType = false;
10451       isRecordType = false;
10452       isReferenceType = false;
10453       isInitList = false;
10454       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10455         isPODType = VD->getType().isPODType(S.Context);
10456         isRecordType = VD->getType()->isRecordType();
10457         isReferenceType = VD->getType()->isReferenceType();
10458       }
10459     }
10460 
10461     // For most expressions, just call the visitor.  For initializer lists,
10462     // track the index of the field being initialized since fields are
10463     // initialized in order allowing use of previously initialized fields.
10464     void CheckExpr(Expr *E) {
10465       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10466       if (!InitList) {
10467         Visit(E);
10468         return;
10469       }
10470 
10471       // Track and increment the index here.
10472       isInitList = true;
10473       InitFieldIndex.push_back(0);
10474       for (auto Child : InitList->children()) {
10475         CheckExpr(cast<Expr>(Child));
10476         ++InitFieldIndex.back();
10477       }
10478       InitFieldIndex.pop_back();
10479     }
10480 
10481     // Returns true if MemberExpr is checked and no further checking is needed.
10482     // Returns false if additional checking is required.
10483     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10484       llvm::SmallVector<FieldDecl*, 4> Fields;
10485       Expr *Base = E;
10486       bool ReferenceField = false;
10487 
10488       // Get the field memebers used.
10489       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10490         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10491         if (!FD)
10492           return false;
10493         Fields.push_back(FD);
10494         if (FD->getType()->isReferenceType())
10495           ReferenceField = true;
10496         Base = ME->getBase()->IgnoreParenImpCasts();
10497       }
10498 
10499       // Keep checking only if the base Decl is the same.
10500       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10501       if (!DRE || DRE->getDecl() != OrigDecl)
10502         return false;
10503 
10504       // A reference field can be bound to an unininitialized field.
10505       if (CheckReference && !ReferenceField)
10506         return true;
10507 
10508       // Convert FieldDecls to their index number.
10509       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10510       for (const FieldDecl *I : llvm::reverse(Fields))
10511         UsedFieldIndex.push_back(I->getFieldIndex());
10512 
10513       // See if a warning is needed by checking the first difference in index
10514       // numbers.  If field being used has index less than the field being
10515       // initialized, then the use is safe.
10516       for (auto UsedIter = UsedFieldIndex.begin(),
10517                 UsedEnd = UsedFieldIndex.end(),
10518                 OrigIter = InitFieldIndex.begin(),
10519                 OrigEnd = InitFieldIndex.end();
10520            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10521         if (*UsedIter < *OrigIter)
10522           return true;
10523         if (*UsedIter > *OrigIter)
10524           break;
10525       }
10526 
10527       // TODO: Add a different warning which will print the field names.
10528       HandleDeclRefExpr(DRE);
10529       return true;
10530     }
10531 
10532     // For most expressions, the cast is directly above the DeclRefExpr.
10533     // For conditional operators, the cast can be outside the conditional
10534     // operator if both expressions are DeclRefExpr's.
10535     void HandleValue(Expr *E) {
10536       E = E->IgnoreParens();
10537       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10538         HandleDeclRefExpr(DRE);
10539         return;
10540       }
10541 
10542       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10543         Visit(CO->getCond());
10544         HandleValue(CO->getTrueExpr());
10545         HandleValue(CO->getFalseExpr());
10546         return;
10547       }
10548 
10549       if (BinaryConditionalOperator *BCO =
10550               dyn_cast<BinaryConditionalOperator>(E)) {
10551         Visit(BCO->getCond());
10552         HandleValue(BCO->getFalseExpr());
10553         return;
10554       }
10555 
10556       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10557         HandleValue(OVE->getSourceExpr());
10558         return;
10559       }
10560 
10561       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10562         if (BO->getOpcode() == BO_Comma) {
10563           Visit(BO->getLHS());
10564           HandleValue(BO->getRHS());
10565           return;
10566         }
10567       }
10568 
10569       if (isa<MemberExpr>(E)) {
10570         if (isInitList) {
10571           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10572                                       false /*CheckReference*/))
10573             return;
10574         }
10575 
10576         Expr *Base = E->IgnoreParenImpCasts();
10577         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10578           // Check for static member variables and don't warn on them.
10579           if (!isa<FieldDecl>(ME->getMemberDecl()))
10580             return;
10581           Base = ME->getBase()->IgnoreParenImpCasts();
10582         }
10583         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10584           HandleDeclRefExpr(DRE);
10585         return;
10586       }
10587 
10588       Visit(E);
10589     }
10590 
10591     // Reference types not handled in HandleValue are handled here since all
10592     // uses of references are bad, not just r-value uses.
10593     void VisitDeclRefExpr(DeclRefExpr *E) {
10594       if (isReferenceType)
10595         HandleDeclRefExpr(E);
10596     }
10597 
10598     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10599       if (E->getCastKind() == CK_LValueToRValue) {
10600         HandleValue(E->getSubExpr());
10601         return;
10602       }
10603 
10604       Inherited::VisitImplicitCastExpr(E);
10605     }
10606 
10607     void VisitMemberExpr(MemberExpr *E) {
10608       if (isInitList) {
10609         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10610           return;
10611       }
10612 
10613       // Don't warn on arrays since they can be treated as pointers.
10614       if (E->getType()->canDecayToPointerType()) return;
10615 
10616       // Warn when a non-static method call is followed by non-static member
10617       // field accesses, which is followed by a DeclRefExpr.
10618       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10619       bool Warn = (MD && !MD->isStatic());
10620       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10621       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10622         if (!isa<FieldDecl>(ME->getMemberDecl()))
10623           Warn = false;
10624         Base = ME->getBase()->IgnoreParenImpCasts();
10625       }
10626 
10627       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10628         if (Warn)
10629           HandleDeclRefExpr(DRE);
10630         return;
10631       }
10632 
10633       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10634       // Visit that expression.
10635       Visit(Base);
10636     }
10637 
10638     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10639       Expr *Callee = E->getCallee();
10640 
10641       if (isa<UnresolvedLookupExpr>(Callee))
10642         return Inherited::VisitCXXOperatorCallExpr(E);
10643 
10644       Visit(Callee);
10645       for (auto Arg: E->arguments())
10646         HandleValue(Arg->IgnoreParenImpCasts());
10647     }
10648 
10649     void VisitUnaryOperator(UnaryOperator *E) {
10650       // For POD record types, addresses of its own members are well-defined.
10651       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10652           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10653         if (!isPODType)
10654           HandleValue(E->getSubExpr());
10655         return;
10656       }
10657 
10658       if (E->isIncrementDecrementOp()) {
10659         HandleValue(E->getSubExpr());
10660         return;
10661       }
10662 
10663       Inherited::VisitUnaryOperator(E);
10664     }
10665 
10666     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10667 
10668     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10669       if (E->getConstructor()->isCopyConstructor()) {
10670         Expr *ArgExpr = E->getArg(0);
10671         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10672           if (ILE->getNumInits() == 1)
10673             ArgExpr = ILE->getInit(0);
10674         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10675           if (ICE->getCastKind() == CK_NoOp)
10676             ArgExpr = ICE->getSubExpr();
10677         HandleValue(ArgExpr);
10678         return;
10679       }
10680       Inherited::VisitCXXConstructExpr(E);
10681     }
10682 
10683     void VisitCallExpr(CallExpr *E) {
10684       // Treat std::move as a use.
10685       if (E->isCallToStdMove()) {
10686         HandleValue(E->getArg(0));
10687         return;
10688       }
10689 
10690       Inherited::VisitCallExpr(E);
10691     }
10692 
10693     void VisitBinaryOperator(BinaryOperator *E) {
10694       if (E->isCompoundAssignmentOp()) {
10695         HandleValue(E->getLHS());
10696         Visit(E->getRHS());
10697         return;
10698       }
10699 
10700       Inherited::VisitBinaryOperator(E);
10701     }
10702 
10703     // A custom visitor for BinaryConditionalOperator is needed because the
10704     // regular visitor would check the condition and true expression separately
10705     // but both point to the same place giving duplicate diagnostics.
10706     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10707       Visit(E->getCond());
10708       Visit(E->getFalseExpr());
10709     }
10710 
10711     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10712       Decl* ReferenceDecl = DRE->getDecl();
10713       if (OrigDecl != ReferenceDecl) return;
10714       unsigned diag;
10715       if (isReferenceType) {
10716         diag = diag::warn_uninit_self_reference_in_reference_init;
10717       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10718         diag = diag::warn_static_self_reference_in_init;
10719       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10720                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10721                  DRE->getDecl()->getType()->isRecordType()) {
10722         diag = diag::warn_uninit_self_reference_in_init;
10723       } else {
10724         // Local variables will be handled by the CFG analysis.
10725         return;
10726       }
10727 
10728       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10729                             S.PDiag(diag)
10730                                 << DRE->getDecl() << OrigDecl->getLocation()
10731                                 << DRE->getSourceRange());
10732     }
10733   };
10734 
10735   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10736   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10737                                  bool DirectInit) {
10738     // Parameters arguments are occassionially constructed with itself,
10739     // for instance, in recursive functions.  Skip them.
10740     if (isa<ParmVarDecl>(OrigDecl))
10741       return;
10742 
10743     E = E->IgnoreParens();
10744 
10745     // Skip checking T a = a where T is not a record or reference type.
10746     // Doing so is a way to silence uninitialized warnings.
10747     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10748       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10749         if (ICE->getCastKind() == CK_LValueToRValue)
10750           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10751             if (DRE->getDecl() == OrigDecl)
10752               return;
10753 
10754     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10755   }
10756 } // end anonymous namespace
10757 
10758 namespace {
10759   // Simple wrapper to add the name of a variable or (if no variable is
10760   // available) a DeclarationName into a diagnostic.
10761   struct VarDeclOrName {
10762     VarDecl *VDecl;
10763     DeclarationName Name;
10764 
10765     friend const Sema::SemaDiagnosticBuilder &
10766     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10767       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10768     }
10769   };
10770 } // end anonymous namespace
10771 
10772 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10773                                             DeclarationName Name, QualType Type,
10774                                             TypeSourceInfo *TSI,
10775                                             SourceRange Range, bool DirectInit,
10776                                             Expr *Init) {
10777   bool IsInitCapture = !VDecl;
10778   assert((!VDecl || !VDecl->isInitCapture()) &&
10779          "init captures are expected to be deduced prior to initialization");
10780 
10781   VarDeclOrName VN{VDecl, Name};
10782 
10783   DeducedType *Deduced = Type->getContainedDeducedType();
10784   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10785 
10786   // C++11 [dcl.spec.auto]p3
10787   if (!Init) {
10788     assert(VDecl && "no init for init capture deduction?");
10789 
10790     // Except for class argument deduction, and then for an initializing
10791     // declaration only, i.e. no static at class scope or extern.
10792     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10793         VDecl->hasExternalStorage() ||
10794         VDecl->isStaticDataMember()) {
10795       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10796         << VDecl->getDeclName() << Type;
10797       return QualType();
10798     }
10799   }
10800 
10801   ArrayRef<Expr*> DeduceInits;
10802   if (Init)
10803     DeduceInits = Init;
10804 
10805   if (DirectInit) {
10806     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10807       DeduceInits = PL->exprs();
10808   }
10809 
10810   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10811     assert(VDecl && "non-auto type for init capture deduction?");
10812     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10813     InitializationKind Kind = InitializationKind::CreateForInit(
10814         VDecl->getLocation(), DirectInit, Init);
10815     // FIXME: Initialization should not be taking a mutable list of inits.
10816     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10817     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10818                                                        InitsCopy);
10819   }
10820 
10821   if (DirectInit) {
10822     if (auto *IL = dyn_cast<InitListExpr>(Init))
10823       DeduceInits = IL->inits();
10824   }
10825 
10826   // Deduction only works if we have exactly one source expression.
10827   if (DeduceInits.empty()) {
10828     // It isn't possible to write this directly, but it is possible to
10829     // end up in this situation with "auto x(some_pack...);"
10830     Diag(Init->getBeginLoc(), IsInitCapture
10831                                   ? diag::err_init_capture_no_expression
10832                                   : diag::err_auto_var_init_no_expression)
10833         << VN << Type << Range;
10834     return QualType();
10835   }
10836 
10837   if (DeduceInits.size() > 1) {
10838     Diag(DeduceInits[1]->getBeginLoc(),
10839          IsInitCapture ? diag::err_init_capture_multiple_expressions
10840                        : diag::err_auto_var_init_multiple_expressions)
10841         << VN << Type << Range;
10842     return QualType();
10843   }
10844 
10845   Expr *DeduceInit = DeduceInits[0];
10846   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10847     Diag(Init->getBeginLoc(), IsInitCapture
10848                                   ? diag::err_init_capture_paren_braces
10849                                   : diag::err_auto_var_init_paren_braces)
10850         << isa<InitListExpr>(Init) << VN << Type << Range;
10851     return QualType();
10852   }
10853 
10854   // Expressions default to 'id' when we're in a debugger.
10855   bool DefaultedAnyToId = false;
10856   if (getLangOpts().DebuggerCastResultToId &&
10857       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10858     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10859     if (Result.isInvalid()) {
10860       return QualType();
10861     }
10862     Init = Result.get();
10863     DefaultedAnyToId = true;
10864   }
10865 
10866   // C++ [dcl.decomp]p1:
10867   //   If the assignment-expression [...] has array type A and no ref-qualifier
10868   //   is present, e has type cv A
10869   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10870       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10871       DeduceInit->getType()->isConstantArrayType())
10872     return Context.getQualifiedType(DeduceInit->getType(),
10873                                     Type.getQualifiers());
10874 
10875   QualType DeducedType;
10876   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10877     if (!IsInitCapture)
10878       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10879     else if (isa<InitListExpr>(Init))
10880       Diag(Range.getBegin(),
10881            diag::err_init_capture_deduction_failure_from_init_list)
10882           << VN
10883           << (DeduceInit->getType().isNull() ? TSI->getType()
10884                                              : DeduceInit->getType())
10885           << DeduceInit->getSourceRange();
10886     else
10887       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10888           << VN << TSI->getType()
10889           << (DeduceInit->getType().isNull() ? TSI->getType()
10890                                              : DeduceInit->getType())
10891           << DeduceInit->getSourceRange();
10892   }
10893 
10894   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10895   // 'id' instead of a specific object type prevents most of our usual
10896   // checks.
10897   // We only want to warn outside of template instantiations, though:
10898   // inside a template, the 'id' could have come from a parameter.
10899   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10900       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10901     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10902     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10903   }
10904 
10905   return DeducedType;
10906 }
10907 
10908 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10909                                          Expr *Init) {
10910   QualType DeducedType = deduceVarTypeFromInitializer(
10911       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10912       VDecl->getSourceRange(), DirectInit, Init);
10913   if (DeducedType.isNull()) {
10914     VDecl->setInvalidDecl();
10915     return true;
10916   }
10917 
10918   VDecl->setType(DeducedType);
10919   assert(VDecl->isLinkageValid());
10920 
10921   // In ARC, infer lifetime.
10922   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10923     VDecl->setInvalidDecl();
10924 
10925   // If this is a redeclaration, check that the type we just deduced matches
10926   // the previously declared type.
10927   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10928     // We never need to merge the type, because we cannot form an incomplete
10929     // array of auto, nor deduce such a type.
10930     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10931   }
10932 
10933   // Check the deduced type is valid for a variable declaration.
10934   CheckVariableDeclarationType(VDecl);
10935   return VDecl->isInvalidDecl();
10936 }
10937 
10938 /// AddInitializerToDecl - Adds the initializer Init to the
10939 /// declaration dcl. If DirectInit is true, this is C++ direct
10940 /// initialization rather than copy initialization.
10941 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10942   // If there is no declaration, there was an error parsing it.  Just ignore
10943   // the initializer.
10944   if (!RealDecl || RealDecl->isInvalidDecl()) {
10945     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10946     return;
10947   }
10948 
10949   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10950     // Pure-specifiers are handled in ActOnPureSpecifier.
10951     Diag(Method->getLocation(), diag::err_member_function_initialization)
10952       << Method->getDeclName() << Init->getSourceRange();
10953     Method->setInvalidDecl();
10954     return;
10955   }
10956 
10957   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10958   if (!VDecl) {
10959     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10960     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10961     RealDecl->setInvalidDecl();
10962     return;
10963   }
10964 
10965   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10966   if (VDecl->getType()->isUndeducedType()) {
10967     // Attempt typo correction early so that the type of the init expression can
10968     // be deduced based on the chosen correction if the original init contains a
10969     // TypoExpr.
10970     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10971     if (!Res.isUsable()) {
10972       RealDecl->setInvalidDecl();
10973       return;
10974     }
10975     Init = Res.get();
10976 
10977     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10978       return;
10979   }
10980 
10981   // dllimport cannot be used on variable definitions.
10982   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10983     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10984     VDecl->setInvalidDecl();
10985     return;
10986   }
10987 
10988   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10989     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10990     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10991     VDecl->setInvalidDecl();
10992     return;
10993   }
10994 
10995   if (!VDecl->getType()->isDependentType()) {
10996     // A definition must end up with a complete type, which means it must be
10997     // complete with the restriction that an array type might be completed by
10998     // the initializer; note that later code assumes this restriction.
10999     QualType BaseDeclType = VDecl->getType();
11000     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11001       BaseDeclType = Array->getElementType();
11002     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11003                             diag::err_typecheck_decl_incomplete_type)) {
11004       RealDecl->setInvalidDecl();
11005       return;
11006     }
11007 
11008     // The variable can not have an abstract class type.
11009     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11010                                diag::err_abstract_type_in_decl,
11011                                AbstractVariableType))
11012       VDecl->setInvalidDecl();
11013   }
11014 
11015   // If adding the initializer will turn this declaration into a definition,
11016   // and we already have a definition for this variable, diagnose or otherwise
11017   // handle the situation.
11018   VarDecl *Def;
11019   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11020       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11021       !VDecl->isThisDeclarationADemotedDefinition() &&
11022       checkVarDeclRedefinition(Def, VDecl))
11023     return;
11024 
11025   if (getLangOpts().CPlusPlus) {
11026     // C++ [class.static.data]p4
11027     //   If a static data member is of const integral or const
11028     //   enumeration type, its declaration in the class definition can
11029     //   specify a constant-initializer which shall be an integral
11030     //   constant expression (5.19). In that case, the member can appear
11031     //   in integral constant expressions. The member shall still be
11032     //   defined in a namespace scope if it is used in the program and the
11033     //   namespace scope definition shall not contain an initializer.
11034     //
11035     // We already performed a redefinition check above, but for static
11036     // data members we also need to check whether there was an in-class
11037     // declaration with an initializer.
11038     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11039       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11040           << VDecl->getDeclName();
11041       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11042            diag::note_previous_initializer)
11043           << 0;
11044       return;
11045     }
11046 
11047     if (VDecl->hasLocalStorage())
11048       setFunctionHasBranchProtectedScope();
11049 
11050     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11051       VDecl->setInvalidDecl();
11052       return;
11053     }
11054   }
11055 
11056   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11057   // a kernel function cannot be initialized."
11058   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11059     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11060     VDecl->setInvalidDecl();
11061     return;
11062   }
11063 
11064   // Get the decls type and save a reference for later, since
11065   // CheckInitializerTypes may change it.
11066   QualType DclT = VDecl->getType(), SavT = DclT;
11067 
11068   // Expressions default to 'id' when we're in a debugger
11069   // and we are assigning it to a variable of Objective-C pointer type.
11070   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11071       Init->getType() == Context.UnknownAnyTy) {
11072     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11073     if (Result.isInvalid()) {
11074       VDecl->setInvalidDecl();
11075       return;
11076     }
11077     Init = Result.get();
11078   }
11079 
11080   // Perform the initialization.
11081   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11082   if (!VDecl->isInvalidDecl()) {
11083     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11084     InitializationKind Kind = InitializationKind::CreateForInit(
11085         VDecl->getLocation(), DirectInit, Init);
11086 
11087     MultiExprArg Args = Init;
11088     if (CXXDirectInit)
11089       Args = MultiExprArg(CXXDirectInit->getExprs(),
11090                           CXXDirectInit->getNumExprs());
11091 
11092     // Try to correct any TypoExprs in the initialization arguments.
11093     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11094       ExprResult Res = CorrectDelayedTyposInExpr(
11095           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11096             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11097             return Init.Failed() ? ExprError() : E;
11098           });
11099       if (Res.isInvalid()) {
11100         VDecl->setInvalidDecl();
11101       } else if (Res.get() != Args[Idx]) {
11102         Args[Idx] = Res.get();
11103       }
11104     }
11105     if (VDecl->isInvalidDecl())
11106       return;
11107 
11108     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11109                                    /*TopLevelOfInitList=*/false,
11110                                    /*TreatUnavailableAsInvalid=*/false);
11111     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11112     if (Result.isInvalid()) {
11113       VDecl->setInvalidDecl();
11114       return;
11115     }
11116 
11117     Init = Result.getAs<Expr>();
11118   }
11119 
11120   // Check for self-references within variable initializers.
11121   // Variables declared within a function/method body (except for references)
11122   // are handled by a dataflow analysis.
11123   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11124       VDecl->getType()->isReferenceType()) {
11125     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11126   }
11127 
11128   // If the type changed, it means we had an incomplete type that was
11129   // completed by the initializer. For example:
11130   //   int ary[] = { 1, 3, 5 };
11131   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11132   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11133     VDecl->setType(DclT);
11134 
11135   if (!VDecl->isInvalidDecl()) {
11136     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11137 
11138     if (VDecl->hasAttr<BlocksAttr>())
11139       checkRetainCycles(VDecl, Init);
11140 
11141     // It is safe to assign a weak reference into a strong variable.
11142     // Although this code can still have problems:
11143     //   id x = self.weakProp;
11144     //   id y = self.weakProp;
11145     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11146     // paths through the function. This should be revisited if
11147     // -Wrepeated-use-of-weak is made flow-sensitive.
11148     if (FunctionScopeInfo *FSI = getCurFunction())
11149       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11150            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11151           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11152                            Init->getBeginLoc()))
11153         FSI->markSafeWeakUse(Init);
11154   }
11155 
11156   // The initialization is usually a full-expression.
11157   //
11158   // FIXME: If this is a braced initialization of an aggregate, it is not
11159   // an expression, and each individual field initializer is a separate
11160   // full-expression. For instance, in:
11161   //
11162   //   struct Temp { ~Temp(); };
11163   //   struct S { S(Temp); };
11164   //   struct T { S a, b; } t = { Temp(), Temp() }
11165   //
11166   // we should destroy the first Temp before constructing the second.
11167   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
11168                                           false,
11169                                           VDecl->isConstexpr());
11170   if (Result.isInvalid()) {
11171     VDecl->setInvalidDecl();
11172     return;
11173   }
11174   Init = Result.get();
11175 
11176   // Attach the initializer to the decl.
11177   VDecl->setInit(Init);
11178 
11179   if (VDecl->isLocalVarDecl()) {
11180     // Don't check the initializer if the declaration is malformed.
11181     if (VDecl->isInvalidDecl()) {
11182       // do nothing
11183 
11184     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11185     // This is true even in OpenCL C++.
11186     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11187       CheckForConstantInitializer(Init, DclT);
11188 
11189     // Otherwise, C++ does not restrict the initializer.
11190     } else if (getLangOpts().CPlusPlus) {
11191       // do nothing
11192 
11193     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11194     // static storage duration shall be constant expressions or string literals.
11195     } else if (VDecl->getStorageClass() == SC_Static) {
11196       CheckForConstantInitializer(Init, DclT);
11197 
11198     // C89 is stricter than C99 for aggregate initializers.
11199     // C89 6.5.7p3: All the expressions [...] in an initializer list
11200     // for an object that has aggregate or union type shall be
11201     // constant expressions.
11202     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11203                isa<InitListExpr>(Init)) {
11204       const Expr *Culprit;
11205       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11206         Diag(Culprit->getExprLoc(),
11207              diag::ext_aggregate_init_not_constant)
11208           << Culprit->getSourceRange();
11209       }
11210     }
11211   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11212              VDecl->getLexicalDeclContext()->isRecord()) {
11213     // This is an in-class initialization for a static data member, e.g.,
11214     //
11215     // struct S {
11216     //   static const int value = 17;
11217     // };
11218 
11219     // C++ [class.mem]p4:
11220     //   A member-declarator can contain a constant-initializer only
11221     //   if it declares a static member (9.4) of const integral or
11222     //   const enumeration type, see 9.4.2.
11223     //
11224     // C++11 [class.static.data]p3:
11225     //   If a non-volatile non-inline const static data member is of integral
11226     //   or enumeration type, its declaration in the class definition can
11227     //   specify a brace-or-equal-initializer in which every initializer-clause
11228     //   that is an assignment-expression is a constant expression. A static
11229     //   data member of literal type can be declared in the class definition
11230     //   with the constexpr specifier; if so, its declaration shall specify a
11231     //   brace-or-equal-initializer in which every initializer-clause that is
11232     //   an assignment-expression is a constant expression.
11233 
11234     // Do nothing on dependent types.
11235     if (DclT->isDependentType()) {
11236 
11237     // Allow any 'static constexpr' members, whether or not they are of literal
11238     // type. We separately check that every constexpr variable is of literal
11239     // type.
11240     } else if (VDecl->isConstexpr()) {
11241 
11242     // Require constness.
11243     } else if (!DclT.isConstQualified()) {
11244       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11245         << Init->getSourceRange();
11246       VDecl->setInvalidDecl();
11247 
11248     // We allow integer constant expressions in all cases.
11249     } else if (DclT->isIntegralOrEnumerationType()) {
11250       // Check whether the expression is a constant expression.
11251       SourceLocation Loc;
11252       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11253         // In C++11, a non-constexpr const static data member with an
11254         // in-class initializer cannot be volatile.
11255         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11256       else if (Init->isValueDependent())
11257         ; // Nothing to check.
11258       else if (Init->isIntegerConstantExpr(Context, &Loc))
11259         ; // Ok, it's an ICE!
11260       else if (Init->getType()->isScopedEnumeralType() &&
11261                Init->isCXX11ConstantExpr(Context))
11262         ; // Ok, it is a scoped-enum constant expression.
11263       else if (Init->isEvaluatable(Context)) {
11264         // If we can constant fold the initializer through heroics, accept it,
11265         // but report this as a use of an extension for -pedantic.
11266         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11267           << Init->getSourceRange();
11268       } else {
11269         // Otherwise, this is some crazy unknown case.  Report the issue at the
11270         // location provided by the isIntegerConstantExpr failed check.
11271         Diag(Loc, diag::err_in_class_initializer_non_constant)
11272           << Init->getSourceRange();
11273         VDecl->setInvalidDecl();
11274       }
11275 
11276     // We allow foldable floating-point constants as an extension.
11277     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11278       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11279       // it anyway and provide a fixit to add the 'constexpr'.
11280       if (getLangOpts().CPlusPlus11) {
11281         Diag(VDecl->getLocation(),
11282              diag::ext_in_class_initializer_float_type_cxx11)
11283             << DclT << Init->getSourceRange();
11284         Diag(VDecl->getBeginLoc(),
11285              diag::note_in_class_initializer_float_type_cxx11)
11286             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11287       } else {
11288         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11289           << DclT << Init->getSourceRange();
11290 
11291         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11292           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11293             << Init->getSourceRange();
11294           VDecl->setInvalidDecl();
11295         }
11296       }
11297 
11298     // Suggest adding 'constexpr' in C++11 for literal types.
11299     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11300       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11301           << DclT << Init->getSourceRange()
11302           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11303       VDecl->setConstexpr(true);
11304 
11305     } else {
11306       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11307         << DclT << Init->getSourceRange();
11308       VDecl->setInvalidDecl();
11309     }
11310   } else if (VDecl->isFileVarDecl()) {
11311     // In C, extern is typically used to avoid tentative definitions when
11312     // declaring variables in headers, but adding an intializer makes it a
11313     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11314     // In C++, extern is often used to give implictly static const variables
11315     // external linkage, so don't warn in that case. If selectany is present,
11316     // this might be header code intended for C and C++ inclusion, so apply the
11317     // C++ rules.
11318     if (VDecl->getStorageClass() == SC_Extern &&
11319         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11320          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11321         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11322         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11323       Diag(VDecl->getLocation(), diag::warn_extern_init);
11324 
11325     // C99 6.7.8p4. All file scoped initializers need to be constant.
11326     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11327       CheckForConstantInitializer(Init, DclT);
11328   }
11329 
11330   // We will represent direct-initialization similarly to copy-initialization:
11331   //    int x(1);  -as-> int x = 1;
11332   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11333   //
11334   // Clients that want to distinguish between the two forms, can check for
11335   // direct initializer using VarDecl::getInitStyle().
11336   // A major benefit is that clients that don't particularly care about which
11337   // exactly form was it (like the CodeGen) can handle both cases without
11338   // special case code.
11339 
11340   // C++ 8.5p11:
11341   // The form of initialization (using parentheses or '=') is generally
11342   // insignificant, but does matter when the entity being initialized has a
11343   // class type.
11344   if (CXXDirectInit) {
11345     assert(DirectInit && "Call-style initializer must be direct init.");
11346     VDecl->setInitStyle(VarDecl::CallInit);
11347   } else if (DirectInit) {
11348     // This must be list-initialization. No other way is direct-initialization.
11349     VDecl->setInitStyle(VarDecl::ListInit);
11350   }
11351 
11352   CheckCompleteVariableDeclaration(VDecl);
11353 }
11354 
11355 /// ActOnInitializerError - Given that there was an error parsing an
11356 /// initializer for the given declaration, try to return to some form
11357 /// of sanity.
11358 void Sema::ActOnInitializerError(Decl *D) {
11359   // Our main concern here is re-establishing invariants like "a
11360   // variable's type is either dependent or complete".
11361   if (!D || D->isInvalidDecl()) return;
11362 
11363   VarDecl *VD = dyn_cast<VarDecl>(D);
11364   if (!VD) return;
11365 
11366   // Bindings are not usable if we can't make sense of the initializer.
11367   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11368     for (auto *BD : DD->bindings())
11369       BD->setInvalidDecl();
11370 
11371   // Auto types are meaningless if we can't make sense of the initializer.
11372   if (ParsingInitForAutoVars.count(D)) {
11373     D->setInvalidDecl();
11374     return;
11375   }
11376 
11377   QualType Ty = VD->getType();
11378   if (Ty->isDependentType()) return;
11379 
11380   // Require a complete type.
11381   if (RequireCompleteType(VD->getLocation(),
11382                           Context.getBaseElementType(Ty),
11383                           diag::err_typecheck_decl_incomplete_type)) {
11384     VD->setInvalidDecl();
11385     return;
11386   }
11387 
11388   // Require a non-abstract type.
11389   if (RequireNonAbstractType(VD->getLocation(), Ty,
11390                              diag::err_abstract_type_in_decl,
11391                              AbstractVariableType)) {
11392     VD->setInvalidDecl();
11393     return;
11394   }
11395 
11396   // Don't bother complaining about constructors or destructors,
11397   // though.
11398 }
11399 
11400 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11401   // If there is no declaration, there was an error parsing it. Just ignore it.
11402   if (!RealDecl)
11403     return;
11404 
11405   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11406     QualType Type = Var->getType();
11407 
11408     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11409     if (isa<DecompositionDecl>(RealDecl)) {
11410       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11411       Var->setInvalidDecl();
11412       return;
11413     }
11414 
11415     if (Type->isUndeducedType() &&
11416         DeduceVariableDeclarationType(Var, false, nullptr))
11417       return;
11418 
11419     // C++11 [class.static.data]p3: A static data member can be declared with
11420     // the constexpr specifier; if so, its declaration shall specify
11421     // a brace-or-equal-initializer.
11422     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11423     // the definition of a variable [...] or the declaration of a static data
11424     // member.
11425     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11426         !Var->isThisDeclarationADemotedDefinition()) {
11427       if (Var->isStaticDataMember()) {
11428         // C++1z removes the relevant rule; the in-class declaration is always
11429         // a definition there.
11430         if (!getLangOpts().CPlusPlus17) {
11431           Diag(Var->getLocation(),
11432                diag::err_constexpr_static_mem_var_requires_init)
11433             << Var->getDeclName();
11434           Var->setInvalidDecl();
11435           return;
11436         }
11437       } else {
11438         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11439         Var->setInvalidDecl();
11440         return;
11441       }
11442     }
11443 
11444     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11445     // be initialized.
11446     if (!Var->isInvalidDecl() &&
11447         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11448         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11449       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11450       Var->setInvalidDecl();
11451       return;
11452     }
11453 
11454     switch (Var->isThisDeclarationADefinition()) {
11455     case VarDecl::Definition:
11456       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11457         break;
11458 
11459       // We have an out-of-line definition of a static data member
11460       // that has an in-class initializer, so we type-check this like
11461       // a declaration.
11462       //
11463       LLVM_FALLTHROUGH;
11464 
11465     case VarDecl::DeclarationOnly:
11466       // It's only a declaration.
11467 
11468       // Block scope. C99 6.7p7: If an identifier for an object is
11469       // declared with no linkage (C99 6.2.2p6), the type for the
11470       // object shall be complete.
11471       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11472           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11473           RequireCompleteType(Var->getLocation(), Type,
11474                               diag::err_typecheck_decl_incomplete_type))
11475         Var->setInvalidDecl();
11476 
11477       // Make sure that the type is not abstract.
11478       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11479           RequireNonAbstractType(Var->getLocation(), Type,
11480                                  diag::err_abstract_type_in_decl,
11481                                  AbstractVariableType))
11482         Var->setInvalidDecl();
11483       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11484           Var->getStorageClass() == SC_PrivateExtern) {
11485         Diag(Var->getLocation(), diag::warn_private_extern);
11486         Diag(Var->getLocation(), diag::note_private_extern);
11487       }
11488 
11489       return;
11490 
11491     case VarDecl::TentativeDefinition:
11492       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11493       // object that has file scope without an initializer, and without a
11494       // storage-class specifier or with the storage-class specifier "static",
11495       // constitutes a tentative definition. Note: A tentative definition with
11496       // external linkage is valid (C99 6.2.2p5).
11497       if (!Var->isInvalidDecl()) {
11498         if (const IncompleteArrayType *ArrayT
11499                                     = Context.getAsIncompleteArrayType(Type)) {
11500           if (RequireCompleteType(Var->getLocation(),
11501                                   ArrayT->getElementType(),
11502                                   diag::err_illegal_decl_array_incomplete_type))
11503             Var->setInvalidDecl();
11504         } else if (Var->getStorageClass() == SC_Static) {
11505           // C99 6.9.2p3: If the declaration of an identifier for an object is
11506           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11507           // declared type shall not be an incomplete type.
11508           // NOTE: code such as the following
11509           //     static struct s;
11510           //     struct s { int a; };
11511           // is accepted by gcc. Hence here we issue a warning instead of
11512           // an error and we do not invalidate the static declaration.
11513           // NOTE: to avoid multiple warnings, only check the first declaration.
11514           if (Var->isFirstDecl())
11515             RequireCompleteType(Var->getLocation(), Type,
11516                                 diag::ext_typecheck_decl_incomplete_type);
11517         }
11518       }
11519 
11520       // Record the tentative definition; we're done.
11521       if (!Var->isInvalidDecl())
11522         TentativeDefinitions.push_back(Var);
11523       return;
11524     }
11525 
11526     // Provide a specific diagnostic for uninitialized variable
11527     // definitions with incomplete array type.
11528     if (Type->isIncompleteArrayType()) {
11529       Diag(Var->getLocation(),
11530            diag::err_typecheck_incomplete_array_needs_initializer);
11531       Var->setInvalidDecl();
11532       return;
11533     }
11534 
11535     // Provide a specific diagnostic for uninitialized variable
11536     // definitions with reference type.
11537     if (Type->isReferenceType()) {
11538       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11539         << Var->getDeclName()
11540         << SourceRange(Var->getLocation(), Var->getLocation());
11541       Var->setInvalidDecl();
11542       return;
11543     }
11544 
11545     // Do not attempt to type-check the default initializer for a
11546     // variable with dependent type.
11547     if (Type->isDependentType())
11548       return;
11549 
11550     if (Var->isInvalidDecl())
11551       return;
11552 
11553     if (!Var->hasAttr<AliasAttr>()) {
11554       if (RequireCompleteType(Var->getLocation(),
11555                               Context.getBaseElementType(Type),
11556                               diag::err_typecheck_decl_incomplete_type)) {
11557         Var->setInvalidDecl();
11558         return;
11559       }
11560     } else {
11561       return;
11562     }
11563 
11564     // The variable can not have an abstract class type.
11565     if (RequireNonAbstractType(Var->getLocation(), Type,
11566                                diag::err_abstract_type_in_decl,
11567                                AbstractVariableType)) {
11568       Var->setInvalidDecl();
11569       return;
11570     }
11571 
11572     // Check for jumps past the implicit initializer.  C++0x
11573     // clarifies that this applies to a "variable with automatic
11574     // storage duration", not a "local variable".
11575     // C++11 [stmt.dcl]p3
11576     //   A program that jumps from a point where a variable with automatic
11577     //   storage duration is not in scope to a point where it is in scope is
11578     //   ill-formed unless the variable has scalar type, class type with a
11579     //   trivial default constructor and a trivial destructor, a cv-qualified
11580     //   version of one of these types, or an array of one of the preceding
11581     //   types and is declared without an initializer.
11582     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11583       if (const RecordType *Record
11584             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11585         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11586         // Mark the function (if we're in one) for further checking even if the
11587         // looser rules of C++11 do not require such checks, so that we can
11588         // diagnose incompatibilities with C++98.
11589         if (!CXXRecord->isPOD())
11590           setFunctionHasBranchProtectedScope();
11591       }
11592     }
11593 
11594     // C++03 [dcl.init]p9:
11595     //   If no initializer is specified for an object, and the
11596     //   object is of (possibly cv-qualified) non-POD class type (or
11597     //   array thereof), the object shall be default-initialized; if
11598     //   the object is of const-qualified type, the underlying class
11599     //   type shall have a user-declared default
11600     //   constructor. Otherwise, if no initializer is specified for
11601     //   a non- static object, the object and its subobjects, if
11602     //   any, have an indeterminate initial value); if the object
11603     //   or any of its subobjects are of const-qualified type, the
11604     //   program is ill-formed.
11605     // C++0x [dcl.init]p11:
11606     //   If no initializer is specified for an object, the object is
11607     //   default-initialized; [...].
11608     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11609     InitializationKind Kind
11610       = InitializationKind::CreateDefault(Var->getLocation());
11611 
11612     InitializationSequence InitSeq(*this, Entity, Kind, None);
11613     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11614     if (Init.isInvalid())
11615       Var->setInvalidDecl();
11616     else if (Init.get()) {
11617       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11618       // This is important for template substitution.
11619       Var->setInitStyle(VarDecl::CallInit);
11620     }
11621 
11622     CheckCompleteVariableDeclaration(Var);
11623   }
11624 }
11625 
11626 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11627   // If there is no declaration, there was an error parsing it. Ignore it.
11628   if (!D)
11629     return;
11630 
11631   VarDecl *VD = dyn_cast<VarDecl>(D);
11632   if (!VD) {
11633     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11634     D->setInvalidDecl();
11635     return;
11636   }
11637 
11638   VD->setCXXForRangeDecl(true);
11639 
11640   // for-range-declaration cannot be given a storage class specifier.
11641   int Error = -1;
11642   switch (VD->getStorageClass()) {
11643   case SC_None:
11644     break;
11645   case SC_Extern:
11646     Error = 0;
11647     break;
11648   case SC_Static:
11649     Error = 1;
11650     break;
11651   case SC_PrivateExtern:
11652     Error = 2;
11653     break;
11654   case SC_Auto:
11655     Error = 3;
11656     break;
11657   case SC_Register:
11658     Error = 4;
11659     break;
11660   }
11661   if (Error != -1) {
11662     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11663       << VD->getDeclName() << Error;
11664     D->setInvalidDecl();
11665   }
11666 }
11667 
11668 StmtResult
11669 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11670                                  IdentifierInfo *Ident,
11671                                  ParsedAttributes &Attrs,
11672                                  SourceLocation AttrEnd) {
11673   // C++1y [stmt.iter]p1:
11674   //   A range-based for statement of the form
11675   //      for ( for-range-identifier : for-range-initializer ) statement
11676   //   is equivalent to
11677   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11678   DeclSpec DS(Attrs.getPool().getFactory());
11679 
11680   const char *PrevSpec;
11681   unsigned DiagID;
11682   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11683                      getPrintingPolicy());
11684 
11685   Declarator D(DS, DeclaratorContext::ForContext);
11686   D.SetIdentifier(Ident, IdentLoc);
11687   D.takeAttributes(Attrs, AttrEnd);
11688 
11689   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11690   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11691                 IdentLoc);
11692   Decl *Var = ActOnDeclarator(S, D);
11693   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11694   FinalizeDeclaration(Var);
11695   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11696                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11697 }
11698 
11699 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11700   if (var->isInvalidDecl()) return;
11701 
11702   if (getLangOpts().OpenCL) {
11703     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11704     // initialiser
11705     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11706         !var->hasInit()) {
11707       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11708           << 1 /*Init*/;
11709       var->setInvalidDecl();
11710       return;
11711     }
11712   }
11713 
11714   // In Objective-C, don't allow jumps past the implicit initialization of a
11715   // local retaining variable.
11716   if (getLangOpts().ObjC &&
11717       var->hasLocalStorage()) {
11718     switch (var->getType().getObjCLifetime()) {
11719     case Qualifiers::OCL_None:
11720     case Qualifiers::OCL_ExplicitNone:
11721     case Qualifiers::OCL_Autoreleasing:
11722       break;
11723 
11724     case Qualifiers::OCL_Weak:
11725     case Qualifiers::OCL_Strong:
11726       setFunctionHasBranchProtectedScope();
11727       break;
11728     }
11729   }
11730 
11731   if (var->hasLocalStorage() &&
11732       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11733     setFunctionHasBranchProtectedScope();
11734 
11735   // Warn about externally-visible variables being defined without a
11736   // prior declaration.  We only want to do this for global
11737   // declarations, but we also specifically need to avoid doing it for
11738   // class members because the linkage of an anonymous class can
11739   // change if it's later given a typedef name.
11740   if (var->isThisDeclarationADefinition() &&
11741       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11742       var->isExternallyVisible() && var->hasLinkage() &&
11743       !var->isInline() && !var->getDescribedVarTemplate() &&
11744       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11745       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11746                                   var->getLocation())) {
11747     // Find a previous declaration that's not a definition.
11748     VarDecl *prev = var->getPreviousDecl();
11749     while (prev && prev->isThisDeclarationADefinition())
11750       prev = prev->getPreviousDecl();
11751 
11752     if (!prev)
11753       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11754   }
11755 
11756   // Cache the result of checking for constant initialization.
11757   Optional<bool> CacheHasConstInit;
11758   const Expr *CacheCulprit;
11759   auto checkConstInit = [&]() mutable {
11760     if (!CacheHasConstInit)
11761       CacheHasConstInit = var->getInit()->isConstantInitializer(
11762             Context, var->getType()->isReferenceType(), &CacheCulprit);
11763     return *CacheHasConstInit;
11764   };
11765 
11766   if (var->getTLSKind() == VarDecl::TLS_Static) {
11767     if (var->getType().isDestructedType()) {
11768       // GNU C++98 edits for __thread, [basic.start.term]p3:
11769       //   The type of an object with thread storage duration shall not
11770       //   have a non-trivial destructor.
11771       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11772       if (getLangOpts().CPlusPlus11)
11773         Diag(var->getLocation(), diag::note_use_thread_local);
11774     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11775       if (!checkConstInit()) {
11776         // GNU C++98 edits for __thread, [basic.start.init]p4:
11777         //   An object of thread storage duration shall not require dynamic
11778         //   initialization.
11779         // FIXME: Need strict checking here.
11780         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11781           << CacheCulprit->getSourceRange();
11782         if (getLangOpts().CPlusPlus11)
11783           Diag(var->getLocation(), diag::note_use_thread_local);
11784       }
11785     }
11786   }
11787 
11788   // Apply section attributes and pragmas to global variables.
11789   bool GlobalStorage = var->hasGlobalStorage();
11790   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11791       !inTemplateInstantiation()) {
11792     PragmaStack<StringLiteral *> *Stack = nullptr;
11793     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11794     if (var->getType().isConstQualified())
11795       Stack = &ConstSegStack;
11796     else if (!var->getInit()) {
11797       Stack = &BSSSegStack;
11798       SectionFlags |= ASTContext::PSF_Write;
11799     } else {
11800       Stack = &DataSegStack;
11801       SectionFlags |= ASTContext::PSF_Write;
11802     }
11803     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11804       var->addAttr(SectionAttr::CreateImplicit(
11805           Context, SectionAttr::Declspec_allocate,
11806           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11807     }
11808     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11809       if (UnifySection(SA->getName(), SectionFlags, var))
11810         var->dropAttr<SectionAttr>();
11811 
11812     // Apply the init_seg attribute if this has an initializer.  If the
11813     // initializer turns out to not be dynamic, we'll end up ignoring this
11814     // attribute.
11815     if (CurInitSeg && var->getInit())
11816       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11817                                                CurInitSegLoc));
11818   }
11819 
11820   // All the following checks are C++ only.
11821   if (!getLangOpts().CPlusPlus) {
11822       // If this variable must be emitted, add it as an initializer for the
11823       // current module.
11824      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11825        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11826      return;
11827   }
11828 
11829   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11830     CheckCompleteDecompositionDeclaration(DD);
11831 
11832   QualType type = var->getType();
11833   if (type->isDependentType()) return;
11834 
11835   if (var->hasAttr<BlocksAttr>())
11836     getCurFunction()->addByrefBlockVar(var);
11837 
11838   Expr *Init = var->getInit();
11839   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11840   QualType baseType = Context.getBaseElementType(type);
11841 
11842   if (Init && !Init->isValueDependent()) {
11843     if (var->isConstexpr()) {
11844       SmallVector<PartialDiagnosticAt, 8> Notes;
11845       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11846         SourceLocation DiagLoc = var->getLocation();
11847         // If the note doesn't add any useful information other than a source
11848         // location, fold it into the primary diagnostic.
11849         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11850               diag::note_invalid_subexpr_in_const_expr) {
11851           DiagLoc = Notes[0].first;
11852           Notes.clear();
11853         }
11854         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11855           << var << Init->getSourceRange();
11856         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11857           Diag(Notes[I].first, Notes[I].second);
11858       }
11859     } else if (var->isUsableInConstantExpressions(Context)) {
11860       // Check whether the initializer of a const variable of integral or
11861       // enumeration type is an ICE now, since we can't tell whether it was
11862       // initialized by a constant expression if we check later.
11863       var->checkInitIsICE();
11864     }
11865 
11866     // Don't emit further diagnostics about constexpr globals since they
11867     // were just diagnosed.
11868     if (!var->isConstexpr() && GlobalStorage &&
11869             var->hasAttr<RequireConstantInitAttr>()) {
11870       // FIXME: Need strict checking in C++03 here.
11871       bool DiagErr = getLangOpts().CPlusPlus11
11872           ? !var->checkInitIsICE() : !checkConstInit();
11873       if (DiagErr) {
11874         auto attr = var->getAttr<RequireConstantInitAttr>();
11875         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11876           << Init->getSourceRange();
11877         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11878           << attr->getRange();
11879         if (getLangOpts().CPlusPlus11) {
11880           APValue Value;
11881           SmallVector<PartialDiagnosticAt, 8> Notes;
11882           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11883           for (auto &it : Notes)
11884             Diag(it.first, it.second);
11885         } else {
11886           Diag(CacheCulprit->getExprLoc(),
11887                diag::note_invalid_subexpr_in_const_expr)
11888               << CacheCulprit->getSourceRange();
11889         }
11890       }
11891     }
11892     else if (!var->isConstexpr() && IsGlobal &&
11893              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11894                                     var->getLocation())) {
11895       // Warn about globals which don't have a constant initializer.  Don't
11896       // warn about globals with a non-trivial destructor because we already
11897       // warned about them.
11898       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11899       if (!(RD && !RD->hasTrivialDestructor())) {
11900         if (!checkConstInit())
11901           Diag(var->getLocation(), diag::warn_global_constructor)
11902             << Init->getSourceRange();
11903       }
11904     }
11905   }
11906 
11907   // Require the destructor.
11908   if (const RecordType *recordType = baseType->getAs<RecordType>())
11909     FinalizeVarWithDestructor(var, recordType);
11910 
11911   // If this variable must be emitted, add it as an initializer for the current
11912   // module.
11913   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11914     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11915 }
11916 
11917 /// Determines if a variable's alignment is dependent.
11918 static bool hasDependentAlignment(VarDecl *VD) {
11919   if (VD->getType()->isDependentType())
11920     return true;
11921   for (auto *I : VD->specific_attrs<AlignedAttr>())
11922     if (I->isAlignmentDependent())
11923       return true;
11924   return false;
11925 }
11926 
11927 /// Check if VD needs to be dllexport/dllimport due to being in a
11928 /// dllexport/import function.
11929 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
11930   assert(VD->isStaticLocal());
11931 
11932   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11933 
11934   // Find outermost function when VD is in lambda function.
11935   while (FD && !getDLLAttr(FD) &&
11936          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
11937          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
11938     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
11939   }
11940 
11941   if (!FD)
11942     return;
11943 
11944   // Static locals inherit dll attributes from their function.
11945   if (Attr *A = getDLLAttr(FD)) {
11946     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11947     NewAttr->setInherited(true);
11948     VD->addAttr(NewAttr);
11949   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
11950     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
11951                                                           getASTContext(),
11952                                                           A->getSpellingListIndex());
11953     NewAttr->setInherited(true);
11954     VD->addAttr(NewAttr);
11955 
11956     // Export this function to enforce exporting this static variable even
11957     // if it is not used in this compilation unit.
11958     if (!FD->hasAttr<DLLExportAttr>())
11959       FD->addAttr(NewAttr);
11960 
11961   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
11962     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
11963                                                           getASTContext(),
11964                                                           A->getSpellingListIndex());
11965     NewAttr->setInherited(true);
11966     VD->addAttr(NewAttr);
11967   }
11968 }
11969 
11970 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11971 /// any semantic actions necessary after any initializer has been attached.
11972 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11973   // Note that we are no longer parsing the initializer for this declaration.
11974   ParsingInitForAutoVars.erase(ThisDecl);
11975 
11976   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11977   if (!VD)
11978     return;
11979 
11980   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11981   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11982       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11983     if (PragmaClangBSSSection.Valid)
11984       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11985                                                             PragmaClangBSSSection.SectionName,
11986                                                             PragmaClangBSSSection.PragmaLocation));
11987     if (PragmaClangDataSection.Valid)
11988       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11989                                                              PragmaClangDataSection.SectionName,
11990                                                              PragmaClangDataSection.PragmaLocation));
11991     if (PragmaClangRodataSection.Valid)
11992       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11993                                                                PragmaClangRodataSection.SectionName,
11994                                                                PragmaClangRodataSection.PragmaLocation));
11995   }
11996 
11997   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11998     for (auto *BD : DD->bindings()) {
11999       FinalizeDeclaration(BD);
12000     }
12001   }
12002 
12003   checkAttributesAfterMerging(*this, *VD);
12004 
12005   // Perform TLS alignment check here after attributes attached to the variable
12006   // which may affect the alignment have been processed. Only perform the check
12007   // if the target has a maximum TLS alignment (zero means no constraints).
12008   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12009     // Protect the check so that it's not performed on dependent types and
12010     // dependent alignments (we can't determine the alignment in that case).
12011     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12012         !VD->isInvalidDecl()) {
12013       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12014       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12015         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12016           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12017           << (unsigned)MaxAlignChars.getQuantity();
12018       }
12019     }
12020   }
12021 
12022   if (VD->isStaticLocal()) {
12023     CheckStaticLocalForDllExport(VD);
12024 
12025     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12026       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12027       // function, only __shared__ variables or variables without any device
12028       // memory qualifiers may be declared with static storage class.
12029       // Note: It is unclear how a function-scope non-const static variable
12030       // without device memory qualifier is implemented, therefore only static
12031       // const variable without device memory qualifier is allowed.
12032       [&]() {
12033         if (!getLangOpts().CUDA)
12034           return;
12035         if (VD->hasAttr<CUDASharedAttr>())
12036           return;
12037         if (VD->getType().isConstQualified() &&
12038             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12039           return;
12040         if (CUDADiagIfDeviceCode(VD->getLocation(),
12041                                  diag::err_device_static_local_var)
12042             << CurrentCUDATarget())
12043           VD->setInvalidDecl();
12044       }();
12045     }
12046   }
12047 
12048   // Perform check for initializers of device-side global variables.
12049   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12050   // 7.5). We must also apply the same checks to all __shared__
12051   // variables whether they are local or not. CUDA also allows
12052   // constant initializers for __constant__ and __device__ variables.
12053   if (getLangOpts().CUDA)
12054     checkAllowedCUDAInitializer(VD);
12055 
12056   // Grab the dllimport or dllexport attribute off of the VarDecl.
12057   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12058 
12059   // Imported static data members cannot be defined out-of-line.
12060   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12061     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12062         VD->isThisDeclarationADefinition()) {
12063       // We allow definitions of dllimport class template static data members
12064       // with a warning.
12065       CXXRecordDecl *Context =
12066         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12067       bool IsClassTemplateMember =
12068           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12069           Context->getDescribedClassTemplate();
12070 
12071       Diag(VD->getLocation(),
12072            IsClassTemplateMember
12073                ? diag::warn_attribute_dllimport_static_field_definition
12074                : diag::err_attribute_dllimport_static_field_definition);
12075       Diag(IA->getLocation(), diag::note_attribute);
12076       if (!IsClassTemplateMember)
12077         VD->setInvalidDecl();
12078     }
12079   }
12080 
12081   // dllimport/dllexport variables cannot be thread local, their TLS index
12082   // isn't exported with the variable.
12083   if (DLLAttr && VD->getTLSKind()) {
12084     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12085     if (F && getDLLAttr(F)) {
12086       assert(VD->isStaticLocal());
12087       // But if this is a static local in a dlimport/dllexport function, the
12088       // function will never be inlined, which means the var would never be
12089       // imported, so having it marked import/export is safe.
12090     } else {
12091       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12092                                                                     << DLLAttr;
12093       VD->setInvalidDecl();
12094     }
12095   }
12096 
12097   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12098     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12099       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12100       VD->dropAttr<UsedAttr>();
12101     }
12102   }
12103 
12104   const DeclContext *DC = VD->getDeclContext();
12105   // If there's a #pragma GCC visibility in scope, and this isn't a class
12106   // member, set the visibility of this variable.
12107   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12108     AddPushedVisibilityAttribute(VD);
12109 
12110   // FIXME: Warn on unused var template partial specializations.
12111   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12112     MarkUnusedFileScopedDecl(VD);
12113 
12114   // Now we have parsed the initializer and can update the table of magic
12115   // tag values.
12116   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12117       !VD->getType()->isIntegralOrEnumerationType())
12118     return;
12119 
12120   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12121     const Expr *MagicValueExpr = VD->getInit();
12122     if (!MagicValueExpr) {
12123       continue;
12124     }
12125     llvm::APSInt MagicValueInt;
12126     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12127       Diag(I->getRange().getBegin(),
12128            diag::err_type_tag_for_datatype_not_ice)
12129         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12130       continue;
12131     }
12132     if (MagicValueInt.getActiveBits() > 64) {
12133       Diag(I->getRange().getBegin(),
12134            diag::err_type_tag_for_datatype_too_large)
12135         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12136       continue;
12137     }
12138     uint64_t MagicValue = MagicValueInt.getZExtValue();
12139     RegisterTypeTagForDatatype(I->getArgumentKind(),
12140                                MagicValue,
12141                                I->getMatchingCType(),
12142                                I->getLayoutCompatible(),
12143                                I->getMustBeNull());
12144   }
12145 }
12146 
12147 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12148   auto *VD = dyn_cast<VarDecl>(DD);
12149   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12150 }
12151 
12152 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12153                                                    ArrayRef<Decl *> Group) {
12154   SmallVector<Decl*, 8> Decls;
12155 
12156   if (DS.isTypeSpecOwned())
12157     Decls.push_back(DS.getRepAsDecl());
12158 
12159   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12160   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12161   bool DiagnosedMultipleDecomps = false;
12162   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12163   bool DiagnosedNonDeducedAuto = false;
12164 
12165   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12166     if (Decl *D = Group[i]) {
12167       // For declarators, there are some additional syntactic-ish checks we need
12168       // to perform.
12169       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12170         if (!FirstDeclaratorInGroup)
12171           FirstDeclaratorInGroup = DD;
12172         if (!FirstDecompDeclaratorInGroup)
12173           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12174         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12175             !hasDeducedAuto(DD))
12176           FirstNonDeducedAutoInGroup = DD;
12177 
12178         if (FirstDeclaratorInGroup != DD) {
12179           // A decomposition declaration cannot be combined with any other
12180           // declaration in the same group.
12181           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12182             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12183                  diag::err_decomp_decl_not_alone)
12184                 << FirstDeclaratorInGroup->getSourceRange()
12185                 << DD->getSourceRange();
12186             DiagnosedMultipleDecomps = true;
12187           }
12188 
12189           // A declarator that uses 'auto' in any way other than to declare a
12190           // variable with a deduced type cannot be combined with any other
12191           // declarator in the same group.
12192           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12193             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12194                  diag::err_auto_non_deduced_not_alone)
12195                 << FirstNonDeducedAutoInGroup->getType()
12196                        ->hasAutoForTrailingReturnType()
12197                 << FirstDeclaratorInGroup->getSourceRange()
12198                 << DD->getSourceRange();
12199             DiagnosedNonDeducedAuto = true;
12200           }
12201         }
12202       }
12203 
12204       Decls.push_back(D);
12205     }
12206   }
12207 
12208   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12209     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12210       handleTagNumbering(Tag, S);
12211       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12212           getLangOpts().CPlusPlus)
12213         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12214     }
12215   }
12216 
12217   return BuildDeclaratorGroup(Decls);
12218 }
12219 
12220 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12221 /// group, performing any necessary semantic checking.
12222 Sema::DeclGroupPtrTy
12223 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12224   // C++14 [dcl.spec.auto]p7: (DR1347)
12225   //   If the type that replaces the placeholder type is not the same in each
12226   //   deduction, the program is ill-formed.
12227   if (Group.size() > 1) {
12228     QualType Deduced;
12229     VarDecl *DeducedDecl = nullptr;
12230     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12231       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12232       if (!D || D->isInvalidDecl())
12233         break;
12234       DeducedType *DT = D->getType()->getContainedDeducedType();
12235       if (!DT || DT->getDeducedType().isNull())
12236         continue;
12237       if (Deduced.isNull()) {
12238         Deduced = DT->getDeducedType();
12239         DeducedDecl = D;
12240       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12241         auto *AT = dyn_cast<AutoType>(DT);
12242         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12243              diag::err_auto_different_deductions)
12244           << (AT ? (unsigned)AT->getKeyword() : 3)
12245           << Deduced << DeducedDecl->getDeclName()
12246           << DT->getDeducedType() << D->getDeclName()
12247           << DeducedDecl->getInit()->getSourceRange()
12248           << D->getInit()->getSourceRange();
12249         D->setInvalidDecl();
12250         break;
12251       }
12252     }
12253   }
12254 
12255   ActOnDocumentableDecls(Group);
12256 
12257   return DeclGroupPtrTy::make(
12258       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12259 }
12260 
12261 void Sema::ActOnDocumentableDecl(Decl *D) {
12262   ActOnDocumentableDecls(D);
12263 }
12264 
12265 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12266   // Don't parse the comment if Doxygen diagnostics are ignored.
12267   if (Group.empty() || !Group[0])
12268     return;
12269 
12270   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12271                       Group[0]->getLocation()) &&
12272       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12273                       Group[0]->getLocation()))
12274     return;
12275 
12276   if (Group.size() >= 2) {
12277     // This is a decl group.  Normally it will contain only declarations
12278     // produced from declarator list.  But in case we have any definitions or
12279     // additional declaration references:
12280     //   'typedef struct S {} S;'
12281     //   'typedef struct S *S;'
12282     //   'struct S *pS;'
12283     // FinalizeDeclaratorGroup adds these as separate declarations.
12284     Decl *MaybeTagDecl = Group[0];
12285     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12286       Group = Group.slice(1);
12287     }
12288   }
12289 
12290   // See if there are any new comments that are not attached to a decl.
12291   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12292   if (!Comments.empty() &&
12293       !Comments.back()->isAttached()) {
12294     // There is at least one comment that not attached to a decl.
12295     // Maybe it should be attached to one of these decls?
12296     //
12297     // Note that this way we pick up not only comments that precede the
12298     // declaration, but also comments that *follow* the declaration -- thanks to
12299     // the lookahead in the lexer: we've consumed the semicolon and looked
12300     // ahead through comments.
12301     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12302       Context.getCommentForDecl(Group[i], &PP);
12303   }
12304 }
12305 
12306 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12307 /// to introduce parameters into function prototype scope.
12308 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12309   const DeclSpec &DS = D.getDeclSpec();
12310 
12311   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12312 
12313   // C++03 [dcl.stc]p2 also permits 'auto'.
12314   StorageClass SC = SC_None;
12315   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12316     SC = SC_Register;
12317     // In C++11, the 'register' storage class specifier is deprecated.
12318     // In C++17, it is not allowed, but we tolerate it as an extension.
12319     if (getLangOpts().CPlusPlus11) {
12320       Diag(DS.getStorageClassSpecLoc(),
12321            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12322                                      : diag::warn_deprecated_register)
12323         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12324     }
12325   } else if (getLangOpts().CPlusPlus &&
12326              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12327     SC = SC_Auto;
12328   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12329     Diag(DS.getStorageClassSpecLoc(),
12330          diag::err_invalid_storage_class_in_func_decl);
12331     D.getMutableDeclSpec().ClearStorageClassSpecs();
12332   }
12333 
12334   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12335     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12336       << DeclSpec::getSpecifierName(TSCS);
12337   if (DS.isInlineSpecified())
12338     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12339         << getLangOpts().CPlusPlus17;
12340   if (DS.isConstexprSpecified())
12341     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12342       << 0;
12343 
12344   DiagnoseFunctionSpecifiers(DS);
12345 
12346   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12347   QualType parmDeclType = TInfo->getType();
12348 
12349   if (getLangOpts().CPlusPlus) {
12350     // Check that there are no default arguments inside the type of this
12351     // parameter.
12352     CheckExtraCXXDefaultArguments(D);
12353 
12354     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12355     if (D.getCXXScopeSpec().isSet()) {
12356       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12357         << D.getCXXScopeSpec().getRange();
12358       D.getCXXScopeSpec().clear();
12359     }
12360   }
12361 
12362   // Ensure we have a valid name
12363   IdentifierInfo *II = nullptr;
12364   if (D.hasName()) {
12365     II = D.getIdentifier();
12366     if (!II) {
12367       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12368         << GetNameForDeclarator(D).getName();
12369       D.setInvalidType(true);
12370     }
12371   }
12372 
12373   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12374   if (II) {
12375     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12376                    ForVisibleRedeclaration);
12377     LookupName(R, S);
12378     if (R.isSingleResult()) {
12379       NamedDecl *PrevDecl = R.getFoundDecl();
12380       if (PrevDecl->isTemplateParameter()) {
12381         // Maybe we will complain about the shadowed template parameter.
12382         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12383         // Just pretend that we didn't see the previous declaration.
12384         PrevDecl = nullptr;
12385       } else if (S->isDeclScope(PrevDecl)) {
12386         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12387         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12388 
12389         // Recover by removing the name
12390         II = nullptr;
12391         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12392         D.setInvalidType(true);
12393       }
12394     }
12395 
12396     if (LangOpts.CPlusPlus) {
12397       DeclarationNameInfo DNI = GetNameForDeclarator(D);
12398       if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12399         CheckShadowInheritedFields(DNI.getLoc(), DNI.getName(), RD,
12400                                    /*DeclIsField*/ false);
12401     }
12402   }
12403 
12404   // Temporarily put parameter variables in the translation unit, not
12405   // the enclosing context.  This prevents them from accidentally
12406   // looking like class members in C++.
12407   ParmVarDecl *New =
12408       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12409                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12410 
12411   if (D.isInvalidType())
12412     New->setInvalidDecl();
12413 
12414   assert(S->isFunctionPrototypeScope());
12415   assert(S->getFunctionPrototypeDepth() >= 1);
12416   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12417                     S->getNextFunctionPrototypeIndex());
12418 
12419   // Add the parameter declaration into this scope.
12420   S->AddDecl(New);
12421   if (II)
12422     IdResolver.AddDecl(New);
12423 
12424   ProcessDeclAttributes(S, New, D);
12425 
12426   if (D.getDeclSpec().isModulePrivateSpecified())
12427     Diag(New->getLocation(), diag::err_module_private_local)
12428       << 1 << New->getDeclName()
12429       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12430       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12431 
12432   if (New->hasAttr<BlocksAttr>()) {
12433     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12434   }
12435   return New;
12436 }
12437 
12438 /// Synthesizes a variable for a parameter arising from a
12439 /// typedef.
12440 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12441                                               SourceLocation Loc,
12442                                               QualType T) {
12443   /* FIXME: setting StartLoc == Loc.
12444      Would it be worth to modify callers so as to provide proper source
12445      location for the unnamed parameters, embedding the parameter's type? */
12446   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12447                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12448                                            SC_None, nullptr);
12449   Param->setImplicit();
12450   return Param;
12451 }
12452 
12453 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12454   // Don't diagnose unused-parameter errors in template instantiations; we
12455   // will already have done so in the template itself.
12456   if (inTemplateInstantiation())
12457     return;
12458 
12459   for (const ParmVarDecl *Parameter : Parameters) {
12460     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12461         !Parameter->hasAttr<UnusedAttr>()) {
12462       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12463         << Parameter->getDeclName();
12464     }
12465   }
12466 }
12467 
12468 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12469     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12470   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12471     return;
12472 
12473   // Warn if the return value is pass-by-value and larger than the specified
12474   // threshold.
12475   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12476     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12477     if (Size > LangOpts.NumLargeByValueCopy)
12478       Diag(D->getLocation(), diag::warn_return_value_size)
12479           << D->getDeclName() << Size;
12480   }
12481 
12482   // Warn if any parameter is pass-by-value and larger than the specified
12483   // threshold.
12484   for (const ParmVarDecl *Parameter : Parameters) {
12485     QualType T = Parameter->getType();
12486     if (T->isDependentType() || !T.isPODType(Context))
12487       continue;
12488     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12489     if (Size > LangOpts.NumLargeByValueCopy)
12490       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12491           << Parameter->getDeclName() << Size;
12492   }
12493 }
12494 
12495 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12496                                   SourceLocation NameLoc, IdentifierInfo *Name,
12497                                   QualType T, TypeSourceInfo *TSInfo,
12498                                   StorageClass SC) {
12499   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12500   if (getLangOpts().ObjCAutoRefCount &&
12501       T.getObjCLifetime() == Qualifiers::OCL_None &&
12502       T->isObjCLifetimeType()) {
12503 
12504     Qualifiers::ObjCLifetime lifetime;
12505 
12506     // Special cases for arrays:
12507     //   - if it's const, use __unsafe_unretained
12508     //   - otherwise, it's an error
12509     if (T->isArrayType()) {
12510       if (!T.isConstQualified()) {
12511         DelayedDiagnostics.add(
12512             sema::DelayedDiagnostic::makeForbiddenType(
12513             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12514       }
12515       lifetime = Qualifiers::OCL_ExplicitNone;
12516     } else {
12517       lifetime = T->getObjCARCImplicitLifetime();
12518     }
12519     T = Context.getLifetimeQualifiedType(T, lifetime);
12520   }
12521 
12522   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12523                                          Context.getAdjustedParameterType(T),
12524                                          TSInfo, SC, nullptr);
12525 
12526   // Parameters can not be abstract class types.
12527   // For record types, this is done by the AbstractClassUsageDiagnoser once
12528   // the class has been completely parsed.
12529   if (!CurContext->isRecord() &&
12530       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12531                              AbstractParamType))
12532     New->setInvalidDecl();
12533 
12534   // Parameter declarators cannot be interface types. All ObjC objects are
12535   // passed by reference.
12536   if (T->isObjCObjectType()) {
12537     SourceLocation TypeEndLoc =
12538         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12539     Diag(NameLoc,
12540          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12541       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12542     T = Context.getObjCObjectPointerType(T);
12543     New->setType(T);
12544   }
12545 
12546   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12547   // duration shall not be qualified by an address-space qualifier."
12548   // Since all parameters have automatic store duration, they can not have
12549   // an address space.
12550   if (T.getAddressSpace() != LangAS::Default &&
12551       // OpenCL allows function arguments declared to be an array of a type
12552       // to be qualified with an address space.
12553       !(getLangOpts().OpenCL &&
12554         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12555     Diag(NameLoc, diag::err_arg_with_address_space);
12556     New->setInvalidDecl();
12557   }
12558 
12559   return New;
12560 }
12561 
12562 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12563                                            SourceLocation LocAfterDecls) {
12564   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12565 
12566   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12567   // for a K&R function.
12568   if (!FTI.hasPrototype) {
12569     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12570       --i;
12571       if (FTI.Params[i].Param == nullptr) {
12572         SmallString<256> Code;
12573         llvm::raw_svector_ostream(Code)
12574             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12575         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12576             << FTI.Params[i].Ident
12577             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12578 
12579         // Implicitly declare the argument as type 'int' for lack of a better
12580         // type.
12581         AttributeFactory attrs;
12582         DeclSpec DS(attrs);
12583         const char* PrevSpec; // unused
12584         unsigned DiagID; // unused
12585         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12586                            DiagID, Context.getPrintingPolicy());
12587         // Use the identifier location for the type source range.
12588         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12589         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12590         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12591         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12592         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12593       }
12594     }
12595   }
12596 }
12597 
12598 Decl *
12599 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12600                               MultiTemplateParamsArg TemplateParameterLists,
12601                               SkipBodyInfo *SkipBody) {
12602   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12603   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12604   Scope *ParentScope = FnBodyScope->getParent();
12605 
12606   D.setFunctionDefinitionKind(FDK_Definition);
12607   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12608   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12609 }
12610 
12611 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12612   Consumer.HandleInlineFunctionDefinition(D);
12613 }
12614 
12615 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12616                              const FunctionDecl*& PossibleZeroParamPrototype) {
12617   // Don't warn about invalid declarations.
12618   if (FD->isInvalidDecl())
12619     return false;
12620 
12621   // Or declarations that aren't global.
12622   if (!FD->isGlobal())
12623     return false;
12624 
12625   // Don't warn about C++ member functions.
12626   if (isa<CXXMethodDecl>(FD))
12627     return false;
12628 
12629   // Don't warn about 'main'.
12630   if (FD->isMain())
12631     return false;
12632 
12633   // Don't warn about inline functions.
12634   if (FD->isInlined())
12635     return false;
12636 
12637   // Don't warn about function templates.
12638   if (FD->getDescribedFunctionTemplate())
12639     return false;
12640 
12641   // Don't warn about function template specializations.
12642   if (FD->isFunctionTemplateSpecialization())
12643     return false;
12644 
12645   // Don't warn for OpenCL kernels.
12646   if (FD->hasAttr<OpenCLKernelAttr>())
12647     return false;
12648 
12649   // Don't warn on explicitly deleted functions.
12650   if (FD->isDeleted())
12651     return false;
12652 
12653   bool MissingPrototype = true;
12654   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12655        Prev; Prev = Prev->getPreviousDecl()) {
12656     // Ignore any declarations that occur in function or method
12657     // scope, because they aren't visible from the header.
12658     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12659       continue;
12660 
12661     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12662     if (FD->getNumParams() == 0)
12663       PossibleZeroParamPrototype = Prev;
12664     break;
12665   }
12666 
12667   return MissingPrototype;
12668 }
12669 
12670 void
12671 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12672                                    const FunctionDecl *EffectiveDefinition,
12673                                    SkipBodyInfo *SkipBody) {
12674   const FunctionDecl *Definition = EffectiveDefinition;
12675   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12676     // If this is a friend function defined in a class template, it does not
12677     // have a body until it is used, nevertheless it is a definition, see
12678     // [temp.inst]p2:
12679     //
12680     // ... for the purpose of determining whether an instantiated redeclaration
12681     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12682     // corresponds to a definition in the template is considered to be a
12683     // definition.
12684     //
12685     // The following code must produce redefinition error:
12686     //
12687     //     template<typename T> struct C20 { friend void func_20() {} };
12688     //     C20<int> c20i;
12689     //     void func_20() {}
12690     //
12691     for (auto I : FD->redecls()) {
12692       if (I != FD && !I->isInvalidDecl() &&
12693           I->getFriendObjectKind() != Decl::FOK_None) {
12694         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12695           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12696             // A merged copy of the same function, instantiated as a member of
12697             // the same class, is OK.
12698             if (declaresSameEntity(OrigFD, Original) &&
12699                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12700                                    cast<Decl>(FD->getLexicalDeclContext())))
12701               continue;
12702           }
12703 
12704           if (Original->isThisDeclarationADefinition()) {
12705             Definition = I;
12706             break;
12707           }
12708         }
12709       }
12710     }
12711   }
12712   if (!Definition)
12713     return;
12714 
12715   if (canRedefineFunction(Definition, getLangOpts()))
12716     return;
12717 
12718   // Don't emit an error when this is redefinition of a typo-corrected
12719   // definition.
12720   if (TypoCorrectedFunctionDefinitions.count(Definition))
12721     return;
12722 
12723   // If we don't have a visible definition of the function, and it's inline or
12724   // a template, skip the new definition.
12725   if (SkipBody && !hasVisibleDefinition(Definition) &&
12726       (Definition->getFormalLinkage() == InternalLinkage ||
12727        Definition->isInlined() ||
12728        Definition->getDescribedFunctionTemplate() ||
12729        Definition->getNumTemplateParameterLists())) {
12730     SkipBody->ShouldSkip = true;
12731     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12732     if (auto *TD = Definition->getDescribedFunctionTemplate())
12733       makeMergedDefinitionVisible(TD);
12734     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12735     return;
12736   }
12737 
12738   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12739       Definition->getStorageClass() == SC_Extern)
12740     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12741         << FD->getDeclName() << getLangOpts().CPlusPlus;
12742   else
12743     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12744 
12745   Diag(Definition->getLocation(), diag::note_previous_definition);
12746   FD->setInvalidDecl();
12747 }
12748 
12749 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12750                                    Sema &S) {
12751   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12752 
12753   LambdaScopeInfo *LSI = S.PushLambdaScope();
12754   LSI->CallOperator = CallOperator;
12755   LSI->Lambda = LambdaClass;
12756   LSI->ReturnType = CallOperator->getReturnType();
12757   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12758 
12759   if (LCD == LCD_None)
12760     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12761   else if (LCD == LCD_ByCopy)
12762     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12763   else if (LCD == LCD_ByRef)
12764     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12765   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12766 
12767   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12768   LSI->Mutable = !CallOperator->isConst();
12769 
12770   // Add the captures to the LSI so they can be noted as already
12771   // captured within tryCaptureVar.
12772   auto I = LambdaClass->field_begin();
12773   for (const auto &C : LambdaClass->captures()) {
12774     if (C.capturesVariable()) {
12775       VarDecl *VD = C.getCapturedVar();
12776       if (VD->isInitCapture())
12777         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12778       QualType CaptureType = VD->getType();
12779       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12780       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12781           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12782           /*EllipsisLoc*/C.isPackExpansion()
12783                          ? C.getEllipsisLoc() : SourceLocation(),
12784           CaptureType, /*Expr*/ nullptr);
12785 
12786     } else if (C.capturesThis()) {
12787       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12788                               /*Expr*/ nullptr,
12789                               C.getCaptureKind() == LCK_StarThis);
12790     } else {
12791       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12792     }
12793     ++I;
12794   }
12795 }
12796 
12797 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12798                                     SkipBodyInfo *SkipBody) {
12799   if (!D) {
12800     // Parsing the function declaration failed in some way. Push on a fake scope
12801     // anyway so we can try to parse the function body.
12802     PushFunctionScope();
12803     return D;
12804   }
12805 
12806   FunctionDecl *FD = nullptr;
12807 
12808   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12809     FD = FunTmpl->getTemplatedDecl();
12810   else
12811     FD = cast<FunctionDecl>(D);
12812 
12813   // Check for defining attributes before the check for redefinition.
12814   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12815     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12816     FD->dropAttr<AliasAttr>();
12817     FD->setInvalidDecl();
12818   }
12819   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12820     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12821     FD->dropAttr<IFuncAttr>();
12822     FD->setInvalidDecl();
12823   }
12824 
12825   // See if this is a redefinition. If 'will have body' is already set, then
12826   // these checks were already performed when it was set.
12827   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12828     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12829 
12830     // If we're skipping the body, we're done. Don't enter the scope.
12831     if (SkipBody && SkipBody->ShouldSkip)
12832       return D;
12833   }
12834 
12835   // Mark this function as "will have a body eventually".  This lets users to
12836   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12837   // this function.
12838   FD->setWillHaveBody();
12839 
12840   // If we are instantiating a generic lambda call operator, push
12841   // a LambdaScopeInfo onto the function stack.  But use the information
12842   // that's already been calculated (ActOnLambdaExpr) to prime the current
12843   // LambdaScopeInfo.
12844   // When the template operator is being specialized, the LambdaScopeInfo,
12845   // has to be properly restored so that tryCaptureVariable doesn't try
12846   // and capture any new variables. In addition when calculating potential
12847   // captures during transformation of nested lambdas, it is necessary to
12848   // have the LSI properly restored.
12849   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12850     assert(inTemplateInstantiation() &&
12851            "There should be an active template instantiation on the stack "
12852            "when instantiating a generic lambda!");
12853     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12854   } else {
12855     // Enter a new function scope
12856     PushFunctionScope();
12857   }
12858 
12859   // Builtin functions cannot be defined.
12860   if (unsigned BuiltinID = FD->getBuiltinID()) {
12861     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12862         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12863       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12864       FD->setInvalidDecl();
12865     }
12866   }
12867 
12868   // The return type of a function definition must be complete
12869   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12870   QualType ResultType = FD->getReturnType();
12871   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12872       !FD->isInvalidDecl() &&
12873       RequireCompleteType(FD->getLocation(), ResultType,
12874                           diag::err_func_def_incomplete_result))
12875     FD->setInvalidDecl();
12876 
12877   if (FnBodyScope)
12878     PushDeclContext(FnBodyScope, FD);
12879 
12880   // Check the validity of our function parameters
12881   CheckParmsForFunctionDef(FD->parameters(),
12882                            /*CheckParameterNames=*/true);
12883 
12884   // Add non-parameter declarations already in the function to the current
12885   // scope.
12886   if (FnBodyScope) {
12887     for (Decl *NPD : FD->decls()) {
12888       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12889       if (!NonParmDecl)
12890         continue;
12891       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12892              "parameters should not be in newly created FD yet");
12893 
12894       // If the decl has a name, make it accessible in the current scope.
12895       if (NonParmDecl->getDeclName())
12896         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12897 
12898       // Similarly, dive into enums and fish their constants out, making them
12899       // accessible in this scope.
12900       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12901         for (auto *EI : ED->enumerators())
12902           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12903       }
12904     }
12905   }
12906 
12907   // Introduce our parameters into the function scope
12908   for (auto Param : FD->parameters()) {
12909     Param->setOwningFunction(FD);
12910 
12911     // If this has an identifier, add it to the scope stack.
12912     if (Param->getIdentifier() && FnBodyScope) {
12913       CheckShadow(FnBodyScope, Param);
12914 
12915       PushOnScopeChains(Param, FnBodyScope);
12916     }
12917   }
12918 
12919   // Ensure that the function's exception specification is instantiated.
12920   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12921     ResolveExceptionSpec(D->getLocation(), FPT);
12922 
12923   // dllimport cannot be applied to non-inline function definitions.
12924   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12925       !FD->isTemplateInstantiation()) {
12926     assert(!FD->hasAttr<DLLExportAttr>());
12927     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12928     FD->setInvalidDecl();
12929     return D;
12930   }
12931   // We want to attach documentation to original Decl (which might be
12932   // a function template).
12933   ActOnDocumentableDecl(D);
12934   if (getCurLexicalContext()->isObjCContainer() &&
12935       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12936       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12937     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12938 
12939   return D;
12940 }
12941 
12942 /// Given the set of return statements within a function body,
12943 /// compute the variables that are subject to the named return value
12944 /// optimization.
12945 ///
12946 /// Each of the variables that is subject to the named return value
12947 /// optimization will be marked as NRVO variables in the AST, and any
12948 /// return statement that has a marked NRVO variable as its NRVO candidate can
12949 /// use the named return value optimization.
12950 ///
12951 /// This function applies a very simplistic algorithm for NRVO: if every return
12952 /// statement in the scope of a variable has the same NRVO candidate, that
12953 /// candidate is an NRVO variable.
12954 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12955   ReturnStmt **Returns = Scope->Returns.data();
12956 
12957   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12958     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12959       if (!NRVOCandidate->isNRVOVariable())
12960         Returns[I]->setNRVOCandidate(nullptr);
12961     }
12962   }
12963 }
12964 
12965 bool Sema::canDelayFunctionBody(const Declarator &D) {
12966   // We can't delay parsing the body of a constexpr function template (yet).
12967   if (D.getDeclSpec().isConstexprSpecified())
12968     return false;
12969 
12970   // We can't delay parsing the body of a function template with a deduced
12971   // return type (yet).
12972   if (D.getDeclSpec().hasAutoTypeSpec()) {
12973     // If the placeholder introduces a non-deduced trailing return type,
12974     // we can still delay parsing it.
12975     if (D.getNumTypeObjects()) {
12976       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12977       if (Outer.Kind == DeclaratorChunk::Function &&
12978           Outer.Fun.hasTrailingReturnType()) {
12979         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12980         return Ty.isNull() || !Ty->isUndeducedType();
12981       }
12982     }
12983     return false;
12984   }
12985 
12986   return true;
12987 }
12988 
12989 bool Sema::canSkipFunctionBody(Decl *D) {
12990   // We cannot skip the body of a function (or function template) which is
12991   // constexpr, since we may need to evaluate its body in order to parse the
12992   // rest of the file.
12993   // We cannot skip the body of a function with an undeduced return type,
12994   // because any callers of that function need to know the type.
12995   if (const FunctionDecl *FD = D->getAsFunction()) {
12996     if (FD->isConstexpr())
12997       return false;
12998     // We can't simply call Type::isUndeducedType here, because inside template
12999     // auto can be deduced to a dependent type, which is not considered
13000     // "undeduced".
13001     if (FD->getReturnType()->getContainedDeducedType())
13002       return false;
13003   }
13004   return Consumer.shouldSkipFunctionBody(D);
13005 }
13006 
13007 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13008   if (!Decl)
13009     return nullptr;
13010   if (FunctionDecl *FD = Decl->getAsFunction())
13011     FD->setHasSkippedBody();
13012   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13013     MD->setHasSkippedBody();
13014   return Decl;
13015 }
13016 
13017 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13018   return ActOnFinishFunctionBody(D, BodyArg, false);
13019 }
13020 
13021 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13022                                     bool IsInstantiation) {
13023   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13024 
13025   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13026   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13027 
13028   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
13029     CheckCompletedCoroutineBody(FD, Body);
13030 
13031   if (FD) {
13032     FD->setBody(Body);
13033     FD->setWillHaveBody(false);
13034 
13035     if (getLangOpts().CPlusPlus14) {
13036       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13037           FD->getReturnType()->isUndeducedType()) {
13038         // If the function has a deduced result type but contains no 'return'
13039         // statements, the result type as written must be exactly 'auto', and
13040         // the deduced result type is 'void'.
13041         if (!FD->getReturnType()->getAs<AutoType>()) {
13042           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13043               << FD->getReturnType();
13044           FD->setInvalidDecl();
13045         } else {
13046           // Substitute 'void' for the 'auto' in the type.
13047           TypeLoc ResultType = getReturnTypeLoc(FD);
13048           Context.adjustDeducedFunctionResultType(
13049               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13050         }
13051       }
13052     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13053       // In C++11, we don't use 'auto' deduction rules for lambda call
13054       // operators because we don't support return type deduction.
13055       auto *LSI = getCurLambda();
13056       if (LSI->HasImplicitReturnType) {
13057         deduceClosureReturnType(*LSI);
13058 
13059         // C++11 [expr.prim.lambda]p4:
13060         //   [...] if there are no return statements in the compound-statement
13061         //   [the deduced type is] the type void
13062         QualType RetType =
13063             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13064 
13065         // Update the return type to the deduced type.
13066         const FunctionProtoType *Proto =
13067             FD->getType()->getAs<FunctionProtoType>();
13068         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13069                                             Proto->getExtProtoInfo()));
13070       }
13071     }
13072 
13073     // If the function implicitly returns zero (like 'main') or is naked,
13074     // don't complain about missing return statements.
13075     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13076       WP.disableCheckFallThrough();
13077 
13078     // MSVC permits the use of pure specifier (=0) on function definition,
13079     // defined at class scope, warn about this non-standard construct.
13080     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13081       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13082 
13083     if (!FD->isInvalidDecl()) {
13084       // Don't diagnose unused parameters of defaulted or deleted functions.
13085       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13086         DiagnoseUnusedParameters(FD->parameters());
13087       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13088                                              FD->getReturnType(), FD);
13089 
13090       // If this is a structor, we need a vtable.
13091       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13092         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13093       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13094         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13095 
13096       // Try to apply the named return value optimization. We have to check
13097       // if we can do this here because lambdas keep return statements around
13098       // to deduce an implicit return type.
13099       if (FD->getReturnType()->isRecordType() &&
13100           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13101         computeNRVO(Body, getCurFunction());
13102     }
13103 
13104     // GNU warning -Wmissing-prototypes:
13105     //   Warn if a global function is defined without a previous
13106     //   prototype declaration. This warning is issued even if the
13107     //   definition itself provides a prototype. The aim is to detect
13108     //   global functions that fail to be declared in header files.
13109     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13110     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13111       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13112 
13113       if (PossibleZeroParamPrototype) {
13114         // We found a declaration that is not a prototype,
13115         // but that could be a zero-parameter prototype
13116         if (TypeSourceInfo *TI =
13117                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13118           TypeLoc TL = TI->getTypeLoc();
13119           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13120             Diag(PossibleZeroParamPrototype->getLocation(),
13121                  diag::note_declaration_not_a_prototype)
13122                 << PossibleZeroParamPrototype
13123                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13124         }
13125       }
13126 
13127       // GNU warning -Wstrict-prototypes
13128       //   Warn if K&R function is defined without a previous declaration.
13129       //   This warning is issued only if the definition itself does not provide
13130       //   a prototype. Only K&R definitions do not provide a prototype.
13131       //   An empty list in a function declarator that is part of a definition
13132       //   of that function specifies that the function has no parameters
13133       //   (C99 6.7.5.3p14)
13134       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13135           !LangOpts.CPlusPlus) {
13136         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13137         TypeLoc TL = TI->getTypeLoc();
13138         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13139         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13140       }
13141     }
13142 
13143     // Warn on CPUDispatch with an actual body.
13144     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13145       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13146         if (!CmpndBody->body_empty())
13147           Diag(CmpndBody->body_front()->getBeginLoc(),
13148                diag::warn_dispatch_body_ignored);
13149 
13150     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13151       const CXXMethodDecl *KeyFunction;
13152       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13153           MD->isVirtual() &&
13154           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13155           MD == KeyFunction->getCanonicalDecl()) {
13156         // Update the key-function state if necessary for this ABI.
13157         if (FD->isInlined() &&
13158             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13159           Context.setNonKeyFunction(MD);
13160 
13161           // If the newly-chosen key function is already defined, then we
13162           // need to mark the vtable as used retroactively.
13163           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13164           const FunctionDecl *Definition;
13165           if (KeyFunction && KeyFunction->isDefined(Definition))
13166             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13167         } else {
13168           // We just defined they key function; mark the vtable as used.
13169           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13170         }
13171       }
13172     }
13173 
13174     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13175            "Function parsing confused");
13176   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13177     assert(MD == getCurMethodDecl() && "Method parsing confused");
13178     MD->setBody(Body);
13179     if (!MD->isInvalidDecl()) {
13180       if (!MD->hasSkippedBody())
13181         DiagnoseUnusedParameters(MD->parameters());
13182       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13183                                              MD->getReturnType(), MD);
13184 
13185       if (Body)
13186         computeNRVO(Body, getCurFunction());
13187     }
13188     if (getCurFunction()->ObjCShouldCallSuper) {
13189       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13190           << MD->getSelector().getAsString();
13191       getCurFunction()->ObjCShouldCallSuper = false;
13192     }
13193     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13194       const ObjCMethodDecl *InitMethod = nullptr;
13195       bool isDesignated =
13196           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13197       assert(isDesignated && InitMethod);
13198       (void)isDesignated;
13199 
13200       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13201         auto IFace = MD->getClassInterface();
13202         if (!IFace)
13203           return false;
13204         auto SuperD = IFace->getSuperClass();
13205         if (!SuperD)
13206           return false;
13207         return SuperD->getIdentifier() ==
13208             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13209       };
13210       // Don't issue this warning for unavailable inits or direct subclasses
13211       // of NSObject.
13212       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13213         Diag(MD->getLocation(),
13214              diag::warn_objc_designated_init_missing_super_call);
13215         Diag(InitMethod->getLocation(),
13216              diag::note_objc_designated_init_marked_here);
13217       }
13218       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13219     }
13220     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13221       // Don't issue this warning for unavaialable inits.
13222       if (!MD->isUnavailable())
13223         Diag(MD->getLocation(),
13224              diag::warn_objc_secondary_init_missing_init_call);
13225       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13226     }
13227   } else {
13228     // Parsing the function declaration failed in some way. Pop the fake scope
13229     // we pushed on.
13230     PopFunctionScopeInfo(ActivePolicy, dcl);
13231     return nullptr;
13232   }
13233 
13234   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13235     DiagnoseUnguardedAvailabilityViolations(dcl);
13236 
13237   assert(!getCurFunction()->ObjCShouldCallSuper &&
13238          "This should only be set for ObjC methods, which should have been "
13239          "handled in the block above.");
13240 
13241   // Verify and clean out per-function state.
13242   if (Body && (!FD || !FD->isDefaulted())) {
13243     // C++ constructors that have function-try-blocks can't have return
13244     // statements in the handlers of that block. (C++ [except.handle]p14)
13245     // Verify this.
13246     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13247       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13248 
13249     // Verify that gotos and switch cases don't jump into scopes illegally.
13250     if (getCurFunction()->NeedsScopeChecking() &&
13251         !PP.isCodeCompletionEnabled())
13252       DiagnoseInvalidJumps(Body);
13253 
13254     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13255       if (!Destructor->getParent()->isDependentType())
13256         CheckDestructor(Destructor);
13257 
13258       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13259                                              Destructor->getParent());
13260     }
13261 
13262     // If any errors have occurred, clear out any temporaries that may have
13263     // been leftover. This ensures that these temporaries won't be picked up for
13264     // deletion in some later function.
13265     if (getDiagnostics().hasErrorOccurred() ||
13266         getDiagnostics().getSuppressAllDiagnostics()) {
13267       DiscardCleanupsInEvaluationContext();
13268     }
13269     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13270         !isa<FunctionTemplateDecl>(dcl)) {
13271       // Since the body is valid, issue any analysis-based warnings that are
13272       // enabled.
13273       ActivePolicy = &WP;
13274     }
13275 
13276     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13277         (!CheckConstexprFunctionDecl(FD) ||
13278          !CheckConstexprFunctionBody(FD, Body)))
13279       FD->setInvalidDecl();
13280 
13281     if (FD && FD->hasAttr<NakedAttr>()) {
13282       for (const Stmt *S : Body->children()) {
13283         // Allow local register variables without initializer as they don't
13284         // require prologue.
13285         bool RegisterVariables = false;
13286         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13287           for (const auto *Decl : DS->decls()) {
13288             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13289               RegisterVariables =
13290                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13291               if (!RegisterVariables)
13292                 break;
13293             }
13294           }
13295         }
13296         if (RegisterVariables)
13297           continue;
13298         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13299           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13300           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13301           FD->setInvalidDecl();
13302           break;
13303         }
13304       }
13305     }
13306 
13307     assert(ExprCleanupObjects.size() ==
13308                ExprEvalContexts.back().NumCleanupObjects &&
13309            "Leftover temporaries in function");
13310     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13311     assert(MaybeODRUseExprs.empty() &&
13312            "Leftover expressions for odr-use checking");
13313   }
13314 
13315   if (!IsInstantiation)
13316     PopDeclContext();
13317 
13318   PopFunctionScopeInfo(ActivePolicy, dcl);
13319   // If any errors have occurred, clear out any temporaries that may have
13320   // been leftover. This ensures that these temporaries won't be picked up for
13321   // deletion in some later function.
13322   if (getDiagnostics().hasErrorOccurred()) {
13323     DiscardCleanupsInEvaluationContext();
13324   }
13325 
13326   return dcl;
13327 }
13328 
13329 /// When we finish delayed parsing of an attribute, we must attach it to the
13330 /// relevant Decl.
13331 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13332                                        ParsedAttributes &Attrs) {
13333   // Always attach attributes to the underlying decl.
13334   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13335     D = TD->getTemplatedDecl();
13336   ProcessDeclAttributeList(S, D, Attrs);
13337 
13338   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13339     if (Method->isStatic())
13340       checkThisInStaticMemberFunctionAttributes(Method);
13341 }
13342 
13343 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13344 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13345 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13346                                           IdentifierInfo &II, Scope *S) {
13347   // Find the scope in which the identifier is injected and the corresponding
13348   // DeclContext.
13349   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13350   // In that case, we inject the declaration into the translation unit scope
13351   // instead.
13352   Scope *BlockScope = S;
13353   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13354     BlockScope = BlockScope->getParent();
13355 
13356   Scope *ContextScope = BlockScope;
13357   while (!ContextScope->getEntity())
13358     ContextScope = ContextScope->getParent();
13359   ContextRAII SavedContext(*this, ContextScope->getEntity());
13360 
13361   // Before we produce a declaration for an implicitly defined
13362   // function, see whether there was a locally-scoped declaration of
13363   // this name as a function or variable. If so, use that
13364   // (non-visible) declaration, and complain about it.
13365   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13366   if (ExternCPrev) {
13367     // We still need to inject the function into the enclosing block scope so
13368     // that later (non-call) uses can see it.
13369     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13370 
13371     // C89 footnote 38:
13372     //   If in fact it is not defined as having type "function returning int",
13373     //   the behavior is undefined.
13374     if (!isa<FunctionDecl>(ExternCPrev) ||
13375         !Context.typesAreCompatible(
13376             cast<FunctionDecl>(ExternCPrev)->getType(),
13377             Context.getFunctionNoProtoType(Context.IntTy))) {
13378       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13379           << ExternCPrev << !getLangOpts().C99;
13380       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13381       return ExternCPrev;
13382     }
13383   }
13384 
13385   // Extension in C99.  Legal in C90, but warn about it.
13386   unsigned diag_id;
13387   if (II.getName().startswith("__builtin_"))
13388     diag_id = diag::warn_builtin_unknown;
13389   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13390   else if (getLangOpts().OpenCL)
13391     diag_id = diag::err_opencl_implicit_function_decl;
13392   else if (getLangOpts().C99)
13393     diag_id = diag::ext_implicit_function_decl;
13394   else
13395     diag_id = diag::warn_implicit_function_decl;
13396   Diag(Loc, diag_id) << &II;
13397 
13398   // If we found a prior declaration of this function, don't bother building
13399   // another one. We've already pushed that one into scope, so there's nothing
13400   // more to do.
13401   if (ExternCPrev)
13402     return ExternCPrev;
13403 
13404   // Because typo correction is expensive, only do it if the implicit
13405   // function declaration is going to be treated as an error.
13406   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13407     TypoCorrection Corrected;
13408     if (S &&
13409         (Corrected = CorrectTypo(
13410              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13411              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13412       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13413                    /*ErrorRecovery*/false);
13414   }
13415 
13416   // Set a Declarator for the implicit definition: int foo();
13417   const char *Dummy;
13418   AttributeFactory attrFactory;
13419   DeclSpec DS(attrFactory);
13420   unsigned DiagID;
13421   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13422                                   Context.getPrintingPolicy());
13423   (void)Error; // Silence warning.
13424   assert(!Error && "Error setting up implicit decl!");
13425   SourceLocation NoLoc;
13426   Declarator D(DS, DeclaratorContext::BlockContext);
13427   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13428                                              /*IsAmbiguous=*/false,
13429                                              /*LParenLoc=*/NoLoc,
13430                                              /*Params=*/nullptr,
13431                                              /*NumParams=*/0,
13432                                              /*EllipsisLoc=*/NoLoc,
13433                                              /*RParenLoc=*/NoLoc,
13434                                              /*TypeQuals=*/0,
13435                                              /*RefQualifierIsLvalueRef=*/true,
13436                                              /*RefQualifierLoc=*/NoLoc,
13437                                              /*ConstQualifierLoc=*/NoLoc,
13438                                              /*VolatileQualifierLoc=*/NoLoc,
13439                                              /*RestrictQualifierLoc=*/NoLoc,
13440                                              /*MutableLoc=*/NoLoc, EST_None,
13441                                              /*ESpecRange=*/SourceRange(),
13442                                              /*Exceptions=*/nullptr,
13443                                              /*ExceptionRanges=*/nullptr,
13444                                              /*NumExceptions=*/0,
13445                                              /*NoexceptExpr=*/nullptr,
13446                                              /*ExceptionSpecTokens=*/nullptr,
13447                                              /*DeclsInPrototype=*/None, Loc,
13448                                              Loc, D),
13449                 std::move(DS.getAttributes()), SourceLocation());
13450   D.SetIdentifier(&II, Loc);
13451 
13452   // Insert this function into the enclosing block scope.
13453   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13454   FD->setImplicit();
13455 
13456   AddKnownFunctionAttributes(FD);
13457 
13458   return FD;
13459 }
13460 
13461 /// Adds any function attributes that we know a priori based on
13462 /// the declaration of this function.
13463 ///
13464 /// These attributes can apply both to implicitly-declared builtins
13465 /// (like __builtin___printf_chk) or to library-declared functions
13466 /// like NSLog or printf.
13467 ///
13468 /// We need to check for duplicate attributes both here and where user-written
13469 /// attributes are applied to declarations.
13470 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13471   if (FD->isInvalidDecl())
13472     return;
13473 
13474   // If this is a built-in function, map its builtin attributes to
13475   // actual attributes.
13476   if (unsigned BuiltinID = FD->getBuiltinID()) {
13477     // Handle printf-formatting attributes.
13478     unsigned FormatIdx;
13479     bool HasVAListArg;
13480     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13481       if (!FD->hasAttr<FormatAttr>()) {
13482         const char *fmt = "printf";
13483         unsigned int NumParams = FD->getNumParams();
13484         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13485             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13486           fmt = "NSString";
13487         FD->addAttr(FormatAttr::CreateImplicit(Context,
13488                                                &Context.Idents.get(fmt),
13489                                                FormatIdx+1,
13490                                                HasVAListArg ? 0 : FormatIdx+2,
13491                                                FD->getLocation()));
13492       }
13493     }
13494     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13495                                              HasVAListArg)) {
13496      if (!FD->hasAttr<FormatAttr>())
13497        FD->addAttr(FormatAttr::CreateImplicit(Context,
13498                                               &Context.Idents.get("scanf"),
13499                                               FormatIdx+1,
13500                                               HasVAListArg ? 0 : FormatIdx+2,
13501                                               FD->getLocation()));
13502     }
13503 
13504     // Mark const if we don't care about errno and that is the only thing
13505     // preventing the function from being const. This allows IRgen to use LLVM
13506     // intrinsics for such functions.
13507     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13508         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13509       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13510 
13511     // We make "fma" on some platforms const because we know it does not set
13512     // errno in those environments even though it could set errno based on the
13513     // C standard.
13514     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13515     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13516         !FD->hasAttr<ConstAttr>()) {
13517       switch (BuiltinID) {
13518       case Builtin::BI__builtin_fma:
13519       case Builtin::BI__builtin_fmaf:
13520       case Builtin::BI__builtin_fmal:
13521       case Builtin::BIfma:
13522       case Builtin::BIfmaf:
13523       case Builtin::BIfmal:
13524         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13525         break;
13526       default:
13527         break;
13528       }
13529     }
13530 
13531     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13532         !FD->hasAttr<ReturnsTwiceAttr>())
13533       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13534                                          FD->getLocation()));
13535     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13536       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13537     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13538       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13539     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13540       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13541     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13542         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13543       // Add the appropriate attribute, depending on the CUDA compilation mode
13544       // and which target the builtin belongs to. For example, during host
13545       // compilation, aux builtins are __device__, while the rest are __host__.
13546       if (getLangOpts().CUDAIsDevice !=
13547           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13548         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13549       else
13550         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13551     }
13552   }
13553 
13554   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13555   // throw, add an implicit nothrow attribute to any extern "C" function we come
13556   // across.
13557   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13558       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13559     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13560     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13561       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13562   }
13563 
13564   IdentifierInfo *Name = FD->getIdentifier();
13565   if (!Name)
13566     return;
13567   if ((!getLangOpts().CPlusPlus &&
13568        FD->getDeclContext()->isTranslationUnit()) ||
13569       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13570        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13571        LinkageSpecDecl::lang_c)) {
13572     // Okay: this could be a libc/libm/Objective-C function we know
13573     // about.
13574   } else
13575     return;
13576 
13577   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13578     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13579     // target-specific builtins, perhaps?
13580     if (!FD->hasAttr<FormatAttr>())
13581       FD->addAttr(FormatAttr::CreateImplicit(Context,
13582                                              &Context.Idents.get("printf"), 2,
13583                                              Name->isStr("vasprintf") ? 0 : 3,
13584                                              FD->getLocation()));
13585   }
13586 
13587   if (Name->isStr("__CFStringMakeConstantString")) {
13588     // We already have a __builtin___CFStringMakeConstantString,
13589     // but builds that use -fno-constant-cfstrings don't go through that.
13590     if (!FD->hasAttr<FormatArgAttr>())
13591       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13592                                                 FD->getLocation()));
13593   }
13594 }
13595 
13596 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13597                                     TypeSourceInfo *TInfo) {
13598   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13599   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13600 
13601   if (!TInfo) {
13602     assert(D.isInvalidType() && "no declarator info for valid type");
13603     TInfo = Context.getTrivialTypeSourceInfo(T);
13604   }
13605 
13606   // Scope manipulation handled by caller.
13607   TypedefDecl *NewTD =
13608       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13609                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13610 
13611   // Bail out immediately if we have an invalid declaration.
13612   if (D.isInvalidType()) {
13613     NewTD->setInvalidDecl();
13614     return NewTD;
13615   }
13616 
13617   if (D.getDeclSpec().isModulePrivateSpecified()) {
13618     if (CurContext->isFunctionOrMethod())
13619       Diag(NewTD->getLocation(), diag::err_module_private_local)
13620         << 2 << NewTD->getDeclName()
13621         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13622         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13623     else
13624       NewTD->setModulePrivate();
13625   }
13626 
13627   // C++ [dcl.typedef]p8:
13628   //   If the typedef declaration defines an unnamed class (or
13629   //   enum), the first typedef-name declared by the declaration
13630   //   to be that class type (or enum type) is used to denote the
13631   //   class type (or enum type) for linkage purposes only.
13632   // We need to check whether the type was declared in the declaration.
13633   switch (D.getDeclSpec().getTypeSpecType()) {
13634   case TST_enum:
13635   case TST_struct:
13636   case TST_interface:
13637   case TST_union:
13638   case TST_class: {
13639     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13640     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13641     break;
13642   }
13643 
13644   default:
13645     break;
13646   }
13647 
13648   return NewTD;
13649 }
13650 
13651 /// Check that this is a valid underlying type for an enum declaration.
13652 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13653   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13654   QualType T = TI->getType();
13655 
13656   if (T->isDependentType())
13657     return false;
13658 
13659   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13660     if (BT->isInteger())
13661       return false;
13662 
13663   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13664   return true;
13665 }
13666 
13667 /// Check whether this is a valid redeclaration of a previous enumeration.
13668 /// \return true if the redeclaration was invalid.
13669 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13670                                   QualType EnumUnderlyingTy, bool IsFixed,
13671                                   const EnumDecl *Prev) {
13672   if (IsScoped != Prev->isScoped()) {
13673     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13674       << Prev->isScoped();
13675     Diag(Prev->getLocation(), diag::note_previous_declaration);
13676     return true;
13677   }
13678 
13679   if (IsFixed && Prev->isFixed()) {
13680     if (!EnumUnderlyingTy->isDependentType() &&
13681         !Prev->getIntegerType()->isDependentType() &&
13682         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13683                                         Prev->getIntegerType())) {
13684       // TODO: Highlight the underlying type of the redeclaration.
13685       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13686         << EnumUnderlyingTy << Prev->getIntegerType();
13687       Diag(Prev->getLocation(), diag::note_previous_declaration)
13688           << Prev->getIntegerTypeRange();
13689       return true;
13690     }
13691   } else if (IsFixed != Prev->isFixed()) {
13692     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13693       << Prev->isFixed();
13694     Diag(Prev->getLocation(), diag::note_previous_declaration);
13695     return true;
13696   }
13697 
13698   return false;
13699 }
13700 
13701 /// Get diagnostic %select index for tag kind for
13702 /// redeclaration diagnostic message.
13703 /// WARNING: Indexes apply to particular diagnostics only!
13704 ///
13705 /// \returns diagnostic %select index.
13706 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13707   switch (Tag) {
13708   case TTK_Struct: return 0;
13709   case TTK_Interface: return 1;
13710   case TTK_Class:  return 2;
13711   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13712   }
13713 }
13714 
13715 /// Determine if tag kind is a class-key compatible with
13716 /// class for redeclaration (class, struct, or __interface).
13717 ///
13718 /// \returns true iff the tag kind is compatible.
13719 static bool isClassCompatTagKind(TagTypeKind Tag)
13720 {
13721   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13722 }
13723 
13724 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13725                                              TagTypeKind TTK) {
13726   if (isa<TypedefDecl>(PrevDecl))
13727     return NTK_Typedef;
13728   else if (isa<TypeAliasDecl>(PrevDecl))
13729     return NTK_TypeAlias;
13730   else if (isa<ClassTemplateDecl>(PrevDecl))
13731     return NTK_Template;
13732   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13733     return NTK_TypeAliasTemplate;
13734   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13735     return NTK_TemplateTemplateArgument;
13736   switch (TTK) {
13737   case TTK_Struct:
13738   case TTK_Interface:
13739   case TTK_Class:
13740     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13741   case TTK_Union:
13742     return NTK_NonUnion;
13743   case TTK_Enum:
13744     return NTK_NonEnum;
13745   }
13746   llvm_unreachable("invalid TTK");
13747 }
13748 
13749 /// Determine whether a tag with a given kind is acceptable
13750 /// as a redeclaration of the given tag declaration.
13751 ///
13752 /// \returns true if the new tag kind is acceptable, false otherwise.
13753 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13754                                         TagTypeKind NewTag, bool isDefinition,
13755                                         SourceLocation NewTagLoc,
13756                                         const IdentifierInfo *Name) {
13757   // C++ [dcl.type.elab]p3:
13758   //   The class-key or enum keyword present in the
13759   //   elaborated-type-specifier shall agree in kind with the
13760   //   declaration to which the name in the elaborated-type-specifier
13761   //   refers. This rule also applies to the form of
13762   //   elaborated-type-specifier that declares a class-name or
13763   //   friend class since it can be construed as referring to the
13764   //   definition of the class. Thus, in any
13765   //   elaborated-type-specifier, the enum keyword shall be used to
13766   //   refer to an enumeration (7.2), the union class-key shall be
13767   //   used to refer to a union (clause 9), and either the class or
13768   //   struct class-key shall be used to refer to a class (clause 9)
13769   //   declared using the class or struct class-key.
13770   TagTypeKind OldTag = Previous->getTagKind();
13771   if (!isDefinition || !isClassCompatTagKind(NewTag))
13772     if (OldTag == NewTag)
13773       return true;
13774 
13775   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13776     // Warn about the struct/class tag mismatch.
13777     bool isTemplate = false;
13778     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13779       isTemplate = Record->getDescribedClassTemplate();
13780 
13781     if (inTemplateInstantiation()) {
13782       // In a template instantiation, do not offer fix-its for tag mismatches
13783       // since they usually mess up the template instead of fixing the problem.
13784       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13785         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13786         << getRedeclDiagFromTagKind(OldTag);
13787       return true;
13788     }
13789 
13790     if (isDefinition) {
13791       // On definitions, check previous tags and issue a fix-it for each
13792       // one that doesn't match the current tag.
13793       if (Previous->getDefinition()) {
13794         // Don't suggest fix-its for redefinitions.
13795         return true;
13796       }
13797 
13798       bool previousMismatch = false;
13799       for (auto I : Previous->redecls()) {
13800         if (I->getTagKind() != NewTag) {
13801           if (!previousMismatch) {
13802             previousMismatch = true;
13803             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13804               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13805               << getRedeclDiagFromTagKind(I->getTagKind());
13806           }
13807           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13808             << getRedeclDiagFromTagKind(NewTag)
13809             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13810                  TypeWithKeyword::getTagTypeKindName(NewTag));
13811         }
13812       }
13813       return true;
13814     }
13815 
13816     // Check for a previous definition.  If current tag and definition
13817     // are same type, do nothing.  If no definition, but disagree with
13818     // with previous tag type, give a warning, but no fix-it.
13819     const TagDecl *Redecl = Previous->getDefinition() ?
13820                             Previous->getDefinition() : Previous;
13821     if (Redecl->getTagKind() == NewTag) {
13822       return true;
13823     }
13824 
13825     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13826       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13827       << getRedeclDiagFromTagKind(OldTag);
13828     Diag(Redecl->getLocation(), diag::note_previous_use);
13829 
13830     // If there is a previous definition, suggest a fix-it.
13831     if (Previous->getDefinition()) {
13832         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13833           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13834           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13835                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13836     }
13837 
13838     return true;
13839   }
13840   return false;
13841 }
13842 
13843 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13844 /// from an outer enclosing namespace or file scope inside a friend declaration.
13845 /// This should provide the commented out code in the following snippet:
13846 ///   namespace N {
13847 ///     struct X;
13848 ///     namespace M {
13849 ///       struct Y { friend struct /*N::*/ X; };
13850 ///     }
13851 ///   }
13852 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13853                                          SourceLocation NameLoc) {
13854   // While the decl is in a namespace, do repeated lookup of that name and see
13855   // if we get the same namespace back.  If we do not, continue until
13856   // translation unit scope, at which point we have a fully qualified NNS.
13857   SmallVector<IdentifierInfo *, 4> Namespaces;
13858   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13859   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13860     // This tag should be declared in a namespace, which can only be enclosed by
13861     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13862     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13863     if (!Namespace || Namespace->isAnonymousNamespace())
13864       return FixItHint();
13865     IdentifierInfo *II = Namespace->getIdentifier();
13866     Namespaces.push_back(II);
13867     NamedDecl *Lookup = SemaRef.LookupSingleName(
13868         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13869     if (Lookup == Namespace)
13870       break;
13871   }
13872 
13873   // Once we have all the namespaces, reverse them to go outermost first, and
13874   // build an NNS.
13875   SmallString<64> Insertion;
13876   llvm::raw_svector_ostream OS(Insertion);
13877   if (DC->isTranslationUnit())
13878     OS << "::";
13879   std::reverse(Namespaces.begin(), Namespaces.end());
13880   for (auto *II : Namespaces)
13881     OS << II->getName() << "::";
13882   return FixItHint::CreateInsertion(NameLoc, Insertion);
13883 }
13884 
13885 /// Determine whether a tag originally declared in context \p OldDC can
13886 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13887 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13888 /// using-declaration).
13889 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13890                                          DeclContext *NewDC) {
13891   OldDC = OldDC->getRedeclContext();
13892   NewDC = NewDC->getRedeclContext();
13893 
13894   if (OldDC->Equals(NewDC))
13895     return true;
13896 
13897   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13898   // encloses the other).
13899   if (S.getLangOpts().MSVCCompat &&
13900       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13901     return true;
13902 
13903   return false;
13904 }
13905 
13906 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
13907 /// former case, Name will be non-null.  In the later case, Name will be null.
13908 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13909 /// reference/declaration/definition of a tag.
13910 ///
13911 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13912 /// trailing-type-specifier) other than one in an alias-declaration.
13913 ///
13914 /// \param SkipBody If non-null, will be set to indicate if the caller should
13915 /// skip the definition of this tag and treat it as if it were a declaration.
13916 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13917                      SourceLocation KWLoc, CXXScopeSpec &SS,
13918                      IdentifierInfo *Name, SourceLocation NameLoc,
13919                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
13920                      SourceLocation ModulePrivateLoc,
13921                      MultiTemplateParamsArg TemplateParameterLists,
13922                      bool &OwnedDecl, bool &IsDependent,
13923                      SourceLocation ScopedEnumKWLoc,
13924                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
13925                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13926                      SkipBodyInfo *SkipBody) {
13927   // If this is not a definition, it must have a name.
13928   IdentifierInfo *OrigName = Name;
13929   assert((Name != nullptr || TUK == TUK_Definition) &&
13930          "Nameless record must be a definition!");
13931   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13932 
13933   OwnedDecl = false;
13934   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13935   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13936 
13937   // FIXME: Check member specializations more carefully.
13938   bool isMemberSpecialization = false;
13939   bool Invalid = false;
13940 
13941   // We only need to do this matching if we have template parameters
13942   // or a scope specifier, which also conveniently avoids this work
13943   // for non-C++ cases.
13944   if (TemplateParameterLists.size() > 0 ||
13945       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13946     if (TemplateParameterList *TemplateParams =
13947             MatchTemplateParametersToScopeSpecifier(
13948                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13949                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13950       if (Kind == TTK_Enum) {
13951         Diag(KWLoc, diag::err_enum_template);
13952         return nullptr;
13953       }
13954 
13955       if (TemplateParams->size() > 0) {
13956         // This is a declaration or definition of a class template (which may
13957         // be a member of another template).
13958 
13959         if (Invalid)
13960           return nullptr;
13961 
13962         OwnedDecl = false;
13963         DeclResult Result = CheckClassTemplate(
13964             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
13965             AS, ModulePrivateLoc,
13966             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
13967             TemplateParameterLists.data(), SkipBody);
13968         return Result.get();
13969       } else {
13970         // The "template<>" header is extraneous.
13971         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13972           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13973         isMemberSpecialization = true;
13974       }
13975     }
13976   }
13977 
13978   // Figure out the underlying type if this a enum declaration. We need to do
13979   // this early, because it's needed to detect if this is an incompatible
13980   // redeclaration.
13981   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13982   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13983 
13984   if (Kind == TTK_Enum) {
13985     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13986       // No underlying type explicitly specified, or we failed to parse the
13987       // type, default to int.
13988       EnumUnderlying = Context.IntTy.getTypePtr();
13989     } else if (UnderlyingType.get()) {
13990       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13991       // integral type; any cv-qualification is ignored.
13992       TypeSourceInfo *TI = nullptr;
13993       GetTypeFromParser(UnderlyingType.get(), &TI);
13994       EnumUnderlying = TI;
13995 
13996       if (CheckEnumUnderlyingType(TI))
13997         // Recover by falling back to int.
13998         EnumUnderlying = Context.IntTy.getTypePtr();
13999 
14000       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14001                                           UPPC_FixedUnderlyingType))
14002         EnumUnderlying = Context.IntTy.getTypePtr();
14003 
14004     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14005       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14006       // of 'int'. However, if this is an unfixed forward declaration, don't set
14007       // the underlying type unless the user enables -fms-compatibility. This
14008       // makes unfixed forward declared enums incomplete and is more conforming.
14009       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14010         EnumUnderlying = Context.IntTy.getTypePtr();
14011     }
14012   }
14013 
14014   DeclContext *SearchDC = CurContext;
14015   DeclContext *DC = CurContext;
14016   bool isStdBadAlloc = false;
14017   bool isStdAlignValT = false;
14018 
14019   RedeclarationKind Redecl = forRedeclarationInCurContext();
14020   if (TUK == TUK_Friend || TUK == TUK_Reference)
14021     Redecl = NotForRedeclaration;
14022 
14023   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14024   /// implemented asks for structural equivalence checking, the returned decl
14025   /// here is passed back to the parser, allowing the tag body to be parsed.
14026   auto createTagFromNewDecl = [&]() -> TagDecl * {
14027     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14028     // If there is an identifier, use the location of the identifier as the
14029     // location of the decl, otherwise use the location of the struct/union
14030     // keyword.
14031     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14032     TagDecl *New = nullptr;
14033 
14034     if (Kind == TTK_Enum) {
14035       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14036                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14037       // If this is an undefined enum, bail.
14038       if (TUK != TUK_Definition && !Invalid)
14039         return nullptr;
14040       if (EnumUnderlying) {
14041         EnumDecl *ED = cast<EnumDecl>(New);
14042         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14043           ED->setIntegerTypeSourceInfo(TI);
14044         else
14045           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14046         ED->setPromotionType(ED->getIntegerType());
14047       }
14048     } else { // struct/union
14049       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14050                                nullptr);
14051     }
14052 
14053     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14054       // Add alignment attributes if necessary; these attributes are checked
14055       // when the ASTContext lays out the structure.
14056       //
14057       // It is important for implementing the correct semantics that this
14058       // happen here (in ActOnTag). The #pragma pack stack is
14059       // maintained as a result of parser callbacks which can occur at
14060       // many points during the parsing of a struct declaration (because
14061       // the #pragma tokens are effectively skipped over during the
14062       // parsing of the struct).
14063       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14064         AddAlignmentAttributesForRecord(RD);
14065         AddMsStructLayoutForRecord(RD);
14066       }
14067     }
14068     New->setLexicalDeclContext(CurContext);
14069     return New;
14070   };
14071 
14072   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14073   if (Name && SS.isNotEmpty()) {
14074     // We have a nested-name tag ('struct foo::bar').
14075 
14076     // Check for invalid 'foo::'.
14077     if (SS.isInvalid()) {
14078       Name = nullptr;
14079       goto CreateNewDecl;
14080     }
14081 
14082     // If this is a friend or a reference to a class in a dependent
14083     // context, don't try to make a decl for it.
14084     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14085       DC = computeDeclContext(SS, false);
14086       if (!DC) {
14087         IsDependent = true;
14088         return nullptr;
14089       }
14090     } else {
14091       DC = computeDeclContext(SS, true);
14092       if (!DC) {
14093         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14094           << SS.getRange();
14095         return nullptr;
14096       }
14097     }
14098 
14099     if (RequireCompleteDeclContext(SS, DC))
14100       return nullptr;
14101 
14102     SearchDC = DC;
14103     // Look-up name inside 'foo::'.
14104     LookupQualifiedName(Previous, DC);
14105 
14106     if (Previous.isAmbiguous())
14107       return nullptr;
14108 
14109     if (Previous.empty()) {
14110       // Name lookup did not find anything. However, if the
14111       // nested-name-specifier refers to the current instantiation,
14112       // and that current instantiation has any dependent base
14113       // classes, we might find something at instantiation time: treat
14114       // this as a dependent elaborated-type-specifier.
14115       // But this only makes any sense for reference-like lookups.
14116       if (Previous.wasNotFoundInCurrentInstantiation() &&
14117           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14118         IsDependent = true;
14119         return nullptr;
14120       }
14121 
14122       // A tag 'foo::bar' must already exist.
14123       Diag(NameLoc, diag::err_not_tag_in_scope)
14124         << Kind << Name << DC << SS.getRange();
14125       Name = nullptr;
14126       Invalid = true;
14127       goto CreateNewDecl;
14128     }
14129   } else if (Name) {
14130     // C++14 [class.mem]p14:
14131     //   If T is the name of a class, then each of the following shall have a
14132     //   name different from T:
14133     //    -- every member of class T that is itself a type
14134     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14135         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14136       return nullptr;
14137 
14138     // If this is a named struct, check to see if there was a previous forward
14139     // declaration or definition.
14140     // FIXME: We're looking into outer scopes here, even when we
14141     // shouldn't be. Doing so can result in ambiguities that we
14142     // shouldn't be diagnosing.
14143     LookupName(Previous, S);
14144 
14145     // When declaring or defining a tag, ignore ambiguities introduced
14146     // by types using'ed into this scope.
14147     if (Previous.isAmbiguous() &&
14148         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14149       LookupResult::Filter F = Previous.makeFilter();
14150       while (F.hasNext()) {
14151         NamedDecl *ND = F.next();
14152         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14153                 SearchDC->getRedeclContext()))
14154           F.erase();
14155       }
14156       F.done();
14157     }
14158 
14159     // C++11 [namespace.memdef]p3:
14160     //   If the name in a friend declaration is neither qualified nor
14161     //   a template-id and the declaration is a function or an
14162     //   elaborated-type-specifier, the lookup to determine whether
14163     //   the entity has been previously declared shall not consider
14164     //   any scopes outside the innermost enclosing namespace.
14165     //
14166     // MSVC doesn't implement the above rule for types, so a friend tag
14167     // declaration may be a redeclaration of a type declared in an enclosing
14168     // scope.  They do implement this rule for friend functions.
14169     //
14170     // Does it matter that this should be by scope instead of by
14171     // semantic context?
14172     if (!Previous.empty() && TUK == TUK_Friend) {
14173       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14174       LookupResult::Filter F = Previous.makeFilter();
14175       bool FriendSawTagOutsideEnclosingNamespace = false;
14176       while (F.hasNext()) {
14177         NamedDecl *ND = F.next();
14178         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14179         if (DC->isFileContext() &&
14180             !EnclosingNS->Encloses(ND->getDeclContext())) {
14181           if (getLangOpts().MSVCCompat)
14182             FriendSawTagOutsideEnclosingNamespace = true;
14183           else
14184             F.erase();
14185         }
14186       }
14187       F.done();
14188 
14189       // Diagnose this MSVC extension in the easy case where lookup would have
14190       // unambiguously found something outside the enclosing namespace.
14191       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14192         NamedDecl *ND = Previous.getFoundDecl();
14193         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14194             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14195       }
14196     }
14197 
14198     // Note:  there used to be some attempt at recovery here.
14199     if (Previous.isAmbiguous())
14200       return nullptr;
14201 
14202     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14203       // FIXME: This makes sure that we ignore the contexts associated
14204       // with C structs, unions, and enums when looking for a matching
14205       // tag declaration or definition. See the similar lookup tweak
14206       // in Sema::LookupName; is there a better way to deal with this?
14207       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14208         SearchDC = SearchDC->getParent();
14209     }
14210   }
14211 
14212   if (Previous.isSingleResult() &&
14213       Previous.getFoundDecl()->isTemplateParameter()) {
14214     // Maybe we will complain about the shadowed template parameter.
14215     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14216     // Just pretend that we didn't see the previous declaration.
14217     Previous.clear();
14218   }
14219 
14220   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14221       DC->Equals(getStdNamespace())) {
14222     if (Name->isStr("bad_alloc")) {
14223       // This is a declaration of or a reference to "std::bad_alloc".
14224       isStdBadAlloc = true;
14225 
14226       // If std::bad_alloc has been implicitly declared (but made invisible to
14227       // name lookup), fill in this implicit declaration as the previous
14228       // declaration, so that the declarations get chained appropriately.
14229       if (Previous.empty() && StdBadAlloc)
14230         Previous.addDecl(getStdBadAlloc());
14231     } else if (Name->isStr("align_val_t")) {
14232       isStdAlignValT = true;
14233       if (Previous.empty() && StdAlignValT)
14234         Previous.addDecl(getStdAlignValT());
14235     }
14236   }
14237 
14238   // If we didn't find a previous declaration, and this is a reference
14239   // (or friend reference), move to the correct scope.  In C++, we
14240   // also need to do a redeclaration lookup there, just in case
14241   // there's a shadow friend decl.
14242   if (Name && Previous.empty() &&
14243       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14244     if (Invalid) goto CreateNewDecl;
14245     assert(SS.isEmpty());
14246 
14247     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14248       // C++ [basic.scope.pdecl]p5:
14249       //   -- for an elaborated-type-specifier of the form
14250       //
14251       //          class-key identifier
14252       //
14253       //      if the elaborated-type-specifier is used in the
14254       //      decl-specifier-seq or parameter-declaration-clause of a
14255       //      function defined in namespace scope, the identifier is
14256       //      declared as a class-name in the namespace that contains
14257       //      the declaration; otherwise, except as a friend
14258       //      declaration, the identifier is declared in the smallest
14259       //      non-class, non-function-prototype scope that contains the
14260       //      declaration.
14261       //
14262       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14263       // C structs and unions.
14264       //
14265       // It is an error in C++ to declare (rather than define) an enum
14266       // type, including via an elaborated type specifier.  We'll
14267       // diagnose that later; for now, declare the enum in the same
14268       // scope as we would have picked for any other tag type.
14269       //
14270       // GNU C also supports this behavior as part of its incomplete
14271       // enum types extension, while GNU C++ does not.
14272       //
14273       // Find the context where we'll be declaring the tag.
14274       // FIXME: We would like to maintain the current DeclContext as the
14275       // lexical context,
14276       SearchDC = getTagInjectionContext(SearchDC);
14277 
14278       // Find the scope where we'll be declaring the tag.
14279       S = getTagInjectionScope(S, getLangOpts());
14280     } else {
14281       assert(TUK == TUK_Friend);
14282       // C++ [namespace.memdef]p3:
14283       //   If a friend declaration in a non-local class first declares a
14284       //   class or function, the friend class or function is a member of
14285       //   the innermost enclosing namespace.
14286       SearchDC = SearchDC->getEnclosingNamespaceContext();
14287     }
14288 
14289     // In C++, we need to do a redeclaration lookup to properly
14290     // diagnose some problems.
14291     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14292     // hidden declaration so that we don't get ambiguity errors when using a
14293     // type declared by an elaborated-type-specifier.  In C that is not correct
14294     // and we should instead merge compatible types found by lookup.
14295     if (getLangOpts().CPlusPlus) {
14296       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14297       LookupQualifiedName(Previous, SearchDC);
14298     } else {
14299       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14300       LookupName(Previous, S);
14301     }
14302   }
14303 
14304   // If we have a known previous declaration to use, then use it.
14305   if (Previous.empty() && SkipBody && SkipBody->Previous)
14306     Previous.addDecl(SkipBody->Previous);
14307 
14308   if (!Previous.empty()) {
14309     NamedDecl *PrevDecl = Previous.getFoundDecl();
14310     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14311 
14312     // It's okay to have a tag decl in the same scope as a typedef
14313     // which hides a tag decl in the same scope.  Finding this
14314     // insanity with a redeclaration lookup can only actually happen
14315     // in C++.
14316     //
14317     // This is also okay for elaborated-type-specifiers, which is
14318     // technically forbidden by the current standard but which is
14319     // okay according to the likely resolution of an open issue;
14320     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14321     if (getLangOpts().CPlusPlus) {
14322       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14323         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14324           TagDecl *Tag = TT->getDecl();
14325           if (Tag->getDeclName() == Name &&
14326               Tag->getDeclContext()->getRedeclContext()
14327                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14328             PrevDecl = Tag;
14329             Previous.clear();
14330             Previous.addDecl(Tag);
14331             Previous.resolveKind();
14332           }
14333         }
14334       }
14335     }
14336 
14337     // If this is a redeclaration of a using shadow declaration, it must
14338     // declare a tag in the same context. In MSVC mode, we allow a
14339     // redefinition if either context is within the other.
14340     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14341       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14342       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14343           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14344           !(OldTag && isAcceptableTagRedeclContext(
14345                           *this, OldTag->getDeclContext(), SearchDC))) {
14346         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14347         Diag(Shadow->getTargetDecl()->getLocation(),
14348              diag::note_using_decl_target);
14349         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14350             << 0;
14351         // Recover by ignoring the old declaration.
14352         Previous.clear();
14353         goto CreateNewDecl;
14354       }
14355     }
14356 
14357     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14358       // If this is a use of a previous tag, or if the tag is already declared
14359       // in the same scope (so that the definition/declaration completes or
14360       // rementions the tag), reuse the decl.
14361       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14362           isDeclInScope(DirectPrevDecl, SearchDC, S,
14363                         SS.isNotEmpty() || isMemberSpecialization)) {
14364         // Make sure that this wasn't declared as an enum and now used as a
14365         // struct or something similar.
14366         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14367                                           TUK == TUK_Definition, KWLoc,
14368                                           Name)) {
14369           bool SafeToContinue
14370             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14371                Kind != TTK_Enum);
14372           if (SafeToContinue)
14373             Diag(KWLoc, diag::err_use_with_wrong_tag)
14374               << Name
14375               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14376                                               PrevTagDecl->getKindName());
14377           else
14378             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14379           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14380 
14381           if (SafeToContinue)
14382             Kind = PrevTagDecl->getTagKind();
14383           else {
14384             // Recover by making this an anonymous redefinition.
14385             Name = nullptr;
14386             Previous.clear();
14387             Invalid = true;
14388           }
14389         }
14390 
14391         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14392           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14393 
14394           // If this is an elaborated-type-specifier for a scoped enumeration,
14395           // the 'class' keyword is not necessary and not permitted.
14396           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14397             if (ScopedEnum)
14398               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14399                 << PrevEnum->isScoped()
14400                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14401             return PrevTagDecl;
14402           }
14403 
14404           QualType EnumUnderlyingTy;
14405           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14406             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14407           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14408             EnumUnderlyingTy = QualType(T, 0);
14409 
14410           // All conflicts with previous declarations are recovered by
14411           // returning the previous declaration, unless this is a definition,
14412           // in which case we want the caller to bail out.
14413           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14414                                      ScopedEnum, EnumUnderlyingTy,
14415                                      IsFixed, PrevEnum))
14416             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14417         }
14418 
14419         // C++11 [class.mem]p1:
14420         //   A member shall not be declared twice in the member-specification,
14421         //   except that a nested class or member class template can be declared
14422         //   and then later defined.
14423         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14424             S->isDeclScope(PrevDecl)) {
14425           Diag(NameLoc, diag::ext_member_redeclared);
14426           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14427         }
14428 
14429         if (!Invalid) {
14430           // If this is a use, just return the declaration we found, unless
14431           // we have attributes.
14432           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14433             if (!Attrs.empty()) {
14434               // FIXME: Diagnose these attributes. For now, we create a new
14435               // declaration to hold them.
14436             } else if (TUK == TUK_Reference &&
14437                        (PrevTagDecl->getFriendObjectKind() ==
14438                             Decl::FOK_Undeclared ||
14439                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14440                        SS.isEmpty()) {
14441               // This declaration is a reference to an existing entity, but
14442               // has different visibility from that entity: it either makes
14443               // a friend visible or it makes a type visible in a new module.
14444               // In either case, create a new declaration. We only do this if
14445               // the declaration would have meant the same thing if no prior
14446               // declaration were found, that is, if it was found in the same
14447               // scope where we would have injected a declaration.
14448               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14449                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14450                 return PrevTagDecl;
14451               // This is in the injected scope, create a new declaration in
14452               // that scope.
14453               S = getTagInjectionScope(S, getLangOpts());
14454             } else {
14455               return PrevTagDecl;
14456             }
14457           }
14458 
14459           // Diagnose attempts to redefine a tag.
14460           if (TUK == TUK_Definition) {
14461             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14462               // If we're defining a specialization and the previous definition
14463               // is from an implicit instantiation, don't emit an error
14464               // here; we'll catch this in the general case below.
14465               bool IsExplicitSpecializationAfterInstantiation = false;
14466               if (isMemberSpecialization) {
14467                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14468                   IsExplicitSpecializationAfterInstantiation =
14469                     RD->getTemplateSpecializationKind() !=
14470                     TSK_ExplicitSpecialization;
14471                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14472                   IsExplicitSpecializationAfterInstantiation =
14473                     ED->getTemplateSpecializationKind() !=
14474                     TSK_ExplicitSpecialization;
14475               }
14476 
14477               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14478               // not keep more that one definition around (merge them). However,
14479               // ensure the decl passes the structural compatibility check in
14480               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14481               NamedDecl *Hidden = nullptr;
14482               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14483                 // There is a definition of this tag, but it is not visible. We
14484                 // explicitly make use of C++'s one definition rule here, and
14485                 // assume that this definition is identical to the hidden one
14486                 // we already have. Make the existing definition visible and
14487                 // use it in place of this one.
14488                 if (!getLangOpts().CPlusPlus) {
14489                   // Postpone making the old definition visible until after we
14490                   // complete parsing the new one and do the structural
14491                   // comparison.
14492                   SkipBody->CheckSameAsPrevious = true;
14493                   SkipBody->New = createTagFromNewDecl();
14494                   SkipBody->Previous = Def;
14495                   return Def;
14496                 } else {
14497                   SkipBody->ShouldSkip = true;
14498                   SkipBody->Previous = Def;
14499                   makeMergedDefinitionVisible(Hidden);
14500                   // Carry on and handle it like a normal definition. We'll
14501                   // skip starting the definitiion later.
14502                 }
14503               } else if (!IsExplicitSpecializationAfterInstantiation) {
14504                 // A redeclaration in function prototype scope in C isn't
14505                 // visible elsewhere, so merely issue a warning.
14506                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14507                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14508                 else
14509                   Diag(NameLoc, diag::err_redefinition) << Name;
14510                 notePreviousDefinition(Def,
14511                                        NameLoc.isValid() ? NameLoc : KWLoc);
14512                 // If this is a redefinition, recover by making this
14513                 // struct be anonymous, which will make any later
14514                 // references get the previous definition.
14515                 Name = nullptr;
14516                 Previous.clear();
14517                 Invalid = true;
14518               }
14519             } else {
14520               // If the type is currently being defined, complain
14521               // about a nested redefinition.
14522               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14523               if (TD->isBeingDefined()) {
14524                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14525                 Diag(PrevTagDecl->getLocation(),
14526                      diag::note_previous_definition);
14527                 Name = nullptr;
14528                 Previous.clear();
14529                 Invalid = true;
14530               }
14531             }
14532 
14533             // Okay, this is definition of a previously declared or referenced
14534             // tag. We're going to create a new Decl for it.
14535           }
14536 
14537           // Okay, we're going to make a redeclaration.  If this is some kind
14538           // of reference, make sure we build the redeclaration in the same DC
14539           // as the original, and ignore the current access specifier.
14540           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14541             SearchDC = PrevTagDecl->getDeclContext();
14542             AS = AS_none;
14543           }
14544         }
14545         // If we get here we have (another) forward declaration or we
14546         // have a definition.  Just create a new decl.
14547 
14548       } else {
14549         // If we get here, this is a definition of a new tag type in a nested
14550         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14551         // new decl/type.  We set PrevDecl to NULL so that the entities
14552         // have distinct types.
14553         Previous.clear();
14554       }
14555       // If we get here, we're going to create a new Decl. If PrevDecl
14556       // is non-NULL, it's a definition of the tag declared by
14557       // PrevDecl. If it's NULL, we have a new definition.
14558 
14559     // Otherwise, PrevDecl is not a tag, but was found with tag
14560     // lookup.  This is only actually possible in C++, where a few
14561     // things like templates still live in the tag namespace.
14562     } else {
14563       // Use a better diagnostic if an elaborated-type-specifier
14564       // found the wrong kind of type on the first
14565       // (non-redeclaration) lookup.
14566       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14567           !Previous.isForRedeclaration()) {
14568         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14569         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14570                                                        << Kind;
14571         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14572         Invalid = true;
14573 
14574       // Otherwise, only diagnose if the declaration is in scope.
14575       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14576                                 SS.isNotEmpty() || isMemberSpecialization)) {
14577         // do nothing
14578 
14579       // Diagnose implicit declarations introduced by elaborated types.
14580       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14581         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14582         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14583         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14584         Invalid = true;
14585 
14586       // Otherwise it's a declaration.  Call out a particularly common
14587       // case here.
14588       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14589         unsigned Kind = 0;
14590         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14591         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14592           << Name << Kind << TND->getUnderlyingType();
14593         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14594         Invalid = true;
14595 
14596       // Otherwise, diagnose.
14597       } else {
14598         // The tag name clashes with something else in the target scope,
14599         // issue an error and recover by making this tag be anonymous.
14600         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14601         notePreviousDefinition(PrevDecl, NameLoc);
14602         Name = nullptr;
14603         Invalid = true;
14604       }
14605 
14606       // The existing declaration isn't relevant to us; we're in a
14607       // new scope, so clear out the previous declaration.
14608       Previous.clear();
14609     }
14610   }
14611 
14612 CreateNewDecl:
14613 
14614   TagDecl *PrevDecl = nullptr;
14615   if (Previous.isSingleResult())
14616     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14617 
14618   // If there is an identifier, use the location of the identifier as the
14619   // location of the decl, otherwise use the location of the struct/union
14620   // keyword.
14621   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14622 
14623   // Otherwise, create a new declaration. If there is a previous
14624   // declaration of the same entity, the two will be linked via
14625   // PrevDecl.
14626   TagDecl *New;
14627 
14628   if (Kind == TTK_Enum) {
14629     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14630     // enum X { A, B, C } D;    D should chain to X.
14631     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14632                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14633                            ScopedEnumUsesClassTag, IsFixed);
14634 
14635     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14636       StdAlignValT = cast<EnumDecl>(New);
14637 
14638     // If this is an undefined enum, warn.
14639     if (TUK != TUK_Definition && !Invalid) {
14640       TagDecl *Def;
14641       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) &&
14642           cast<EnumDecl>(New)->isFixed()) {
14643         // C++0x: 7.2p2: opaque-enum-declaration.
14644         // Conflicts are diagnosed above. Do nothing.
14645       }
14646       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14647         Diag(Loc, diag::ext_forward_ref_enum_def)
14648           << New;
14649         Diag(Def->getLocation(), diag::note_previous_definition);
14650       } else {
14651         unsigned DiagID = diag::ext_forward_ref_enum;
14652         if (getLangOpts().MSVCCompat)
14653           DiagID = diag::ext_ms_forward_ref_enum;
14654         else if (getLangOpts().CPlusPlus)
14655           DiagID = diag::err_forward_ref_enum;
14656         Diag(Loc, DiagID);
14657       }
14658     }
14659 
14660     if (EnumUnderlying) {
14661       EnumDecl *ED = cast<EnumDecl>(New);
14662       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14663         ED->setIntegerTypeSourceInfo(TI);
14664       else
14665         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14666       ED->setPromotionType(ED->getIntegerType());
14667       assert(ED->isComplete() && "enum with type should be complete");
14668     }
14669   } else {
14670     // struct/union/class
14671 
14672     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14673     // struct X { int A; } D;    D should chain to X.
14674     if (getLangOpts().CPlusPlus) {
14675       // FIXME: Look for a way to use RecordDecl for simple structs.
14676       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14677                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14678 
14679       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14680         StdBadAlloc = cast<CXXRecordDecl>(New);
14681     } else
14682       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14683                                cast_or_null<RecordDecl>(PrevDecl));
14684   }
14685 
14686   // C++11 [dcl.type]p3:
14687   //   A type-specifier-seq shall not define a class or enumeration [...].
14688   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14689       TUK == TUK_Definition) {
14690     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14691       << Context.getTagDeclType(New);
14692     Invalid = true;
14693   }
14694 
14695   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14696       DC->getDeclKind() == Decl::Enum) {
14697     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14698       << Context.getTagDeclType(New);
14699     Invalid = true;
14700   }
14701 
14702   // Maybe add qualifier info.
14703   if (SS.isNotEmpty()) {
14704     if (SS.isSet()) {
14705       // If this is either a declaration or a definition, check the
14706       // nested-name-specifier against the current context.
14707       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14708           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14709                                        isMemberSpecialization))
14710         Invalid = true;
14711 
14712       New->setQualifierInfo(SS.getWithLocInContext(Context));
14713       if (TemplateParameterLists.size() > 0) {
14714         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14715       }
14716     }
14717     else
14718       Invalid = true;
14719   }
14720 
14721   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14722     // Add alignment attributes if necessary; these attributes are checked when
14723     // the ASTContext lays out the structure.
14724     //
14725     // It is important for implementing the correct semantics that this
14726     // happen here (in ActOnTag). The #pragma pack stack is
14727     // maintained as a result of parser callbacks which can occur at
14728     // many points during the parsing of a struct declaration (because
14729     // the #pragma tokens are effectively skipped over during the
14730     // parsing of the struct).
14731     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14732       AddAlignmentAttributesForRecord(RD);
14733       AddMsStructLayoutForRecord(RD);
14734     }
14735   }
14736 
14737   if (ModulePrivateLoc.isValid()) {
14738     if (isMemberSpecialization)
14739       Diag(New->getLocation(), diag::err_module_private_specialization)
14740         << 2
14741         << FixItHint::CreateRemoval(ModulePrivateLoc);
14742     // __module_private__ does not apply to local classes. However, we only
14743     // diagnose this as an error when the declaration specifiers are
14744     // freestanding. Here, we just ignore the __module_private__.
14745     else if (!SearchDC->isFunctionOrMethod())
14746       New->setModulePrivate();
14747   }
14748 
14749   // If this is a specialization of a member class (of a class template),
14750   // check the specialization.
14751   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14752     Invalid = true;
14753 
14754   // If we're declaring or defining a tag in function prototype scope in C,
14755   // note that this type can only be used within the function and add it to
14756   // the list of decls to inject into the function definition scope.
14757   if ((Name || Kind == TTK_Enum) &&
14758       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14759     if (getLangOpts().CPlusPlus) {
14760       // C++ [dcl.fct]p6:
14761       //   Types shall not be defined in return or parameter types.
14762       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14763         Diag(Loc, diag::err_type_defined_in_param_type)
14764             << Name;
14765         Invalid = true;
14766       }
14767     } else if (!PrevDecl) {
14768       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14769     }
14770   }
14771 
14772   if (Invalid)
14773     New->setInvalidDecl();
14774 
14775   // Set the lexical context. If the tag has a C++ scope specifier, the
14776   // lexical context will be different from the semantic context.
14777   New->setLexicalDeclContext(CurContext);
14778 
14779   // Mark this as a friend decl if applicable.
14780   // In Microsoft mode, a friend declaration also acts as a forward
14781   // declaration so we always pass true to setObjectOfFriendDecl to make
14782   // the tag name visible.
14783   if (TUK == TUK_Friend)
14784     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14785 
14786   // Set the access specifier.
14787   if (!Invalid && SearchDC->isRecord())
14788     SetMemberAccessSpecifier(New, PrevDecl, AS);
14789 
14790   if (PrevDecl)
14791     CheckRedeclarationModuleOwnership(New, PrevDecl);
14792 
14793   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14794     New->startDefinition();
14795 
14796   ProcessDeclAttributeList(S, New, Attrs);
14797   AddPragmaAttributes(S, New);
14798 
14799   // If this has an identifier, add it to the scope stack.
14800   if (TUK == TUK_Friend) {
14801     // We might be replacing an existing declaration in the lookup tables;
14802     // if so, borrow its access specifier.
14803     if (PrevDecl)
14804       New->setAccess(PrevDecl->getAccess());
14805 
14806     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14807     DC->makeDeclVisibleInContext(New);
14808     if (Name) // can be null along some error paths
14809       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14810         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14811   } else if (Name) {
14812     S = getNonFieldDeclScope(S);
14813     PushOnScopeChains(New, S, true);
14814   } else {
14815     CurContext->addDecl(New);
14816   }
14817 
14818   // If this is the C FILE type, notify the AST context.
14819   if (IdentifierInfo *II = New->getIdentifier())
14820     if (!New->isInvalidDecl() &&
14821         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14822         II->isStr("FILE"))
14823       Context.setFILEDecl(New);
14824 
14825   if (PrevDecl)
14826     mergeDeclAttributes(New, PrevDecl);
14827 
14828   // If there's a #pragma GCC visibility in scope, set the visibility of this
14829   // record.
14830   AddPushedVisibilityAttribute(New);
14831 
14832   if (isMemberSpecialization && !New->isInvalidDecl())
14833     CompleteMemberSpecialization(New, Previous);
14834 
14835   OwnedDecl = true;
14836   // In C++, don't return an invalid declaration. We can't recover well from
14837   // the cases where we make the type anonymous.
14838   if (Invalid && getLangOpts().CPlusPlus) {
14839     if (New->isBeingDefined())
14840       if (auto RD = dyn_cast<RecordDecl>(New))
14841         RD->completeDefinition();
14842     return nullptr;
14843   } else if (SkipBody && SkipBody->ShouldSkip) {
14844     return SkipBody->Previous;
14845   } else {
14846     return New;
14847   }
14848 }
14849 
14850 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14851   AdjustDeclIfTemplate(TagD);
14852   TagDecl *Tag = cast<TagDecl>(TagD);
14853 
14854   // Enter the tag context.
14855   PushDeclContext(S, Tag);
14856 
14857   ActOnDocumentableDecl(TagD);
14858 
14859   // If there's a #pragma GCC visibility in scope, set the visibility of this
14860   // record.
14861   AddPushedVisibilityAttribute(Tag);
14862 }
14863 
14864 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14865                                     SkipBodyInfo &SkipBody) {
14866   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14867     return false;
14868 
14869   // Make the previous decl visible.
14870   makeMergedDefinitionVisible(SkipBody.Previous);
14871   return true;
14872 }
14873 
14874 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14875   assert(isa<ObjCContainerDecl>(IDecl) &&
14876          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14877   DeclContext *OCD = cast<DeclContext>(IDecl);
14878   assert(getContainingDC(OCD) == CurContext &&
14879       "The next DeclContext should be lexically contained in the current one.");
14880   CurContext = OCD;
14881   return IDecl;
14882 }
14883 
14884 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14885                                            SourceLocation FinalLoc,
14886                                            bool IsFinalSpelledSealed,
14887                                            SourceLocation LBraceLoc) {
14888   AdjustDeclIfTemplate(TagD);
14889   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14890 
14891   FieldCollector->StartClass();
14892 
14893   if (!Record->getIdentifier())
14894     return;
14895 
14896   if (FinalLoc.isValid())
14897     Record->addAttr(new (Context)
14898                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14899 
14900   // C++ [class]p2:
14901   //   [...] The class-name is also inserted into the scope of the
14902   //   class itself; this is known as the injected-class-name. For
14903   //   purposes of access checking, the injected-class-name is treated
14904   //   as if it were a public member name.
14905   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
14906       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
14907       Record->getLocation(), Record->getIdentifier(),
14908       /*PrevDecl=*/nullptr,
14909       /*DelayTypeCreation=*/true);
14910   Context.getTypeDeclType(InjectedClassName, Record);
14911   InjectedClassName->setImplicit();
14912   InjectedClassName->setAccess(AS_public);
14913   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14914       InjectedClassName->setDescribedClassTemplate(Template);
14915   PushOnScopeChains(InjectedClassName, S);
14916   assert(InjectedClassName->isInjectedClassName() &&
14917          "Broken injected-class-name");
14918 }
14919 
14920 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14921                                     SourceRange BraceRange) {
14922   AdjustDeclIfTemplate(TagD);
14923   TagDecl *Tag = cast<TagDecl>(TagD);
14924   Tag->setBraceRange(BraceRange);
14925 
14926   // Make sure we "complete" the definition even it is invalid.
14927   if (Tag->isBeingDefined()) {
14928     assert(Tag->isInvalidDecl() && "We should already have completed it");
14929     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14930       RD->completeDefinition();
14931   }
14932 
14933   if (isa<CXXRecordDecl>(Tag)) {
14934     FieldCollector->FinishClass();
14935   }
14936 
14937   // Exit this scope of this tag's definition.
14938   PopDeclContext();
14939 
14940   if (getCurLexicalContext()->isObjCContainer() &&
14941       Tag->getDeclContext()->isFileContext())
14942     Tag->setTopLevelDeclInObjCContainer();
14943 
14944   // Notify the consumer that we've defined a tag.
14945   if (!Tag->isInvalidDecl())
14946     Consumer.HandleTagDeclDefinition(Tag);
14947 }
14948 
14949 void Sema::ActOnObjCContainerFinishDefinition() {
14950   // Exit this scope of this interface definition.
14951   PopDeclContext();
14952 }
14953 
14954 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14955   assert(DC == CurContext && "Mismatch of container contexts");
14956   OriginalLexicalContext = DC;
14957   ActOnObjCContainerFinishDefinition();
14958 }
14959 
14960 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14961   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14962   OriginalLexicalContext = nullptr;
14963 }
14964 
14965 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14966   AdjustDeclIfTemplate(TagD);
14967   TagDecl *Tag = cast<TagDecl>(TagD);
14968   Tag->setInvalidDecl();
14969 
14970   // Make sure we "complete" the definition even it is invalid.
14971   if (Tag->isBeingDefined()) {
14972     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14973       RD->completeDefinition();
14974   }
14975 
14976   // We're undoing ActOnTagStartDefinition here, not
14977   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14978   // the FieldCollector.
14979 
14980   PopDeclContext();
14981 }
14982 
14983 // Note that FieldName may be null for anonymous bitfields.
14984 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14985                                 IdentifierInfo *FieldName,
14986                                 QualType FieldTy, bool IsMsStruct,
14987                                 Expr *BitWidth, bool *ZeroWidth) {
14988   // Default to true; that shouldn't confuse checks for emptiness
14989   if (ZeroWidth)
14990     *ZeroWidth = true;
14991 
14992   // C99 6.7.2.1p4 - verify the field type.
14993   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14994   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14995     // Handle incomplete types with specific error.
14996     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14997       return ExprError();
14998     if (FieldName)
14999       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15000         << FieldName << FieldTy << BitWidth->getSourceRange();
15001     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15002       << FieldTy << BitWidth->getSourceRange();
15003   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15004                                              UPPC_BitFieldWidth))
15005     return ExprError();
15006 
15007   // If the bit-width is type- or value-dependent, don't try to check
15008   // it now.
15009   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15010     return BitWidth;
15011 
15012   llvm::APSInt Value;
15013   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15014   if (ICE.isInvalid())
15015     return ICE;
15016   BitWidth = ICE.get();
15017 
15018   if (Value != 0 && ZeroWidth)
15019     *ZeroWidth = false;
15020 
15021   // Zero-width bitfield is ok for anonymous field.
15022   if (Value == 0 && FieldName)
15023     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15024 
15025   if (Value.isSigned() && Value.isNegative()) {
15026     if (FieldName)
15027       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15028                << FieldName << Value.toString(10);
15029     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15030       << Value.toString(10);
15031   }
15032 
15033   if (!FieldTy->isDependentType()) {
15034     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15035     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15036     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15037 
15038     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15039     // ABI.
15040     bool CStdConstraintViolation =
15041         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15042     bool MSBitfieldViolation =
15043         Value.ugt(TypeStorageSize) &&
15044         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15045     if (CStdConstraintViolation || MSBitfieldViolation) {
15046       unsigned DiagWidth =
15047           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15048       if (FieldName)
15049         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15050                << FieldName << (unsigned)Value.getZExtValue()
15051                << !CStdConstraintViolation << DiagWidth;
15052 
15053       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15054              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15055              << DiagWidth;
15056     }
15057 
15058     // Warn on types where the user might conceivably expect to get all
15059     // specified bits as value bits: that's all integral types other than
15060     // 'bool'.
15061     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15062       if (FieldName)
15063         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15064             << FieldName << (unsigned)Value.getZExtValue()
15065             << (unsigned)TypeWidth;
15066       else
15067         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15068             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15069     }
15070   }
15071 
15072   return BitWidth;
15073 }
15074 
15075 /// ActOnField - Each field of a C struct/union is passed into this in order
15076 /// to create a FieldDecl object for it.
15077 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15078                        Declarator &D, Expr *BitfieldWidth) {
15079   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15080                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15081                                /*InitStyle=*/ICIS_NoInit, AS_public);
15082   return Res;
15083 }
15084 
15085 /// HandleField - Analyze a field of a C struct or a C++ data member.
15086 ///
15087 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15088                              SourceLocation DeclStart,
15089                              Declarator &D, Expr *BitWidth,
15090                              InClassInitStyle InitStyle,
15091                              AccessSpecifier AS) {
15092   if (D.isDecompositionDeclarator()) {
15093     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15094     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15095       << Decomp.getSourceRange();
15096     return nullptr;
15097   }
15098 
15099   IdentifierInfo *II = D.getIdentifier();
15100   SourceLocation Loc = DeclStart;
15101   if (II) Loc = D.getIdentifierLoc();
15102 
15103   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15104   QualType T = TInfo->getType();
15105   if (getLangOpts().CPlusPlus) {
15106     CheckExtraCXXDefaultArguments(D);
15107 
15108     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15109                                         UPPC_DataMemberType)) {
15110       D.setInvalidType();
15111       T = Context.IntTy;
15112       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15113     }
15114   }
15115 
15116   // TR 18037 does not allow fields to be declared with address spaces.
15117   if (T.getQualifiers().hasAddressSpace() ||
15118       T->isDependentAddressSpaceType() ||
15119       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15120     Diag(Loc, diag::err_field_with_address_space);
15121     D.setInvalidType();
15122   }
15123 
15124   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15125   // used as structure or union field: image, sampler, event or block types.
15126   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
15127                           T->isSamplerT() || T->isBlockPointerType())) {
15128     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15129     D.setInvalidType();
15130   }
15131 
15132   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15133 
15134   if (D.getDeclSpec().isInlineSpecified())
15135     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15136         << getLangOpts().CPlusPlus17;
15137   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15138     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15139          diag::err_invalid_thread)
15140       << DeclSpec::getSpecifierName(TSCS);
15141 
15142   // Check to see if this name was declared as a member previously
15143   NamedDecl *PrevDecl = nullptr;
15144   LookupResult Previous(*this, II, Loc, LookupMemberName,
15145                         ForVisibleRedeclaration);
15146   LookupName(Previous, S);
15147   switch (Previous.getResultKind()) {
15148     case LookupResult::Found:
15149     case LookupResult::FoundUnresolvedValue:
15150       PrevDecl = Previous.getAsSingle<NamedDecl>();
15151       break;
15152 
15153     case LookupResult::FoundOverloaded:
15154       PrevDecl = Previous.getRepresentativeDecl();
15155       break;
15156 
15157     case LookupResult::NotFound:
15158     case LookupResult::NotFoundInCurrentInstantiation:
15159     case LookupResult::Ambiguous:
15160       break;
15161   }
15162   Previous.suppressDiagnostics();
15163 
15164   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15165     // Maybe we will complain about the shadowed template parameter.
15166     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15167     // Just pretend that we didn't see the previous declaration.
15168     PrevDecl = nullptr;
15169   }
15170 
15171   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15172     PrevDecl = nullptr;
15173 
15174   bool Mutable
15175     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15176   SourceLocation TSSL = D.getBeginLoc();
15177   FieldDecl *NewFD
15178     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15179                      TSSL, AS, PrevDecl, &D);
15180 
15181   if (NewFD->isInvalidDecl())
15182     Record->setInvalidDecl();
15183 
15184   if (D.getDeclSpec().isModulePrivateSpecified())
15185     NewFD->setModulePrivate();
15186 
15187   if (NewFD->isInvalidDecl() && PrevDecl) {
15188     // Don't introduce NewFD into scope; there's already something
15189     // with the same name in the same scope.
15190   } else if (II) {
15191     PushOnScopeChains(NewFD, S);
15192   } else
15193     Record->addDecl(NewFD);
15194 
15195   return NewFD;
15196 }
15197 
15198 /// Build a new FieldDecl and check its well-formedness.
15199 ///
15200 /// This routine builds a new FieldDecl given the fields name, type,
15201 /// record, etc. \p PrevDecl should refer to any previous declaration
15202 /// with the same name and in the same scope as the field to be
15203 /// created.
15204 ///
15205 /// \returns a new FieldDecl.
15206 ///
15207 /// \todo The Declarator argument is a hack. It will be removed once
15208 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15209                                 TypeSourceInfo *TInfo,
15210                                 RecordDecl *Record, SourceLocation Loc,
15211                                 bool Mutable, Expr *BitWidth,
15212                                 InClassInitStyle InitStyle,
15213                                 SourceLocation TSSL,
15214                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15215                                 Declarator *D) {
15216   IdentifierInfo *II = Name.getAsIdentifierInfo();
15217   bool InvalidDecl = false;
15218   if (D) InvalidDecl = D->isInvalidType();
15219 
15220   // If we receive a broken type, recover by assuming 'int' and
15221   // marking this declaration as invalid.
15222   if (T.isNull()) {
15223     InvalidDecl = true;
15224     T = Context.IntTy;
15225   }
15226 
15227   QualType EltTy = Context.getBaseElementType(T);
15228   if (!EltTy->isDependentType()) {
15229     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15230       // Fields of incomplete type force their record to be invalid.
15231       Record->setInvalidDecl();
15232       InvalidDecl = true;
15233     } else {
15234       NamedDecl *Def;
15235       EltTy->isIncompleteType(&Def);
15236       if (Def && Def->isInvalidDecl()) {
15237         Record->setInvalidDecl();
15238         InvalidDecl = true;
15239       }
15240     }
15241   }
15242 
15243   // OpenCL v1.2 s6.9.c: bitfields are not supported.
15244   if (BitWidth && getLangOpts().OpenCL) {
15245     Diag(Loc, diag::err_opencl_bitfields);
15246     InvalidDecl = true;
15247   }
15248 
15249   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15250   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15251       T.hasQualifiers()) {
15252     InvalidDecl = true;
15253     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15254   }
15255 
15256   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15257   // than a variably modified type.
15258   if (!InvalidDecl && T->isVariablyModifiedType()) {
15259     bool SizeIsNegative;
15260     llvm::APSInt Oversized;
15261 
15262     TypeSourceInfo *FixedTInfo =
15263       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15264                                                     SizeIsNegative,
15265                                                     Oversized);
15266     if (FixedTInfo) {
15267       Diag(Loc, diag::warn_illegal_constant_array_size);
15268       TInfo = FixedTInfo;
15269       T = FixedTInfo->getType();
15270     } else {
15271       if (SizeIsNegative)
15272         Diag(Loc, diag::err_typecheck_negative_array_size);
15273       else if (Oversized.getBoolValue())
15274         Diag(Loc, diag::err_array_too_large)
15275           << Oversized.toString(10);
15276       else
15277         Diag(Loc, diag::err_typecheck_field_variable_size);
15278       InvalidDecl = true;
15279     }
15280   }
15281 
15282   // Fields can not have abstract class types
15283   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15284                                              diag::err_abstract_type_in_decl,
15285                                              AbstractFieldType))
15286     InvalidDecl = true;
15287 
15288   bool ZeroWidth = false;
15289   if (InvalidDecl)
15290     BitWidth = nullptr;
15291   // If this is declared as a bit-field, check the bit-field.
15292   if (BitWidth) {
15293     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15294                               &ZeroWidth).get();
15295     if (!BitWidth) {
15296       InvalidDecl = true;
15297       BitWidth = nullptr;
15298       ZeroWidth = false;
15299     }
15300   }
15301 
15302   // Check that 'mutable' is consistent with the type of the declaration.
15303   if (!InvalidDecl && Mutable) {
15304     unsigned DiagID = 0;
15305     if (T->isReferenceType())
15306       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15307                                         : diag::err_mutable_reference;
15308     else if (T.isConstQualified())
15309       DiagID = diag::err_mutable_const;
15310 
15311     if (DiagID) {
15312       SourceLocation ErrLoc = Loc;
15313       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15314         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15315       Diag(ErrLoc, DiagID);
15316       if (DiagID != diag::ext_mutable_reference) {
15317         Mutable = false;
15318         InvalidDecl = true;
15319       }
15320     }
15321   }
15322 
15323   // C++11 [class.union]p8 (DR1460):
15324   //   At most one variant member of a union may have a
15325   //   brace-or-equal-initializer.
15326   if (InitStyle != ICIS_NoInit)
15327     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15328 
15329   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15330                                        BitWidth, Mutable, InitStyle);
15331   if (InvalidDecl)
15332     NewFD->setInvalidDecl();
15333 
15334   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15335     Diag(Loc, diag::err_duplicate_member) << II;
15336     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15337     NewFD->setInvalidDecl();
15338   }
15339 
15340   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15341     if (Record->isUnion()) {
15342       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15343         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15344         if (RDecl->getDefinition()) {
15345           // C++ [class.union]p1: An object of a class with a non-trivial
15346           // constructor, a non-trivial copy constructor, a non-trivial
15347           // destructor, or a non-trivial copy assignment operator
15348           // cannot be a member of a union, nor can an array of such
15349           // objects.
15350           if (CheckNontrivialField(NewFD))
15351             NewFD->setInvalidDecl();
15352         }
15353       }
15354 
15355       // C++ [class.union]p1: If a union contains a member of reference type,
15356       // the program is ill-formed, except when compiling with MSVC extensions
15357       // enabled.
15358       if (EltTy->isReferenceType()) {
15359         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15360                                     diag::ext_union_member_of_reference_type :
15361                                     diag::err_union_member_of_reference_type)
15362           << NewFD->getDeclName() << EltTy;
15363         if (!getLangOpts().MicrosoftExt)
15364           NewFD->setInvalidDecl();
15365       }
15366     }
15367   }
15368 
15369   // FIXME: We need to pass in the attributes given an AST
15370   // representation, not a parser representation.
15371   if (D) {
15372     // FIXME: The current scope is almost... but not entirely... correct here.
15373     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15374 
15375     if (NewFD->hasAttrs())
15376       CheckAlignasUnderalignment(NewFD);
15377   }
15378 
15379   // In auto-retain/release, infer strong retension for fields of
15380   // retainable type.
15381   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15382     NewFD->setInvalidDecl();
15383 
15384   if (T.isObjCGCWeak())
15385     Diag(Loc, diag::warn_attribute_weak_on_field);
15386 
15387   NewFD->setAccess(AS);
15388   return NewFD;
15389 }
15390 
15391 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15392   assert(FD);
15393   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15394 
15395   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15396     return false;
15397 
15398   QualType EltTy = Context.getBaseElementType(FD->getType());
15399   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15400     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15401     if (RDecl->getDefinition()) {
15402       // We check for copy constructors before constructors
15403       // because otherwise we'll never get complaints about
15404       // copy constructors.
15405 
15406       CXXSpecialMember member = CXXInvalid;
15407       // We're required to check for any non-trivial constructors. Since the
15408       // implicit default constructor is suppressed if there are any
15409       // user-declared constructors, we just need to check that there is a
15410       // trivial default constructor and a trivial copy constructor. (We don't
15411       // worry about move constructors here, since this is a C++98 check.)
15412       if (RDecl->hasNonTrivialCopyConstructor())
15413         member = CXXCopyConstructor;
15414       else if (!RDecl->hasTrivialDefaultConstructor())
15415         member = CXXDefaultConstructor;
15416       else if (RDecl->hasNonTrivialCopyAssignment())
15417         member = CXXCopyAssignment;
15418       else if (RDecl->hasNonTrivialDestructor())
15419         member = CXXDestructor;
15420 
15421       if (member != CXXInvalid) {
15422         if (!getLangOpts().CPlusPlus11 &&
15423             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15424           // Objective-C++ ARC: it is an error to have a non-trivial field of
15425           // a union. However, system headers in Objective-C programs
15426           // occasionally have Objective-C lifetime objects within unions,
15427           // and rather than cause the program to fail, we make those
15428           // members unavailable.
15429           SourceLocation Loc = FD->getLocation();
15430           if (getSourceManager().isInSystemHeader(Loc)) {
15431             if (!FD->hasAttr<UnavailableAttr>())
15432               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15433                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15434             return false;
15435           }
15436         }
15437 
15438         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15439                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15440                diag::err_illegal_union_or_anon_struct_member)
15441           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15442         DiagnoseNontrivial(RDecl, member);
15443         return !getLangOpts().CPlusPlus11;
15444       }
15445     }
15446   }
15447 
15448   return false;
15449 }
15450 
15451 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15452 ///  AST enum value.
15453 static ObjCIvarDecl::AccessControl
15454 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15455   switch (ivarVisibility) {
15456   default: llvm_unreachable("Unknown visitibility kind");
15457   case tok::objc_private: return ObjCIvarDecl::Private;
15458   case tok::objc_public: return ObjCIvarDecl::Public;
15459   case tok::objc_protected: return ObjCIvarDecl::Protected;
15460   case tok::objc_package: return ObjCIvarDecl::Package;
15461   }
15462 }
15463 
15464 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15465 /// in order to create an IvarDecl object for it.
15466 Decl *Sema::ActOnIvar(Scope *S,
15467                                 SourceLocation DeclStart,
15468                                 Declarator &D, Expr *BitfieldWidth,
15469                                 tok::ObjCKeywordKind Visibility) {
15470 
15471   IdentifierInfo *II = D.getIdentifier();
15472   Expr *BitWidth = (Expr*)BitfieldWidth;
15473   SourceLocation Loc = DeclStart;
15474   if (II) Loc = D.getIdentifierLoc();
15475 
15476   // FIXME: Unnamed fields can be handled in various different ways, for
15477   // example, unnamed unions inject all members into the struct namespace!
15478 
15479   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15480   QualType T = TInfo->getType();
15481 
15482   if (BitWidth) {
15483     // 6.7.2.1p3, 6.7.2.1p4
15484     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15485     if (!BitWidth)
15486       D.setInvalidType();
15487   } else {
15488     // Not a bitfield.
15489 
15490     // validate II.
15491 
15492   }
15493   if (T->isReferenceType()) {
15494     Diag(Loc, diag::err_ivar_reference_type);
15495     D.setInvalidType();
15496   }
15497   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15498   // than a variably modified type.
15499   else if (T->isVariablyModifiedType()) {
15500     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15501     D.setInvalidType();
15502   }
15503 
15504   // Get the visibility (access control) for this ivar.
15505   ObjCIvarDecl::AccessControl ac =
15506     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15507                                         : ObjCIvarDecl::None;
15508   // Must set ivar's DeclContext to its enclosing interface.
15509   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15510   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15511     return nullptr;
15512   ObjCContainerDecl *EnclosingContext;
15513   if (ObjCImplementationDecl *IMPDecl =
15514       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15515     if (LangOpts.ObjCRuntime.isFragile()) {
15516     // Case of ivar declared in an implementation. Context is that of its class.
15517       EnclosingContext = IMPDecl->getClassInterface();
15518       assert(EnclosingContext && "Implementation has no class interface!");
15519     }
15520     else
15521       EnclosingContext = EnclosingDecl;
15522   } else {
15523     if (ObjCCategoryDecl *CDecl =
15524         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15525       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15526         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15527         return nullptr;
15528       }
15529     }
15530     EnclosingContext = EnclosingDecl;
15531   }
15532 
15533   // Construct the decl.
15534   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15535                                              DeclStart, Loc, II, T,
15536                                              TInfo, ac, (Expr *)BitfieldWidth);
15537 
15538   if (II) {
15539     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15540                                            ForVisibleRedeclaration);
15541     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15542         && !isa<TagDecl>(PrevDecl)) {
15543       Diag(Loc, diag::err_duplicate_member) << II;
15544       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15545       NewID->setInvalidDecl();
15546     }
15547   }
15548 
15549   // Process attributes attached to the ivar.
15550   ProcessDeclAttributes(S, NewID, D);
15551 
15552   if (D.isInvalidType())
15553     NewID->setInvalidDecl();
15554 
15555   // In ARC, infer 'retaining' for ivars of retainable type.
15556   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15557     NewID->setInvalidDecl();
15558 
15559   if (D.getDeclSpec().isModulePrivateSpecified())
15560     NewID->setModulePrivate();
15561 
15562   if (II) {
15563     // FIXME: When interfaces are DeclContexts, we'll need to add
15564     // these to the interface.
15565     S->AddDecl(NewID);
15566     IdResolver.AddDecl(NewID);
15567   }
15568 
15569   if (LangOpts.ObjCRuntime.isNonFragile() &&
15570       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15571     Diag(Loc, diag::warn_ivars_in_interface);
15572 
15573   return NewID;
15574 }
15575 
15576 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15577 /// class and class extensions. For every class \@interface and class
15578 /// extension \@interface, if the last ivar is a bitfield of any type,
15579 /// then add an implicit `char :0` ivar to the end of that interface.
15580 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15581                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15582   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15583     return;
15584 
15585   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15586   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15587 
15588   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15589     return;
15590   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15591   if (!ID) {
15592     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15593       if (!CD->IsClassExtension())
15594         return;
15595     }
15596     // No need to add this to end of @implementation.
15597     else
15598       return;
15599   }
15600   // All conditions are met. Add a new bitfield to the tail end of ivars.
15601   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15602   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15603 
15604   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15605                               DeclLoc, DeclLoc, nullptr,
15606                               Context.CharTy,
15607                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15608                                                                DeclLoc),
15609                               ObjCIvarDecl::Private, BW,
15610                               true);
15611   AllIvarDecls.push_back(Ivar);
15612 }
15613 
15614 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15615                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15616                        SourceLocation RBrac,
15617                        const ParsedAttributesView &Attrs) {
15618   assert(EnclosingDecl && "missing record or interface decl");
15619 
15620   // If this is an Objective-C @implementation or category and we have
15621   // new fields here we should reset the layout of the interface since
15622   // it will now change.
15623   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15624     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15625     switch (DC->getKind()) {
15626     default: break;
15627     case Decl::ObjCCategory:
15628       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15629       break;
15630     case Decl::ObjCImplementation:
15631       Context.
15632         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15633       break;
15634     }
15635   }
15636 
15637   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15638   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15639 
15640   // Start counting up the number of named members; make sure to include
15641   // members of anonymous structs and unions in the total.
15642   unsigned NumNamedMembers = 0;
15643   if (Record) {
15644     for (const auto *I : Record->decls()) {
15645       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15646         if (IFD->getDeclName())
15647           ++NumNamedMembers;
15648     }
15649   }
15650 
15651   // Verify that all the fields are okay.
15652   SmallVector<FieldDecl*, 32> RecFields;
15653 
15654   bool ObjCFieldLifetimeErrReported = false;
15655   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15656        i != end; ++i) {
15657     FieldDecl *FD = cast<FieldDecl>(*i);
15658 
15659     // Get the type for the field.
15660     const Type *FDTy = FD->getType().getTypePtr();
15661 
15662     if (!FD->isAnonymousStructOrUnion()) {
15663       // Remember all fields written by the user.
15664       RecFields.push_back(FD);
15665     }
15666 
15667     // If the field is already invalid for some reason, don't emit more
15668     // diagnostics about it.
15669     if (FD->isInvalidDecl()) {
15670       EnclosingDecl->setInvalidDecl();
15671       continue;
15672     }
15673 
15674     // C99 6.7.2.1p2:
15675     //   A structure or union shall not contain a member with
15676     //   incomplete or function type (hence, a structure shall not
15677     //   contain an instance of itself, but may contain a pointer to
15678     //   an instance of itself), except that the last member of a
15679     //   structure with more than one named member may have incomplete
15680     //   array type; such a structure (and any union containing,
15681     //   possibly recursively, a member that is such a structure)
15682     //   shall not be a member of a structure or an element of an
15683     //   array.
15684     bool IsLastField = (i + 1 == Fields.end());
15685     if (FDTy->isFunctionType()) {
15686       // Field declared as a function.
15687       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15688         << FD->getDeclName();
15689       FD->setInvalidDecl();
15690       EnclosingDecl->setInvalidDecl();
15691       continue;
15692     } else if (FDTy->isIncompleteArrayType() &&
15693                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15694       if (Record) {
15695         // Flexible array member.
15696         // Microsoft and g++ is more permissive regarding flexible array.
15697         // It will accept flexible array in union and also
15698         // as the sole element of a struct/class.
15699         unsigned DiagID = 0;
15700         if (!Record->isUnion() && !IsLastField) {
15701           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15702             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15703           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15704           FD->setInvalidDecl();
15705           EnclosingDecl->setInvalidDecl();
15706           continue;
15707         } else if (Record->isUnion())
15708           DiagID = getLangOpts().MicrosoftExt
15709                        ? diag::ext_flexible_array_union_ms
15710                        : getLangOpts().CPlusPlus
15711                              ? diag::ext_flexible_array_union_gnu
15712                              : diag::err_flexible_array_union;
15713         else if (NumNamedMembers < 1)
15714           DiagID = getLangOpts().MicrosoftExt
15715                        ? diag::ext_flexible_array_empty_aggregate_ms
15716                        : getLangOpts().CPlusPlus
15717                              ? diag::ext_flexible_array_empty_aggregate_gnu
15718                              : diag::err_flexible_array_empty_aggregate;
15719 
15720         if (DiagID)
15721           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15722                                           << Record->getTagKind();
15723         // While the layout of types that contain virtual bases is not specified
15724         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15725         // virtual bases after the derived members.  This would make a flexible
15726         // array member declared at the end of an object not adjacent to the end
15727         // of the type.
15728         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15729           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15730               << FD->getDeclName() << Record->getTagKind();
15731         if (!getLangOpts().C99)
15732           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15733             << FD->getDeclName() << Record->getTagKind();
15734 
15735         // If the element type has a non-trivial destructor, we would not
15736         // implicitly destroy the elements, so disallow it for now.
15737         //
15738         // FIXME: GCC allows this. We should probably either implicitly delete
15739         // the destructor of the containing class, or just allow this.
15740         QualType BaseElem = Context.getBaseElementType(FD->getType());
15741         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15742           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15743             << FD->getDeclName() << FD->getType();
15744           FD->setInvalidDecl();
15745           EnclosingDecl->setInvalidDecl();
15746           continue;
15747         }
15748         // Okay, we have a legal flexible array member at the end of the struct.
15749         Record->setHasFlexibleArrayMember(true);
15750       } else {
15751         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15752         // unless they are followed by another ivar. That check is done
15753         // elsewhere, after synthesized ivars are known.
15754       }
15755     } else if (!FDTy->isDependentType() &&
15756                RequireCompleteType(FD->getLocation(), FD->getType(),
15757                                    diag::err_field_incomplete)) {
15758       // Incomplete type
15759       FD->setInvalidDecl();
15760       EnclosingDecl->setInvalidDecl();
15761       continue;
15762     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15763       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15764         // A type which contains a flexible array member is considered to be a
15765         // flexible array member.
15766         Record->setHasFlexibleArrayMember(true);
15767         if (!Record->isUnion()) {
15768           // If this is a struct/class and this is not the last element, reject
15769           // it.  Note that GCC supports variable sized arrays in the middle of
15770           // structures.
15771           if (!IsLastField)
15772             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15773               << FD->getDeclName() << FD->getType();
15774           else {
15775             // We support flexible arrays at the end of structs in
15776             // other structs as an extension.
15777             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15778               << FD->getDeclName();
15779           }
15780         }
15781       }
15782       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15783           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15784                                  diag::err_abstract_type_in_decl,
15785                                  AbstractIvarType)) {
15786         // Ivars can not have abstract class types
15787         FD->setInvalidDecl();
15788       }
15789       if (Record && FDTTy->getDecl()->hasObjectMember())
15790         Record->setHasObjectMember(true);
15791       if (Record && FDTTy->getDecl()->hasVolatileMember())
15792         Record->setHasVolatileMember(true);
15793     } else if (FDTy->isObjCObjectType()) {
15794       /// A field cannot be an Objective-c object
15795       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15796         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15797       QualType T = Context.getObjCObjectPointerType(FD->getType());
15798       FD->setType(T);
15799     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15800                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15801       // It's an error in ARC or Weak if a field has lifetime.
15802       // We don't want to report this in a system header, though,
15803       // so we just make the field unavailable.
15804       // FIXME: that's really not sufficient; we need to make the type
15805       // itself invalid to, say, initialize or copy.
15806       QualType T = FD->getType();
15807       if (T.hasNonTrivialObjCLifetime()) {
15808         SourceLocation loc = FD->getLocation();
15809         if (getSourceManager().isInSystemHeader(loc)) {
15810           if (!FD->hasAttr<UnavailableAttr>()) {
15811             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15812                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15813           }
15814         } else {
15815           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15816             << T->isBlockPointerType() << Record->getTagKind();
15817         }
15818         ObjCFieldLifetimeErrReported = true;
15819       }
15820     } else if (getLangOpts().ObjC &&
15821                getLangOpts().getGC() != LangOptions::NonGC &&
15822                Record && !Record->hasObjectMember()) {
15823       if (FD->getType()->isObjCObjectPointerType() ||
15824           FD->getType().isObjCGCStrong())
15825         Record->setHasObjectMember(true);
15826       else if (Context.getAsArrayType(FD->getType())) {
15827         QualType BaseType = Context.getBaseElementType(FD->getType());
15828         if (BaseType->isRecordType() &&
15829             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15830           Record->setHasObjectMember(true);
15831         else if (BaseType->isObjCObjectPointerType() ||
15832                  BaseType.isObjCGCStrong())
15833                Record->setHasObjectMember(true);
15834       }
15835     }
15836 
15837     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15838       QualType FT = FD->getType();
15839       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15840         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15841       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15842       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15843         Record->setNonTrivialToPrimitiveCopy(true);
15844       if (FT.isDestructedType()) {
15845         Record->setNonTrivialToPrimitiveDestroy(true);
15846         Record->setParamDestroyedInCallee(true);
15847       }
15848 
15849       if (const auto *RT = FT->getAs<RecordType>()) {
15850         if (RT->getDecl()->getArgPassingRestrictions() ==
15851             RecordDecl::APK_CanNeverPassInRegs)
15852           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15853       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15854         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15855     }
15856 
15857     if (Record && FD->getType().isVolatileQualified())
15858       Record->setHasVolatileMember(true);
15859     // Keep track of the number of named members.
15860     if (FD->getIdentifier())
15861       ++NumNamedMembers;
15862   }
15863 
15864   // Okay, we successfully defined 'Record'.
15865   if (Record) {
15866     bool Completed = false;
15867     if (CXXRecord) {
15868       if (!CXXRecord->isInvalidDecl()) {
15869         // Set access bits correctly on the directly-declared conversions.
15870         for (CXXRecordDecl::conversion_iterator
15871                I = CXXRecord->conversion_begin(),
15872                E = CXXRecord->conversion_end(); I != E; ++I)
15873           I.setAccess((*I)->getAccess());
15874       }
15875 
15876       if (!CXXRecord->isDependentType()) {
15877         // Add any implicitly-declared members to this class.
15878         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15879 
15880         if (!CXXRecord->isInvalidDecl()) {
15881           // If we have virtual base classes, we may end up finding multiple
15882           // final overriders for a given virtual function. Check for this
15883           // problem now.
15884           if (CXXRecord->getNumVBases()) {
15885             CXXFinalOverriderMap FinalOverriders;
15886             CXXRecord->getFinalOverriders(FinalOverriders);
15887 
15888             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15889                                              MEnd = FinalOverriders.end();
15890                  M != MEnd; ++M) {
15891               for (OverridingMethods::iterator SO = M->second.begin(),
15892                                             SOEnd = M->second.end();
15893                    SO != SOEnd; ++SO) {
15894                 assert(SO->second.size() > 0 &&
15895                        "Virtual function without overriding functions?");
15896                 if (SO->second.size() == 1)
15897                   continue;
15898 
15899                 // C++ [class.virtual]p2:
15900                 //   In a derived class, if a virtual member function of a base
15901                 //   class subobject has more than one final overrider the
15902                 //   program is ill-formed.
15903                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15904                   << (const NamedDecl *)M->first << Record;
15905                 Diag(M->first->getLocation(),
15906                      diag::note_overridden_virtual_function);
15907                 for (OverridingMethods::overriding_iterator
15908                           OM = SO->second.begin(),
15909                        OMEnd = SO->second.end();
15910                      OM != OMEnd; ++OM)
15911                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15912                     << (const NamedDecl *)M->first << OM->Method->getParent();
15913 
15914                 Record->setInvalidDecl();
15915               }
15916             }
15917             CXXRecord->completeDefinition(&FinalOverriders);
15918             Completed = true;
15919           }
15920         }
15921       }
15922     }
15923 
15924     if (!Completed)
15925       Record->completeDefinition();
15926 
15927     // Handle attributes before checking the layout.
15928     ProcessDeclAttributeList(S, Record, Attrs);
15929 
15930     // We may have deferred checking for a deleted destructor. Check now.
15931     if (CXXRecord) {
15932       auto *Dtor = CXXRecord->getDestructor();
15933       if (Dtor && Dtor->isImplicit() &&
15934           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15935         CXXRecord->setImplicitDestructorIsDeleted();
15936         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15937       }
15938     }
15939 
15940     if (Record->hasAttrs()) {
15941       CheckAlignasUnderalignment(Record);
15942 
15943       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15944         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15945                                            IA->getRange(), IA->getBestCase(),
15946                                            IA->getSemanticSpelling());
15947     }
15948 
15949     // Check if the structure/union declaration is a type that can have zero
15950     // size in C. For C this is a language extension, for C++ it may cause
15951     // compatibility problems.
15952     bool CheckForZeroSize;
15953     if (!getLangOpts().CPlusPlus) {
15954       CheckForZeroSize = true;
15955     } else {
15956       // For C++ filter out types that cannot be referenced in C code.
15957       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15958       CheckForZeroSize =
15959           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15960           !CXXRecord->isDependentType() &&
15961           CXXRecord->isCLike();
15962     }
15963     if (CheckForZeroSize) {
15964       bool ZeroSize = true;
15965       bool IsEmpty = true;
15966       unsigned NonBitFields = 0;
15967       for (RecordDecl::field_iterator I = Record->field_begin(),
15968                                       E = Record->field_end();
15969            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15970         IsEmpty = false;
15971         if (I->isUnnamedBitfield()) {
15972           if (!I->isZeroLengthBitField(Context))
15973             ZeroSize = false;
15974         } else {
15975           ++NonBitFields;
15976           QualType FieldType = I->getType();
15977           if (FieldType->isIncompleteType() ||
15978               !Context.getTypeSizeInChars(FieldType).isZero())
15979             ZeroSize = false;
15980         }
15981       }
15982 
15983       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15984       // allowed in C++, but warn if its declaration is inside
15985       // extern "C" block.
15986       if (ZeroSize) {
15987         Diag(RecLoc, getLangOpts().CPlusPlus ?
15988                          diag::warn_zero_size_struct_union_in_extern_c :
15989                          diag::warn_zero_size_struct_union_compat)
15990           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15991       }
15992 
15993       // Structs without named members are extension in C (C99 6.7.2.1p7),
15994       // but are accepted by GCC.
15995       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15996         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15997                                diag::ext_no_named_members_in_struct_union)
15998           << Record->isUnion();
15999       }
16000     }
16001   } else {
16002     ObjCIvarDecl **ClsFields =
16003       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16004     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16005       ID->setEndOfDefinitionLoc(RBrac);
16006       // Add ivar's to class's DeclContext.
16007       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16008         ClsFields[i]->setLexicalDeclContext(ID);
16009         ID->addDecl(ClsFields[i]);
16010       }
16011       // Must enforce the rule that ivars in the base classes may not be
16012       // duplicates.
16013       if (ID->getSuperClass())
16014         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16015     } else if (ObjCImplementationDecl *IMPDecl =
16016                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16017       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16018       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16019         // Ivar declared in @implementation never belongs to the implementation.
16020         // Only it is in implementation's lexical context.
16021         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16022       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16023       IMPDecl->setIvarLBraceLoc(LBrac);
16024       IMPDecl->setIvarRBraceLoc(RBrac);
16025     } else if (ObjCCategoryDecl *CDecl =
16026                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16027       // case of ivars in class extension; all other cases have been
16028       // reported as errors elsewhere.
16029       // FIXME. Class extension does not have a LocEnd field.
16030       // CDecl->setLocEnd(RBrac);
16031       // Add ivar's to class extension's DeclContext.
16032       // Diagnose redeclaration of private ivars.
16033       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16034       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16035         if (IDecl) {
16036           if (const ObjCIvarDecl *ClsIvar =
16037               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16038             Diag(ClsFields[i]->getLocation(),
16039                  diag::err_duplicate_ivar_declaration);
16040             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16041             continue;
16042           }
16043           for (const auto *Ext : IDecl->known_extensions()) {
16044             if (const ObjCIvarDecl *ClsExtIvar
16045                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16046               Diag(ClsFields[i]->getLocation(),
16047                    diag::err_duplicate_ivar_declaration);
16048               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16049               continue;
16050             }
16051           }
16052         }
16053         ClsFields[i]->setLexicalDeclContext(CDecl);
16054         CDecl->addDecl(ClsFields[i]);
16055       }
16056       CDecl->setIvarLBraceLoc(LBrac);
16057       CDecl->setIvarRBraceLoc(RBrac);
16058     }
16059   }
16060 }
16061 
16062 /// Determine whether the given integral value is representable within
16063 /// the given type T.
16064 static bool isRepresentableIntegerValue(ASTContext &Context,
16065                                         llvm::APSInt &Value,
16066                                         QualType T) {
16067   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16068          "Integral type required!");
16069   unsigned BitWidth = Context.getIntWidth(T);
16070 
16071   if (Value.isUnsigned() || Value.isNonNegative()) {
16072     if (T->isSignedIntegerOrEnumerationType())
16073       --BitWidth;
16074     return Value.getActiveBits() <= BitWidth;
16075   }
16076   return Value.getMinSignedBits() <= BitWidth;
16077 }
16078 
16079 // Given an integral type, return the next larger integral type
16080 // (or a NULL type of no such type exists).
16081 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16082   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16083   // enum checking below.
16084   assert((T->isIntegralType(Context) ||
16085          T->isEnumeralType()) && "Integral type required!");
16086   const unsigned NumTypes = 4;
16087   QualType SignedIntegralTypes[NumTypes] = {
16088     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16089   };
16090   QualType UnsignedIntegralTypes[NumTypes] = {
16091     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16092     Context.UnsignedLongLongTy
16093   };
16094 
16095   unsigned BitWidth = Context.getTypeSize(T);
16096   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16097                                                         : UnsignedIntegralTypes;
16098   for (unsigned I = 0; I != NumTypes; ++I)
16099     if (Context.getTypeSize(Types[I]) > BitWidth)
16100       return Types[I];
16101 
16102   return QualType();
16103 }
16104 
16105 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16106                                           EnumConstantDecl *LastEnumConst,
16107                                           SourceLocation IdLoc,
16108                                           IdentifierInfo *Id,
16109                                           Expr *Val) {
16110   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16111   llvm::APSInt EnumVal(IntWidth);
16112   QualType EltTy;
16113 
16114   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16115     Val = nullptr;
16116 
16117   if (Val)
16118     Val = DefaultLvalueConversion(Val).get();
16119 
16120   if (Val) {
16121     if (Enum->isDependentType() || Val->isTypeDependent())
16122       EltTy = Context.DependentTy;
16123     else {
16124       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16125           !getLangOpts().MSVCCompat) {
16126         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16127         // constant-expression in the enumerator-definition shall be a converted
16128         // constant expression of the underlying type.
16129         EltTy = Enum->getIntegerType();
16130         ExprResult Converted =
16131           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16132                                            CCEK_Enumerator);
16133         if (Converted.isInvalid())
16134           Val = nullptr;
16135         else
16136           Val = Converted.get();
16137       } else if (!Val->isValueDependent() &&
16138                  !(Val = VerifyIntegerConstantExpression(Val,
16139                                                          &EnumVal).get())) {
16140         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16141       } else {
16142         if (Enum->isComplete()) {
16143           EltTy = Enum->getIntegerType();
16144 
16145           // In Obj-C and Microsoft mode, require the enumeration value to be
16146           // representable in the underlying type of the enumeration. In C++11,
16147           // we perform a non-narrowing conversion as part of converted constant
16148           // expression checking.
16149           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16150             if (getLangOpts().MSVCCompat) {
16151               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16152               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16153             } else
16154               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16155           } else
16156             Val = ImpCastExprToType(Val, EltTy,
16157                                     EltTy->isBooleanType() ?
16158                                     CK_IntegralToBoolean : CK_IntegralCast)
16159                     .get();
16160         } else if (getLangOpts().CPlusPlus) {
16161           // C++11 [dcl.enum]p5:
16162           //   If the underlying type is not fixed, the type of each enumerator
16163           //   is the type of its initializing value:
16164           //     - If an initializer is specified for an enumerator, the
16165           //       initializing value has the same type as the expression.
16166           EltTy = Val->getType();
16167         } else {
16168           // C99 6.7.2.2p2:
16169           //   The expression that defines the value of an enumeration constant
16170           //   shall be an integer constant expression that has a value
16171           //   representable as an int.
16172 
16173           // Complain if the value is not representable in an int.
16174           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16175             Diag(IdLoc, diag::ext_enum_value_not_int)
16176               << EnumVal.toString(10) << Val->getSourceRange()
16177               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16178           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16179             // Force the type of the expression to 'int'.
16180             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16181           }
16182           EltTy = Val->getType();
16183         }
16184       }
16185     }
16186   }
16187 
16188   if (!Val) {
16189     if (Enum->isDependentType())
16190       EltTy = Context.DependentTy;
16191     else if (!LastEnumConst) {
16192       // C++0x [dcl.enum]p5:
16193       //   If the underlying type is not fixed, the type of each enumerator
16194       //   is the type of its initializing value:
16195       //     - If no initializer is specified for the first enumerator, the
16196       //       initializing value has an unspecified integral type.
16197       //
16198       // GCC uses 'int' for its unspecified integral type, as does
16199       // C99 6.7.2.2p3.
16200       if (Enum->isFixed()) {
16201         EltTy = Enum->getIntegerType();
16202       }
16203       else {
16204         EltTy = Context.IntTy;
16205       }
16206     } else {
16207       // Assign the last value + 1.
16208       EnumVal = LastEnumConst->getInitVal();
16209       ++EnumVal;
16210       EltTy = LastEnumConst->getType();
16211 
16212       // Check for overflow on increment.
16213       if (EnumVal < LastEnumConst->getInitVal()) {
16214         // C++0x [dcl.enum]p5:
16215         //   If the underlying type is not fixed, the type of each enumerator
16216         //   is the type of its initializing value:
16217         //
16218         //     - Otherwise the type of the initializing value is the same as
16219         //       the type of the initializing value of the preceding enumerator
16220         //       unless the incremented value is not representable in that type,
16221         //       in which case the type is an unspecified integral type
16222         //       sufficient to contain the incremented value. If no such type
16223         //       exists, the program is ill-formed.
16224         QualType T = getNextLargerIntegralType(Context, EltTy);
16225         if (T.isNull() || Enum->isFixed()) {
16226           // There is no integral type larger enough to represent this
16227           // value. Complain, then allow the value to wrap around.
16228           EnumVal = LastEnumConst->getInitVal();
16229           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16230           ++EnumVal;
16231           if (Enum->isFixed())
16232             // When the underlying type is fixed, this is ill-formed.
16233             Diag(IdLoc, diag::err_enumerator_wrapped)
16234               << EnumVal.toString(10)
16235               << EltTy;
16236           else
16237             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16238               << EnumVal.toString(10);
16239         } else {
16240           EltTy = T;
16241         }
16242 
16243         // Retrieve the last enumerator's value, extent that type to the
16244         // type that is supposed to be large enough to represent the incremented
16245         // value, then increment.
16246         EnumVal = LastEnumConst->getInitVal();
16247         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16248         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16249         ++EnumVal;
16250 
16251         // If we're not in C++, diagnose the overflow of enumerator values,
16252         // which in C99 means that the enumerator value is not representable in
16253         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16254         // permits enumerator values that are representable in some larger
16255         // integral type.
16256         if (!getLangOpts().CPlusPlus && !T.isNull())
16257           Diag(IdLoc, diag::warn_enum_value_overflow);
16258       } else if (!getLangOpts().CPlusPlus &&
16259                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16260         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16261         Diag(IdLoc, diag::ext_enum_value_not_int)
16262           << EnumVal.toString(10) << 1;
16263       }
16264     }
16265   }
16266 
16267   if (!EltTy->isDependentType()) {
16268     // Make the enumerator value match the signedness and size of the
16269     // enumerator's type.
16270     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16271     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16272   }
16273 
16274   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16275                                   Val, EnumVal);
16276 }
16277 
16278 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16279                                                 SourceLocation IILoc) {
16280   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16281       !getLangOpts().CPlusPlus)
16282     return SkipBodyInfo();
16283 
16284   // We have an anonymous enum definition. Look up the first enumerator to
16285   // determine if we should merge the definition with an existing one and
16286   // skip the body.
16287   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16288                                          forRedeclarationInCurContext());
16289   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16290   if (!PrevECD)
16291     return SkipBodyInfo();
16292 
16293   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16294   NamedDecl *Hidden;
16295   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16296     SkipBodyInfo Skip;
16297     Skip.Previous = Hidden;
16298     return Skip;
16299   }
16300 
16301   return SkipBodyInfo();
16302 }
16303 
16304 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16305                               SourceLocation IdLoc, IdentifierInfo *Id,
16306                               const ParsedAttributesView &Attrs,
16307                               SourceLocation EqualLoc, Expr *Val) {
16308   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16309   EnumConstantDecl *LastEnumConst =
16310     cast_or_null<EnumConstantDecl>(lastEnumConst);
16311 
16312   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16313   // we find one that is.
16314   S = getNonFieldDeclScope(S);
16315 
16316   // Verify that there isn't already something declared with this name in this
16317   // scope.
16318   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16319   LookupName(R, S);
16320   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16321 
16322   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16323     // Maybe we will complain about the shadowed template parameter.
16324     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16325     // Just pretend that we didn't see the previous declaration.
16326     PrevDecl = nullptr;
16327   }
16328 
16329   // C++ [class.mem]p15:
16330   // If T is the name of a class, then each of the following shall have a name
16331   // different from T:
16332   // - every enumerator of every member of class T that is an unscoped
16333   // enumerated type
16334   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16335     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16336                             DeclarationNameInfo(Id, IdLoc));
16337 
16338   EnumConstantDecl *New =
16339     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16340   if (!New)
16341     return nullptr;
16342 
16343   if (PrevDecl) {
16344     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16345       // Check for other kinds of shadowing not already handled.
16346       CheckShadow(New, PrevDecl, R);
16347     }
16348 
16349     // When in C++, we may get a TagDecl with the same name; in this case the
16350     // enum constant will 'hide' the tag.
16351     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16352            "Received TagDecl when not in C++!");
16353     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16354       if (isa<EnumConstantDecl>(PrevDecl))
16355         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16356       else
16357         Diag(IdLoc, diag::err_redefinition) << Id;
16358       notePreviousDefinition(PrevDecl, IdLoc);
16359       return nullptr;
16360     }
16361   }
16362 
16363   // Process attributes.
16364   ProcessDeclAttributeList(S, New, Attrs);
16365   AddPragmaAttributes(S, New);
16366 
16367   // Register this decl in the current scope stack.
16368   New->setAccess(TheEnumDecl->getAccess());
16369   PushOnScopeChains(New, S);
16370 
16371   ActOnDocumentableDecl(New);
16372 
16373   return New;
16374 }
16375 
16376 // Returns true when the enum initial expression does not trigger the
16377 // duplicate enum warning.  A few common cases are exempted as follows:
16378 // Element2 = Element1
16379 // Element2 = Element1 + 1
16380 // Element2 = Element1 - 1
16381 // Where Element2 and Element1 are from the same enum.
16382 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16383   Expr *InitExpr = ECD->getInitExpr();
16384   if (!InitExpr)
16385     return true;
16386   InitExpr = InitExpr->IgnoreImpCasts();
16387 
16388   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16389     if (!BO->isAdditiveOp())
16390       return true;
16391     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16392     if (!IL)
16393       return true;
16394     if (IL->getValue() != 1)
16395       return true;
16396 
16397     InitExpr = BO->getLHS();
16398   }
16399 
16400   // This checks if the elements are from the same enum.
16401   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16402   if (!DRE)
16403     return true;
16404 
16405   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16406   if (!EnumConstant)
16407     return true;
16408 
16409   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16410       Enum)
16411     return true;
16412 
16413   return false;
16414 }
16415 
16416 // Emits a warning when an element is implicitly set a value that
16417 // a previous element has already been set to.
16418 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16419                                         EnumDecl *Enum, QualType EnumType) {
16420   // Avoid anonymous enums
16421   if (!Enum->getIdentifier())
16422     return;
16423 
16424   // Only check for small enums.
16425   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16426     return;
16427 
16428   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16429     return;
16430 
16431   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16432   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16433 
16434   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16435   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16436 
16437   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16438   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16439     llvm::APSInt Val = D->getInitVal();
16440     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16441   };
16442 
16443   DuplicatesVector DupVector;
16444   ValueToVectorMap EnumMap;
16445 
16446   // Populate the EnumMap with all values represented by enum constants without
16447   // an initializer.
16448   for (auto *Element : Elements) {
16449     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16450 
16451     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16452     // this constant.  Skip this enum since it may be ill-formed.
16453     if (!ECD) {
16454       return;
16455     }
16456 
16457     // Constants with initalizers are handled in the next loop.
16458     if (ECD->getInitExpr())
16459       continue;
16460 
16461     // Duplicate values are handled in the next loop.
16462     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16463   }
16464 
16465   if (EnumMap.size() == 0)
16466     return;
16467 
16468   // Create vectors for any values that has duplicates.
16469   for (auto *Element : Elements) {
16470     // The last loop returned if any constant was null.
16471     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16472     if (!ValidDuplicateEnum(ECD, Enum))
16473       continue;
16474 
16475     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16476     if (Iter == EnumMap.end())
16477       continue;
16478 
16479     DeclOrVector& Entry = Iter->second;
16480     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16481       // Ensure constants are different.
16482       if (D == ECD)
16483         continue;
16484 
16485       // Create new vector and push values onto it.
16486       auto Vec = llvm::make_unique<ECDVector>();
16487       Vec->push_back(D);
16488       Vec->push_back(ECD);
16489 
16490       // Update entry to point to the duplicates vector.
16491       Entry = Vec.get();
16492 
16493       // Store the vector somewhere we can consult later for quick emission of
16494       // diagnostics.
16495       DupVector.emplace_back(std::move(Vec));
16496       continue;
16497     }
16498 
16499     ECDVector *Vec = Entry.get<ECDVector*>();
16500     // Make sure constants are not added more than once.
16501     if (*Vec->begin() == ECD)
16502       continue;
16503 
16504     Vec->push_back(ECD);
16505   }
16506 
16507   // Emit diagnostics.
16508   for (const auto &Vec : DupVector) {
16509     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16510 
16511     // Emit warning for one enum constant.
16512     auto *FirstECD = Vec->front();
16513     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16514       << FirstECD << FirstECD->getInitVal().toString(10)
16515       << FirstECD->getSourceRange();
16516 
16517     // Emit one note for each of the remaining enum constants with
16518     // the same value.
16519     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16520       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16521         << ECD << ECD->getInitVal().toString(10)
16522         << ECD->getSourceRange();
16523   }
16524 }
16525 
16526 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16527                              bool AllowMask) const {
16528   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16529   assert(ED->isCompleteDefinition() && "expected enum definition");
16530 
16531   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16532   llvm::APInt &FlagBits = R.first->second;
16533 
16534   if (R.second) {
16535     for (auto *E : ED->enumerators()) {
16536       const auto &EVal = E->getInitVal();
16537       // Only single-bit enumerators introduce new flag values.
16538       if (EVal.isPowerOf2())
16539         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16540     }
16541   }
16542 
16543   // A value is in a flag enum if either its bits are a subset of the enum's
16544   // flag bits (the first condition) or we are allowing masks and the same is
16545   // true of its complement (the second condition). When masks are allowed, we
16546   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16547   //
16548   // While it's true that any value could be used as a mask, the assumption is
16549   // that a mask will have all of the insignificant bits set. Anything else is
16550   // likely a logic error.
16551   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16552   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16553 }
16554 
16555 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16556                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16557                          const ParsedAttributesView &Attrs) {
16558   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16559   QualType EnumType = Context.getTypeDeclType(Enum);
16560 
16561   ProcessDeclAttributeList(S, Enum, Attrs);
16562 
16563   if (Enum->isDependentType()) {
16564     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16565       EnumConstantDecl *ECD =
16566         cast_or_null<EnumConstantDecl>(Elements[i]);
16567       if (!ECD) continue;
16568 
16569       ECD->setType(EnumType);
16570     }
16571 
16572     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16573     return;
16574   }
16575 
16576   // TODO: If the result value doesn't fit in an int, it must be a long or long
16577   // long value.  ISO C does not support this, but GCC does as an extension,
16578   // emit a warning.
16579   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16580   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16581   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16582 
16583   // Verify that all the values are okay, compute the size of the values, and
16584   // reverse the list.
16585   unsigned NumNegativeBits = 0;
16586   unsigned NumPositiveBits = 0;
16587 
16588   // Keep track of whether all elements have type int.
16589   bool AllElementsInt = true;
16590 
16591   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16592     EnumConstantDecl *ECD =
16593       cast_or_null<EnumConstantDecl>(Elements[i]);
16594     if (!ECD) continue;  // Already issued a diagnostic.
16595 
16596     const llvm::APSInt &InitVal = ECD->getInitVal();
16597 
16598     // Keep track of the size of positive and negative values.
16599     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16600       NumPositiveBits = std::max(NumPositiveBits,
16601                                  (unsigned)InitVal.getActiveBits());
16602     else
16603       NumNegativeBits = std::max(NumNegativeBits,
16604                                  (unsigned)InitVal.getMinSignedBits());
16605 
16606     // Keep track of whether every enum element has type int (very commmon).
16607     if (AllElementsInt)
16608       AllElementsInt = ECD->getType() == Context.IntTy;
16609   }
16610 
16611   // Figure out the type that should be used for this enum.
16612   QualType BestType;
16613   unsigned BestWidth;
16614 
16615   // C++0x N3000 [conv.prom]p3:
16616   //   An rvalue of an unscoped enumeration type whose underlying
16617   //   type is not fixed can be converted to an rvalue of the first
16618   //   of the following types that can represent all the values of
16619   //   the enumeration: int, unsigned int, long int, unsigned long
16620   //   int, long long int, or unsigned long long int.
16621   // C99 6.4.4.3p2:
16622   //   An identifier declared as an enumeration constant has type int.
16623   // The C99 rule is modified by a gcc extension
16624   QualType BestPromotionType;
16625 
16626   bool Packed = Enum->hasAttr<PackedAttr>();
16627   // -fshort-enums is the equivalent to specifying the packed attribute on all
16628   // enum definitions.
16629   if (LangOpts.ShortEnums)
16630     Packed = true;
16631 
16632   // If the enum already has a type because it is fixed or dictated by the
16633   // target, promote that type instead of analyzing the enumerators.
16634   if (Enum->isComplete()) {
16635     BestType = Enum->getIntegerType();
16636     if (BestType->isPromotableIntegerType())
16637       BestPromotionType = Context.getPromotedIntegerType(BestType);
16638     else
16639       BestPromotionType = BestType;
16640 
16641     BestWidth = Context.getIntWidth(BestType);
16642   }
16643   else if (NumNegativeBits) {
16644     // If there is a negative value, figure out the smallest integer type (of
16645     // int/long/longlong) that fits.
16646     // If it's packed, check also if it fits a char or a short.
16647     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16648       BestType = Context.SignedCharTy;
16649       BestWidth = CharWidth;
16650     } else if (Packed && NumNegativeBits <= ShortWidth &&
16651                NumPositiveBits < ShortWidth) {
16652       BestType = Context.ShortTy;
16653       BestWidth = ShortWidth;
16654     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16655       BestType = Context.IntTy;
16656       BestWidth = IntWidth;
16657     } else {
16658       BestWidth = Context.getTargetInfo().getLongWidth();
16659 
16660       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16661         BestType = Context.LongTy;
16662       } else {
16663         BestWidth = Context.getTargetInfo().getLongLongWidth();
16664 
16665         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16666           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16667         BestType = Context.LongLongTy;
16668       }
16669     }
16670     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16671   } else {
16672     // If there is no negative value, figure out the smallest type that fits
16673     // all of the enumerator values.
16674     // If it's packed, check also if it fits a char or a short.
16675     if (Packed && NumPositiveBits <= CharWidth) {
16676       BestType = Context.UnsignedCharTy;
16677       BestPromotionType = Context.IntTy;
16678       BestWidth = CharWidth;
16679     } else if (Packed && NumPositiveBits <= ShortWidth) {
16680       BestType = Context.UnsignedShortTy;
16681       BestPromotionType = Context.IntTy;
16682       BestWidth = ShortWidth;
16683     } else if (NumPositiveBits <= IntWidth) {
16684       BestType = Context.UnsignedIntTy;
16685       BestWidth = IntWidth;
16686       BestPromotionType
16687         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16688                            ? Context.UnsignedIntTy : Context.IntTy;
16689     } else if (NumPositiveBits <=
16690                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16691       BestType = Context.UnsignedLongTy;
16692       BestPromotionType
16693         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16694                            ? Context.UnsignedLongTy : Context.LongTy;
16695     } else {
16696       BestWidth = Context.getTargetInfo().getLongLongWidth();
16697       assert(NumPositiveBits <= BestWidth &&
16698              "How could an initializer get larger than ULL?");
16699       BestType = Context.UnsignedLongLongTy;
16700       BestPromotionType
16701         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16702                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16703     }
16704   }
16705 
16706   // Loop over all of the enumerator constants, changing their types to match
16707   // the type of the enum if needed.
16708   for (auto *D : Elements) {
16709     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16710     if (!ECD) continue;  // Already issued a diagnostic.
16711 
16712     // Standard C says the enumerators have int type, but we allow, as an
16713     // extension, the enumerators to be larger than int size.  If each
16714     // enumerator value fits in an int, type it as an int, otherwise type it the
16715     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16716     // that X has type 'int', not 'unsigned'.
16717 
16718     // Determine whether the value fits into an int.
16719     llvm::APSInt InitVal = ECD->getInitVal();
16720 
16721     // If it fits into an integer type, force it.  Otherwise force it to match
16722     // the enum decl type.
16723     QualType NewTy;
16724     unsigned NewWidth;
16725     bool NewSign;
16726     if (!getLangOpts().CPlusPlus &&
16727         !Enum->isFixed() &&
16728         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16729       NewTy = Context.IntTy;
16730       NewWidth = IntWidth;
16731       NewSign = true;
16732     } else if (ECD->getType() == BestType) {
16733       // Already the right type!
16734       if (getLangOpts().CPlusPlus)
16735         // C++ [dcl.enum]p4: Following the closing brace of an
16736         // enum-specifier, each enumerator has the type of its
16737         // enumeration.
16738         ECD->setType(EnumType);
16739       continue;
16740     } else {
16741       NewTy = BestType;
16742       NewWidth = BestWidth;
16743       NewSign = BestType->isSignedIntegerOrEnumerationType();
16744     }
16745 
16746     // Adjust the APSInt value.
16747     InitVal = InitVal.extOrTrunc(NewWidth);
16748     InitVal.setIsSigned(NewSign);
16749     ECD->setInitVal(InitVal);
16750 
16751     // Adjust the Expr initializer and type.
16752     if (ECD->getInitExpr() &&
16753         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16754       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16755                                                 CK_IntegralCast,
16756                                                 ECD->getInitExpr(),
16757                                                 /*base paths*/ nullptr,
16758                                                 VK_RValue));
16759     if (getLangOpts().CPlusPlus)
16760       // C++ [dcl.enum]p4: Following the closing brace of an
16761       // enum-specifier, each enumerator has the type of its
16762       // enumeration.
16763       ECD->setType(EnumType);
16764     else
16765       ECD->setType(NewTy);
16766   }
16767 
16768   Enum->completeDefinition(BestType, BestPromotionType,
16769                            NumPositiveBits, NumNegativeBits);
16770 
16771   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16772 
16773   if (Enum->isClosedFlag()) {
16774     for (Decl *D : Elements) {
16775       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16776       if (!ECD) continue;  // Already issued a diagnostic.
16777 
16778       llvm::APSInt InitVal = ECD->getInitVal();
16779       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16780           !IsValueInFlagEnum(Enum, InitVal, true))
16781         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16782           << ECD << Enum;
16783     }
16784   }
16785 
16786   // Now that the enum type is defined, ensure it's not been underaligned.
16787   if (Enum->hasAttrs())
16788     CheckAlignasUnderalignment(Enum);
16789 }
16790 
16791 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16792                                   SourceLocation StartLoc,
16793                                   SourceLocation EndLoc) {
16794   StringLiteral *AsmString = cast<StringLiteral>(expr);
16795 
16796   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16797                                                    AsmString, StartLoc,
16798                                                    EndLoc);
16799   CurContext->addDecl(New);
16800   return New;
16801 }
16802 
16803 static void checkModuleImportContext(Sema &S, Module *M,
16804                                      SourceLocation ImportLoc, DeclContext *DC,
16805                                      bool FromInclude = false) {
16806   SourceLocation ExternCLoc;
16807 
16808   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16809     switch (LSD->getLanguage()) {
16810     case LinkageSpecDecl::lang_c:
16811       if (ExternCLoc.isInvalid())
16812         ExternCLoc = LSD->getBeginLoc();
16813       break;
16814     case LinkageSpecDecl::lang_cxx:
16815       break;
16816     }
16817     DC = LSD->getParent();
16818   }
16819 
16820   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16821     DC = DC->getParent();
16822 
16823   if (!isa<TranslationUnitDecl>(DC)) {
16824     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16825                           ? diag::ext_module_import_not_at_top_level_noop
16826                           : diag::err_module_import_not_at_top_level_fatal)
16827         << M->getFullModuleName() << DC;
16828     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16829            diag::note_module_import_not_at_top_level)
16830         << DC;
16831   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16832     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16833       << M->getFullModuleName();
16834     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16835   }
16836 }
16837 
16838 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16839                                            SourceLocation ModuleLoc,
16840                                            ModuleDeclKind MDK,
16841                                            ModuleIdPath Path) {
16842   assert(getLangOpts().ModulesTS &&
16843          "should only have module decl in modules TS");
16844 
16845   // A module implementation unit requires that we are not compiling a module
16846   // of any kind. A module interface unit requires that we are not compiling a
16847   // module map.
16848   switch (getLangOpts().getCompilingModule()) {
16849   case LangOptions::CMK_None:
16850     // It's OK to compile a module interface as a normal translation unit.
16851     break;
16852 
16853   case LangOptions::CMK_ModuleInterface:
16854     if (MDK != ModuleDeclKind::Implementation)
16855       break;
16856 
16857     // We were asked to compile a module interface unit but this is a module
16858     // implementation unit. That indicates the 'export' is missing.
16859     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16860       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16861     MDK = ModuleDeclKind::Interface;
16862     break;
16863 
16864   case LangOptions::CMK_ModuleMap:
16865     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16866     return nullptr;
16867 
16868   case LangOptions::CMK_HeaderModule:
16869     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
16870     return nullptr;
16871   }
16872 
16873   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16874 
16875   // FIXME: Most of this work should be done by the preprocessor rather than
16876   // here, in order to support macro import.
16877 
16878   // Only one module-declaration is permitted per source file.
16879   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16880     Diag(ModuleLoc, diag::err_module_redeclaration);
16881     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16882          diag::note_prev_module_declaration);
16883     return nullptr;
16884   }
16885 
16886   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16887   // modules, the dots here are just another character that can appear in a
16888   // module name.
16889   std::string ModuleName;
16890   for (auto &Piece : Path) {
16891     if (!ModuleName.empty())
16892       ModuleName += ".";
16893     ModuleName += Piece.first->getName();
16894   }
16895 
16896   // If a module name was explicitly specified on the command line, it must be
16897   // correct.
16898   if (!getLangOpts().CurrentModule.empty() &&
16899       getLangOpts().CurrentModule != ModuleName) {
16900     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16901         << SourceRange(Path.front().second, Path.back().second)
16902         << getLangOpts().CurrentModule;
16903     return nullptr;
16904   }
16905   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16906 
16907   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16908   Module *Mod;
16909 
16910   switch (MDK) {
16911   case ModuleDeclKind::Interface: {
16912     // We can't have parsed or imported a definition of this module or parsed a
16913     // module map defining it already.
16914     if (auto *M = Map.findModule(ModuleName)) {
16915       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16916       if (M->DefinitionLoc.isValid())
16917         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16918       else if (const auto *FE = M->getASTFile())
16919         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16920             << FE->getName();
16921       Mod = M;
16922       break;
16923     }
16924 
16925     // Create a Module for the module that we're defining.
16926     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16927                                            ModuleScopes.front().Module);
16928     assert(Mod && "module creation should not fail");
16929     break;
16930   }
16931 
16932   case ModuleDeclKind::Partition:
16933     // FIXME: Check we are in a submodule of the named module.
16934     return nullptr;
16935 
16936   case ModuleDeclKind::Implementation:
16937     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16938         PP.getIdentifierInfo(ModuleName), Path[0].second);
16939     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
16940                                        Module::AllVisible,
16941                                        /*IsIncludeDirective=*/false);
16942     if (!Mod) {
16943       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16944       // Create an empty module interface unit for error recovery.
16945       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16946                                              ModuleScopes.front().Module);
16947     }
16948     break;
16949   }
16950 
16951   // Switch from the global module to the named module.
16952   ModuleScopes.back().Module = Mod;
16953   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16954   VisibleModules.setVisible(Mod, ModuleLoc);
16955 
16956   // From now on, we have an owning module for all declarations we see.
16957   // However, those declarations are module-private unless explicitly
16958   // exported.
16959   auto *TU = Context.getTranslationUnitDecl();
16960   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16961   TU->setLocalOwningModule(Mod);
16962 
16963   // FIXME: Create a ModuleDecl.
16964   return nullptr;
16965 }
16966 
16967 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16968                                    SourceLocation ImportLoc,
16969                                    ModuleIdPath Path) {
16970   // Flatten the module path for a Modules TS module name.
16971   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
16972   if (getLangOpts().ModulesTS) {
16973     std::string ModuleName;
16974     for (auto &Piece : Path) {
16975       if (!ModuleName.empty())
16976         ModuleName += ".";
16977       ModuleName += Piece.first->getName();
16978     }
16979     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
16980     Path = ModuleIdPath(ModuleNameLoc);
16981   }
16982 
16983   Module *Mod =
16984       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16985                                    /*IsIncludeDirective=*/false);
16986   if (!Mod)
16987     return true;
16988 
16989   VisibleModules.setVisible(Mod, ImportLoc);
16990 
16991   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16992 
16993   // FIXME: we should support importing a submodule within a different submodule
16994   // of the same top-level module. Until we do, make it an error rather than
16995   // silently ignoring the import.
16996   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16997   // warn on a redundant import of the current module?
16998   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16999       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17000     Diag(ImportLoc, getLangOpts().isCompilingModule()
17001                         ? diag::err_module_self_import
17002                         : diag::err_module_import_in_implementation)
17003         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17004 
17005   SmallVector<SourceLocation, 2> IdentifierLocs;
17006   Module *ModCheck = Mod;
17007   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17008     // If we've run out of module parents, just drop the remaining identifiers.
17009     // We need the length to be consistent.
17010     if (!ModCheck)
17011       break;
17012     ModCheck = ModCheck->Parent;
17013 
17014     IdentifierLocs.push_back(Path[I].second);
17015   }
17016 
17017   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17018                                           Mod, IdentifierLocs);
17019   if (!ModuleScopes.empty())
17020     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17021   CurContext->addDecl(Import);
17022 
17023   // Re-export the module if needed.
17024   if (Import->isExported() &&
17025       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17026     getCurrentModule()->Exports.emplace_back(Mod, false);
17027 
17028   return Import;
17029 }
17030 
17031 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17032   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17033   BuildModuleInclude(DirectiveLoc, Mod);
17034 }
17035 
17036 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17037   // Determine whether we're in the #include buffer for a module. The #includes
17038   // in that buffer do not qualify as module imports; they're just an
17039   // implementation detail of us building the module.
17040   //
17041   // FIXME: Should we even get ActOnModuleInclude calls for those?
17042   bool IsInModuleIncludes =
17043       TUKind == TU_Module &&
17044       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17045 
17046   bool ShouldAddImport = !IsInModuleIncludes;
17047 
17048   // If this module import was due to an inclusion directive, create an
17049   // implicit import declaration to capture it in the AST.
17050   if (ShouldAddImport) {
17051     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17052     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17053                                                      DirectiveLoc, Mod,
17054                                                      DirectiveLoc);
17055     if (!ModuleScopes.empty())
17056       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17057     TU->addDecl(ImportD);
17058     Consumer.HandleImplicitImportDecl(ImportD);
17059   }
17060 
17061   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17062   VisibleModules.setVisible(Mod, DirectiveLoc);
17063 }
17064 
17065 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17066   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17067 
17068   ModuleScopes.push_back({});
17069   ModuleScopes.back().Module = Mod;
17070   if (getLangOpts().ModulesLocalVisibility)
17071     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17072 
17073   VisibleModules.setVisible(Mod, DirectiveLoc);
17074 
17075   // The enclosing context is now part of this module.
17076   // FIXME: Consider creating a child DeclContext to hold the entities
17077   // lexically within the module.
17078   if (getLangOpts().trackLocalOwningModule()) {
17079     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17080       cast<Decl>(DC)->setModuleOwnershipKind(
17081           getLangOpts().ModulesLocalVisibility
17082               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17083               : Decl::ModuleOwnershipKind::Visible);
17084       cast<Decl>(DC)->setLocalOwningModule(Mod);
17085     }
17086   }
17087 }
17088 
17089 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17090   if (getLangOpts().ModulesLocalVisibility) {
17091     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17092     // Leaving a module hides namespace names, so our visible namespace cache
17093     // is now out of date.
17094     VisibleNamespaceCache.clear();
17095   }
17096 
17097   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17098          "left the wrong module scope");
17099   ModuleScopes.pop_back();
17100 
17101   // We got to the end of processing a local module. Create an
17102   // ImportDecl as we would for an imported module.
17103   FileID File = getSourceManager().getFileID(EomLoc);
17104   SourceLocation DirectiveLoc;
17105   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17106     // We reached the end of a #included module header. Use the #include loc.
17107     assert(File != getSourceManager().getMainFileID() &&
17108            "end of submodule in main source file");
17109     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17110   } else {
17111     // We reached an EOM pragma. Use the pragma location.
17112     DirectiveLoc = EomLoc;
17113   }
17114   BuildModuleInclude(DirectiveLoc, Mod);
17115 
17116   // Any further declarations are in whatever module we returned to.
17117   if (getLangOpts().trackLocalOwningModule()) {
17118     // The parser guarantees that this is the same context that we entered
17119     // the module within.
17120     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17121       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17122       if (!getCurrentModule())
17123         cast<Decl>(DC)->setModuleOwnershipKind(
17124             Decl::ModuleOwnershipKind::Unowned);
17125     }
17126   }
17127 }
17128 
17129 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17130                                                       Module *Mod) {
17131   // Bail if we're not allowed to implicitly import a module here.
17132   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17133       VisibleModules.isVisible(Mod))
17134     return;
17135 
17136   // Create the implicit import declaration.
17137   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17138   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17139                                                    Loc, Mod, Loc);
17140   TU->addDecl(ImportD);
17141   Consumer.HandleImplicitImportDecl(ImportD);
17142 
17143   // Make the module visible.
17144   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17145   VisibleModules.setVisible(Mod, Loc);
17146 }
17147 
17148 /// We have parsed the start of an export declaration, including the '{'
17149 /// (if present).
17150 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17151                                  SourceLocation LBraceLoc) {
17152   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17153 
17154   // C++ Modules TS draft:
17155   //   An export-declaration shall appear in the purview of a module other than
17156   //   the global module.
17157   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17158     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17159 
17160   //   An export-declaration [...] shall not contain more than one
17161   //   export keyword.
17162   //
17163   // The intent here is that an export-declaration cannot appear within another
17164   // export-declaration.
17165   if (D->isExported())
17166     Diag(ExportLoc, diag::err_export_within_export);
17167 
17168   CurContext->addDecl(D);
17169   PushDeclContext(S, D);
17170   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17171   return D;
17172 }
17173 
17174 /// Complete the definition of an export declaration.
17175 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17176   auto *ED = cast<ExportDecl>(D);
17177   if (RBraceLoc.isValid())
17178     ED->setRBraceLoc(RBraceLoc);
17179 
17180   // FIXME: Diagnose export of internal-linkage declaration (including
17181   // anonymous namespace).
17182 
17183   PopDeclContext();
17184   return D;
17185 }
17186 
17187 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17188                                       IdentifierInfo* AliasName,
17189                                       SourceLocation PragmaLoc,
17190                                       SourceLocation NameLoc,
17191                                       SourceLocation AliasNameLoc) {
17192   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17193                                          LookupOrdinaryName);
17194   AsmLabelAttr *Attr =
17195       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17196 
17197   // If a declaration that:
17198   // 1) declares a function or a variable
17199   // 2) has external linkage
17200   // already exists, add a label attribute to it.
17201   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17202     if (isDeclExternC(PrevDecl))
17203       PrevDecl->addAttr(Attr);
17204     else
17205       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17206           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17207   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17208   } else
17209     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17210 }
17211 
17212 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17213                              SourceLocation PragmaLoc,
17214                              SourceLocation NameLoc) {
17215   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17216 
17217   if (PrevDecl) {
17218     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17219   } else {
17220     (void)WeakUndeclaredIdentifiers.insert(
17221       std::pair<IdentifierInfo*,WeakInfo>
17222         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17223   }
17224 }
17225 
17226 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17227                                 IdentifierInfo* AliasName,
17228                                 SourceLocation PragmaLoc,
17229                                 SourceLocation NameLoc,
17230                                 SourceLocation AliasNameLoc) {
17231   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17232                                     LookupOrdinaryName);
17233   WeakInfo W = WeakInfo(Name, NameLoc);
17234 
17235   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17236     if (!PrevDecl->hasAttr<AliasAttr>())
17237       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17238         DeclApplyPragmaWeak(TUScope, ND, W);
17239   } else {
17240     (void)WeakUndeclaredIdentifiers.insert(
17241       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17242   }
17243 }
17244 
17245 Decl *Sema::getObjCDeclContext() const {
17246   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17247 }
17248