xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision 0d66206fff44f864ea8a4b220c3a53b4caa959a0)
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw___ibm128:
146   case tok::kw_wchar_t:
147   case tok::kw_bool:
148   case tok::kw___underlying_type:
149   case tok::kw___auto_type:
150     return true;
151 
152   case tok::annot_typename:
153   case tok::kw_char16_t:
154   case tok::kw_char32_t:
155   case tok::kw_typeof:
156   case tok::annot_decltype:
157   case tok::kw_decltype:
158     return getLangOpts().CPlusPlus;
159 
160   case tok::kw_char8_t:
161     return getLangOpts().Char8;
162 
163   default:
164     break;
165   }
166 
167   return false;
168 }
169 
170 namespace {
171 enum class UnqualifiedTypeNameLookupResult {
172   NotFound,
173   FoundNonType,
174   FoundType
175 };
176 } // end anonymous namespace
177 
178 /// Tries to perform unqualified lookup of the type decls in bases for
179 /// dependent class.
180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181 /// type decl, \a FoundType if only type decls are found.
182 static UnqualifiedTypeNameLookupResult
183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184                                 SourceLocation NameLoc,
185                                 const CXXRecordDecl *RD) {
186   if (!RD->hasDefinition())
187     return UnqualifiedTypeNameLookupResult::NotFound;
188   // Look for type decls in base classes.
189   UnqualifiedTypeNameLookupResult FoundTypeDecl =
190       UnqualifiedTypeNameLookupResult::NotFound;
191   for (const auto &Base : RD->bases()) {
192     const CXXRecordDecl *BaseRD = nullptr;
193     if (auto *BaseTT = Base.getType()->getAs<TagType>())
194       BaseRD = BaseTT->getAsCXXRecordDecl();
195     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
196       // Look for type decls in dependent base classes that have known primary
197       // templates.
198       if (!TST || !TST->isDependentType())
199         continue;
200       auto *TD = TST->getTemplateName().getAsTemplateDecl();
201       if (!TD)
202         continue;
203       if (auto *BasePrimaryTemplate =
204           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206           BaseRD = BasePrimaryTemplate;
207         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208           if (const ClassTemplatePartialSpecializationDecl *PS =
209                   CTD->findPartialSpecialization(Base.getType()))
210             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211               BaseRD = PS;
212         }
213       }
214     }
215     if (BaseRD) {
216       for (NamedDecl *ND : BaseRD->lookup(&II)) {
217         if (!isa<TypeDecl>(ND))
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220       }
221       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
223         case UnqualifiedTypeNameLookupResult::FoundNonType:
224           return UnqualifiedTypeNameLookupResult::FoundNonType;
225         case UnqualifiedTypeNameLookupResult::FoundType:
226           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227           break;
228         case UnqualifiedTypeNameLookupResult::NotFound:
229           break;
230         }
231       }
232     }
233   }
234 
235   return FoundTypeDecl;
236 }
237 
238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239                                                       const IdentifierInfo &II,
240                                                       SourceLocation NameLoc) {
241   // Lookup in the parent class template context, if any.
242   const CXXRecordDecl *RD = nullptr;
243   UnqualifiedTypeNameLookupResult FoundTypeDecl =
244       UnqualifiedTypeNameLookupResult::NotFound;
245   for (DeclContext *DC = S.CurContext;
246        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247        DC = DC->getParent()) {
248     // Look for type decls in dependent base classes that have known primary
249     // templates.
250     RD = dyn_cast<CXXRecordDecl>(DC);
251     if (RD && RD->getDescribedClassTemplate())
252       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253   }
254   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255     return nullptr;
256 
257   // We found some types in dependent base classes.  Recover as if the user
258   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
259   // lookup during template instantiation.
260   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
261 
262   ASTContext &Context = S.Context;
263   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
264                                           cast<Type>(Context.getRecordType(RD)));
265   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
266 
267   CXXScopeSpec SS;
268   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
269 
270   TypeLocBuilder Builder;
271   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272   DepTL.setNameLoc(NameLoc);
273   DepTL.setElaboratedKeywordLoc(SourceLocation());
274   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
276 }
277 
278 /// If the identifier refers to a type name within this scope,
279 /// return the declaration of that type.
280 ///
281 /// This routine performs ordinary name lookup of the identifier II
282 /// within the given scope, with optional C++ scope specifier SS, to
283 /// determine whether the name refers to a type. If so, returns an
284 /// opaque pointer (actually a QualType) corresponding to that
285 /// type. Otherwise, returns NULL.
286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
287                              Scope *S, CXXScopeSpec *SS,
288                              bool isClassName, bool HasTrailingDot,
289                              ParsedType ObjectTypePtr,
290                              bool IsCtorOrDtorName,
291                              bool WantNontrivialTypeSourceInfo,
292                              bool IsClassTemplateDeductionContext,
293                              IdentifierInfo **CorrectedII) {
294   // FIXME: Consider allowing this outside C++1z mode as an extension.
295   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297                               !isClassName && !HasTrailingDot;
298 
299   // Determine where we will perform name lookup.
300   DeclContext *LookupCtx = nullptr;
301   if (ObjectTypePtr) {
302     QualType ObjectType = ObjectTypePtr.get();
303     if (ObjectType->isRecordType())
304       LookupCtx = computeDeclContext(ObjectType);
305   } else if (SS && SS->isNotEmpty()) {
306     LookupCtx = computeDeclContext(*SS, false);
307 
308     if (!LookupCtx) {
309       if (isDependentScopeSpecifier(*SS)) {
310         // C++ [temp.res]p3:
311         //   A qualified-id that refers to a type and in which the
312         //   nested-name-specifier depends on a template-parameter (14.6.2)
313         //   shall be prefixed by the keyword typename to indicate that the
314         //   qualified-id denotes a type, forming an
315         //   elaborated-type-specifier (7.1.5.3).
316         //
317         // We therefore do not perform any name lookup if the result would
318         // refer to a member of an unknown specialization.
319         if (!isClassName && !IsCtorOrDtorName)
320           return nullptr;
321 
322         // We know from the grammar that this name refers to a type,
323         // so build a dependent node to describe the type.
324         if (WantNontrivialTypeSourceInfo)
325           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
326 
327         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
328         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
329                                        II, NameLoc);
330         return ParsedType::make(T);
331       }
332 
333       return nullptr;
334     }
335 
336     if (!LookupCtx->isDependentContext() &&
337         RequireCompleteDeclContext(*SS, LookupCtx))
338       return nullptr;
339   }
340 
341   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
342   // lookup for class-names.
343   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
344                                       LookupOrdinaryName;
345   LookupResult Result(*this, &II, NameLoc, Kind);
346   if (LookupCtx) {
347     // Perform "qualified" name lookup into the declaration context we
348     // computed, which is either the type of the base of a member access
349     // expression or the declaration context associated with a prior
350     // nested-name-specifier.
351     LookupQualifiedName(Result, LookupCtx);
352 
353     if (ObjectTypePtr && Result.empty()) {
354       // C++ [basic.lookup.classref]p3:
355       //   If the unqualified-id is ~type-name, the type-name is looked up
356       //   in the context of the entire postfix-expression. If the type T of
357       //   the object expression is of a class type C, the type-name is also
358       //   looked up in the scope of class C. At least one of the lookups shall
359       //   find a name that refers to (possibly cv-qualified) T.
360       LookupName(Result, S);
361     }
362   } else {
363     // Perform unqualified name lookup.
364     LookupName(Result, S);
365 
366     // For unqualified lookup in a class template in MSVC mode, look into
367     // dependent base classes where the primary class template is known.
368     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
369       if (ParsedType TypeInBase =
370               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
371         return TypeInBase;
372     }
373   }
374 
375   NamedDecl *IIDecl = nullptr;
376   UsingShadowDecl *FoundUsingShadow = nullptr;
377   switch (Result.getResultKind()) {
378   case LookupResult::NotFound:
379   case LookupResult::NotFoundInCurrentInstantiation:
380     if (CorrectedII) {
381       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
382                                AllowDeducedTemplate);
383       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
384                                               S, SS, CCC, CTK_ErrorRecovery);
385       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
386       TemplateTy Template;
387       bool MemberOfUnknownSpecialization;
388       UnqualifiedId TemplateName;
389       TemplateName.setIdentifier(NewII, NameLoc);
390       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
391       CXXScopeSpec NewSS, *NewSSPtr = SS;
392       if (SS && NNS) {
393         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
394         NewSSPtr = &NewSS;
395       }
396       if (Correction && (NNS || NewII != &II) &&
397           // Ignore a correction to a template type as the to-be-corrected
398           // identifier is not a template (typo correction for template names
399           // is handled elsewhere).
400           !(getLangOpts().CPlusPlus && NewSSPtr &&
401             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
402                            Template, MemberOfUnknownSpecialization))) {
403         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
404                                     isClassName, HasTrailingDot, ObjectTypePtr,
405                                     IsCtorOrDtorName,
406                                     WantNontrivialTypeSourceInfo,
407                                     IsClassTemplateDeductionContext);
408         if (Ty) {
409           diagnoseTypo(Correction,
410                        PDiag(diag::err_unknown_type_or_class_name_suggest)
411                          << Result.getLookupName() << isClassName);
412           if (SS && NNS)
413             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
414           *CorrectedII = NewII;
415           return Ty;
416         }
417       }
418     }
419     // If typo correction failed or was not performed, fall through
420     LLVM_FALLTHROUGH;
421   case LookupResult::FoundOverloaded:
422   case LookupResult::FoundUnresolvedValue:
423     Result.suppressDiagnostics();
424     return nullptr;
425 
426   case LookupResult::Ambiguous:
427     // Recover from type-hiding ambiguities by hiding the type.  We'll
428     // do the lookup again when looking for an object, and we can
429     // diagnose the error then.  If we don't do this, then the error
430     // about hiding the type will be immediately followed by an error
431     // that only makes sense if the identifier was treated like a type.
432     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
433       Result.suppressDiagnostics();
434       return nullptr;
435     }
436 
437     // Look to see if we have a type anywhere in the list of results.
438     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
439          Res != ResEnd; ++Res) {
440       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
441       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
442               RealRes) ||
443           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
444         if (!IIDecl ||
445             // Make the selection of the recovery decl deterministic.
446             RealRes->getLocation() < IIDecl->getLocation()) {
447           IIDecl = RealRes;
448           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
449         }
450       }
451     }
452 
453     if (!IIDecl) {
454       // None of the entities we found is a type, so there is no way
455       // to even assume that the result is a type. In this case, don't
456       // complain about the ambiguity. The parser will either try to
457       // perform this lookup again (e.g., as an object name), which
458       // will produce the ambiguity, or will complain that it expected
459       // a type name.
460       Result.suppressDiagnostics();
461       return nullptr;
462     }
463 
464     // We found a type within the ambiguous lookup; diagnose the
465     // ambiguity and then return that type. This might be the right
466     // answer, or it might not be, but it suppresses any attempt to
467     // perform the name lookup again.
468     break;
469 
470   case LookupResult::Found:
471     IIDecl = Result.getFoundDecl();
472     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
473     break;
474   }
475 
476   assert(IIDecl && "Didn't find decl");
477 
478   QualType T;
479   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
480     // C++ [class.qual]p2: A lookup that would find the injected-class-name
481     // instead names the constructors of the class, except when naming a class.
482     // This is ill-formed when we're not actually forming a ctor or dtor name.
483     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
484     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
485     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
486         FoundRD->isInjectedClassName() &&
487         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
488       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
489           << &II << /*Type*/1;
490 
491     DiagnoseUseOfDecl(IIDecl, NameLoc);
492 
493     T = Context.getTypeDeclType(TD);
494     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
495   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
496     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
497     if (!HasTrailingDot)
498       T = Context.getObjCInterfaceType(IDecl);
499     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
500   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
501     (void)DiagnoseUseOfDecl(UD, NameLoc);
502     // Recover with 'int'
503     T = Context.IntTy;
504     FoundUsingShadow = nullptr;
505   } else if (AllowDeducedTemplate) {
506     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
507       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
508       TemplateName Template =
509           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
510       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
511                                                        false);
512       // Don't wrap in a further UsingType.
513       FoundUsingShadow = nullptr;
514     }
515   }
516 
517   if (T.isNull()) {
518     // If it's not plausibly a type, suppress diagnostics.
519     Result.suppressDiagnostics();
520     return nullptr;
521   }
522 
523   if (FoundUsingShadow)
524     T = Context.getUsingType(FoundUsingShadow, T);
525 
526   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
527   // constructor or destructor name (in such a case, the scope specifier
528   // will be attached to the enclosing Expr or Decl node).
529   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
530       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
531     if (WantNontrivialTypeSourceInfo) {
532       // Construct a type with type-source information.
533       TypeLocBuilder Builder;
534       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
535 
536       T = getElaboratedType(ETK_None, *SS, T);
537       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
538       ElabTL.setElaboratedKeywordLoc(SourceLocation());
539       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
540       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
541     } else {
542       T = getElaboratedType(ETK_None, *SS, T);
543     }
544   }
545 
546   return ParsedType::make(T);
547 }
548 
549 // Builds a fake NNS for the given decl context.
550 static NestedNameSpecifier *
551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
552   for (;; DC = DC->getLookupParent()) {
553     DC = DC->getPrimaryContext();
554     auto *ND = dyn_cast<NamespaceDecl>(DC);
555     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
556       return NestedNameSpecifier::Create(Context, nullptr, ND);
557     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
558       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
559                                          RD->getTypeForDecl());
560     else if (isa<TranslationUnitDecl>(DC))
561       return NestedNameSpecifier::GlobalSpecifier(Context);
562   }
563   llvm_unreachable("something isn't in TU scope?");
564 }
565 
566 /// Find the parent class with dependent bases of the innermost enclosing method
567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
568 /// up allowing unqualified dependent type names at class-level, which MSVC
569 /// correctly rejects.
570 static const CXXRecordDecl *
571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
572   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
573     DC = DC->getPrimaryContext();
574     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
575       if (MD->getParent()->hasAnyDependentBases())
576         return MD->getParent();
577   }
578   return nullptr;
579 }
580 
581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
582                                           SourceLocation NameLoc,
583                                           bool IsTemplateTypeArg) {
584   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
585 
586   NestedNameSpecifier *NNS = nullptr;
587   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
588     // If we weren't able to parse a default template argument, delay lookup
589     // until instantiation time by making a non-dependent DependentTypeName. We
590     // pretend we saw a NestedNameSpecifier referring to the current scope, and
591     // lookup is retried.
592     // FIXME: This hurts our diagnostic quality, since we get errors like "no
593     // type named 'Foo' in 'current_namespace'" when the user didn't write any
594     // name specifiers.
595     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
596     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
597   } else if (const CXXRecordDecl *RD =
598                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
599     // Build a DependentNameType that will perform lookup into RD at
600     // instantiation time.
601     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
602                                       RD->getTypeForDecl());
603 
604     // Diagnose that this identifier was undeclared, and retry the lookup during
605     // template instantiation.
606     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
607                                                                       << RD;
608   } else {
609     // This is not a situation that we should recover from.
610     return ParsedType();
611   }
612 
613   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
614 
615   // Build type location information.  We synthesized the qualifier, so we have
616   // to build a fake NestedNameSpecifierLoc.
617   NestedNameSpecifierLocBuilder NNSLocBuilder;
618   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
619   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
620 
621   TypeLocBuilder Builder;
622   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
623   DepTL.setNameLoc(NameLoc);
624   DepTL.setElaboratedKeywordLoc(SourceLocation());
625   DepTL.setQualifierLoc(QualifierLoc);
626   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
627 }
628 
629 /// isTagName() - This method is called *for error recovery purposes only*
630 /// to determine if the specified name is a valid tag name ("struct foo").  If
631 /// so, this returns the TST for the tag corresponding to it (TST_enum,
632 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
633 /// cases in C where the user forgot to specify the tag.
634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
635   // Do a tag name lookup in this scope.
636   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
637   LookupName(R, S, false);
638   R.suppressDiagnostics();
639   if (R.getResultKind() == LookupResult::Found)
640     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
641       switch (TD->getTagKind()) {
642       case TTK_Struct: return DeclSpec::TST_struct;
643       case TTK_Interface: return DeclSpec::TST_interface;
644       case TTK_Union:  return DeclSpec::TST_union;
645       case TTK_Class:  return DeclSpec::TST_class;
646       case TTK_Enum:   return DeclSpec::TST_enum;
647       }
648     }
649 
650   return DeclSpec::TST_unspecified;
651 }
652 
653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
655 /// then downgrade the missing typename error to a warning.
656 /// This is needed for MSVC compatibility; Example:
657 /// @code
658 /// template<class T> class A {
659 /// public:
660 ///   typedef int TYPE;
661 /// };
662 /// template<class T> class B : public A<T> {
663 /// public:
664 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
665 /// };
666 /// @endcode
667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
668   if (CurContext->isRecord()) {
669     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
670       return true;
671 
672     const Type *Ty = SS->getScopeRep()->getAsType();
673 
674     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675     for (const auto &Base : RD->bases())
676       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677         return true;
678     return S->isFunctionPrototypeScope();
679   }
680   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681 }
682 
683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
684                                    SourceLocation IILoc,
685                                    Scope *S,
686                                    CXXScopeSpec *SS,
687                                    ParsedType &SuggestedType,
688                                    bool IsTemplateName) {
689   // Don't report typename errors for editor placeholders.
690   if (II->isEditorPlaceholder())
691     return;
692   // We don't have anything to suggest (yet).
693   SuggestedType = nullptr;
694 
695   // There may have been a typo in the name of the type. Look up typo
696   // results, in case we have something that we can suggest.
697   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698                            /*AllowTemplates=*/IsTemplateName,
699                            /*AllowNonTemplates=*/!IsTemplateName);
700   if (TypoCorrection Corrected =
701           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
702                       CCC, CTK_ErrorRecovery)) {
703     // FIXME: Support error recovery for the template-name case.
704     bool CanRecover = !IsTemplateName;
705     if (Corrected.isKeyword()) {
706       // We corrected to a keyword.
707       diagnoseTypo(Corrected,
708                    PDiag(IsTemplateName ? diag::err_no_template_suggest
709                                         : diag::err_unknown_typename_suggest)
710                        << II);
711       II = Corrected.getCorrectionAsIdentifierInfo();
712     } else {
713       // We found a similarly-named type or interface; suggest that.
714       if (!SS || !SS->isSet()) {
715         diagnoseTypo(Corrected,
716                      PDiag(IsTemplateName ? diag::err_no_template_suggest
717                                           : diag::err_unknown_typename_suggest)
718                          << II, CanRecover);
719       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
722                                 II->getName().equals(CorrectedStr);
723         diagnoseTypo(Corrected,
724                      PDiag(IsTemplateName
725                                ? diag::err_no_member_template_suggest
726                                : diag::err_unknown_nested_typename_suggest)
727                          << II << DC << DroppedSpecifier << SS->getRange(),
728                      CanRecover);
729       } else {
730         llvm_unreachable("could not have corrected a typo here");
731       }
732 
733       if (!CanRecover)
734         return;
735 
736       CXXScopeSpec tmpSS;
737       if (Corrected.getCorrectionSpecifier())
738         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739                           SourceRange(IILoc));
740       // FIXME: Support class template argument deduction here.
741       SuggestedType =
742           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744                       /*IsCtorOrDtorName=*/false,
745                       /*WantNontrivialTypeSourceInfo=*/true);
746     }
747     return;
748   }
749 
750   if (getLangOpts().CPlusPlus && !IsTemplateName) {
751     // See if II is a class template that the user forgot to pass arguments to.
752     UnqualifiedId Name;
753     Name.setIdentifier(II, IILoc);
754     CXXScopeSpec EmptySS;
755     TemplateTy TemplateResult;
756     bool MemberOfUnknownSpecialization;
757     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758                        Name, nullptr, true, TemplateResult,
759                        MemberOfUnknownSpecialization) == TNK_Type_template) {
760       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761       return;
762     }
763   }
764 
765   // FIXME: Should we move the logic that tries to recover from a missing tag
766   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767 
768   if (!SS || (!SS->isSet() && !SS->isInvalid()))
769     Diag(IILoc, IsTemplateName ? diag::err_no_template
770                                : diag::err_unknown_typename)
771         << II;
772   else if (DeclContext *DC = computeDeclContext(*SS, false))
773     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774                                : diag::err_typename_nested_not_found)
775         << II << DC << SS->getRange();
776   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777     SuggestedType =
778         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779   } else if (isDependentScopeSpecifier(*SS)) {
780     unsigned DiagID = diag::err_typename_missing;
781     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782       DiagID = diag::ext_typename_missing;
783 
784     Diag(SS->getRange().getBegin(), DiagID)
785       << SS->getScopeRep() << II->getName()
786       << SourceRange(SS->getRange().getBegin(), IILoc)
787       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788     SuggestedType = ActOnTypenameType(S, SourceLocation(),
789                                       *SS, *II, IILoc).get();
790   } else {
791     assert(SS && SS->isInvalid() &&
792            "Invalid scope specifier has already been diagnosed");
793   }
794 }
795 
796 /// Determine whether the given result set contains either a type name
797 /// or
798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800                        NextToken.is(tok::less);
801 
802   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804       return true;
805 
806     if (CheckTemplate && isa<TemplateDecl>(*I))
807       return true;
808   }
809 
810   return false;
811 }
812 
813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
814                                     Scope *S, CXXScopeSpec &SS,
815                                     IdentifierInfo *&Name,
816                                     SourceLocation NameLoc) {
817   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818   SemaRef.LookupParsedName(R, S, &SS);
819   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820     StringRef FixItTagName;
821     switch (Tag->getTagKind()) {
822       case TTK_Class:
823         FixItTagName = "class ";
824         break;
825 
826       case TTK_Enum:
827         FixItTagName = "enum ";
828         break;
829 
830       case TTK_Struct:
831         FixItTagName = "struct ";
832         break;
833 
834       case TTK_Interface:
835         FixItTagName = "__interface ";
836         break;
837 
838       case TTK_Union:
839         FixItTagName = "union ";
840         break;
841     }
842 
843     StringRef TagName = FixItTagName.drop_back();
844     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847 
848     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849          I != IEnd; ++I)
850       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851         << Name << TagName;
852 
853     // Replace lookup results with just the tag decl.
854     Result.clear(Sema::LookupTagName);
855     SemaRef.LookupParsedName(Result, S, &SS);
856     return true;
857   }
858 
859   return false;
860 }
861 
862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
863                                             IdentifierInfo *&Name,
864                                             SourceLocation NameLoc,
865                                             const Token &NextToken,
866                                             CorrectionCandidateCallback *CCC) {
867   DeclarationNameInfo NameInfo(Name, NameLoc);
868   ObjCMethodDecl *CurMethod = getCurMethodDecl();
869 
870   assert(NextToken.isNot(tok::coloncolon) &&
871          "parse nested name specifiers before calling ClassifyName");
872   if (getLangOpts().CPlusPlus && SS.isSet() &&
873       isCurrentClassName(*Name, S, &SS)) {
874     // Per [class.qual]p2, this names the constructors of SS, not the
875     // injected-class-name. We don't have a classification for that.
876     // There's not much point caching this result, since the parser
877     // will reject it later.
878     return NameClassification::Unknown();
879   }
880 
881   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882   LookupParsedName(Result, S, &SS, !CurMethod);
883 
884   if (SS.isInvalid())
885     return NameClassification::Error();
886 
887   // For unqualified lookup in a class template in MSVC mode, look into
888   // dependent base classes where the primary class template is known.
889   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
890     if (ParsedType TypeInBase =
891             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
892       return TypeInBase;
893   }
894 
895   // Perform lookup for Objective-C instance variables (including automatically
896   // synthesized instance variables), if we're in an Objective-C method.
897   // FIXME: This lookup really, really needs to be folded in to the normal
898   // unqualified lookup mechanism.
899   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
900     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
901     if (Ivar.isInvalid())
902       return NameClassification::Error();
903     if (Ivar.isUsable())
904       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
905 
906     // We defer builtin creation until after ivar lookup inside ObjC methods.
907     if (Result.empty())
908       LookupBuiltin(Result);
909   }
910 
911   bool SecondTry = false;
912   bool IsFilteredTemplateName = false;
913 
914 Corrected:
915   switch (Result.getResultKind()) {
916   case LookupResult::NotFound:
917     // If an unqualified-id is followed by a '(', then we have a function
918     // call.
919     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
920       // In C++, this is an ADL-only call.
921       // FIXME: Reference?
922       if (getLangOpts().CPlusPlus)
923         return NameClassification::UndeclaredNonType();
924 
925       // C90 6.3.2.2:
926       //   If the expression that precedes the parenthesized argument list in a
927       //   function call consists solely of an identifier, and if no
928       //   declaration is visible for this identifier, the identifier is
929       //   implicitly declared exactly as if, in the innermost block containing
930       //   the function call, the declaration
931       //
932       //     extern int identifier ();
933       //
934       //   appeared.
935       //
936       // We also allow this in C99 as an extension. However, this is not
937       // allowed in all language modes as functions without prototypes may not
938       // be supported.
939       if (getLangOpts().implicitFunctionsAllowed()) {
940         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
941           return NameClassification::NonType(D);
942       }
943     }
944 
945     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
946       // In C++20 onwards, this could be an ADL-only call to a function
947       // template, and we're required to assume that this is a template name.
948       //
949       // FIXME: Find a way to still do typo correction in this case.
950       TemplateName Template =
951           Context.getAssumedTemplateName(NameInfo.getName());
952       return NameClassification::UndeclaredTemplate(Template);
953     }
954 
955     // In C, we first see whether there is a tag type by the same name, in
956     // which case it's likely that the user just forgot to write "enum",
957     // "struct", or "union".
958     if (!getLangOpts().CPlusPlus && !SecondTry &&
959         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
960       break;
961     }
962 
963     // Perform typo correction to determine if there is another name that is
964     // close to this name.
965     if (!SecondTry && CCC) {
966       SecondTry = true;
967       if (TypoCorrection Corrected =
968               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
969                           &SS, *CCC, CTK_ErrorRecovery)) {
970         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
971         unsigned QualifiedDiag = diag::err_no_member_suggest;
972 
973         NamedDecl *FirstDecl = Corrected.getFoundDecl();
974         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
975         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
976             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
977           UnqualifiedDiag = diag::err_no_template_suggest;
978           QualifiedDiag = diag::err_no_member_template_suggest;
979         } else if (UnderlyingFirstDecl &&
980                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
981                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
982                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
983           UnqualifiedDiag = diag::err_unknown_typename_suggest;
984           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
985         }
986 
987         if (SS.isEmpty()) {
988           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
989         } else {// FIXME: is this even reachable? Test it.
990           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
991           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
992                                   Name->getName().equals(CorrectedStr);
993           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
994                                     << Name << computeDeclContext(SS, false)
995                                     << DroppedSpecifier << SS.getRange());
996         }
997 
998         // Update the name, so that the caller has the new name.
999         Name = Corrected.getCorrectionAsIdentifierInfo();
1000 
1001         // Typo correction corrected to a keyword.
1002         if (Corrected.isKeyword())
1003           return Name;
1004 
1005         // Also update the LookupResult...
1006         // FIXME: This should probably go away at some point
1007         Result.clear();
1008         Result.setLookupName(Corrected.getCorrection());
1009         if (FirstDecl)
1010           Result.addDecl(FirstDecl);
1011 
1012         // If we found an Objective-C instance variable, let
1013         // LookupInObjCMethod build the appropriate expression to
1014         // reference the ivar.
1015         // FIXME: This is a gross hack.
1016         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1017           DeclResult R =
1018               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1019           if (R.isInvalid())
1020             return NameClassification::Error();
1021           if (R.isUsable())
1022             return NameClassification::NonType(Ivar);
1023         }
1024 
1025         goto Corrected;
1026       }
1027     }
1028 
1029     // We failed to correct; just fall through and let the parser deal with it.
1030     Result.suppressDiagnostics();
1031     return NameClassification::Unknown();
1032 
1033   case LookupResult::NotFoundInCurrentInstantiation: {
1034     // We performed name lookup into the current instantiation, and there were
1035     // dependent bases, so we treat this result the same way as any other
1036     // dependent nested-name-specifier.
1037 
1038     // C++ [temp.res]p2:
1039     //   A name used in a template declaration or definition and that is
1040     //   dependent on a template-parameter is assumed not to name a type
1041     //   unless the applicable name lookup finds a type name or the name is
1042     //   qualified by the keyword typename.
1043     //
1044     // FIXME: If the next token is '<', we might want to ask the parser to
1045     // perform some heroics to see if we actually have a
1046     // template-argument-list, which would indicate a missing 'template'
1047     // keyword here.
1048     return NameClassification::DependentNonType();
1049   }
1050 
1051   case LookupResult::Found:
1052   case LookupResult::FoundOverloaded:
1053   case LookupResult::FoundUnresolvedValue:
1054     break;
1055 
1056   case LookupResult::Ambiguous:
1057     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1059                                       /*AllowDependent=*/false)) {
1060       // C++ [temp.local]p3:
1061       //   A lookup that finds an injected-class-name (10.2) can result in an
1062       //   ambiguity in certain cases (for example, if it is found in more than
1063       //   one base class). If all of the injected-class-names that are found
1064       //   refer to specializations of the same class template, and if the name
1065       //   is followed by a template-argument-list, the reference refers to the
1066       //   class template itself and not a specialization thereof, and is not
1067       //   ambiguous.
1068       //
1069       // This filtering can make an ambiguous result into an unambiguous one,
1070       // so try again after filtering out template names.
1071       FilterAcceptableTemplateNames(Result);
1072       if (!Result.isAmbiguous()) {
1073         IsFilteredTemplateName = true;
1074         break;
1075       }
1076     }
1077 
1078     // Diagnose the ambiguity and return an error.
1079     return NameClassification::Error();
1080   }
1081 
1082   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1083       (IsFilteredTemplateName ||
1084        hasAnyAcceptableTemplateNames(
1085            Result, /*AllowFunctionTemplates=*/true,
1086            /*AllowDependent=*/false,
1087            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1088                getLangOpts().CPlusPlus20))) {
1089     // C++ [temp.names]p3:
1090     //   After name lookup (3.4) finds that a name is a template-name or that
1091     //   an operator-function-id or a literal- operator-id refers to a set of
1092     //   overloaded functions any member of which is a function template if
1093     //   this is followed by a <, the < is always taken as the delimiter of a
1094     //   template-argument-list and never as the less-than operator.
1095     // C++2a [temp.names]p2:
1096     //   A name is also considered to refer to a template if it is an
1097     //   unqualified-id followed by a < and name lookup finds either one
1098     //   or more functions or finds nothing.
1099     if (!IsFilteredTemplateName)
1100       FilterAcceptableTemplateNames(Result);
1101 
1102     bool IsFunctionTemplate;
1103     bool IsVarTemplate;
1104     TemplateName Template;
1105     if (Result.end() - Result.begin() > 1) {
1106       IsFunctionTemplate = true;
1107       Template = Context.getOverloadedTemplateName(Result.begin(),
1108                                                    Result.end());
1109     } else if (!Result.empty()) {
1110       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1111           *Result.begin(), /*AllowFunctionTemplates=*/true,
1112           /*AllowDependent=*/false));
1113       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1114       IsVarTemplate = isa<VarTemplateDecl>(TD);
1115 
1116       UsingShadowDecl *FoundUsingShadow =
1117           dyn_cast<UsingShadowDecl>(*Result.begin());
1118       assert(!FoundUsingShadow ||
1119              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1120       Template =
1121           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1122       if (SS.isNotEmpty())
1123         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1124                                                     /*TemplateKeyword=*/false,
1125                                                     Template);
1126     } else {
1127       // All results were non-template functions. This is a function template
1128       // name.
1129       IsFunctionTemplate = true;
1130       Template = Context.getAssumedTemplateName(NameInfo.getName());
1131     }
1132 
1133     if (IsFunctionTemplate) {
1134       // Function templates always go through overload resolution, at which
1135       // point we'll perform the various checks (e.g., accessibility) we need
1136       // to based on which function we selected.
1137       Result.suppressDiagnostics();
1138 
1139       return NameClassification::FunctionTemplate(Template);
1140     }
1141 
1142     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143                          : NameClassification::TypeTemplate(Template);
1144   }
1145 
1146   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147     QualType T = Context.getTypeDeclType(Type);
1148     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1149       T = Context.getUsingType(USD, T);
1150 
1151     if (SS.isEmpty()) // No elaborated type, trivial location info
1152       return ParsedType::make(T);
1153 
1154     TypeLocBuilder Builder;
1155     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1156     T = getElaboratedType(ETK_None, SS, T);
1157     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1158     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1159     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1160     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1161   };
1162 
1163   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1164   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1165     DiagnoseUseOfDecl(Type, NameLoc);
1166     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1167     return BuildTypeFor(Type, *Result.begin());
1168   }
1169 
1170   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1171   if (!Class) {
1172     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1173     if (ObjCCompatibleAliasDecl *Alias =
1174             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1175       Class = Alias->getClassInterface();
1176   }
1177 
1178   if (Class) {
1179     DiagnoseUseOfDecl(Class, NameLoc);
1180 
1181     if (NextToken.is(tok::period)) {
1182       // Interface. <something> is parsed as a property reference expression.
1183       // Just return "unknown" as a fall-through for now.
1184       Result.suppressDiagnostics();
1185       return NameClassification::Unknown();
1186     }
1187 
1188     QualType T = Context.getObjCInterfaceType(Class);
1189     return ParsedType::make(T);
1190   }
1191 
1192   if (isa<ConceptDecl>(FirstDecl))
1193     return NameClassification::Concept(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1197     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1198     return NameClassification::Error();
1199   }
1200 
1201   // We can have a type template here if we're classifying a template argument.
1202   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1203       !isa<VarTemplateDecl>(FirstDecl))
1204     return NameClassification::TypeTemplate(
1205         TemplateName(cast<TemplateDecl>(FirstDecl)));
1206 
1207   // Check for a tag type hidden by a non-type decl in a few cases where it
1208   // seems likely a type is wanted instead of the non-type that was found.
1209   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1210   if ((NextToken.is(tok::identifier) ||
1211        (NextIsOp &&
1212         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1213       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1214     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1215     DiagnoseUseOfDecl(Type, NameLoc);
1216     return BuildTypeFor(Type, *Result.begin());
1217   }
1218 
1219   // If we already know which single declaration is referenced, just annotate
1220   // that declaration directly. Defer resolving even non-overloaded class
1221   // member accesses, as we need to defer certain access checks until we know
1222   // the context.
1223   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1224   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1225     return NameClassification::NonType(Result.getRepresentativeDecl());
1226 
1227   // Otherwise, this is an overload set that we will need to resolve later.
1228   Result.suppressDiagnostics();
1229   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1230       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1231       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1232       Result.begin(), Result.end()));
1233 }
1234 
1235 ExprResult
1236 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1237                                              SourceLocation NameLoc) {
1238   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1239   CXXScopeSpec SS;
1240   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1241   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1242 }
1243 
1244 ExprResult
1245 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1246                                             IdentifierInfo *Name,
1247                                             SourceLocation NameLoc,
1248                                             bool IsAddressOfOperand) {
1249   DeclarationNameInfo NameInfo(Name, NameLoc);
1250   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1251                                     NameInfo, IsAddressOfOperand,
1252                                     /*TemplateArgs=*/nullptr);
1253 }
1254 
1255 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1256                                               NamedDecl *Found,
1257                                               SourceLocation NameLoc,
1258                                               const Token &NextToken) {
1259   if (getCurMethodDecl() && SS.isEmpty())
1260     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1261       return BuildIvarRefExpr(S, NameLoc, Ivar);
1262 
1263   // Reconstruct the lookup result.
1264   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1265   Result.addDecl(Found);
1266   Result.resolveKind();
1267 
1268   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1269   return BuildDeclarationNameExpr(SS, Result, ADL);
1270 }
1271 
1272 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1273   // For an implicit class member access, transform the result into a member
1274   // access expression if necessary.
1275   auto *ULE = cast<UnresolvedLookupExpr>(E);
1276   if ((*ULE->decls_begin())->isCXXClassMember()) {
1277     CXXScopeSpec SS;
1278     SS.Adopt(ULE->getQualifierLoc());
1279 
1280     // Reconstruct the lookup result.
1281     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1282                         LookupOrdinaryName);
1283     Result.setNamingClass(ULE->getNamingClass());
1284     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1285       Result.addDecl(*I, I.getAccess());
1286     Result.resolveKind();
1287     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1288                                            nullptr, S);
1289   }
1290 
1291   // Otherwise, this is already in the form we needed, and no further checks
1292   // are necessary.
1293   return ULE;
1294 }
1295 
1296 Sema::TemplateNameKindForDiagnostics
1297 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1298   auto *TD = Name.getAsTemplateDecl();
1299   if (!TD)
1300     return TemplateNameKindForDiagnostics::DependentTemplate;
1301   if (isa<ClassTemplateDecl>(TD))
1302     return TemplateNameKindForDiagnostics::ClassTemplate;
1303   if (isa<FunctionTemplateDecl>(TD))
1304     return TemplateNameKindForDiagnostics::FunctionTemplate;
1305   if (isa<VarTemplateDecl>(TD))
1306     return TemplateNameKindForDiagnostics::VarTemplate;
1307   if (isa<TypeAliasTemplateDecl>(TD))
1308     return TemplateNameKindForDiagnostics::AliasTemplate;
1309   if (isa<TemplateTemplateParmDecl>(TD))
1310     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1311   if (isa<ConceptDecl>(TD))
1312     return TemplateNameKindForDiagnostics::Concept;
1313   return TemplateNameKindForDiagnostics::DependentTemplate;
1314 }
1315 
1316 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1317   assert(DC->getLexicalParent() == CurContext &&
1318       "The next DeclContext should be lexically contained in the current one.");
1319   CurContext = DC;
1320   S->setEntity(DC);
1321 }
1322 
1323 void Sema::PopDeclContext() {
1324   assert(CurContext && "DeclContext imbalance!");
1325 
1326   CurContext = CurContext->getLexicalParent();
1327   assert(CurContext && "Popped translation unit!");
1328 }
1329 
1330 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1331                                                                     Decl *D) {
1332   // Unlike PushDeclContext, the context to which we return is not necessarily
1333   // the containing DC of TD, because the new context will be some pre-existing
1334   // TagDecl definition instead of a fresh one.
1335   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1336   CurContext = cast<TagDecl>(D)->getDefinition();
1337   assert(CurContext && "skipping definition of undefined tag");
1338   // Start lookups from the parent of the current context; we don't want to look
1339   // into the pre-existing complete definition.
1340   S->setEntity(CurContext->getLookupParent());
1341   return Result;
1342 }
1343 
1344 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1345   CurContext = static_cast<decltype(CurContext)>(Context);
1346 }
1347 
1348 /// EnterDeclaratorContext - Used when we must lookup names in the context
1349 /// of a declarator's nested name specifier.
1350 ///
1351 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1352   // C++0x [basic.lookup.unqual]p13:
1353   //   A name used in the definition of a static data member of class
1354   //   X (after the qualified-id of the static member) is looked up as
1355   //   if the name was used in a member function of X.
1356   // C++0x [basic.lookup.unqual]p14:
1357   //   If a variable member of a namespace is defined outside of the
1358   //   scope of its namespace then any name used in the definition of
1359   //   the variable member (after the declarator-id) is looked up as
1360   //   if the definition of the variable member occurred in its
1361   //   namespace.
1362   // Both of these imply that we should push a scope whose context
1363   // is the semantic context of the declaration.  We can't use
1364   // PushDeclContext here because that context is not necessarily
1365   // lexically contained in the current context.  Fortunately,
1366   // the containing scope should have the appropriate information.
1367 
1368   assert(!S->getEntity() && "scope already has entity");
1369 
1370 #ifndef NDEBUG
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1374 #endif
1375 
1376   CurContext = DC;
1377   S->setEntity(DC);
1378 
1379   if (S->getParent()->isTemplateParamScope()) {
1380     // Also set the corresponding entities for all immediately-enclosing
1381     // template parameter scopes.
1382     EnterTemplatedContext(S->getParent(), DC);
1383   }
1384 }
1385 
1386 void Sema::ExitDeclaratorContext(Scope *S) {
1387   assert(S->getEntity() == CurContext && "Context imbalance!");
1388 
1389   // Switch back to the lexical context.  The safety of this is
1390   // enforced by an assert in EnterDeclaratorContext.
1391   Scope *Ancestor = S->getParent();
1392   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1393   CurContext = Ancestor->getEntity();
1394 
1395   // We don't need to do anything with the scope, which is going to
1396   // disappear.
1397 }
1398 
1399 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1400   assert(S->isTemplateParamScope() &&
1401          "expected to be initializing a template parameter scope");
1402 
1403   // C++20 [temp.local]p7:
1404   //   In the definition of a member of a class template that appears outside
1405   //   of the class template definition, the name of a member of the class
1406   //   template hides the name of a template-parameter of any enclosing class
1407   //   templates (but not a template-parameter of the member if the member is a
1408   //   class or function template).
1409   // C++20 [temp.local]p9:
1410   //   In the definition of a class template or in the definition of a member
1411   //   of such a template that appears outside of the template definition, for
1412   //   each non-dependent base class (13.8.2.1), if the name of the base class
1413   //   or the name of a member of the base class is the same as the name of a
1414   //   template-parameter, the base class name or member name hides the
1415   //   template-parameter name (6.4.10).
1416   //
1417   // This means that a template parameter scope should be searched immediately
1418   // after searching the DeclContext for which it is a template parameter
1419   // scope. For example, for
1420   //   template<typename T> template<typename U> template<typename V>
1421   //     void N::A<T>::B<U>::f(...)
1422   // we search V then B<U> (and base classes) then U then A<T> (and base
1423   // classes) then T then N then ::.
1424   unsigned ScopeDepth = getTemplateDepth(S);
1425   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1426     DeclContext *SearchDCAfterScope = DC;
1427     for (; DC; DC = DC->getLookupParent()) {
1428       if (const TemplateParameterList *TPL =
1429               cast<Decl>(DC)->getDescribedTemplateParams()) {
1430         unsigned DCDepth = TPL->getDepth() + 1;
1431         if (DCDepth > ScopeDepth)
1432           continue;
1433         if (ScopeDepth == DCDepth)
1434           SearchDCAfterScope = DC = DC->getLookupParent();
1435         break;
1436       }
1437     }
1438     S->setLookupEntity(SearchDCAfterScope);
1439   }
1440 }
1441 
1442 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1443   // We assume that the caller has already called
1444   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1445   FunctionDecl *FD = D->getAsFunction();
1446   if (!FD)
1447     return;
1448 
1449   // Same implementation as PushDeclContext, but enters the context
1450   // from the lexical parent, rather than the top-level class.
1451   assert(CurContext == FD->getLexicalParent() &&
1452     "The next DeclContext should be lexically contained in the current one.");
1453   CurContext = FD;
1454   S->setEntity(CurContext);
1455 
1456   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1457     ParmVarDecl *Param = FD->getParamDecl(P);
1458     // If the parameter has an identifier, then add it to the scope
1459     if (Param->getIdentifier()) {
1460       S->AddDecl(Param);
1461       IdResolver.AddDecl(Param);
1462     }
1463   }
1464 }
1465 
1466 void Sema::ActOnExitFunctionContext() {
1467   // Same implementation as PopDeclContext, but returns to the lexical parent,
1468   // rather than the top-level class.
1469   assert(CurContext && "DeclContext imbalance!");
1470   CurContext = CurContext->getLexicalParent();
1471   assert(CurContext && "Popped translation unit!");
1472 }
1473 
1474 /// Determine whether overloading is allowed for a new function
1475 /// declaration considering prior declarations of the same name.
1476 ///
1477 /// This routine determines whether overloading is possible, not
1478 /// whether a new declaration actually overloads a previous one.
1479 /// It will return true in C++ (where overloads are alway permitted)
1480 /// or, as a C extension, when either the new declaration or a
1481 /// previous one is declared with the 'overloadable' attribute.
1482 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1483                                        ASTContext &Context,
1484                                        const FunctionDecl *New) {
1485   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1486     return true;
1487 
1488   // Multiversion function declarations are not overloads in the
1489   // usual sense of that term, but lookup will report that an
1490   // overload set was found if more than one multiversion function
1491   // declaration is present for the same name. It is therefore
1492   // inadequate to assume that some prior declaration(s) had
1493   // the overloadable attribute; checking is required. Since one
1494   // declaration is permitted to omit the attribute, it is necessary
1495   // to check at least two; hence the 'any_of' check below. Note that
1496   // the overloadable attribute is implicitly added to declarations
1497   // that were required to have it but did not.
1498   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1499     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1500       return ND->hasAttr<OverloadableAttr>();
1501     });
1502   } else if (Previous.getResultKind() == LookupResult::Found)
1503     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1504 
1505   return false;
1506 }
1507 
1508 /// Add this decl to the scope shadowed decl chains.
1509 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1510   // Move up the scope chain until we find the nearest enclosing
1511   // non-transparent context. The declaration will be introduced into this
1512   // scope.
1513   while (S->getEntity() && S->getEntity()->isTransparentContext())
1514     S = S->getParent();
1515 
1516   // Add scoped declarations into their context, so that they can be
1517   // found later. Declarations without a context won't be inserted
1518   // into any context.
1519   if (AddToContext)
1520     CurContext->addDecl(D);
1521 
1522   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1523   // are function-local declarations.
1524   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1525     return;
1526 
1527   // Template instantiations should also not be pushed into scope.
1528   if (isa<FunctionDecl>(D) &&
1529       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1530     return;
1531 
1532   // If this replaces anything in the current scope,
1533   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1534                                IEnd = IdResolver.end();
1535   for (; I != IEnd; ++I) {
1536     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1537       S->RemoveDecl(*I);
1538       IdResolver.RemoveDecl(*I);
1539 
1540       // Should only need to replace one decl.
1541       break;
1542     }
1543   }
1544 
1545   S->AddDecl(D);
1546 
1547   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1548     // Implicitly-generated labels may end up getting generated in an order that
1549     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1550     // the label at the appropriate place in the identifier chain.
1551     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1552       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1553       if (IDC == CurContext) {
1554         if (!S->isDeclScope(*I))
1555           continue;
1556       } else if (IDC->Encloses(CurContext))
1557         break;
1558     }
1559 
1560     IdResolver.InsertDeclAfter(I, D);
1561   } else {
1562     IdResolver.AddDecl(D);
1563   }
1564   warnOnReservedIdentifier(D);
1565 }
1566 
1567 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1568                          bool AllowInlineNamespace) {
1569   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1570 }
1571 
1572 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1573   DeclContext *TargetDC = DC->getPrimaryContext();
1574   do {
1575     if (DeclContext *ScopeDC = S->getEntity())
1576       if (ScopeDC->getPrimaryContext() == TargetDC)
1577         return S;
1578   } while ((S = S->getParent()));
1579 
1580   return nullptr;
1581 }
1582 
1583 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1584                                             DeclContext*,
1585                                             ASTContext&);
1586 
1587 /// Filters out lookup results that don't fall within the given scope
1588 /// as determined by isDeclInScope.
1589 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1590                                 bool ConsiderLinkage,
1591                                 bool AllowInlineNamespace) {
1592   LookupResult::Filter F = R.makeFilter();
1593   while (F.hasNext()) {
1594     NamedDecl *D = F.next();
1595 
1596     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1597       continue;
1598 
1599     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1600       continue;
1601 
1602     F.erase();
1603   }
1604 
1605   F.done();
1606 }
1607 
1608 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1609 /// have compatible owning modules.
1610 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1611   // [module.interface]p7:
1612   // A declaration is attached to a module as follows:
1613   // - If the declaration is a non-dependent friend declaration that nominates a
1614   // function with a declarator-id that is a qualified-id or template-id or that
1615   // nominates a class other than with an elaborated-type-specifier with neither
1616   // a nested-name-specifier nor a simple-template-id, it is attached to the
1617   // module to which the friend is attached ([basic.link]).
1618   if (New->getFriendObjectKind() &&
1619       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1620     New->setLocalOwningModule(Old->getOwningModule());
1621     makeMergedDefinitionVisible(New);
1622     return false;
1623   }
1624 
1625   Module *NewM = New->getOwningModule();
1626   Module *OldM = Old->getOwningModule();
1627 
1628   if (NewM && NewM->isPrivateModule())
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->isPrivateModule())
1631     OldM = OldM->Parent;
1632 
1633   if (NewM == OldM)
1634     return false;
1635 
1636   // Partitions are part of the module, but a partition could import another
1637   // module, so verify that the PMIs agree.
1638   if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
1639     return NewM->getPrimaryModuleInterfaceName() ==
1640            OldM->getPrimaryModuleInterfaceName();
1641 
1642   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1643   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1644   if (NewIsModuleInterface || OldIsModuleInterface) {
1645     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1646     //   if a declaration of D [...] appears in the purview of a module, all
1647     //   other such declarations shall appear in the purview of the same module
1648     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1649       << New
1650       << NewIsModuleInterface
1651       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1652       << OldIsModuleInterface
1653       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1654     Diag(Old->getLocation(), diag::note_previous_declaration);
1655     New->setInvalidDecl();
1656     return true;
1657   }
1658 
1659   return false;
1660 }
1661 
1662 // [module.interface]p6:
1663 // A redeclaration of an entity X is implicitly exported if X was introduced by
1664 // an exported declaration; otherwise it shall not be exported.
1665 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1666   // [module.interface]p1:
1667   // An export-declaration shall inhabit a namespace scope.
1668   //
1669   // So it is meaningless to talk about redeclaration which is not at namespace
1670   // scope.
1671   if (!New->getLexicalDeclContext()
1672            ->getNonTransparentContext()
1673            ->isFileContext() ||
1674       !Old->getLexicalDeclContext()
1675            ->getNonTransparentContext()
1676            ->isFileContext())
1677     return false;
1678 
1679   bool IsNewExported = New->isInExportDeclContext();
1680   bool IsOldExported = Old->isInExportDeclContext();
1681 
1682   // It should be irrevelant if both of them are not exported.
1683   if (!IsNewExported && !IsOldExported)
1684     return false;
1685 
1686   if (IsOldExported)
1687     return false;
1688 
1689   assert(IsNewExported);
1690 
1691   auto Lk = Old->getFormalLinkage();
1692   int S = 0;
1693   if (Lk == Linkage::InternalLinkage)
1694     S = 1;
1695   else if (Lk == Linkage::ModuleLinkage)
1696     S = 2;
1697   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698   Diag(Old->getLocation(), diag::note_previous_declaration);
1699   return true;
1700 }
1701 
1702 // A wrapper function for checking the semantic restrictions of
1703 // a redeclaration within a module.
1704 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1705   if (CheckRedeclarationModuleOwnership(New, Old))
1706     return true;
1707 
1708   if (CheckRedeclarationExported(New, Old))
1709     return true;
1710 
1711   return false;
1712 }
1713 
1714 // Check the redefinition in C++20 Modules.
1715 //
1716 // [basic.def.odr]p14:
1717 // For any definable item D with definitions in multiple translation units,
1718 // - if D is a non-inline non-templated function or variable, or
1719 // - if the definitions in different translation units do not satisfy the
1720 // following requirements,
1721 //   the program is ill-formed; a diagnostic is required only if the definable
1722 //   item is attached to a named module and a prior definition is reachable at
1723 //   the point where a later definition occurs.
1724 // - Each such definition shall not be attached to a named module
1725 // ([module.unit]).
1726 // - Each such definition shall consist of the same sequence of tokens, ...
1727 // ...
1728 //
1729 // Return true if the redefinition is not allowed. Return false otherwise.
1730 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1731                                      const NamedDecl *Old) const {
1732   assert(getASTContext().isSameEntity(New, Old) &&
1733          "New and Old are not the same definition, we should diagnostic it "
1734          "immediately instead of checking it.");
1735   assert(const_cast<Sema *>(this)->isReachable(New) &&
1736          const_cast<Sema *>(this)->isReachable(Old) &&
1737          "We shouldn't see unreachable definitions here.");
1738 
1739   Module *NewM = New->getOwningModule();
1740   Module *OldM = Old->getOwningModule();
1741 
1742   // We only checks for named modules here. The header like modules is skipped.
1743   // FIXME: This is not right if we import the header like modules in the module
1744   // purview.
1745   //
1746   // For example, assuming "header.h" provides definition for `D`.
1747   // ```C++
1748   // //--- M.cppm
1749   // export module M;
1750   // import "header.h"; // or #include "header.h" but import it by clang modules
1751   // actually.
1752   //
1753   // //--- Use.cpp
1754   // import M;
1755   // import "header.h"; // or uses clang modules.
1756   // ```
1757   //
1758   // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1759   // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1760   // reject it. But the current implementation couldn't detect the case since we
1761   // don't record the information about the importee modules.
1762   //
1763   // But this might not be painful in practice. Since the design of C++20 Named
1764   // Modules suggests us to use headers in global module fragment instead of
1765   // module purview.
1766   if (NewM && NewM->isHeaderLikeModule())
1767     NewM = nullptr;
1768   if (OldM && OldM->isHeaderLikeModule())
1769     OldM = nullptr;
1770 
1771   if (!NewM && !OldM)
1772     return true;
1773 
1774   // [basic.def.odr]p14.3
1775   // Each such definition shall not be attached to a named module
1776   // ([module.unit]).
1777   if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1778     return true;
1779 
1780   // Then New and Old lives in the same TU if their share one same module unit.
1781   if (NewM)
1782     NewM = NewM->getTopLevelModule();
1783   if (OldM)
1784     OldM = OldM->getTopLevelModule();
1785   return OldM == NewM;
1786 }
1787 
1788 static bool isUsingDecl(NamedDecl *D) {
1789   return isa<UsingShadowDecl>(D) ||
1790          isa<UnresolvedUsingTypenameDecl>(D) ||
1791          isa<UnresolvedUsingValueDecl>(D);
1792 }
1793 
1794 /// Removes using shadow declarations from the lookup results.
1795 static void RemoveUsingDecls(LookupResult &R) {
1796   LookupResult::Filter F = R.makeFilter();
1797   while (F.hasNext())
1798     if (isUsingDecl(F.next()))
1799       F.erase();
1800 
1801   F.done();
1802 }
1803 
1804 /// Check for this common pattern:
1805 /// @code
1806 /// class S {
1807 ///   S(const S&); // DO NOT IMPLEMENT
1808 ///   void operator=(const S&); // DO NOT IMPLEMENT
1809 /// };
1810 /// @endcode
1811 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1812   // FIXME: Should check for private access too but access is set after we get
1813   // the decl here.
1814   if (D->doesThisDeclarationHaveABody())
1815     return false;
1816 
1817   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1818     return CD->isCopyConstructor();
1819   return D->isCopyAssignmentOperator();
1820 }
1821 
1822 // We need this to handle
1823 //
1824 // typedef struct {
1825 //   void *foo() { return 0; }
1826 // } A;
1827 //
1828 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1829 // for example. If 'A', foo will have external linkage. If we have '*A',
1830 // foo will have no linkage. Since we can't know until we get to the end
1831 // of the typedef, this function finds out if D might have non-external linkage.
1832 // Callers should verify at the end of the TU if it D has external linkage or
1833 // not.
1834 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1835   const DeclContext *DC = D->getDeclContext();
1836   while (!DC->isTranslationUnit()) {
1837     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1838       if (!RD->hasNameForLinkage())
1839         return true;
1840     }
1841     DC = DC->getParent();
1842   }
1843 
1844   return !D->isExternallyVisible();
1845 }
1846 
1847 // FIXME: This needs to be refactored; some other isInMainFile users want
1848 // these semantics.
1849 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1850   if (S.TUKind != TU_Complete)
1851     return false;
1852   return S.SourceMgr.isInMainFile(Loc);
1853 }
1854 
1855 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1856   assert(D);
1857 
1858   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1859     return false;
1860 
1861   // Ignore all entities declared within templates, and out-of-line definitions
1862   // of members of class templates.
1863   if (D->getDeclContext()->isDependentContext() ||
1864       D->getLexicalDeclContext()->isDependentContext())
1865     return false;
1866 
1867   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1868     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1869       return false;
1870     // A non-out-of-line declaration of a member specialization was implicitly
1871     // instantiated; it's the out-of-line declaration that we're interested in.
1872     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1873         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1874       return false;
1875 
1876     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1877       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1878         return false;
1879     } else {
1880       // 'static inline' functions are defined in headers; don't warn.
1881       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1882         return false;
1883     }
1884 
1885     if (FD->doesThisDeclarationHaveABody() &&
1886         Context.DeclMustBeEmitted(FD))
1887       return false;
1888   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1889     // Constants and utility variables are defined in headers with internal
1890     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1891     // like "inline".)
1892     if (!isMainFileLoc(*this, VD->getLocation()))
1893       return false;
1894 
1895     if (Context.DeclMustBeEmitted(VD))
1896       return false;
1897 
1898     if (VD->isStaticDataMember() &&
1899         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1900       return false;
1901     if (VD->isStaticDataMember() &&
1902         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1903         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1904       return false;
1905 
1906     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1907       return false;
1908   } else {
1909     return false;
1910   }
1911 
1912   // Only warn for unused decls internal to the translation unit.
1913   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1914   // for inline functions defined in the main source file, for instance.
1915   return mightHaveNonExternalLinkage(D);
1916 }
1917 
1918 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1919   if (!D)
1920     return;
1921 
1922   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1923     const FunctionDecl *First = FD->getFirstDecl();
1924     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1925       return; // First should already be in the vector.
1926   }
1927 
1928   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1929     const VarDecl *First = VD->getFirstDecl();
1930     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1931       return; // First should already be in the vector.
1932   }
1933 
1934   if (ShouldWarnIfUnusedFileScopedDecl(D))
1935     UnusedFileScopedDecls.push_back(D);
1936 }
1937 
1938 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1939   if (D->isInvalidDecl())
1940     return false;
1941 
1942   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1943     // For a decomposition declaration, warn if none of the bindings are
1944     // referenced, instead of if the variable itself is referenced (which
1945     // it is, by the bindings' expressions).
1946     for (auto *BD : DD->bindings())
1947       if (BD->isReferenced())
1948         return false;
1949   } else if (!D->getDeclName()) {
1950     return false;
1951   } else if (D->isReferenced() || D->isUsed()) {
1952     return false;
1953   }
1954 
1955   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1956     return false;
1957 
1958   if (isa<LabelDecl>(D))
1959     return true;
1960 
1961   // Except for labels, we only care about unused decls that are local to
1962   // functions.
1963   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1964   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1965     // For dependent types, the diagnostic is deferred.
1966     WithinFunction =
1967         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1968   if (!WithinFunction)
1969     return false;
1970 
1971   if (isa<TypedefNameDecl>(D))
1972     return true;
1973 
1974   // White-list anything that isn't a local variable.
1975   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1976     return false;
1977 
1978   // Types of valid local variables should be complete, so this should succeed.
1979   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1980 
1981     const Expr *Init = VD->getInit();
1982     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1983       Init = Cleanups->getSubExpr();
1984 
1985     const auto *Ty = VD->getType().getTypePtr();
1986 
1987     // Only look at the outermost level of typedef.
1988     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1989       // Allow anything marked with __attribute__((unused)).
1990       if (TT->getDecl()->hasAttr<UnusedAttr>())
1991         return false;
1992     }
1993 
1994     // Warn for reference variables whose initializtion performs lifetime
1995     // extension.
1996     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1997       if (MTE->getExtendingDecl()) {
1998         Ty = VD->getType().getNonReferenceType().getTypePtr();
1999         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2000       }
2001     }
2002 
2003     // If we failed to complete the type for some reason, or if the type is
2004     // dependent, don't diagnose the variable.
2005     if (Ty->isIncompleteType() || Ty->isDependentType())
2006       return false;
2007 
2008     // Look at the element type to ensure that the warning behaviour is
2009     // consistent for both scalars and arrays.
2010     Ty = Ty->getBaseElementTypeUnsafe();
2011 
2012     if (const TagType *TT = Ty->getAs<TagType>()) {
2013       const TagDecl *Tag = TT->getDecl();
2014       if (Tag->hasAttr<UnusedAttr>())
2015         return false;
2016 
2017       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2018         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2019           return false;
2020 
2021         if (Init) {
2022           const CXXConstructExpr *Construct =
2023             dyn_cast<CXXConstructExpr>(Init);
2024           if (Construct && !Construct->isElidable()) {
2025             CXXConstructorDecl *CD = Construct->getConstructor();
2026             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2027                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2028               return false;
2029           }
2030 
2031           // Suppress the warning if we don't know how this is constructed, and
2032           // it could possibly be non-trivial constructor.
2033           if (Init->isTypeDependent()) {
2034             for (const CXXConstructorDecl *Ctor : RD->ctors())
2035               if (!Ctor->isTrivial())
2036                 return false;
2037           }
2038 
2039           // Suppress the warning if the constructor is unresolved because
2040           // its arguments are dependent.
2041           if (isa<CXXUnresolvedConstructExpr>(Init))
2042             return false;
2043         }
2044       }
2045     }
2046 
2047     // TODO: __attribute__((unused)) templates?
2048   }
2049 
2050   return true;
2051 }
2052 
2053 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2054                                      FixItHint &Hint) {
2055   if (isa<LabelDecl>(D)) {
2056     SourceLocation AfterColon = Lexer::findLocationAfterToken(
2057         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2058         true);
2059     if (AfterColon.isInvalid())
2060       return;
2061     Hint = FixItHint::CreateRemoval(
2062         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2063   }
2064 }
2065 
2066 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2067   if (D->getTypeForDecl()->isDependentType())
2068     return;
2069 
2070   for (auto *TmpD : D->decls()) {
2071     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2072       DiagnoseUnusedDecl(T);
2073     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2074       DiagnoseUnusedNestedTypedefs(R);
2075   }
2076 }
2077 
2078 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2079 /// unless they are marked attr(unused).
2080 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2081   if (!ShouldDiagnoseUnusedDecl(D))
2082     return;
2083 
2084   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2085     // typedefs can be referenced later on, so the diagnostics are emitted
2086     // at end-of-translation-unit.
2087     UnusedLocalTypedefNameCandidates.insert(TD);
2088     return;
2089   }
2090 
2091   FixItHint Hint;
2092   GenerateFixForUnusedDecl(D, Context, Hint);
2093 
2094   unsigned DiagID;
2095   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2096     DiagID = diag::warn_unused_exception_param;
2097   else if (isa<LabelDecl>(D))
2098     DiagID = diag::warn_unused_label;
2099   else
2100     DiagID = diag::warn_unused_variable;
2101 
2102   Diag(D->getLocation(), DiagID) << D << Hint;
2103 }
2104 
2105 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2106   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2107   // it's not really unused.
2108   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2109       VD->hasAttr<CleanupAttr>())
2110     return;
2111 
2112   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2113 
2114   if (Ty->isReferenceType() || Ty->isDependentType())
2115     return;
2116 
2117   if (const TagType *TT = Ty->getAs<TagType>()) {
2118     const TagDecl *Tag = TT->getDecl();
2119     if (Tag->hasAttr<UnusedAttr>())
2120       return;
2121     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2122     // mimic gcc's behavior.
2123     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2124       if (!RD->hasAttr<WarnUnusedAttr>())
2125         return;
2126     }
2127   }
2128 
2129   // Don't warn about __block Objective-C pointer variables, as they might
2130   // be assigned in the block but not used elsewhere for the purpose of lifetime
2131   // extension.
2132   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2133     return;
2134 
2135   // Don't warn about Objective-C pointer variables with precise lifetime
2136   // semantics; they can be used to ensure ARC releases the object at a known
2137   // time, which may mean assignment but no other references.
2138   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2139     return;
2140 
2141   auto iter = RefsMinusAssignments.find(VD);
2142   if (iter == RefsMinusAssignments.end())
2143     return;
2144 
2145   assert(iter->getSecond() >= 0 &&
2146          "Found a negative number of references to a VarDecl");
2147   if (iter->getSecond() != 0)
2148     return;
2149   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2150                                          : diag::warn_unused_but_set_variable;
2151   Diag(VD->getLocation(), DiagID) << VD;
2152 }
2153 
2154 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2155   // Verify that we have no forward references left.  If so, there was a goto
2156   // or address of a label taken, but no definition of it.  Label fwd
2157   // definitions are indicated with a null substmt which is also not a resolved
2158   // MS inline assembly label name.
2159   bool Diagnose = false;
2160   if (L->isMSAsmLabel())
2161     Diagnose = !L->isResolvedMSAsmLabel();
2162   else
2163     Diagnose = L->getStmt() == nullptr;
2164   if (Diagnose)
2165     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2166 }
2167 
2168 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2169   S->applyNRVO();
2170 
2171   if (S->decl_empty()) return;
2172   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2173          "Scope shouldn't contain decls!");
2174 
2175   for (auto *TmpD : S->decls()) {
2176     assert(TmpD && "This decl didn't get pushed??");
2177 
2178     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2179     NamedDecl *D = cast<NamedDecl>(TmpD);
2180 
2181     // Diagnose unused variables in this scope.
2182     if (!S->hasUnrecoverableErrorOccurred()) {
2183       DiagnoseUnusedDecl(D);
2184       if (const auto *RD = dyn_cast<RecordDecl>(D))
2185         DiagnoseUnusedNestedTypedefs(RD);
2186       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2187         DiagnoseUnusedButSetDecl(VD);
2188         RefsMinusAssignments.erase(VD);
2189       }
2190     }
2191 
2192     if (!D->getDeclName()) continue;
2193 
2194     // If this was a forward reference to a label, verify it was defined.
2195     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2196       CheckPoppedLabel(LD, *this);
2197 
2198     // Remove this name from our lexical scope, and warn on it if we haven't
2199     // already.
2200     IdResolver.RemoveDecl(D);
2201     auto ShadowI = ShadowingDecls.find(D);
2202     if (ShadowI != ShadowingDecls.end()) {
2203       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2204         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2205             << D << FD << FD->getParent();
2206         Diag(FD->getLocation(), diag::note_previous_declaration);
2207       }
2208       ShadowingDecls.erase(ShadowI);
2209     }
2210   }
2211 }
2212 
2213 /// Look for an Objective-C class in the translation unit.
2214 ///
2215 /// \param Id The name of the Objective-C class we're looking for. If
2216 /// typo-correction fixes this name, the Id will be updated
2217 /// to the fixed name.
2218 ///
2219 /// \param IdLoc The location of the name in the translation unit.
2220 ///
2221 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2222 /// if there is no class with the given name.
2223 ///
2224 /// \returns The declaration of the named Objective-C class, or NULL if the
2225 /// class could not be found.
2226 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2227                                               SourceLocation IdLoc,
2228                                               bool DoTypoCorrection) {
2229   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2230   // creation from this context.
2231   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2232 
2233   if (!IDecl && DoTypoCorrection) {
2234     // Perform typo correction at the given location, but only if we
2235     // find an Objective-C class name.
2236     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2237     if (TypoCorrection C =
2238             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2239                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2240       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2241       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2242       Id = IDecl->getIdentifier();
2243     }
2244   }
2245   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2246   // This routine must always return a class definition, if any.
2247   if (Def && Def->getDefinition())
2248       Def = Def->getDefinition();
2249   return Def;
2250 }
2251 
2252 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2253 /// from S, where a non-field would be declared. This routine copes
2254 /// with the difference between C and C++ scoping rules in structs and
2255 /// unions. For example, the following code is well-formed in C but
2256 /// ill-formed in C++:
2257 /// @code
2258 /// struct S6 {
2259 ///   enum { BAR } e;
2260 /// };
2261 ///
2262 /// void test_S6() {
2263 ///   struct S6 a;
2264 ///   a.e = BAR;
2265 /// }
2266 /// @endcode
2267 /// For the declaration of BAR, this routine will return a different
2268 /// scope. The scope S will be the scope of the unnamed enumeration
2269 /// within S6. In C++, this routine will return the scope associated
2270 /// with S6, because the enumeration's scope is a transparent
2271 /// context but structures can contain non-field names. In C, this
2272 /// routine will return the translation unit scope, since the
2273 /// enumeration's scope is a transparent context and structures cannot
2274 /// contain non-field names.
2275 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2276   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2277          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2278          (S->isClassScope() && !getLangOpts().CPlusPlus))
2279     S = S->getParent();
2280   return S;
2281 }
2282 
2283 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2284                                ASTContext::GetBuiltinTypeError Error) {
2285   switch (Error) {
2286   case ASTContext::GE_None:
2287     return "";
2288   case ASTContext::GE_Missing_type:
2289     return BuiltinInfo.getHeaderName(ID);
2290   case ASTContext::GE_Missing_stdio:
2291     return "stdio.h";
2292   case ASTContext::GE_Missing_setjmp:
2293     return "setjmp.h";
2294   case ASTContext::GE_Missing_ucontext:
2295     return "ucontext.h";
2296   }
2297   llvm_unreachable("unhandled error kind");
2298 }
2299 
2300 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2301                                   unsigned ID, SourceLocation Loc) {
2302   DeclContext *Parent = Context.getTranslationUnitDecl();
2303 
2304   if (getLangOpts().CPlusPlus) {
2305     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2306         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2307     CLinkageDecl->setImplicit();
2308     Parent->addDecl(CLinkageDecl);
2309     Parent = CLinkageDecl;
2310   }
2311 
2312   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2313                                            /*TInfo=*/nullptr, SC_Extern,
2314                                            getCurFPFeatures().isFPConstrained(),
2315                                            false, Type->isFunctionProtoType());
2316   New->setImplicit();
2317   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2318 
2319   // Create Decl objects for each parameter, adding them to the
2320   // FunctionDecl.
2321   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2322     SmallVector<ParmVarDecl *, 16> Params;
2323     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2324       ParmVarDecl *parm = ParmVarDecl::Create(
2325           Context, New, SourceLocation(), SourceLocation(), nullptr,
2326           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2327       parm->setScopeInfo(0, i);
2328       Params.push_back(parm);
2329     }
2330     New->setParams(Params);
2331   }
2332 
2333   AddKnownFunctionAttributes(New);
2334   return New;
2335 }
2336 
2337 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2338 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2339 /// if we're creating this built-in in anticipation of redeclaring the
2340 /// built-in.
2341 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2342                                      Scope *S, bool ForRedeclaration,
2343                                      SourceLocation Loc) {
2344   LookupNecessaryTypesForBuiltin(S, ID);
2345 
2346   ASTContext::GetBuiltinTypeError Error;
2347   QualType R = Context.GetBuiltinType(ID, Error);
2348   if (Error) {
2349     if (!ForRedeclaration)
2350       return nullptr;
2351 
2352     // If we have a builtin without an associated type we should not emit a
2353     // warning when we were not able to find a type for it.
2354     if (Error == ASTContext::GE_Missing_type ||
2355         Context.BuiltinInfo.allowTypeMismatch(ID))
2356       return nullptr;
2357 
2358     // If we could not find a type for setjmp it is because the jmp_buf type was
2359     // not defined prior to the setjmp declaration.
2360     if (Error == ASTContext::GE_Missing_setjmp) {
2361       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2362           << Context.BuiltinInfo.getName(ID);
2363       return nullptr;
2364     }
2365 
2366     // Generally, we emit a warning that the declaration requires the
2367     // appropriate header.
2368     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2369         << getHeaderName(Context.BuiltinInfo, ID, Error)
2370         << Context.BuiltinInfo.getName(ID);
2371     return nullptr;
2372   }
2373 
2374   if (!ForRedeclaration &&
2375       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2376        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2377     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2378                            : diag::ext_implicit_lib_function_decl)
2379         << Context.BuiltinInfo.getName(ID) << R;
2380     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2381       Diag(Loc, diag::note_include_header_or_declare)
2382           << Header << Context.BuiltinInfo.getName(ID);
2383   }
2384 
2385   if (R.isNull())
2386     return nullptr;
2387 
2388   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2389   RegisterLocallyScopedExternCDecl(New, S);
2390 
2391   // TUScope is the translation-unit scope to insert this function into.
2392   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2393   // relate Scopes to DeclContexts, and probably eliminate CurContext
2394   // entirely, but we're not there yet.
2395   DeclContext *SavedContext = CurContext;
2396   CurContext = New->getDeclContext();
2397   PushOnScopeChains(New, TUScope);
2398   CurContext = SavedContext;
2399   return New;
2400 }
2401 
2402 /// Typedef declarations don't have linkage, but they still denote the same
2403 /// entity if their types are the same.
2404 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2405 /// isSameEntity.
2406 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2407                                                      TypedefNameDecl *Decl,
2408                                                      LookupResult &Previous) {
2409   // This is only interesting when modules are enabled.
2410   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2411     return;
2412 
2413   // Empty sets are uninteresting.
2414   if (Previous.empty())
2415     return;
2416 
2417   LookupResult::Filter Filter = Previous.makeFilter();
2418   while (Filter.hasNext()) {
2419     NamedDecl *Old = Filter.next();
2420 
2421     // Non-hidden declarations are never ignored.
2422     if (S.isVisible(Old))
2423       continue;
2424 
2425     // Declarations of the same entity are not ignored, even if they have
2426     // different linkages.
2427     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2428       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2429                                 Decl->getUnderlyingType()))
2430         continue;
2431 
2432       // If both declarations give a tag declaration a typedef name for linkage
2433       // purposes, then they declare the same entity.
2434       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2435           Decl->getAnonDeclWithTypedefName())
2436         continue;
2437     }
2438 
2439     Filter.erase();
2440   }
2441 
2442   Filter.done();
2443 }
2444 
2445 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2446   QualType OldType;
2447   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2448     OldType = OldTypedef->getUnderlyingType();
2449   else
2450     OldType = Context.getTypeDeclType(Old);
2451   QualType NewType = New->getUnderlyingType();
2452 
2453   if (NewType->isVariablyModifiedType()) {
2454     // Must not redefine a typedef with a variably-modified type.
2455     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2456     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2457       << Kind << NewType;
2458     if (Old->getLocation().isValid())
2459       notePreviousDefinition(Old, New->getLocation());
2460     New->setInvalidDecl();
2461     return true;
2462   }
2463 
2464   if (OldType != NewType &&
2465       !OldType->isDependentType() &&
2466       !NewType->isDependentType() &&
2467       !Context.hasSameType(OldType, NewType)) {
2468     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2469     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2470       << Kind << NewType << OldType;
2471     if (Old->getLocation().isValid())
2472       notePreviousDefinition(Old, New->getLocation());
2473     New->setInvalidDecl();
2474     return true;
2475   }
2476   return false;
2477 }
2478 
2479 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2480 /// same name and scope as a previous declaration 'Old'.  Figure out
2481 /// how to resolve this situation, merging decls or emitting
2482 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2483 ///
2484 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2485                                 LookupResult &OldDecls) {
2486   // If the new decl is known invalid already, don't bother doing any
2487   // merging checks.
2488   if (New->isInvalidDecl()) return;
2489 
2490   // Allow multiple definitions for ObjC built-in typedefs.
2491   // FIXME: Verify the underlying types are equivalent!
2492   if (getLangOpts().ObjC) {
2493     const IdentifierInfo *TypeID = New->getIdentifier();
2494     switch (TypeID->getLength()) {
2495     default: break;
2496     case 2:
2497       {
2498         if (!TypeID->isStr("id"))
2499           break;
2500         QualType T = New->getUnderlyingType();
2501         if (!T->isPointerType())
2502           break;
2503         if (!T->isVoidPointerType()) {
2504           QualType PT = T->castAs<PointerType>()->getPointeeType();
2505           if (!PT->isStructureType())
2506             break;
2507         }
2508         Context.setObjCIdRedefinitionType(T);
2509         // Install the built-in type for 'id', ignoring the current definition.
2510         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2511         return;
2512       }
2513     case 5:
2514       if (!TypeID->isStr("Class"))
2515         break;
2516       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2517       // Install the built-in type for 'Class', ignoring the current definition.
2518       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2519       return;
2520     case 3:
2521       if (!TypeID->isStr("SEL"))
2522         break;
2523       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2524       // Install the built-in type for 'SEL', ignoring the current definition.
2525       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2526       return;
2527     }
2528     // Fall through - the typedef name was not a builtin type.
2529   }
2530 
2531   // Verify the old decl was also a type.
2532   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2533   if (!Old) {
2534     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2535       << New->getDeclName();
2536 
2537     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2538     if (OldD->getLocation().isValid())
2539       notePreviousDefinition(OldD, New->getLocation());
2540 
2541     return New->setInvalidDecl();
2542   }
2543 
2544   // If the old declaration is invalid, just give up here.
2545   if (Old->isInvalidDecl())
2546     return New->setInvalidDecl();
2547 
2548   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2549     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2550     auto *NewTag = New->getAnonDeclWithTypedefName();
2551     NamedDecl *Hidden = nullptr;
2552     if (OldTag && NewTag &&
2553         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2554         !hasVisibleDefinition(OldTag, &Hidden)) {
2555       // There is a definition of this tag, but it is not visible. Use it
2556       // instead of our tag.
2557       New->setTypeForDecl(OldTD->getTypeForDecl());
2558       if (OldTD->isModed())
2559         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2560                                     OldTD->getUnderlyingType());
2561       else
2562         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2563 
2564       // Make the old tag definition visible.
2565       makeMergedDefinitionVisible(Hidden);
2566 
2567       // If this was an unscoped enumeration, yank all of its enumerators
2568       // out of the scope.
2569       if (isa<EnumDecl>(NewTag)) {
2570         Scope *EnumScope = getNonFieldDeclScope(S);
2571         for (auto *D : NewTag->decls()) {
2572           auto *ED = cast<EnumConstantDecl>(D);
2573           assert(EnumScope->isDeclScope(ED));
2574           EnumScope->RemoveDecl(ED);
2575           IdResolver.RemoveDecl(ED);
2576           ED->getLexicalDeclContext()->removeDecl(ED);
2577         }
2578       }
2579     }
2580   }
2581 
2582   // If the typedef types are not identical, reject them in all languages and
2583   // with any extensions enabled.
2584   if (isIncompatibleTypedef(Old, New))
2585     return;
2586 
2587   // The types match.  Link up the redeclaration chain and merge attributes if
2588   // the old declaration was a typedef.
2589   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2590     New->setPreviousDecl(Typedef);
2591     mergeDeclAttributes(New, Old);
2592   }
2593 
2594   if (getLangOpts().MicrosoftExt)
2595     return;
2596 
2597   if (getLangOpts().CPlusPlus) {
2598     // C++ [dcl.typedef]p2:
2599     //   In a given non-class scope, a typedef specifier can be used to
2600     //   redefine the name of any type declared in that scope to refer
2601     //   to the type to which it already refers.
2602     if (!isa<CXXRecordDecl>(CurContext))
2603       return;
2604 
2605     // C++0x [dcl.typedef]p4:
2606     //   In a given class scope, a typedef specifier can be used to redefine
2607     //   any class-name declared in that scope that is not also a typedef-name
2608     //   to refer to the type to which it already refers.
2609     //
2610     // This wording came in via DR424, which was a correction to the
2611     // wording in DR56, which accidentally banned code like:
2612     //
2613     //   struct S {
2614     //     typedef struct A { } A;
2615     //   };
2616     //
2617     // in the C++03 standard. We implement the C++0x semantics, which
2618     // allow the above but disallow
2619     //
2620     //   struct S {
2621     //     typedef int I;
2622     //     typedef int I;
2623     //   };
2624     //
2625     // since that was the intent of DR56.
2626     if (!isa<TypedefNameDecl>(Old))
2627       return;
2628 
2629     Diag(New->getLocation(), diag::err_redefinition)
2630       << New->getDeclName();
2631     notePreviousDefinition(Old, New->getLocation());
2632     return New->setInvalidDecl();
2633   }
2634 
2635   // Modules always permit redefinition of typedefs, as does C11.
2636   if (getLangOpts().Modules || getLangOpts().C11)
2637     return;
2638 
2639   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2640   // is normally mapped to an error, but can be controlled with
2641   // -Wtypedef-redefinition.  If either the original or the redefinition is
2642   // in a system header, don't emit this for compatibility with GCC.
2643   if (getDiagnostics().getSuppressSystemWarnings() &&
2644       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2645       (Old->isImplicit() ||
2646        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2647        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2648     return;
2649 
2650   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2651     << New->getDeclName();
2652   notePreviousDefinition(Old, New->getLocation());
2653 }
2654 
2655 /// DeclhasAttr - returns true if decl Declaration already has the target
2656 /// attribute.
2657 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2658   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2659   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2660   for (const auto *i : D->attrs())
2661     if (i->getKind() == A->getKind()) {
2662       if (Ann) {
2663         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2664           return true;
2665         continue;
2666       }
2667       // FIXME: Don't hardcode this check
2668       if (OA && isa<OwnershipAttr>(i))
2669         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2670       return true;
2671     }
2672 
2673   return false;
2674 }
2675 
2676 static bool isAttributeTargetADefinition(Decl *D) {
2677   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2678     return VD->isThisDeclarationADefinition();
2679   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2680     return TD->isCompleteDefinition() || TD->isBeingDefined();
2681   return true;
2682 }
2683 
2684 /// Merge alignment attributes from \p Old to \p New, taking into account the
2685 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2686 ///
2687 /// \return \c true if any attributes were added to \p New.
2688 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2689   // Look for alignas attributes on Old, and pick out whichever attribute
2690   // specifies the strictest alignment requirement.
2691   AlignedAttr *OldAlignasAttr = nullptr;
2692   AlignedAttr *OldStrictestAlignAttr = nullptr;
2693   unsigned OldAlign = 0;
2694   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2695     // FIXME: We have no way of representing inherited dependent alignments
2696     // in a case like:
2697     //   template<int A, int B> struct alignas(A) X;
2698     //   template<int A, int B> struct alignas(B) X {};
2699     // For now, we just ignore any alignas attributes which are not on the
2700     // definition in such a case.
2701     if (I->isAlignmentDependent())
2702       return false;
2703 
2704     if (I->isAlignas())
2705       OldAlignasAttr = I;
2706 
2707     unsigned Align = I->getAlignment(S.Context);
2708     if (Align > OldAlign) {
2709       OldAlign = Align;
2710       OldStrictestAlignAttr = I;
2711     }
2712   }
2713 
2714   // Look for alignas attributes on New.
2715   AlignedAttr *NewAlignasAttr = nullptr;
2716   unsigned NewAlign = 0;
2717   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2718     if (I->isAlignmentDependent())
2719       return false;
2720 
2721     if (I->isAlignas())
2722       NewAlignasAttr = I;
2723 
2724     unsigned Align = I->getAlignment(S.Context);
2725     if (Align > NewAlign)
2726       NewAlign = Align;
2727   }
2728 
2729   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2730     // Both declarations have 'alignas' attributes. We require them to match.
2731     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2732     // fall short. (If two declarations both have alignas, they must both match
2733     // every definition, and so must match each other if there is a definition.)
2734 
2735     // If either declaration only contains 'alignas(0)' specifiers, then it
2736     // specifies the natural alignment for the type.
2737     if (OldAlign == 0 || NewAlign == 0) {
2738       QualType Ty;
2739       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2740         Ty = VD->getType();
2741       else
2742         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2743 
2744       if (OldAlign == 0)
2745         OldAlign = S.Context.getTypeAlign(Ty);
2746       if (NewAlign == 0)
2747         NewAlign = S.Context.getTypeAlign(Ty);
2748     }
2749 
2750     if (OldAlign != NewAlign) {
2751       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2752         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2753         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2754       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2755     }
2756   }
2757 
2758   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2759     // C++11 [dcl.align]p6:
2760     //   if any declaration of an entity has an alignment-specifier,
2761     //   every defining declaration of that entity shall specify an
2762     //   equivalent alignment.
2763     // C11 6.7.5/7:
2764     //   If the definition of an object does not have an alignment
2765     //   specifier, any other declaration of that object shall also
2766     //   have no alignment specifier.
2767     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2768       << OldAlignasAttr;
2769     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2770       << OldAlignasAttr;
2771   }
2772 
2773   bool AnyAdded = false;
2774 
2775   // Ensure we have an attribute representing the strictest alignment.
2776   if (OldAlign > NewAlign) {
2777     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2778     Clone->setInherited(true);
2779     New->addAttr(Clone);
2780     AnyAdded = true;
2781   }
2782 
2783   // Ensure we have an alignas attribute if the old declaration had one.
2784   if (OldAlignasAttr && !NewAlignasAttr &&
2785       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2786     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2787     Clone->setInherited(true);
2788     New->addAttr(Clone);
2789     AnyAdded = true;
2790   }
2791 
2792   return AnyAdded;
2793 }
2794 
2795 #define WANT_DECL_MERGE_LOGIC
2796 #include "clang/Sema/AttrParsedAttrImpl.inc"
2797 #undef WANT_DECL_MERGE_LOGIC
2798 
2799 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2800                                const InheritableAttr *Attr,
2801                                Sema::AvailabilityMergeKind AMK) {
2802   // Diagnose any mutual exclusions between the attribute that we want to add
2803   // and attributes that already exist on the declaration.
2804   if (!DiagnoseMutualExclusions(S, D, Attr))
2805     return false;
2806 
2807   // This function copies an attribute Attr from a previous declaration to the
2808   // new declaration D if the new declaration doesn't itself have that attribute
2809   // yet or if that attribute allows duplicates.
2810   // If you're adding a new attribute that requires logic different from
2811   // "use explicit attribute on decl if present, else use attribute from
2812   // previous decl", for example if the attribute needs to be consistent
2813   // between redeclarations, you need to call a custom merge function here.
2814   InheritableAttr *NewAttr = nullptr;
2815   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2816     NewAttr = S.mergeAvailabilityAttr(
2817         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2818         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2819         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2820         AA->getPriority());
2821   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2822     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2823   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2824     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2825   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2826     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2827   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2828     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2829   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2830     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2831   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2832     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2833                                 FA->getFirstArg());
2834   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2835     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2836   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2837     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2838   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2839     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2840                                        IA->getInheritanceModel());
2841   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2842     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2843                                       &S.Context.Idents.get(AA->getSpelling()));
2844   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2845            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2846             isa<CUDAGlobalAttr>(Attr))) {
2847     // CUDA target attributes are part of function signature for
2848     // overloading purposes and must not be merged.
2849     return false;
2850   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2851     NewAttr = S.mergeMinSizeAttr(D, *MA);
2852   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2853     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2854   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2855     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2856   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2857     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2858   else if (isa<AlignedAttr>(Attr))
2859     // AlignedAttrs are handled separately, because we need to handle all
2860     // such attributes on a declaration at the same time.
2861     NewAttr = nullptr;
2862   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2863            (AMK == Sema::AMK_Override ||
2864             AMK == Sema::AMK_ProtocolImplementation ||
2865             AMK == Sema::AMK_OptionalProtocolImplementation))
2866     NewAttr = nullptr;
2867   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2868     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2869   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2870     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2871   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2872     NewAttr = S.mergeImportNameAttr(D, *INA);
2873   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2874     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2875   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2876     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2877   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2878     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2879   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2880     NewAttr =
2881         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2882   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2883     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2884   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2885     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2886 
2887   if (NewAttr) {
2888     NewAttr->setInherited(true);
2889     D->addAttr(NewAttr);
2890     if (isa<MSInheritanceAttr>(NewAttr))
2891       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2892     return true;
2893   }
2894 
2895   return false;
2896 }
2897 
2898 static const NamedDecl *getDefinition(const Decl *D) {
2899   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2900     return TD->getDefinition();
2901   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2902     const VarDecl *Def = VD->getDefinition();
2903     if (Def)
2904       return Def;
2905     return VD->getActingDefinition();
2906   }
2907   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2908     const FunctionDecl *Def = nullptr;
2909     if (FD->isDefined(Def, true))
2910       return Def;
2911   }
2912   return nullptr;
2913 }
2914 
2915 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2916   for (const auto *Attribute : D->attrs())
2917     if (Attribute->getKind() == Kind)
2918       return true;
2919   return false;
2920 }
2921 
2922 /// checkNewAttributesAfterDef - If we already have a definition, check that
2923 /// there are no new attributes in this declaration.
2924 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2925   if (!New->hasAttrs())
2926     return;
2927 
2928   const NamedDecl *Def = getDefinition(Old);
2929   if (!Def || Def == New)
2930     return;
2931 
2932   AttrVec &NewAttributes = New->getAttrs();
2933   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2934     const Attr *NewAttribute = NewAttributes[I];
2935 
2936     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2937       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2938         Sema::SkipBodyInfo SkipBody;
2939         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2940 
2941         // If we're skipping this definition, drop the "alias" attribute.
2942         if (SkipBody.ShouldSkip) {
2943           NewAttributes.erase(NewAttributes.begin() + I);
2944           --E;
2945           continue;
2946         }
2947       } else {
2948         VarDecl *VD = cast<VarDecl>(New);
2949         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2950                                 VarDecl::TentativeDefinition
2951                             ? diag::err_alias_after_tentative
2952                             : diag::err_redefinition;
2953         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2954         if (Diag == diag::err_redefinition)
2955           S.notePreviousDefinition(Def, VD->getLocation());
2956         else
2957           S.Diag(Def->getLocation(), diag::note_previous_definition);
2958         VD->setInvalidDecl();
2959       }
2960       ++I;
2961       continue;
2962     }
2963 
2964     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2965       // Tentative definitions are only interesting for the alias check above.
2966       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2967         ++I;
2968         continue;
2969       }
2970     }
2971 
2972     if (hasAttribute(Def, NewAttribute->getKind())) {
2973       ++I;
2974       continue; // regular attr merging will take care of validating this.
2975     }
2976 
2977     if (isa<C11NoReturnAttr>(NewAttribute)) {
2978       // C's _Noreturn is allowed to be added to a function after it is defined.
2979       ++I;
2980       continue;
2981     } else if (isa<UuidAttr>(NewAttribute)) {
2982       // msvc will allow a subsequent definition to add an uuid to a class
2983       ++I;
2984       continue;
2985     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2986       if (AA->isAlignas()) {
2987         // C++11 [dcl.align]p6:
2988         //   if any declaration of an entity has an alignment-specifier,
2989         //   every defining declaration of that entity shall specify an
2990         //   equivalent alignment.
2991         // C11 6.7.5/7:
2992         //   If the definition of an object does not have an alignment
2993         //   specifier, any other declaration of that object shall also
2994         //   have no alignment specifier.
2995         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2996           << AA;
2997         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2998           << AA;
2999         NewAttributes.erase(NewAttributes.begin() + I);
3000         --E;
3001         continue;
3002       }
3003     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3004       // If there is a C definition followed by a redeclaration with this
3005       // attribute then there are two different definitions. In C++, prefer the
3006       // standard diagnostics.
3007       if (!S.getLangOpts().CPlusPlus) {
3008         S.Diag(NewAttribute->getLocation(),
3009                diag::err_loader_uninitialized_redeclaration);
3010         S.Diag(Def->getLocation(), diag::note_previous_definition);
3011         NewAttributes.erase(NewAttributes.begin() + I);
3012         --E;
3013         continue;
3014       }
3015     } else if (isa<SelectAnyAttr>(NewAttribute) &&
3016                cast<VarDecl>(New)->isInline() &&
3017                !cast<VarDecl>(New)->isInlineSpecified()) {
3018       // Don't warn about applying selectany to implicitly inline variables.
3019       // Older compilers and language modes would require the use of selectany
3020       // to make such variables inline, and it would have no effect if we
3021       // honored it.
3022       ++I;
3023       continue;
3024     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3025       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3026       // declarations after defintions.
3027       ++I;
3028       continue;
3029     }
3030 
3031     S.Diag(NewAttribute->getLocation(),
3032            diag::warn_attribute_precede_definition);
3033     S.Diag(Def->getLocation(), diag::note_previous_definition);
3034     NewAttributes.erase(NewAttributes.begin() + I);
3035     --E;
3036   }
3037 }
3038 
3039 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3040                                      const ConstInitAttr *CIAttr,
3041                                      bool AttrBeforeInit) {
3042   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3043 
3044   // Figure out a good way to write this specifier on the old declaration.
3045   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3046   // enough of the attribute list spelling information to extract that without
3047   // heroics.
3048   std::string SuitableSpelling;
3049   if (S.getLangOpts().CPlusPlus20)
3050     SuitableSpelling = std::string(
3051         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3052   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3053     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3054         InsertLoc, {tok::l_square, tok::l_square,
3055                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3056                     S.PP.getIdentifierInfo("require_constant_initialization"),
3057                     tok::r_square, tok::r_square}));
3058   if (SuitableSpelling.empty())
3059     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3060         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3061                     S.PP.getIdentifierInfo("require_constant_initialization"),
3062                     tok::r_paren, tok::r_paren}));
3063   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3064     SuitableSpelling = "constinit";
3065   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3066     SuitableSpelling = "[[clang::require_constant_initialization]]";
3067   if (SuitableSpelling.empty())
3068     SuitableSpelling = "__attribute__((require_constant_initialization))";
3069   SuitableSpelling += " ";
3070 
3071   if (AttrBeforeInit) {
3072     // extern constinit int a;
3073     // int a = 0; // error (missing 'constinit'), accepted as extension
3074     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3075     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3076         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3077     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3078   } else {
3079     // int a = 0;
3080     // constinit extern int a; // error (missing 'constinit')
3081     S.Diag(CIAttr->getLocation(),
3082            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3083                                  : diag::warn_require_const_init_added_too_late)
3084         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3085     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3086         << CIAttr->isConstinit()
3087         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3088   }
3089 }
3090 
3091 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3092 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3093                                AvailabilityMergeKind AMK) {
3094   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3095     UsedAttr *NewAttr = OldAttr->clone(Context);
3096     NewAttr->setInherited(true);
3097     New->addAttr(NewAttr);
3098   }
3099   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3100     RetainAttr *NewAttr = OldAttr->clone(Context);
3101     NewAttr->setInherited(true);
3102     New->addAttr(NewAttr);
3103   }
3104 
3105   if (!Old->hasAttrs() && !New->hasAttrs())
3106     return;
3107 
3108   // [dcl.constinit]p1:
3109   //   If the [constinit] specifier is applied to any declaration of a
3110   //   variable, it shall be applied to the initializing declaration.
3111   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3112   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3113   if (bool(OldConstInit) != bool(NewConstInit)) {
3114     const auto *OldVD = cast<VarDecl>(Old);
3115     auto *NewVD = cast<VarDecl>(New);
3116 
3117     // Find the initializing declaration. Note that we might not have linked
3118     // the new declaration into the redeclaration chain yet.
3119     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3120     if (!InitDecl &&
3121         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3122       InitDecl = NewVD;
3123 
3124     if (InitDecl == NewVD) {
3125       // This is the initializing declaration. If it would inherit 'constinit',
3126       // that's ill-formed. (Note that we do not apply this to the attribute
3127       // form).
3128       if (OldConstInit && OldConstInit->isConstinit())
3129         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3130                                  /*AttrBeforeInit=*/true);
3131     } else if (NewConstInit) {
3132       // This is the first time we've been told that this declaration should
3133       // have a constant initializer. If we already saw the initializing
3134       // declaration, this is too late.
3135       if (InitDecl && InitDecl != NewVD) {
3136         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3137                                  /*AttrBeforeInit=*/false);
3138         NewVD->dropAttr<ConstInitAttr>();
3139       }
3140     }
3141   }
3142 
3143   // Attributes declared post-definition are currently ignored.
3144   checkNewAttributesAfterDef(*this, New, Old);
3145 
3146   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3147     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3148       if (!OldA->isEquivalent(NewA)) {
3149         // This redeclaration changes __asm__ label.
3150         Diag(New->getLocation(), diag::err_different_asm_label);
3151         Diag(OldA->getLocation(), diag::note_previous_declaration);
3152       }
3153     } else if (Old->isUsed()) {
3154       // This redeclaration adds an __asm__ label to a declaration that has
3155       // already been ODR-used.
3156       Diag(New->getLocation(), diag::err_late_asm_label_name)
3157         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3158     }
3159   }
3160 
3161   // Re-declaration cannot add abi_tag's.
3162   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3163     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3164       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3165         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3166           Diag(NewAbiTagAttr->getLocation(),
3167                diag::err_new_abi_tag_on_redeclaration)
3168               << NewTag;
3169           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3170         }
3171       }
3172     } else {
3173       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3174       Diag(Old->getLocation(), diag::note_previous_declaration);
3175     }
3176   }
3177 
3178   // This redeclaration adds a section attribute.
3179   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3180     if (auto *VD = dyn_cast<VarDecl>(New)) {
3181       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3182         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3183         Diag(Old->getLocation(), diag::note_previous_declaration);
3184       }
3185     }
3186   }
3187 
3188   // Redeclaration adds code-seg attribute.
3189   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3190   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3191       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3192     Diag(New->getLocation(), diag::warn_mismatched_section)
3193          << 0 /*codeseg*/;
3194     Diag(Old->getLocation(), diag::note_previous_declaration);
3195   }
3196 
3197   if (!Old->hasAttrs())
3198     return;
3199 
3200   bool foundAny = New->hasAttrs();
3201 
3202   // Ensure that any moving of objects within the allocated map is done before
3203   // we process them.
3204   if (!foundAny) New->setAttrs(AttrVec());
3205 
3206   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3207     // Ignore deprecated/unavailable/availability attributes if requested.
3208     AvailabilityMergeKind LocalAMK = AMK_None;
3209     if (isa<DeprecatedAttr>(I) ||
3210         isa<UnavailableAttr>(I) ||
3211         isa<AvailabilityAttr>(I)) {
3212       switch (AMK) {
3213       case AMK_None:
3214         continue;
3215 
3216       case AMK_Redeclaration:
3217       case AMK_Override:
3218       case AMK_ProtocolImplementation:
3219       case AMK_OptionalProtocolImplementation:
3220         LocalAMK = AMK;
3221         break;
3222       }
3223     }
3224 
3225     // Already handled.
3226     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3227       continue;
3228 
3229     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3230       foundAny = true;
3231   }
3232 
3233   if (mergeAlignedAttrs(*this, New, Old))
3234     foundAny = true;
3235 
3236   if (!foundAny) New->dropAttrs();
3237 }
3238 
3239 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3240 /// to the new one.
3241 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3242                                      const ParmVarDecl *oldDecl,
3243                                      Sema &S) {
3244   // C++11 [dcl.attr.depend]p2:
3245   //   The first declaration of a function shall specify the
3246   //   carries_dependency attribute for its declarator-id if any declaration
3247   //   of the function specifies the carries_dependency attribute.
3248   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3249   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3250     S.Diag(CDA->getLocation(),
3251            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3252     // Find the first declaration of the parameter.
3253     // FIXME: Should we build redeclaration chains for function parameters?
3254     const FunctionDecl *FirstFD =
3255       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3256     const ParmVarDecl *FirstVD =
3257       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3258     S.Diag(FirstVD->getLocation(),
3259            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3260   }
3261 
3262   if (!oldDecl->hasAttrs())
3263     return;
3264 
3265   bool foundAny = newDecl->hasAttrs();
3266 
3267   // Ensure that any moving of objects within the allocated map is
3268   // done before we process them.
3269   if (!foundAny) newDecl->setAttrs(AttrVec());
3270 
3271   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3272     if (!DeclHasAttr(newDecl, I)) {
3273       InheritableAttr *newAttr =
3274         cast<InheritableParamAttr>(I->clone(S.Context));
3275       newAttr->setInherited(true);
3276       newDecl->addAttr(newAttr);
3277       foundAny = true;
3278     }
3279   }
3280 
3281   if (!foundAny) newDecl->dropAttrs();
3282 }
3283 
3284 static bool EquivalentArrayTypes(QualType Old, QualType New,
3285                                  const ASTContext &Ctx) {
3286 
3287   auto NoSizeInfo = [&Ctx](QualType Ty) {
3288     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3289       return true;
3290     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3291       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3292     return false;
3293   };
3294 
3295   // `type[]` is equivalent to `type *` and `type[*]`.
3296   if (NoSizeInfo(Old) && NoSizeInfo(New))
3297     return true;
3298 
3299   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3300   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3301     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3302     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3303     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3304         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3305       return false;
3306     return true;
3307   }
3308 
3309   // Only compare size, ignore Size modifiers and CVR.
3310   if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3311     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3312            Ctx.getAsConstantArrayType(New)->getSize();
3313   }
3314 
3315   // Don't try to compare dependent sized array
3316   if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3317     return true;
3318   }
3319 
3320   return Old == New;
3321 }
3322 
3323 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3324                                 const ParmVarDecl *OldParam,
3325                                 Sema &S) {
3326   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3327     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3328       if (*Oldnullability != *Newnullability) {
3329         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3330           << DiagNullabilityKind(
3331                *Newnullability,
3332                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3333                 != 0))
3334           << DiagNullabilityKind(
3335                *Oldnullability,
3336                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3337                 != 0));
3338         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3339       }
3340     } else {
3341       QualType NewT = NewParam->getType();
3342       NewT = S.Context.getAttributedType(
3343                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3344                          NewT, NewT);
3345       NewParam->setType(NewT);
3346     }
3347   }
3348   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3349   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3350   if (OldParamDT && NewParamDT &&
3351       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3352     QualType OldParamOT = OldParamDT->getOriginalType();
3353     QualType NewParamOT = NewParamDT->getOriginalType();
3354     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3355       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3356           << NewParam << NewParamOT;
3357       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3358           << OldParamOT;
3359     }
3360   }
3361 }
3362 
3363 namespace {
3364 
3365 /// Used in MergeFunctionDecl to keep track of function parameters in
3366 /// C.
3367 struct GNUCompatibleParamWarning {
3368   ParmVarDecl *OldParm;
3369   ParmVarDecl *NewParm;
3370   QualType PromotedType;
3371 };
3372 
3373 } // end anonymous namespace
3374 
3375 // Determine whether the previous declaration was a definition, implicit
3376 // declaration, or a declaration.
3377 template <typename T>
3378 static std::pair<diag::kind, SourceLocation>
3379 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3380   diag::kind PrevDiag;
3381   SourceLocation OldLocation = Old->getLocation();
3382   if (Old->isThisDeclarationADefinition())
3383     PrevDiag = diag::note_previous_definition;
3384   else if (Old->isImplicit()) {
3385     PrevDiag = diag::note_previous_implicit_declaration;
3386     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3387       if (FD->getBuiltinID())
3388         PrevDiag = diag::note_previous_builtin_declaration;
3389     }
3390     if (OldLocation.isInvalid())
3391       OldLocation = New->getLocation();
3392   } else
3393     PrevDiag = diag::note_previous_declaration;
3394   return std::make_pair(PrevDiag, OldLocation);
3395 }
3396 
3397 /// canRedefineFunction - checks if a function can be redefined. Currently,
3398 /// only extern inline functions can be redefined, and even then only in
3399 /// GNU89 mode.
3400 static bool canRedefineFunction(const FunctionDecl *FD,
3401                                 const LangOptions& LangOpts) {
3402   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3403           !LangOpts.CPlusPlus &&
3404           FD->isInlineSpecified() &&
3405           FD->getStorageClass() == SC_Extern);
3406 }
3407 
3408 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3409   const AttributedType *AT = T->getAs<AttributedType>();
3410   while (AT && !AT->isCallingConv())
3411     AT = AT->getModifiedType()->getAs<AttributedType>();
3412   return AT;
3413 }
3414 
3415 template <typename T>
3416 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3417   const DeclContext *DC = Old->getDeclContext();
3418   if (DC->isRecord())
3419     return false;
3420 
3421   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3422   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3423     return true;
3424   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3425     return true;
3426   return false;
3427 }
3428 
3429 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3430 static bool isExternC(VarTemplateDecl *) { return false; }
3431 static bool isExternC(FunctionTemplateDecl *) { return false; }
3432 
3433 /// Check whether a redeclaration of an entity introduced by a
3434 /// using-declaration is valid, given that we know it's not an overload
3435 /// (nor a hidden tag declaration).
3436 template<typename ExpectedDecl>
3437 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3438                                    ExpectedDecl *New) {
3439   // C++11 [basic.scope.declarative]p4:
3440   //   Given a set of declarations in a single declarative region, each of
3441   //   which specifies the same unqualified name,
3442   //   -- they shall all refer to the same entity, or all refer to functions
3443   //      and function templates; or
3444   //   -- exactly one declaration shall declare a class name or enumeration
3445   //      name that is not a typedef name and the other declarations shall all
3446   //      refer to the same variable or enumerator, or all refer to functions
3447   //      and function templates; in this case the class name or enumeration
3448   //      name is hidden (3.3.10).
3449 
3450   // C++11 [namespace.udecl]p14:
3451   //   If a function declaration in namespace scope or block scope has the
3452   //   same name and the same parameter-type-list as a function introduced
3453   //   by a using-declaration, and the declarations do not declare the same
3454   //   function, the program is ill-formed.
3455 
3456   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3457   if (Old &&
3458       !Old->getDeclContext()->getRedeclContext()->Equals(
3459           New->getDeclContext()->getRedeclContext()) &&
3460       !(isExternC(Old) && isExternC(New)))
3461     Old = nullptr;
3462 
3463   if (!Old) {
3464     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3465     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3466     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3467     return true;
3468   }
3469   return false;
3470 }
3471 
3472 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3473                                             const FunctionDecl *B) {
3474   assert(A->getNumParams() == B->getNumParams());
3475 
3476   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3477     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3478     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3479     if (AttrA == AttrB)
3480       return true;
3481     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3482            AttrA->isDynamic() == AttrB->isDynamic();
3483   };
3484 
3485   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3486 }
3487 
3488 /// If necessary, adjust the semantic declaration context for a qualified
3489 /// declaration to name the correct inline namespace within the qualifier.
3490 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3491                                                DeclaratorDecl *OldD) {
3492   // The only case where we need to update the DeclContext is when
3493   // redeclaration lookup for a qualified name finds a declaration
3494   // in an inline namespace within the context named by the qualifier:
3495   //
3496   //   inline namespace N { int f(); }
3497   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3498   //
3499   // For unqualified declarations, the semantic context *can* change
3500   // along the redeclaration chain (for local extern declarations,
3501   // extern "C" declarations, and friend declarations in particular).
3502   if (!NewD->getQualifier())
3503     return;
3504 
3505   // NewD is probably already in the right context.
3506   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3507   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3508   if (NamedDC->Equals(SemaDC))
3509     return;
3510 
3511   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3512           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3513          "unexpected context for redeclaration");
3514 
3515   auto *LexDC = NewD->getLexicalDeclContext();
3516   auto FixSemaDC = [=](NamedDecl *D) {
3517     if (!D)
3518       return;
3519     D->setDeclContext(SemaDC);
3520     D->setLexicalDeclContext(LexDC);
3521   };
3522 
3523   FixSemaDC(NewD);
3524   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3525     FixSemaDC(FD->getDescribedFunctionTemplate());
3526   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3527     FixSemaDC(VD->getDescribedVarTemplate());
3528 }
3529 
3530 /// MergeFunctionDecl - We just parsed a function 'New' from
3531 /// declarator D which has the same name and scope as a previous
3532 /// declaration 'Old'.  Figure out how to resolve this situation,
3533 /// merging decls or emitting diagnostics as appropriate.
3534 ///
3535 /// In C++, New and Old must be declarations that are not
3536 /// overloaded. Use IsOverload to determine whether New and Old are
3537 /// overloaded, and to select the Old declaration that New should be
3538 /// merged with.
3539 ///
3540 /// Returns true if there was an error, false otherwise.
3541 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3542                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3543   // Verify the old decl was also a function.
3544   FunctionDecl *Old = OldD->getAsFunction();
3545   if (!Old) {
3546     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3547       if (New->getFriendObjectKind()) {
3548         Diag(New->getLocation(), diag::err_using_decl_friend);
3549         Diag(Shadow->getTargetDecl()->getLocation(),
3550              diag::note_using_decl_target);
3551         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3552             << 0;
3553         return true;
3554       }
3555 
3556       // Check whether the two declarations might declare the same function or
3557       // function template.
3558       if (FunctionTemplateDecl *NewTemplate =
3559               New->getDescribedFunctionTemplate()) {
3560         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3561                                                          NewTemplate))
3562           return true;
3563         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3564                          ->getAsFunction();
3565       } else {
3566         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3567           return true;
3568         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3569       }
3570     } else {
3571       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3572         << New->getDeclName();
3573       notePreviousDefinition(OldD, New->getLocation());
3574       return true;
3575     }
3576   }
3577 
3578   // If the old declaration was found in an inline namespace and the new
3579   // declaration was qualified, update the DeclContext to match.
3580   adjustDeclContextForDeclaratorDecl(New, Old);
3581 
3582   // If the old declaration is invalid, just give up here.
3583   if (Old->isInvalidDecl())
3584     return true;
3585 
3586   // Disallow redeclaration of some builtins.
3587   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3588     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3589     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3590         << Old << Old->getType();
3591     return true;
3592   }
3593 
3594   diag::kind PrevDiag;
3595   SourceLocation OldLocation;
3596   std::tie(PrevDiag, OldLocation) =
3597       getNoteDiagForInvalidRedeclaration(Old, New);
3598 
3599   // Don't complain about this if we're in GNU89 mode and the old function
3600   // is an extern inline function.
3601   // Don't complain about specializations. They are not supposed to have
3602   // storage classes.
3603   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3604       New->getStorageClass() == SC_Static &&
3605       Old->hasExternalFormalLinkage() &&
3606       !New->getTemplateSpecializationInfo() &&
3607       !canRedefineFunction(Old, getLangOpts())) {
3608     if (getLangOpts().MicrosoftExt) {
3609       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3610       Diag(OldLocation, PrevDiag);
3611     } else {
3612       Diag(New->getLocation(), diag::err_static_non_static) << New;
3613       Diag(OldLocation, PrevDiag);
3614       return true;
3615     }
3616   }
3617 
3618   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3619     if (!Old->hasAttr<InternalLinkageAttr>()) {
3620       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3621           << ILA;
3622       Diag(Old->getLocation(), diag::note_previous_declaration);
3623       New->dropAttr<InternalLinkageAttr>();
3624     }
3625 
3626   if (auto *EA = New->getAttr<ErrorAttr>()) {
3627     if (!Old->hasAttr<ErrorAttr>()) {
3628       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3629       Diag(Old->getLocation(), diag::note_previous_declaration);
3630       New->dropAttr<ErrorAttr>();
3631     }
3632   }
3633 
3634   if (CheckRedeclarationInModule(New, Old))
3635     return true;
3636 
3637   if (!getLangOpts().CPlusPlus) {
3638     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3639     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3640       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3641         << New << OldOvl;
3642 
3643       // Try our best to find a decl that actually has the overloadable
3644       // attribute for the note. In most cases (e.g. programs with only one
3645       // broken declaration/definition), this won't matter.
3646       //
3647       // FIXME: We could do this if we juggled some extra state in
3648       // OverloadableAttr, rather than just removing it.
3649       const Decl *DiagOld = Old;
3650       if (OldOvl) {
3651         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3652           const auto *A = D->getAttr<OverloadableAttr>();
3653           return A && !A->isImplicit();
3654         });
3655         // If we've implicitly added *all* of the overloadable attrs to this
3656         // chain, emitting a "previous redecl" note is pointless.
3657         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3658       }
3659 
3660       if (DiagOld)
3661         Diag(DiagOld->getLocation(),
3662              diag::note_attribute_overloadable_prev_overload)
3663           << OldOvl;
3664 
3665       if (OldOvl)
3666         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3667       else
3668         New->dropAttr<OverloadableAttr>();
3669     }
3670   }
3671 
3672   // If a function is first declared with a calling convention, but is later
3673   // declared or defined without one, all following decls assume the calling
3674   // convention of the first.
3675   //
3676   // It's OK if a function is first declared without a calling convention,
3677   // but is later declared or defined with the default calling convention.
3678   //
3679   // To test if either decl has an explicit calling convention, we look for
3680   // AttributedType sugar nodes on the type as written.  If they are missing or
3681   // were canonicalized away, we assume the calling convention was implicit.
3682   //
3683   // Note also that we DO NOT return at this point, because we still have
3684   // other tests to run.
3685   QualType OldQType = Context.getCanonicalType(Old->getType());
3686   QualType NewQType = Context.getCanonicalType(New->getType());
3687   const FunctionType *OldType = cast<FunctionType>(OldQType);
3688   const FunctionType *NewType = cast<FunctionType>(NewQType);
3689   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3690   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3691   bool RequiresAdjustment = false;
3692 
3693   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3694     FunctionDecl *First = Old->getFirstDecl();
3695     const FunctionType *FT =
3696         First->getType().getCanonicalType()->castAs<FunctionType>();
3697     FunctionType::ExtInfo FI = FT->getExtInfo();
3698     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3699     if (!NewCCExplicit) {
3700       // Inherit the CC from the previous declaration if it was specified
3701       // there but not here.
3702       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3703       RequiresAdjustment = true;
3704     } else if (Old->getBuiltinID()) {
3705       // Builtin attribute isn't propagated to the new one yet at this point,
3706       // so we check if the old one is a builtin.
3707 
3708       // Calling Conventions on a Builtin aren't really useful and setting a
3709       // default calling convention and cdecl'ing some builtin redeclarations is
3710       // common, so warn and ignore the calling convention on the redeclaration.
3711       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3712           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3713           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3714       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3715       RequiresAdjustment = true;
3716     } else {
3717       // Calling conventions aren't compatible, so complain.
3718       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3719       Diag(New->getLocation(), diag::err_cconv_change)
3720         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3721         << !FirstCCExplicit
3722         << (!FirstCCExplicit ? "" :
3723             FunctionType::getNameForCallConv(FI.getCC()));
3724 
3725       // Put the note on the first decl, since it is the one that matters.
3726       Diag(First->getLocation(), diag::note_previous_declaration);
3727       return true;
3728     }
3729   }
3730 
3731   // FIXME: diagnose the other way around?
3732   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3733     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3734     RequiresAdjustment = true;
3735   }
3736 
3737   // Merge regparm attribute.
3738   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3739       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3740     if (NewTypeInfo.getHasRegParm()) {
3741       Diag(New->getLocation(), diag::err_regparm_mismatch)
3742         << NewType->getRegParmType()
3743         << OldType->getRegParmType();
3744       Diag(OldLocation, diag::note_previous_declaration);
3745       return true;
3746     }
3747 
3748     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3749     RequiresAdjustment = true;
3750   }
3751 
3752   // Merge ns_returns_retained attribute.
3753   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3754     if (NewTypeInfo.getProducesResult()) {
3755       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3756           << "'ns_returns_retained'";
3757       Diag(OldLocation, diag::note_previous_declaration);
3758       return true;
3759     }
3760 
3761     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3762     RequiresAdjustment = true;
3763   }
3764 
3765   if (OldTypeInfo.getNoCallerSavedRegs() !=
3766       NewTypeInfo.getNoCallerSavedRegs()) {
3767     if (NewTypeInfo.getNoCallerSavedRegs()) {
3768       AnyX86NoCallerSavedRegistersAttr *Attr =
3769         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3770       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3771       Diag(OldLocation, diag::note_previous_declaration);
3772       return true;
3773     }
3774 
3775     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3776     RequiresAdjustment = true;
3777   }
3778 
3779   if (RequiresAdjustment) {
3780     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3781     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3782     New->setType(QualType(AdjustedType, 0));
3783     NewQType = Context.getCanonicalType(New->getType());
3784   }
3785 
3786   // If this redeclaration makes the function inline, we may need to add it to
3787   // UndefinedButUsed.
3788   if (!Old->isInlined() && New->isInlined() &&
3789       !New->hasAttr<GNUInlineAttr>() &&
3790       !getLangOpts().GNUInline &&
3791       Old->isUsed(false) &&
3792       !Old->isDefined() && !New->isThisDeclarationADefinition())
3793     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3794                                            SourceLocation()));
3795 
3796   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3797   // about it.
3798   if (New->hasAttr<GNUInlineAttr>() &&
3799       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3800     UndefinedButUsed.erase(Old->getCanonicalDecl());
3801   }
3802 
3803   // If pass_object_size params don't match up perfectly, this isn't a valid
3804   // redeclaration.
3805   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3806       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3807     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3808         << New->getDeclName();
3809     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3810     return true;
3811   }
3812 
3813   if (getLangOpts().CPlusPlus) {
3814     // C++1z [over.load]p2
3815     //   Certain function declarations cannot be overloaded:
3816     //     -- Function declarations that differ only in the return type,
3817     //        the exception specification, or both cannot be overloaded.
3818 
3819     // Check the exception specifications match. This may recompute the type of
3820     // both Old and New if it resolved exception specifications, so grab the
3821     // types again after this. Because this updates the type, we do this before
3822     // any of the other checks below, which may update the "de facto" NewQType
3823     // but do not necessarily update the type of New.
3824     if (CheckEquivalentExceptionSpec(Old, New))
3825       return true;
3826     OldQType = Context.getCanonicalType(Old->getType());
3827     NewQType = Context.getCanonicalType(New->getType());
3828 
3829     // Go back to the type source info to compare the declared return types,
3830     // per C++1y [dcl.type.auto]p13:
3831     //   Redeclarations or specializations of a function or function template
3832     //   with a declared return type that uses a placeholder type shall also
3833     //   use that placeholder, not a deduced type.
3834     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3835     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3836     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3837         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3838                                        OldDeclaredReturnType)) {
3839       QualType ResQT;
3840       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3841           OldDeclaredReturnType->isObjCObjectPointerType())
3842         // FIXME: This does the wrong thing for a deduced return type.
3843         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3844       if (ResQT.isNull()) {
3845         if (New->isCXXClassMember() && New->isOutOfLine())
3846           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3847               << New << New->getReturnTypeSourceRange();
3848         else
3849           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3850               << New->getReturnTypeSourceRange();
3851         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3852                                     << Old->getReturnTypeSourceRange();
3853         return true;
3854       }
3855       else
3856         NewQType = ResQT;
3857     }
3858 
3859     QualType OldReturnType = OldType->getReturnType();
3860     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3861     if (OldReturnType != NewReturnType) {
3862       // If this function has a deduced return type and has already been
3863       // defined, copy the deduced value from the old declaration.
3864       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3865       if (OldAT && OldAT->isDeduced()) {
3866         QualType DT = OldAT->getDeducedType();
3867         if (DT.isNull()) {
3868           New->setType(SubstAutoTypeDependent(New->getType()));
3869           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3870         } else {
3871           New->setType(SubstAutoType(New->getType(), DT));
3872           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3873         }
3874       }
3875     }
3876 
3877     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3878     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3879     if (OldMethod && NewMethod) {
3880       // Preserve triviality.
3881       NewMethod->setTrivial(OldMethod->isTrivial());
3882 
3883       // MSVC allows explicit template specialization at class scope:
3884       // 2 CXXMethodDecls referring to the same function will be injected.
3885       // We don't want a redeclaration error.
3886       bool IsClassScopeExplicitSpecialization =
3887                               OldMethod->isFunctionTemplateSpecialization() &&
3888                               NewMethod->isFunctionTemplateSpecialization();
3889       bool isFriend = NewMethod->getFriendObjectKind();
3890 
3891       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3892           !IsClassScopeExplicitSpecialization) {
3893         //    -- Member function declarations with the same name and the
3894         //       same parameter types cannot be overloaded if any of them
3895         //       is a static member function declaration.
3896         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3897           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3898           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3899           return true;
3900         }
3901 
3902         // C++ [class.mem]p1:
3903         //   [...] A member shall not be declared twice in the
3904         //   member-specification, except that a nested class or member
3905         //   class template can be declared and then later defined.
3906         if (!inTemplateInstantiation()) {
3907           unsigned NewDiag;
3908           if (isa<CXXConstructorDecl>(OldMethod))
3909             NewDiag = diag::err_constructor_redeclared;
3910           else if (isa<CXXDestructorDecl>(NewMethod))
3911             NewDiag = diag::err_destructor_redeclared;
3912           else if (isa<CXXConversionDecl>(NewMethod))
3913             NewDiag = diag::err_conv_function_redeclared;
3914           else
3915             NewDiag = diag::err_member_redeclared;
3916 
3917           Diag(New->getLocation(), NewDiag);
3918         } else {
3919           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3920             << New << New->getType();
3921         }
3922         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3923         return true;
3924 
3925       // Complain if this is an explicit declaration of a special
3926       // member that was initially declared implicitly.
3927       //
3928       // As an exception, it's okay to befriend such methods in order
3929       // to permit the implicit constructor/destructor/operator calls.
3930       } else if (OldMethod->isImplicit()) {
3931         if (isFriend) {
3932           NewMethod->setImplicit();
3933         } else {
3934           Diag(NewMethod->getLocation(),
3935                diag::err_definition_of_implicitly_declared_member)
3936             << New << getSpecialMember(OldMethod);
3937           return true;
3938         }
3939       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3940         Diag(NewMethod->getLocation(),
3941              diag::err_definition_of_explicitly_defaulted_member)
3942           << getSpecialMember(OldMethod);
3943         return true;
3944       }
3945     }
3946 
3947     // C++11 [dcl.attr.noreturn]p1:
3948     //   The first declaration of a function shall specify the noreturn
3949     //   attribute if any declaration of that function specifies the noreturn
3950     //   attribute.
3951     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3952       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3953         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3954             << NRA;
3955         Diag(Old->getLocation(), diag::note_previous_declaration);
3956       }
3957 
3958     // C++11 [dcl.attr.depend]p2:
3959     //   The first declaration of a function shall specify the
3960     //   carries_dependency attribute for its declarator-id if any declaration
3961     //   of the function specifies the carries_dependency attribute.
3962     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3963     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3964       Diag(CDA->getLocation(),
3965            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3966       Diag(Old->getFirstDecl()->getLocation(),
3967            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3968     }
3969 
3970     // (C++98 8.3.5p3):
3971     //   All declarations for a function shall agree exactly in both the
3972     //   return type and the parameter-type-list.
3973     // We also want to respect all the extended bits except noreturn.
3974 
3975     // noreturn should now match unless the old type info didn't have it.
3976     QualType OldQTypeForComparison = OldQType;
3977     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3978       auto *OldType = OldQType->castAs<FunctionProtoType>();
3979       const FunctionType *OldTypeForComparison
3980         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3981       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3982       assert(OldQTypeForComparison.isCanonical());
3983     }
3984 
3985     if (haveIncompatibleLanguageLinkages(Old, New)) {
3986       // As a special case, retain the language linkage from previous
3987       // declarations of a friend function as an extension.
3988       //
3989       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3990       // and is useful because there's otherwise no way to specify language
3991       // linkage within class scope.
3992       //
3993       // Check cautiously as the friend object kind isn't yet complete.
3994       if (New->getFriendObjectKind() != Decl::FOK_None) {
3995         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3996         Diag(OldLocation, PrevDiag);
3997       } else {
3998         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3999         Diag(OldLocation, PrevDiag);
4000         return true;
4001       }
4002     }
4003 
4004     // If the function types are compatible, merge the declarations. Ignore the
4005     // exception specifier because it was already checked above in
4006     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4007     // about incompatible types under -fms-compatibility.
4008     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4009                                                          NewQType))
4010       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4011 
4012     // If the types are imprecise (due to dependent constructs in friends or
4013     // local extern declarations), it's OK if they differ. We'll check again
4014     // during instantiation.
4015     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4016       return false;
4017 
4018     // Fall through for conflicting redeclarations and redefinitions.
4019   }
4020 
4021   // C: Function types need to be compatible, not identical. This handles
4022   // duplicate function decls like "void f(int); void f(enum X);" properly.
4023   if (!getLangOpts().CPlusPlus) {
4024     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4025     // type is specified by a function definition that contains a (possibly
4026     // empty) identifier list, both shall agree in the number of parameters
4027     // and the type of each parameter shall be compatible with the type that
4028     // results from the application of default argument promotions to the
4029     // type of the corresponding identifier. ...
4030     // This cannot be handled by ASTContext::typesAreCompatible() because that
4031     // doesn't know whether the function type is for a definition or not when
4032     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4033     // we need to cover here is that the number of arguments agree as the
4034     // default argument promotion rules were already checked by
4035     // ASTContext::typesAreCompatible().
4036     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4037         Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4038       if (Old->hasInheritedPrototype())
4039         Old = Old->getCanonicalDecl();
4040       Diag(New->getLocation(), diag::err_conflicting_types) << New;
4041       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4042       return true;
4043     }
4044 
4045     // If we are merging two functions where only one of them has a prototype,
4046     // we may have enough information to decide to issue a diagnostic that the
4047     // function without a protoype will change behavior in C2x. This handles
4048     // cases like:
4049     //   void i(); void i(int j);
4050     //   void i(int j); void i();
4051     //   void i(); void i(int j) {}
4052     // See ActOnFinishFunctionBody() for other cases of the behavior change
4053     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4054     // type without a prototype.
4055     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4056         !New->isImplicit() && !Old->isImplicit()) {
4057       const FunctionDecl *WithProto, *WithoutProto;
4058       if (New->hasWrittenPrototype()) {
4059         WithProto = New;
4060         WithoutProto = Old;
4061       } else {
4062         WithProto = Old;
4063         WithoutProto = New;
4064       }
4065 
4066       if (WithProto->getNumParams() != 0) {
4067         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4068           // The one without the prototype will be changing behavior in C2x, so
4069           // warn about that one so long as it's a user-visible declaration.
4070           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4071           if (WithoutProto == New)
4072             IsWithoutProtoADef = NewDeclIsDefn;
4073           else
4074             IsWithProtoADef = NewDeclIsDefn;
4075           Diag(WithoutProto->getLocation(),
4076                diag::warn_non_prototype_changes_behavior)
4077               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4078               << (WithoutProto == Old) << IsWithProtoADef;
4079 
4080           // The reason the one without the prototype will be changing behavior
4081           // is because of the one with the prototype, so note that so long as
4082           // it's a user-visible declaration. There is one exception to this:
4083           // when the new declaration is a definition without a prototype, the
4084           // old declaration with a prototype is not the cause of the issue,
4085           // and that does not need to be noted because the one with a
4086           // prototype will not change behavior in C2x.
4087           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4088               !IsWithoutProtoADef)
4089             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4090         }
4091       }
4092     }
4093 
4094     if (Context.typesAreCompatible(OldQType, NewQType)) {
4095       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4096       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4097       const FunctionProtoType *OldProto = nullptr;
4098       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4099           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4100         // The old declaration provided a function prototype, but the
4101         // new declaration does not. Merge in the prototype.
4102         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4103         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4104         NewQType =
4105             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4106                                     OldProto->getExtProtoInfo());
4107         New->setType(NewQType);
4108         New->setHasInheritedPrototype();
4109 
4110         // Synthesize parameters with the same types.
4111         SmallVector<ParmVarDecl *, 16> Params;
4112         for (const auto &ParamType : OldProto->param_types()) {
4113           ParmVarDecl *Param = ParmVarDecl::Create(
4114               Context, New, SourceLocation(), SourceLocation(), nullptr,
4115               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4116           Param->setScopeInfo(0, Params.size());
4117           Param->setImplicit();
4118           Params.push_back(Param);
4119         }
4120 
4121         New->setParams(Params);
4122       }
4123 
4124       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4125     }
4126   }
4127 
4128   // Check if the function types are compatible when pointer size address
4129   // spaces are ignored.
4130   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4131     return false;
4132 
4133   // GNU C permits a K&R definition to follow a prototype declaration
4134   // if the declared types of the parameters in the K&R definition
4135   // match the types in the prototype declaration, even when the
4136   // promoted types of the parameters from the K&R definition differ
4137   // from the types in the prototype. GCC then keeps the types from
4138   // the prototype.
4139   //
4140   // If a variadic prototype is followed by a non-variadic K&R definition,
4141   // the K&R definition becomes variadic.  This is sort of an edge case, but
4142   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4143   // C99 6.9.1p8.
4144   if (!getLangOpts().CPlusPlus &&
4145       Old->hasPrototype() && !New->hasPrototype() &&
4146       New->getType()->getAs<FunctionProtoType>() &&
4147       Old->getNumParams() == New->getNumParams()) {
4148     SmallVector<QualType, 16> ArgTypes;
4149     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4150     const FunctionProtoType *OldProto
4151       = Old->getType()->getAs<FunctionProtoType>();
4152     const FunctionProtoType *NewProto
4153       = New->getType()->getAs<FunctionProtoType>();
4154 
4155     // Determine whether this is the GNU C extension.
4156     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4157                                                NewProto->getReturnType());
4158     bool LooseCompatible = !MergedReturn.isNull();
4159     for (unsigned Idx = 0, End = Old->getNumParams();
4160          LooseCompatible && Idx != End; ++Idx) {
4161       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4162       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4163       if (Context.typesAreCompatible(OldParm->getType(),
4164                                      NewProto->getParamType(Idx))) {
4165         ArgTypes.push_back(NewParm->getType());
4166       } else if (Context.typesAreCompatible(OldParm->getType(),
4167                                             NewParm->getType(),
4168                                             /*CompareUnqualified=*/true)) {
4169         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4170                                            NewProto->getParamType(Idx) };
4171         Warnings.push_back(Warn);
4172         ArgTypes.push_back(NewParm->getType());
4173       } else
4174         LooseCompatible = false;
4175     }
4176 
4177     if (LooseCompatible) {
4178       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4179         Diag(Warnings[Warn].NewParm->getLocation(),
4180              diag::ext_param_promoted_not_compatible_with_prototype)
4181           << Warnings[Warn].PromotedType
4182           << Warnings[Warn].OldParm->getType();
4183         if (Warnings[Warn].OldParm->getLocation().isValid())
4184           Diag(Warnings[Warn].OldParm->getLocation(),
4185                diag::note_previous_declaration);
4186       }
4187 
4188       if (MergeTypeWithOld)
4189         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4190                                              OldProto->getExtProtoInfo()));
4191       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4192     }
4193 
4194     // Fall through to diagnose conflicting types.
4195   }
4196 
4197   // A function that has already been declared has been redeclared or
4198   // defined with a different type; show an appropriate diagnostic.
4199 
4200   // If the previous declaration was an implicitly-generated builtin
4201   // declaration, then at the very least we should use a specialized note.
4202   unsigned BuiltinID;
4203   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4204     // If it's actually a library-defined builtin function like 'malloc'
4205     // or 'printf', just warn about the incompatible redeclaration.
4206     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4207       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4208       Diag(OldLocation, diag::note_previous_builtin_declaration)
4209         << Old << Old->getType();
4210       return false;
4211     }
4212 
4213     PrevDiag = diag::note_previous_builtin_declaration;
4214   }
4215 
4216   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4217   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4218   return true;
4219 }
4220 
4221 /// Completes the merge of two function declarations that are
4222 /// known to be compatible.
4223 ///
4224 /// This routine handles the merging of attributes and other
4225 /// properties of function declarations from the old declaration to
4226 /// the new declaration, once we know that New is in fact a
4227 /// redeclaration of Old.
4228 ///
4229 /// \returns false
4230 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4231                                         Scope *S, bool MergeTypeWithOld) {
4232   // Merge the attributes
4233   mergeDeclAttributes(New, Old);
4234 
4235   // Merge "pure" flag.
4236   if (Old->isPure())
4237     New->setPure();
4238 
4239   // Merge "used" flag.
4240   if (Old->getMostRecentDecl()->isUsed(false))
4241     New->setIsUsed();
4242 
4243   // Merge attributes from the parameters.  These can mismatch with K&R
4244   // declarations.
4245   if (New->getNumParams() == Old->getNumParams())
4246       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4247         ParmVarDecl *NewParam = New->getParamDecl(i);
4248         ParmVarDecl *OldParam = Old->getParamDecl(i);
4249         mergeParamDeclAttributes(NewParam, OldParam, *this);
4250         mergeParamDeclTypes(NewParam, OldParam, *this);
4251       }
4252 
4253   if (getLangOpts().CPlusPlus)
4254     return MergeCXXFunctionDecl(New, Old, S);
4255 
4256   // Merge the function types so the we get the composite types for the return
4257   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4258   // was visible.
4259   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4260   if (!Merged.isNull() && MergeTypeWithOld)
4261     New->setType(Merged);
4262 
4263   return false;
4264 }
4265 
4266 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4267                                 ObjCMethodDecl *oldMethod) {
4268   // Merge the attributes, including deprecated/unavailable
4269   AvailabilityMergeKind MergeKind =
4270       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4271           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4272                                      : AMK_ProtocolImplementation)
4273           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4274                                                            : AMK_Override;
4275 
4276   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4277 
4278   // Merge attributes from the parameters.
4279   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4280                                        oe = oldMethod->param_end();
4281   for (ObjCMethodDecl::param_iterator
4282          ni = newMethod->param_begin(), ne = newMethod->param_end();
4283        ni != ne && oi != oe; ++ni, ++oi)
4284     mergeParamDeclAttributes(*ni, *oi, *this);
4285 
4286   CheckObjCMethodOverride(newMethod, oldMethod);
4287 }
4288 
4289 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4290   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4291 
4292   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4293          ? diag::err_redefinition_different_type
4294          : diag::err_redeclaration_different_type)
4295     << New->getDeclName() << New->getType() << Old->getType();
4296 
4297   diag::kind PrevDiag;
4298   SourceLocation OldLocation;
4299   std::tie(PrevDiag, OldLocation)
4300     = getNoteDiagForInvalidRedeclaration(Old, New);
4301   S.Diag(OldLocation, PrevDiag);
4302   New->setInvalidDecl();
4303 }
4304 
4305 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4306 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4307 /// emitting diagnostics as appropriate.
4308 ///
4309 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4310 /// to here in AddInitializerToDecl. We can't check them before the initializer
4311 /// is attached.
4312 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4313                              bool MergeTypeWithOld) {
4314   if (New->isInvalidDecl() || Old->isInvalidDecl())
4315     return;
4316 
4317   QualType MergedT;
4318   if (getLangOpts().CPlusPlus) {
4319     if (New->getType()->isUndeducedType()) {
4320       // We don't know what the new type is until the initializer is attached.
4321       return;
4322     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4323       // These could still be something that needs exception specs checked.
4324       return MergeVarDeclExceptionSpecs(New, Old);
4325     }
4326     // C++ [basic.link]p10:
4327     //   [...] the types specified by all declarations referring to a given
4328     //   object or function shall be identical, except that declarations for an
4329     //   array object can specify array types that differ by the presence or
4330     //   absence of a major array bound (8.3.4).
4331     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4332       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4333       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4334 
4335       // We are merging a variable declaration New into Old. If it has an array
4336       // bound, and that bound differs from Old's bound, we should diagnose the
4337       // mismatch.
4338       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4339         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4340              PrevVD = PrevVD->getPreviousDecl()) {
4341           QualType PrevVDTy = PrevVD->getType();
4342           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4343             continue;
4344 
4345           if (!Context.hasSameType(New->getType(), PrevVDTy))
4346             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4347         }
4348       }
4349 
4350       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4351         if (Context.hasSameType(OldArray->getElementType(),
4352                                 NewArray->getElementType()))
4353           MergedT = New->getType();
4354       }
4355       // FIXME: Check visibility. New is hidden but has a complete type. If New
4356       // has no array bound, it should not inherit one from Old, if Old is not
4357       // visible.
4358       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4359         if (Context.hasSameType(OldArray->getElementType(),
4360                                 NewArray->getElementType()))
4361           MergedT = Old->getType();
4362       }
4363     }
4364     else if (New->getType()->isObjCObjectPointerType() &&
4365                Old->getType()->isObjCObjectPointerType()) {
4366       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4367                                               Old->getType());
4368     }
4369   } else {
4370     // C 6.2.7p2:
4371     //   All declarations that refer to the same object or function shall have
4372     //   compatible type.
4373     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4374   }
4375   if (MergedT.isNull()) {
4376     // It's OK if we couldn't merge types if either type is dependent, for a
4377     // block-scope variable. In other cases (static data members of class
4378     // templates, variable templates, ...), we require the types to be
4379     // equivalent.
4380     // FIXME: The C++ standard doesn't say anything about this.
4381     if ((New->getType()->isDependentType() ||
4382          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4383       // If the old type was dependent, we can't merge with it, so the new type
4384       // becomes dependent for now. We'll reproduce the original type when we
4385       // instantiate the TypeSourceInfo for the variable.
4386       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4387         New->setType(Context.DependentTy);
4388       return;
4389     }
4390     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4391   }
4392 
4393   // Don't actually update the type on the new declaration if the old
4394   // declaration was an extern declaration in a different scope.
4395   if (MergeTypeWithOld)
4396     New->setType(MergedT);
4397 }
4398 
4399 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4400                                   LookupResult &Previous) {
4401   // C11 6.2.7p4:
4402   //   For an identifier with internal or external linkage declared
4403   //   in a scope in which a prior declaration of that identifier is
4404   //   visible, if the prior declaration specifies internal or
4405   //   external linkage, the type of the identifier at the later
4406   //   declaration becomes the composite type.
4407   //
4408   // If the variable isn't visible, we do not merge with its type.
4409   if (Previous.isShadowed())
4410     return false;
4411 
4412   if (S.getLangOpts().CPlusPlus) {
4413     // C++11 [dcl.array]p3:
4414     //   If there is a preceding declaration of the entity in the same
4415     //   scope in which the bound was specified, an omitted array bound
4416     //   is taken to be the same as in that earlier declaration.
4417     return NewVD->isPreviousDeclInSameBlockScope() ||
4418            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4419             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4420   } else {
4421     // If the old declaration was function-local, don't merge with its
4422     // type unless we're in the same function.
4423     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4424            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4425   }
4426 }
4427 
4428 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4429 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4430 /// situation, merging decls or emitting diagnostics as appropriate.
4431 ///
4432 /// Tentative definition rules (C99 6.9.2p2) are checked by
4433 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4434 /// definitions here, since the initializer hasn't been attached.
4435 ///
4436 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4437   // If the new decl is already invalid, don't do any other checking.
4438   if (New->isInvalidDecl())
4439     return;
4440 
4441   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4442     return;
4443 
4444   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4445 
4446   // Verify the old decl was also a variable or variable template.
4447   VarDecl *Old = nullptr;
4448   VarTemplateDecl *OldTemplate = nullptr;
4449   if (Previous.isSingleResult()) {
4450     if (NewTemplate) {
4451       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4452       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4453 
4454       if (auto *Shadow =
4455               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4456         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4457           return New->setInvalidDecl();
4458     } else {
4459       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4460 
4461       if (auto *Shadow =
4462               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4463         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4464           return New->setInvalidDecl();
4465     }
4466   }
4467   if (!Old) {
4468     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4469         << New->getDeclName();
4470     notePreviousDefinition(Previous.getRepresentativeDecl(),
4471                            New->getLocation());
4472     return New->setInvalidDecl();
4473   }
4474 
4475   // If the old declaration was found in an inline namespace and the new
4476   // declaration was qualified, update the DeclContext to match.
4477   adjustDeclContextForDeclaratorDecl(New, Old);
4478 
4479   // Ensure the template parameters are compatible.
4480   if (NewTemplate &&
4481       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4482                                       OldTemplate->getTemplateParameters(),
4483                                       /*Complain=*/true, TPL_TemplateMatch))
4484     return New->setInvalidDecl();
4485 
4486   // C++ [class.mem]p1:
4487   //   A member shall not be declared twice in the member-specification [...]
4488   //
4489   // Here, we need only consider static data members.
4490   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4491     Diag(New->getLocation(), diag::err_duplicate_member)
4492       << New->getIdentifier();
4493     Diag(Old->getLocation(), diag::note_previous_declaration);
4494     New->setInvalidDecl();
4495   }
4496 
4497   mergeDeclAttributes(New, Old);
4498   // Warn if an already-declared variable is made a weak_import in a subsequent
4499   // declaration
4500   if (New->hasAttr<WeakImportAttr>() &&
4501       Old->getStorageClass() == SC_None &&
4502       !Old->hasAttr<WeakImportAttr>()) {
4503     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4504     Diag(Old->getLocation(), diag::note_previous_declaration);
4505     // Remove weak_import attribute on new declaration.
4506     New->dropAttr<WeakImportAttr>();
4507   }
4508 
4509   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4510     if (!Old->hasAttr<InternalLinkageAttr>()) {
4511       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4512           << ILA;
4513       Diag(Old->getLocation(), diag::note_previous_declaration);
4514       New->dropAttr<InternalLinkageAttr>();
4515     }
4516 
4517   // Merge the types.
4518   VarDecl *MostRecent = Old->getMostRecentDecl();
4519   if (MostRecent != Old) {
4520     MergeVarDeclTypes(New, MostRecent,
4521                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4522     if (New->isInvalidDecl())
4523       return;
4524   }
4525 
4526   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4527   if (New->isInvalidDecl())
4528     return;
4529 
4530   diag::kind PrevDiag;
4531   SourceLocation OldLocation;
4532   std::tie(PrevDiag, OldLocation) =
4533       getNoteDiagForInvalidRedeclaration(Old, New);
4534 
4535   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4536   if (New->getStorageClass() == SC_Static &&
4537       !New->isStaticDataMember() &&
4538       Old->hasExternalFormalLinkage()) {
4539     if (getLangOpts().MicrosoftExt) {
4540       Diag(New->getLocation(), diag::ext_static_non_static)
4541           << New->getDeclName();
4542       Diag(OldLocation, PrevDiag);
4543     } else {
4544       Diag(New->getLocation(), diag::err_static_non_static)
4545           << New->getDeclName();
4546       Diag(OldLocation, PrevDiag);
4547       return New->setInvalidDecl();
4548     }
4549   }
4550   // C99 6.2.2p4:
4551   //   For an identifier declared with the storage-class specifier
4552   //   extern in a scope in which a prior declaration of that
4553   //   identifier is visible,23) if the prior declaration specifies
4554   //   internal or external linkage, the linkage of the identifier at
4555   //   the later declaration is the same as the linkage specified at
4556   //   the prior declaration. If no prior declaration is visible, or
4557   //   if the prior declaration specifies no linkage, then the
4558   //   identifier has external linkage.
4559   if (New->hasExternalStorage() && Old->hasLinkage())
4560     /* Okay */;
4561   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4562            !New->isStaticDataMember() &&
4563            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4564     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4565     Diag(OldLocation, PrevDiag);
4566     return New->setInvalidDecl();
4567   }
4568 
4569   // Check if extern is followed by non-extern and vice-versa.
4570   if (New->hasExternalStorage() &&
4571       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4572     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4573     Diag(OldLocation, PrevDiag);
4574     return New->setInvalidDecl();
4575   }
4576   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4577       !New->hasExternalStorage()) {
4578     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4579     Diag(OldLocation, PrevDiag);
4580     return New->setInvalidDecl();
4581   }
4582 
4583   if (CheckRedeclarationInModule(New, Old))
4584     return;
4585 
4586   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4587 
4588   // FIXME: The test for external storage here seems wrong? We still
4589   // need to check for mismatches.
4590   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4591       // Don't complain about out-of-line definitions of static members.
4592       !(Old->getLexicalDeclContext()->isRecord() &&
4593         !New->getLexicalDeclContext()->isRecord())) {
4594     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4595     Diag(OldLocation, PrevDiag);
4596     return New->setInvalidDecl();
4597   }
4598 
4599   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4600     if (VarDecl *Def = Old->getDefinition()) {
4601       // C++1z [dcl.fcn.spec]p4:
4602       //   If the definition of a variable appears in a translation unit before
4603       //   its first declaration as inline, the program is ill-formed.
4604       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4605       Diag(Def->getLocation(), diag::note_previous_definition);
4606     }
4607   }
4608 
4609   // If this redeclaration makes the variable inline, we may need to add it to
4610   // UndefinedButUsed.
4611   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4612       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4613     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4614                                            SourceLocation()));
4615 
4616   if (New->getTLSKind() != Old->getTLSKind()) {
4617     if (!Old->getTLSKind()) {
4618       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4619       Diag(OldLocation, PrevDiag);
4620     } else if (!New->getTLSKind()) {
4621       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4622       Diag(OldLocation, PrevDiag);
4623     } else {
4624       // Do not allow redeclaration to change the variable between requiring
4625       // static and dynamic initialization.
4626       // FIXME: GCC allows this, but uses the TLS keyword on the first
4627       // declaration to determine the kind. Do we need to be compatible here?
4628       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4629         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4630       Diag(OldLocation, PrevDiag);
4631     }
4632   }
4633 
4634   // C++ doesn't have tentative definitions, so go right ahead and check here.
4635   if (getLangOpts().CPlusPlus) {
4636     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4637         Old->getCanonicalDecl()->isConstexpr()) {
4638       // This definition won't be a definition any more once it's been merged.
4639       Diag(New->getLocation(),
4640            diag::warn_deprecated_redundant_constexpr_static_def);
4641     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4642       VarDecl *Def = Old->getDefinition();
4643       if (Def && checkVarDeclRedefinition(Def, New))
4644         return;
4645     }
4646   }
4647 
4648   if (haveIncompatibleLanguageLinkages(Old, New)) {
4649     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4650     Diag(OldLocation, PrevDiag);
4651     New->setInvalidDecl();
4652     return;
4653   }
4654 
4655   // Merge "used" flag.
4656   if (Old->getMostRecentDecl()->isUsed(false))
4657     New->setIsUsed();
4658 
4659   // Keep a chain of previous declarations.
4660   New->setPreviousDecl(Old);
4661   if (NewTemplate)
4662     NewTemplate->setPreviousDecl(OldTemplate);
4663 
4664   // Inherit access appropriately.
4665   New->setAccess(Old->getAccess());
4666   if (NewTemplate)
4667     NewTemplate->setAccess(New->getAccess());
4668 
4669   if (Old->isInline())
4670     New->setImplicitlyInline();
4671 }
4672 
4673 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4674   SourceManager &SrcMgr = getSourceManager();
4675   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4676   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4677   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4678   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4679   auto &HSI = PP.getHeaderSearchInfo();
4680   StringRef HdrFilename =
4681       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4682 
4683   auto noteFromModuleOrInclude = [&](Module *Mod,
4684                                      SourceLocation IncLoc) -> bool {
4685     // Redefinition errors with modules are common with non modular mapped
4686     // headers, example: a non-modular header H in module A that also gets
4687     // included directly in a TU. Pointing twice to the same header/definition
4688     // is confusing, try to get better diagnostics when modules is on.
4689     if (IncLoc.isValid()) {
4690       if (Mod) {
4691         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4692             << HdrFilename.str() << Mod->getFullModuleName();
4693         if (!Mod->DefinitionLoc.isInvalid())
4694           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4695               << Mod->getFullModuleName();
4696       } else {
4697         Diag(IncLoc, diag::note_redefinition_include_same_file)
4698             << HdrFilename.str();
4699       }
4700       return true;
4701     }
4702 
4703     return false;
4704   };
4705 
4706   // Is it the same file and same offset? Provide more information on why
4707   // this leads to a redefinition error.
4708   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4709     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4710     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4711     bool EmittedDiag =
4712         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4713     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4714 
4715     // If the header has no guards, emit a note suggesting one.
4716     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4717       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4718 
4719     if (EmittedDiag)
4720       return;
4721   }
4722 
4723   // Redefinition coming from different files or couldn't do better above.
4724   if (Old->getLocation().isValid())
4725     Diag(Old->getLocation(), diag::note_previous_definition);
4726 }
4727 
4728 /// We've just determined that \p Old and \p New both appear to be definitions
4729 /// of the same variable. Either diagnose or fix the problem.
4730 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4731   if (!hasVisibleDefinition(Old) &&
4732       (New->getFormalLinkage() == InternalLinkage ||
4733        New->isInline() ||
4734        New->getDescribedVarTemplate() ||
4735        New->getNumTemplateParameterLists() ||
4736        New->getDeclContext()->isDependentContext())) {
4737     // The previous definition is hidden, and multiple definitions are
4738     // permitted (in separate TUs). Demote this to a declaration.
4739     New->demoteThisDefinitionToDeclaration();
4740 
4741     // Make the canonical definition visible.
4742     if (auto *OldTD = Old->getDescribedVarTemplate())
4743       makeMergedDefinitionVisible(OldTD);
4744     makeMergedDefinitionVisible(Old);
4745     return false;
4746   } else {
4747     Diag(New->getLocation(), diag::err_redefinition) << New;
4748     notePreviousDefinition(Old, New->getLocation());
4749     New->setInvalidDecl();
4750     return true;
4751   }
4752 }
4753 
4754 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4755 /// no declarator (e.g. "struct foo;") is parsed.
4756 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4757                                        DeclSpec &DS,
4758                                        const ParsedAttributesView &DeclAttrs,
4759                                        RecordDecl *&AnonRecord) {
4760   return ParsedFreeStandingDeclSpec(
4761       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4762 }
4763 
4764 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4765 // disambiguate entities defined in different scopes.
4766 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4767 // compatibility.
4768 // We will pick our mangling number depending on which version of MSVC is being
4769 // targeted.
4770 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4771   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4772              ? S->getMSCurManglingNumber()
4773              : S->getMSLastManglingNumber();
4774 }
4775 
4776 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4777   if (!Context.getLangOpts().CPlusPlus)
4778     return;
4779 
4780   if (isa<CXXRecordDecl>(Tag->getParent())) {
4781     // If this tag is the direct child of a class, number it if
4782     // it is anonymous.
4783     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4784       return;
4785     MangleNumberingContext &MCtx =
4786         Context.getManglingNumberContext(Tag->getParent());
4787     Context.setManglingNumber(
4788         Tag, MCtx.getManglingNumber(
4789                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4790     return;
4791   }
4792 
4793   // If this tag isn't a direct child of a class, number it if it is local.
4794   MangleNumberingContext *MCtx;
4795   Decl *ManglingContextDecl;
4796   std::tie(MCtx, ManglingContextDecl) =
4797       getCurrentMangleNumberContext(Tag->getDeclContext());
4798   if (MCtx) {
4799     Context.setManglingNumber(
4800         Tag, MCtx->getManglingNumber(
4801                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4802   }
4803 }
4804 
4805 namespace {
4806 struct NonCLikeKind {
4807   enum {
4808     None,
4809     BaseClass,
4810     DefaultMemberInit,
4811     Lambda,
4812     Friend,
4813     OtherMember,
4814     Invalid,
4815   } Kind = None;
4816   SourceRange Range;
4817 
4818   explicit operator bool() { return Kind != None; }
4819 };
4820 }
4821 
4822 /// Determine whether a class is C-like, according to the rules of C++
4823 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4824 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4825   if (RD->isInvalidDecl())
4826     return {NonCLikeKind::Invalid, {}};
4827 
4828   // C++ [dcl.typedef]p9: [P1766R1]
4829   //   An unnamed class with a typedef name for linkage purposes shall not
4830   //
4831   //    -- have any base classes
4832   if (RD->getNumBases())
4833     return {NonCLikeKind::BaseClass,
4834             SourceRange(RD->bases_begin()->getBeginLoc(),
4835                         RD->bases_end()[-1].getEndLoc())};
4836   bool Invalid = false;
4837   for (Decl *D : RD->decls()) {
4838     // Don't complain about things we already diagnosed.
4839     if (D->isInvalidDecl()) {
4840       Invalid = true;
4841       continue;
4842     }
4843 
4844     //  -- have any [...] default member initializers
4845     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4846       if (FD->hasInClassInitializer()) {
4847         auto *Init = FD->getInClassInitializer();
4848         return {NonCLikeKind::DefaultMemberInit,
4849                 Init ? Init->getSourceRange() : D->getSourceRange()};
4850       }
4851       continue;
4852     }
4853 
4854     // FIXME: We don't allow friend declarations. This violates the wording of
4855     // P1766, but not the intent.
4856     if (isa<FriendDecl>(D))
4857       return {NonCLikeKind::Friend, D->getSourceRange()};
4858 
4859     //  -- declare any members other than non-static data members, member
4860     //     enumerations, or member classes,
4861     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4862         isa<EnumDecl>(D))
4863       continue;
4864     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4865     if (!MemberRD) {
4866       if (D->isImplicit())
4867         continue;
4868       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4869     }
4870 
4871     //  -- contain a lambda-expression,
4872     if (MemberRD->isLambda())
4873       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4874 
4875     //  and all member classes shall also satisfy these requirements
4876     //  (recursively).
4877     if (MemberRD->isThisDeclarationADefinition()) {
4878       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4879         return Kind;
4880     }
4881   }
4882 
4883   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4884 }
4885 
4886 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4887                                         TypedefNameDecl *NewTD) {
4888   if (TagFromDeclSpec->isInvalidDecl())
4889     return;
4890 
4891   // Do nothing if the tag already has a name for linkage purposes.
4892   if (TagFromDeclSpec->hasNameForLinkage())
4893     return;
4894 
4895   // A well-formed anonymous tag must always be a TUK_Definition.
4896   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4897 
4898   // The type must match the tag exactly;  no qualifiers allowed.
4899   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4900                            Context.getTagDeclType(TagFromDeclSpec))) {
4901     if (getLangOpts().CPlusPlus)
4902       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4903     return;
4904   }
4905 
4906   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4907   //   An unnamed class with a typedef name for linkage purposes shall [be
4908   //   C-like].
4909   //
4910   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4911   // shouldn't happen, but there are constructs that the language rule doesn't
4912   // disallow for which we can't reasonably avoid computing linkage early.
4913   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4914   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4915                              : NonCLikeKind();
4916   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4917   if (NonCLike || ChangesLinkage) {
4918     if (NonCLike.Kind == NonCLikeKind::Invalid)
4919       return;
4920 
4921     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4922     if (ChangesLinkage) {
4923       // If the linkage changes, we can't accept this as an extension.
4924       if (NonCLike.Kind == NonCLikeKind::None)
4925         DiagID = diag::err_typedef_changes_linkage;
4926       else
4927         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4928     }
4929 
4930     SourceLocation FixitLoc =
4931         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4932     llvm::SmallString<40> TextToInsert;
4933     TextToInsert += ' ';
4934     TextToInsert += NewTD->getIdentifier()->getName();
4935 
4936     Diag(FixitLoc, DiagID)
4937       << isa<TypeAliasDecl>(NewTD)
4938       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4939     if (NonCLike.Kind != NonCLikeKind::None) {
4940       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4941         << NonCLike.Kind - 1 << NonCLike.Range;
4942     }
4943     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4944       << NewTD << isa<TypeAliasDecl>(NewTD);
4945 
4946     if (ChangesLinkage)
4947       return;
4948   }
4949 
4950   // Otherwise, set this as the anon-decl typedef for the tag.
4951   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4952 }
4953 
4954 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4955   switch (T) {
4956   case DeclSpec::TST_class:
4957     return 0;
4958   case DeclSpec::TST_struct:
4959     return 1;
4960   case DeclSpec::TST_interface:
4961     return 2;
4962   case DeclSpec::TST_union:
4963     return 3;
4964   case DeclSpec::TST_enum:
4965     return 4;
4966   default:
4967     llvm_unreachable("unexpected type specifier");
4968   }
4969 }
4970 
4971 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4972 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4973 /// parameters to cope with template friend declarations.
4974 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4975                                        DeclSpec &DS,
4976                                        const ParsedAttributesView &DeclAttrs,
4977                                        MultiTemplateParamsArg TemplateParams,
4978                                        bool IsExplicitInstantiation,
4979                                        RecordDecl *&AnonRecord) {
4980   Decl *TagD = nullptr;
4981   TagDecl *Tag = nullptr;
4982   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4983       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4984       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4985       DS.getTypeSpecType() == DeclSpec::TST_union ||
4986       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4987     TagD = DS.getRepAsDecl();
4988 
4989     if (!TagD) // We probably had an error
4990       return nullptr;
4991 
4992     // Note that the above type specs guarantee that the
4993     // type rep is a Decl, whereas in many of the others
4994     // it's a Type.
4995     if (isa<TagDecl>(TagD))
4996       Tag = cast<TagDecl>(TagD);
4997     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4998       Tag = CTD->getTemplatedDecl();
4999   }
5000 
5001   if (Tag) {
5002     handleTagNumbering(Tag, S);
5003     Tag->setFreeStanding();
5004     if (Tag->isInvalidDecl())
5005       return Tag;
5006   }
5007 
5008   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5009     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5010     // or incomplete types shall not be restrict-qualified."
5011     if (TypeQuals & DeclSpec::TQ_restrict)
5012       Diag(DS.getRestrictSpecLoc(),
5013            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5014            << DS.getSourceRange();
5015   }
5016 
5017   if (DS.isInlineSpecified())
5018     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5019         << getLangOpts().CPlusPlus17;
5020 
5021   if (DS.hasConstexprSpecifier()) {
5022     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5023     // and definitions of functions and variables.
5024     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5025     // the declaration of a function or function template
5026     if (Tag)
5027       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5028           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
5029           << static_cast<int>(DS.getConstexprSpecifier());
5030     else
5031       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5032           << static_cast<int>(DS.getConstexprSpecifier());
5033     // Don't emit warnings after this error.
5034     return TagD;
5035   }
5036 
5037   DiagnoseFunctionSpecifiers(DS);
5038 
5039   if (DS.isFriendSpecified()) {
5040     // If we're dealing with a decl but not a TagDecl, assume that
5041     // whatever routines created it handled the friendship aspect.
5042     if (TagD && !Tag)
5043       return nullptr;
5044     return ActOnFriendTypeDecl(S, DS, TemplateParams);
5045   }
5046 
5047   const CXXScopeSpec &SS = DS.getTypeSpecScope();
5048   bool IsExplicitSpecialization =
5049     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5050   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5051       !IsExplicitInstantiation && !IsExplicitSpecialization &&
5052       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5053     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5054     // nested-name-specifier unless it is an explicit instantiation
5055     // or an explicit specialization.
5056     //
5057     // FIXME: We allow class template partial specializations here too, per the
5058     // obvious intent of DR1819.
5059     //
5060     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5061     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5062         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
5063     return nullptr;
5064   }
5065 
5066   // Track whether this decl-specifier declares anything.
5067   bool DeclaresAnything = true;
5068 
5069   // Handle anonymous struct definitions.
5070   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5071     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5072         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5073       if (getLangOpts().CPlusPlus ||
5074           Record->getDeclContext()->isRecord()) {
5075         // If CurContext is a DeclContext that can contain statements,
5076         // RecursiveASTVisitor won't visit the decls that
5077         // BuildAnonymousStructOrUnion() will put into CurContext.
5078         // Also store them here so that they can be part of the
5079         // DeclStmt that gets created in this case.
5080         // FIXME: Also return the IndirectFieldDecls created by
5081         // BuildAnonymousStructOr union, for the same reason?
5082         if (CurContext->isFunctionOrMethod())
5083           AnonRecord = Record;
5084         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5085                                            Context.getPrintingPolicy());
5086       }
5087 
5088       DeclaresAnything = false;
5089     }
5090   }
5091 
5092   // C11 6.7.2.1p2:
5093   //   A struct-declaration that does not declare an anonymous structure or
5094   //   anonymous union shall contain a struct-declarator-list.
5095   //
5096   // This rule also existed in C89 and C99; the grammar for struct-declaration
5097   // did not permit a struct-declaration without a struct-declarator-list.
5098   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5099       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5100     // Check for Microsoft C extension: anonymous struct/union member.
5101     // Handle 2 kinds of anonymous struct/union:
5102     //   struct STRUCT;
5103     //   union UNION;
5104     // and
5105     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5106     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5107     if ((Tag && Tag->getDeclName()) ||
5108         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5109       RecordDecl *Record = nullptr;
5110       if (Tag)
5111         Record = dyn_cast<RecordDecl>(Tag);
5112       else if (const RecordType *RT =
5113                    DS.getRepAsType().get()->getAsStructureType())
5114         Record = RT->getDecl();
5115       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5116         Record = UT->getDecl();
5117 
5118       if (Record && getLangOpts().MicrosoftExt) {
5119         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5120             << Record->isUnion() << DS.getSourceRange();
5121         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5122       }
5123 
5124       DeclaresAnything = false;
5125     }
5126   }
5127 
5128   // Skip all the checks below if we have a type error.
5129   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5130       (TagD && TagD->isInvalidDecl()))
5131     return TagD;
5132 
5133   if (getLangOpts().CPlusPlus &&
5134       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5135     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5136       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5137           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5138         DeclaresAnything = false;
5139 
5140   if (!DS.isMissingDeclaratorOk()) {
5141     // Customize diagnostic for a typedef missing a name.
5142     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5143       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5144           << DS.getSourceRange();
5145     else
5146       DeclaresAnything = false;
5147   }
5148 
5149   if (DS.isModulePrivateSpecified() &&
5150       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5151     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5152       << Tag->getTagKind()
5153       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5154 
5155   ActOnDocumentableDecl(TagD);
5156 
5157   // C 6.7/2:
5158   //   A declaration [...] shall declare at least a declarator [...], a tag,
5159   //   or the members of an enumeration.
5160   // C++ [dcl.dcl]p3:
5161   //   [If there are no declarators], and except for the declaration of an
5162   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5163   //   names into the program, or shall redeclare a name introduced by a
5164   //   previous declaration.
5165   if (!DeclaresAnything) {
5166     // In C, we allow this as a (popular) extension / bug. Don't bother
5167     // producing further diagnostics for redundant qualifiers after this.
5168     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5169                                ? diag::err_no_declarators
5170                                : diag::ext_no_declarators)
5171         << DS.getSourceRange();
5172     return TagD;
5173   }
5174 
5175   // C++ [dcl.stc]p1:
5176   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5177   //   init-declarator-list of the declaration shall not be empty.
5178   // C++ [dcl.fct.spec]p1:
5179   //   If a cv-qualifier appears in a decl-specifier-seq, the
5180   //   init-declarator-list of the declaration shall not be empty.
5181   //
5182   // Spurious qualifiers here appear to be valid in C.
5183   unsigned DiagID = diag::warn_standalone_specifier;
5184   if (getLangOpts().CPlusPlus)
5185     DiagID = diag::ext_standalone_specifier;
5186 
5187   // Note that a linkage-specification sets a storage class, but
5188   // 'extern "C" struct foo;' is actually valid and not theoretically
5189   // useless.
5190   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5191     if (SCS == DeclSpec::SCS_mutable)
5192       // Since mutable is not a viable storage class specifier in C, there is
5193       // no reason to treat it as an extension. Instead, diagnose as an error.
5194       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5195     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5196       Diag(DS.getStorageClassSpecLoc(), DiagID)
5197         << DeclSpec::getSpecifierName(SCS);
5198   }
5199 
5200   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5201     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5202       << DeclSpec::getSpecifierName(TSCS);
5203   if (DS.getTypeQualifiers()) {
5204     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5205       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5206     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5207       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5208     // Restrict is covered above.
5209     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5210       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5211     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5212       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5213   }
5214 
5215   // Warn about ignored type attributes, for example:
5216   // __attribute__((aligned)) struct A;
5217   // Attributes should be placed after tag to apply to type declaration.
5218   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5219     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5220     if (TypeSpecType == DeclSpec::TST_class ||
5221         TypeSpecType == DeclSpec::TST_struct ||
5222         TypeSpecType == DeclSpec::TST_interface ||
5223         TypeSpecType == DeclSpec::TST_union ||
5224         TypeSpecType == DeclSpec::TST_enum) {
5225       for (const ParsedAttr &AL : DS.getAttributes())
5226         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5227             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5228       for (const ParsedAttr &AL : DeclAttrs)
5229         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5230             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5231     }
5232   }
5233 
5234   return TagD;
5235 }
5236 
5237 /// We are trying to inject an anonymous member into the given scope;
5238 /// check if there's an existing declaration that can't be overloaded.
5239 ///
5240 /// \return true if this is a forbidden redeclaration
5241 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5242                                          Scope *S,
5243                                          DeclContext *Owner,
5244                                          DeclarationName Name,
5245                                          SourceLocation NameLoc,
5246                                          bool IsUnion) {
5247   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5248                  Sema::ForVisibleRedeclaration);
5249   if (!SemaRef.LookupName(R, S)) return false;
5250 
5251   // Pick a representative declaration.
5252   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5253   assert(PrevDecl && "Expected a non-null Decl");
5254 
5255   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5256     return false;
5257 
5258   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5259     << IsUnion << Name;
5260   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5261 
5262   return true;
5263 }
5264 
5265 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5266 /// anonymous struct or union AnonRecord into the owning context Owner
5267 /// and scope S. This routine will be invoked just after we realize
5268 /// that an unnamed union or struct is actually an anonymous union or
5269 /// struct, e.g.,
5270 ///
5271 /// @code
5272 /// union {
5273 ///   int i;
5274 ///   float f;
5275 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5276 ///    // f into the surrounding scope.x
5277 /// @endcode
5278 ///
5279 /// This routine is recursive, injecting the names of nested anonymous
5280 /// structs/unions into the owning context and scope as well.
5281 static bool
5282 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5283                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5284                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5285   bool Invalid = false;
5286 
5287   // Look every FieldDecl and IndirectFieldDecl with a name.
5288   for (auto *D : AnonRecord->decls()) {
5289     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5290         cast<NamedDecl>(D)->getDeclName()) {
5291       ValueDecl *VD = cast<ValueDecl>(D);
5292       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5293                                        VD->getLocation(),
5294                                        AnonRecord->isUnion())) {
5295         // C++ [class.union]p2:
5296         //   The names of the members of an anonymous union shall be
5297         //   distinct from the names of any other entity in the
5298         //   scope in which the anonymous union is declared.
5299         Invalid = true;
5300       } else {
5301         // C++ [class.union]p2:
5302         //   For the purpose of name lookup, after the anonymous union
5303         //   definition, the members of the anonymous union are
5304         //   considered to have been defined in the scope in which the
5305         //   anonymous union is declared.
5306         unsigned OldChainingSize = Chaining.size();
5307         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5308           Chaining.append(IF->chain_begin(), IF->chain_end());
5309         else
5310           Chaining.push_back(VD);
5311 
5312         assert(Chaining.size() >= 2);
5313         NamedDecl **NamedChain =
5314           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5315         for (unsigned i = 0; i < Chaining.size(); i++)
5316           NamedChain[i] = Chaining[i];
5317 
5318         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5319             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5320             VD->getType(), {NamedChain, Chaining.size()});
5321 
5322         for (const auto *Attr : VD->attrs())
5323           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5324 
5325         IndirectField->setAccess(AS);
5326         IndirectField->setImplicit();
5327         SemaRef.PushOnScopeChains(IndirectField, S);
5328 
5329         // That includes picking up the appropriate access specifier.
5330         if (AS != AS_none) IndirectField->setAccess(AS);
5331 
5332         Chaining.resize(OldChainingSize);
5333       }
5334     }
5335   }
5336 
5337   return Invalid;
5338 }
5339 
5340 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5341 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5342 /// illegal input values are mapped to SC_None.
5343 static StorageClass
5344 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5345   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5346   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5347          "Parser allowed 'typedef' as storage class VarDecl.");
5348   switch (StorageClassSpec) {
5349   case DeclSpec::SCS_unspecified:    return SC_None;
5350   case DeclSpec::SCS_extern:
5351     if (DS.isExternInLinkageSpec())
5352       return SC_None;
5353     return SC_Extern;
5354   case DeclSpec::SCS_static:         return SC_Static;
5355   case DeclSpec::SCS_auto:           return SC_Auto;
5356   case DeclSpec::SCS_register:       return SC_Register;
5357   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5358     // Illegal SCSs map to None: error reporting is up to the caller.
5359   case DeclSpec::SCS_mutable:        // Fall through.
5360   case DeclSpec::SCS_typedef:        return SC_None;
5361   }
5362   llvm_unreachable("unknown storage class specifier");
5363 }
5364 
5365 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5366   assert(Record->hasInClassInitializer());
5367 
5368   for (const auto *I : Record->decls()) {
5369     const auto *FD = dyn_cast<FieldDecl>(I);
5370     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5371       FD = IFD->getAnonField();
5372     if (FD && FD->hasInClassInitializer())
5373       return FD->getLocation();
5374   }
5375 
5376   llvm_unreachable("couldn't find in-class initializer");
5377 }
5378 
5379 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5380                                       SourceLocation DefaultInitLoc) {
5381   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5382     return;
5383 
5384   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5385   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5386 }
5387 
5388 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5389                                       CXXRecordDecl *AnonUnion) {
5390   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5391     return;
5392 
5393   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5394 }
5395 
5396 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5397 /// anonymous structure or union. Anonymous unions are a C++ feature
5398 /// (C++ [class.union]) and a C11 feature; anonymous structures
5399 /// are a C11 feature and GNU C++ extension.
5400 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5401                                         AccessSpecifier AS,
5402                                         RecordDecl *Record,
5403                                         const PrintingPolicy &Policy) {
5404   DeclContext *Owner = Record->getDeclContext();
5405 
5406   // Diagnose whether this anonymous struct/union is an extension.
5407   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5408     Diag(Record->getLocation(), diag::ext_anonymous_union);
5409   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5410     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5411   else if (!Record->isUnion() && !getLangOpts().C11)
5412     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5413 
5414   // C and C++ require different kinds of checks for anonymous
5415   // structs/unions.
5416   bool Invalid = false;
5417   if (getLangOpts().CPlusPlus) {
5418     const char *PrevSpec = nullptr;
5419     if (Record->isUnion()) {
5420       // C++ [class.union]p6:
5421       // C++17 [class.union.anon]p2:
5422       //   Anonymous unions declared in a named namespace or in the
5423       //   global namespace shall be declared static.
5424       unsigned DiagID;
5425       DeclContext *OwnerScope = Owner->getRedeclContext();
5426       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5427           (OwnerScope->isTranslationUnit() ||
5428            (OwnerScope->isNamespace() &&
5429             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5430         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5431           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5432 
5433         // Recover by adding 'static'.
5434         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5435                                PrevSpec, DiagID, Policy);
5436       }
5437       // C++ [class.union]p6:
5438       //   A storage class is not allowed in a declaration of an
5439       //   anonymous union in a class scope.
5440       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5441                isa<RecordDecl>(Owner)) {
5442         Diag(DS.getStorageClassSpecLoc(),
5443              diag::err_anonymous_union_with_storage_spec)
5444           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5445 
5446         // Recover by removing the storage specifier.
5447         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5448                                SourceLocation(),
5449                                PrevSpec, DiagID, Context.getPrintingPolicy());
5450       }
5451     }
5452 
5453     // Ignore const/volatile/restrict qualifiers.
5454     if (DS.getTypeQualifiers()) {
5455       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5456         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5457           << Record->isUnion() << "const"
5458           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5459       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5460         Diag(DS.getVolatileSpecLoc(),
5461              diag::ext_anonymous_struct_union_qualified)
5462           << Record->isUnion() << "volatile"
5463           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5464       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5465         Diag(DS.getRestrictSpecLoc(),
5466              diag::ext_anonymous_struct_union_qualified)
5467           << Record->isUnion() << "restrict"
5468           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5469       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5470         Diag(DS.getAtomicSpecLoc(),
5471              diag::ext_anonymous_struct_union_qualified)
5472           << Record->isUnion() << "_Atomic"
5473           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5474       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5475         Diag(DS.getUnalignedSpecLoc(),
5476              diag::ext_anonymous_struct_union_qualified)
5477           << Record->isUnion() << "__unaligned"
5478           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5479 
5480       DS.ClearTypeQualifiers();
5481     }
5482 
5483     // C++ [class.union]p2:
5484     //   The member-specification of an anonymous union shall only
5485     //   define non-static data members. [Note: nested types and
5486     //   functions cannot be declared within an anonymous union. ]
5487     for (auto *Mem : Record->decls()) {
5488       // Ignore invalid declarations; we already diagnosed them.
5489       if (Mem->isInvalidDecl())
5490         continue;
5491 
5492       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5493         // C++ [class.union]p3:
5494         //   An anonymous union shall not have private or protected
5495         //   members (clause 11).
5496         assert(FD->getAccess() != AS_none);
5497         if (FD->getAccess() != AS_public) {
5498           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5499             << Record->isUnion() << (FD->getAccess() == AS_protected);
5500           Invalid = true;
5501         }
5502 
5503         // C++ [class.union]p1
5504         //   An object of a class with a non-trivial constructor, a non-trivial
5505         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5506         //   assignment operator cannot be a member of a union, nor can an
5507         //   array of such objects.
5508         if (CheckNontrivialField(FD))
5509           Invalid = true;
5510       } else if (Mem->isImplicit()) {
5511         // Any implicit members are fine.
5512       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5513         // This is a type that showed up in an
5514         // elaborated-type-specifier inside the anonymous struct or
5515         // union, but which actually declares a type outside of the
5516         // anonymous struct or union. It's okay.
5517       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5518         if (!MemRecord->isAnonymousStructOrUnion() &&
5519             MemRecord->getDeclName()) {
5520           // Visual C++ allows type definition in anonymous struct or union.
5521           if (getLangOpts().MicrosoftExt)
5522             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5523               << Record->isUnion();
5524           else {
5525             // This is a nested type declaration.
5526             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5527               << Record->isUnion();
5528             Invalid = true;
5529           }
5530         } else {
5531           // This is an anonymous type definition within another anonymous type.
5532           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5533           // not part of standard C++.
5534           Diag(MemRecord->getLocation(),
5535                diag::ext_anonymous_record_with_anonymous_type)
5536             << Record->isUnion();
5537         }
5538       } else if (isa<AccessSpecDecl>(Mem)) {
5539         // Any access specifier is fine.
5540       } else if (isa<StaticAssertDecl>(Mem)) {
5541         // In C++1z, static_assert declarations are also fine.
5542       } else {
5543         // We have something that isn't a non-static data
5544         // member. Complain about it.
5545         unsigned DK = diag::err_anonymous_record_bad_member;
5546         if (isa<TypeDecl>(Mem))
5547           DK = diag::err_anonymous_record_with_type;
5548         else if (isa<FunctionDecl>(Mem))
5549           DK = diag::err_anonymous_record_with_function;
5550         else if (isa<VarDecl>(Mem))
5551           DK = diag::err_anonymous_record_with_static;
5552 
5553         // Visual C++ allows type definition in anonymous struct or union.
5554         if (getLangOpts().MicrosoftExt &&
5555             DK == diag::err_anonymous_record_with_type)
5556           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5557             << Record->isUnion();
5558         else {
5559           Diag(Mem->getLocation(), DK) << Record->isUnion();
5560           Invalid = true;
5561         }
5562       }
5563     }
5564 
5565     // C++11 [class.union]p8 (DR1460):
5566     //   At most one variant member of a union may have a
5567     //   brace-or-equal-initializer.
5568     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5569         Owner->isRecord())
5570       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5571                                 cast<CXXRecordDecl>(Record));
5572   }
5573 
5574   if (!Record->isUnion() && !Owner->isRecord()) {
5575     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5576       << getLangOpts().CPlusPlus;
5577     Invalid = true;
5578   }
5579 
5580   // C++ [dcl.dcl]p3:
5581   //   [If there are no declarators], and except for the declaration of an
5582   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5583   //   names into the program
5584   // C++ [class.mem]p2:
5585   //   each such member-declaration shall either declare at least one member
5586   //   name of the class or declare at least one unnamed bit-field
5587   //
5588   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5589   if (getLangOpts().CPlusPlus && Record->field_empty())
5590     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5591 
5592   // Mock up a declarator.
5593   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5594   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5595   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5596 
5597   // Create a declaration for this anonymous struct/union.
5598   NamedDecl *Anon = nullptr;
5599   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5600     Anon = FieldDecl::Create(
5601         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5602         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5603         /*BitWidth=*/nullptr, /*Mutable=*/false,
5604         /*InitStyle=*/ICIS_NoInit);
5605     Anon->setAccess(AS);
5606     ProcessDeclAttributes(S, Anon, Dc);
5607 
5608     if (getLangOpts().CPlusPlus)
5609       FieldCollector->Add(cast<FieldDecl>(Anon));
5610   } else {
5611     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5612     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5613     if (SCSpec == DeclSpec::SCS_mutable) {
5614       // mutable can only appear on non-static class members, so it's always
5615       // an error here
5616       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5617       Invalid = true;
5618       SC = SC_None;
5619     }
5620 
5621     assert(DS.getAttributes().empty() && "No attribute expected");
5622     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5623                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5624                            Context.getTypeDeclType(Record), TInfo, SC);
5625 
5626     // Default-initialize the implicit variable. This initialization will be
5627     // trivial in almost all cases, except if a union member has an in-class
5628     // initializer:
5629     //   union { int n = 0; };
5630     ActOnUninitializedDecl(Anon);
5631   }
5632   Anon->setImplicit();
5633 
5634   // Mark this as an anonymous struct/union type.
5635   Record->setAnonymousStructOrUnion(true);
5636 
5637   // Add the anonymous struct/union object to the current
5638   // context. We'll be referencing this object when we refer to one of
5639   // its members.
5640   Owner->addDecl(Anon);
5641 
5642   // Inject the members of the anonymous struct/union into the owning
5643   // context and into the identifier resolver chain for name lookup
5644   // purposes.
5645   SmallVector<NamedDecl*, 2> Chain;
5646   Chain.push_back(Anon);
5647 
5648   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5649     Invalid = true;
5650 
5651   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5652     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5653       MangleNumberingContext *MCtx;
5654       Decl *ManglingContextDecl;
5655       std::tie(MCtx, ManglingContextDecl) =
5656           getCurrentMangleNumberContext(NewVD->getDeclContext());
5657       if (MCtx) {
5658         Context.setManglingNumber(
5659             NewVD, MCtx->getManglingNumber(
5660                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5661         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5662       }
5663     }
5664   }
5665 
5666   if (Invalid)
5667     Anon->setInvalidDecl();
5668 
5669   return Anon;
5670 }
5671 
5672 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5673 /// Microsoft C anonymous structure.
5674 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5675 /// Example:
5676 ///
5677 /// struct A { int a; };
5678 /// struct B { struct A; int b; };
5679 ///
5680 /// void foo() {
5681 ///   B var;
5682 ///   var.a = 3;
5683 /// }
5684 ///
5685 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5686                                            RecordDecl *Record) {
5687   assert(Record && "expected a record!");
5688 
5689   // Mock up a declarator.
5690   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5691   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5692   assert(TInfo && "couldn't build declarator info for anonymous struct");
5693 
5694   auto *ParentDecl = cast<RecordDecl>(CurContext);
5695   QualType RecTy = Context.getTypeDeclType(Record);
5696 
5697   // Create a declaration for this anonymous struct.
5698   NamedDecl *Anon =
5699       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5700                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5701                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5702                         /*InitStyle=*/ICIS_NoInit);
5703   Anon->setImplicit();
5704 
5705   // Add the anonymous struct object to the current context.
5706   CurContext->addDecl(Anon);
5707 
5708   // Inject the members of the anonymous struct into the current
5709   // context and into the identifier resolver chain for name lookup
5710   // purposes.
5711   SmallVector<NamedDecl*, 2> Chain;
5712   Chain.push_back(Anon);
5713 
5714   RecordDecl *RecordDef = Record->getDefinition();
5715   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5716                                diag::err_field_incomplete_or_sizeless) ||
5717       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5718                                           AS_none, Chain)) {
5719     Anon->setInvalidDecl();
5720     ParentDecl->setInvalidDecl();
5721   }
5722 
5723   return Anon;
5724 }
5725 
5726 /// GetNameForDeclarator - Determine the full declaration name for the
5727 /// given Declarator.
5728 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5729   return GetNameFromUnqualifiedId(D.getName());
5730 }
5731 
5732 /// Retrieves the declaration name from a parsed unqualified-id.
5733 DeclarationNameInfo
5734 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5735   DeclarationNameInfo NameInfo;
5736   NameInfo.setLoc(Name.StartLocation);
5737 
5738   switch (Name.getKind()) {
5739 
5740   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5741   case UnqualifiedIdKind::IK_Identifier:
5742     NameInfo.setName(Name.Identifier);
5743     return NameInfo;
5744 
5745   case UnqualifiedIdKind::IK_DeductionGuideName: {
5746     // C++ [temp.deduct.guide]p3:
5747     //   The simple-template-id shall name a class template specialization.
5748     //   The template-name shall be the same identifier as the template-name
5749     //   of the simple-template-id.
5750     // These together intend to imply that the template-name shall name a
5751     // class template.
5752     // FIXME: template<typename T> struct X {};
5753     //        template<typename T> using Y = X<T>;
5754     //        Y(int) -> Y<int>;
5755     //   satisfies these rules but does not name a class template.
5756     TemplateName TN = Name.TemplateName.get().get();
5757     auto *Template = TN.getAsTemplateDecl();
5758     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5759       Diag(Name.StartLocation,
5760            diag::err_deduction_guide_name_not_class_template)
5761         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5762       if (Template)
5763         Diag(Template->getLocation(), diag::note_template_decl_here);
5764       return DeclarationNameInfo();
5765     }
5766 
5767     NameInfo.setName(
5768         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5769     return NameInfo;
5770   }
5771 
5772   case UnqualifiedIdKind::IK_OperatorFunctionId:
5773     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5774                                            Name.OperatorFunctionId.Operator));
5775     NameInfo.setCXXOperatorNameRange(SourceRange(
5776         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5777     return NameInfo;
5778 
5779   case UnqualifiedIdKind::IK_LiteralOperatorId:
5780     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5781                                                            Name.Identifier));
5782     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5783     return NameInfo;
5784 
5785   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5786     TypeSourceInfo *TInfo;
5787     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5788     if (Ty.isNull())
5789       return DeclarationNameInfo();
5790     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5791                                                Context.getCanonicalType(Ty)));
5792     NameInfo.setNamedTypeInfo(TInfo);
5793     return NameInfo;
5794   }
5795 
5796   case UnqualifiedIdKind::IK_ConstructorName: {
5797     TypeSourceInfo *TInfo;
5798     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5799     if (Ty.isNull())
5800       return DeclarationNameInfo();
5801     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5802                                               Context.getCanonicalType(Ty)));
5803     NameInfo.setNamedTypeInfo(TInfo);
5804     return NameInfo;
5805   }
5806 
5807   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5808     // In well-formed code, we can only have a constructor
5809     // template-id that refers to the current context, so go there
5810     // to find the actual type being constructed.
5811     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5812     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5813       return DeclarationNameInfo();
5814 
5815     // Determine the type of the class being constructed.
5816     QualType CurClassType = Context.getTypeDeclType(CurClass);
5817 
5818     // FIXME: Check two things: that the template-id names the same type as
5819     // CurClassType, and that the template-id does not occur when the name
5820     // was qualified.
5821 
5822     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5823                                     Context.getCanonicalType(CurClassType)));
5824     // FIXME: should we retrieve TypeSourceInfo?
5825     NameInfo.setNamedTypeInfo(nullptr);
5826     return NameInfo;
5827   }
5828 
5829   case UnqualifiedIdKind::IK_DestructorName: {
5830     TypeSourceInfo *TInfo;
5831     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5832     if (Ty.isNull())
5833       return DeclarationNameInfo();
5834     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5835                                               Context.getCanonicalType(Ty)));
5836     NameInfo.setNamedTypeInfo(TInfo);
5837     return NameInfo;
5838   }
5839 
5840   case UnqualifiedIdKind::IK_TemplateId: {
5841     TemplateName TName = Name.TemplateId->Template.get();
5842     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5843     return Context.getNameForTemplate(TName, TNameLoc);
5844   }
5845 
5846   } // switch (Name.getKind())
5847 
5848   llvm_unreachable("Unknown name kind");
5849 }
5850 
5851 static QualType getCoreType(QualType Ty) {
5852   do {
5853     if (Ty->isPointerType() || Ty->isReferenceType())
5854       Ty = Ty->getPointeeType();
5855     else if (Ty->isArrayType())
5856       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5857     else
5858       return Ty.withoutLocalFastQualifiers();
5859   } while (true);
5860 }
5861 
5862 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5863 /// and Definition have "nearly" matching parameters. This heuristic is
5864 /// used to improve diagnostics in the case where an out-of-line function
5865 /// definition doesn't match any declaration within the class or namespace.
5866 /// Also sets Params to the list of indices to the parameters that differ
5867 /// between the declaration and the definition. If hasSimilarParameters
5868 /// returns true and Params is empty, then all of the parameters match.
5869 static bool hasSimilarParameters(ASTContext &Context,
5870                                      FunctionDecl *Declaration,
5871                                      FunctionDecl *Definition,
5872                                      SmallVectorImpl<unsigned> &Params) {
5873   Params.clear();
5874   if (Declaration->param_size() != Definition->param_size())
5875     return false;
5876   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5877     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5878     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5879 
5880     // The parameter types are identical
5881     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5882       continue;
5883 
5884     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5885     QualType DefParamBaseTy = getCoreType(DefParamTy);
5886     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5887     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5888 
5889     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5890         (DeclTyName && DeclTyName == DefTyName))
5891       Params.push_back(Idx);
5892     else  // The two parameters aren't even close
5893       return false;
5894   }
5895 
5896   return true;
5897 }
5898 
5899 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5900 /// declarator needs to be rebuilt in the current instantiation.
5901 /// Any bits of declarator which appear before the name are valid for
5902 /// consideration here.  That's specifically the type in the decl spec
5903 /// and the base type in any member-pointer chunks.
5904 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5905                                                     DeclarationName Name) {
5906   // The types we specifically need to rebuild are:
5907   //   - typenames, typeofs, and decltypes
5908   //   - types which will become injected class names
5909   // Of course, we also need to rebuild any type referencing such a
5910   // type.  It's safest to just say "dependent", but we call out a
5911   // few cases here.
5912 
5913   DeclSpec &DS = D.getMutableDeclSpec();
5914   switch (DS.getTypeSpecType()) {
5915   case DeclSpec::TST_typename:
5916   case DeclSpec::TST_typeofType:
5917   case DeclSpec::TST_underlyingType:
5918   case DeclSpec::TST_atomic: {
5919     // Grab the type from the parser.
5920     TypeSourceInfo *TSI = nullptr;
5921     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5922     if (T.isNull() || !T->isInstantiationDependentType()) break;
5923 
5924     // Make sure there's a type source info.  This isn't really much
5925     // of a waste; most dependent types should have type source info
5926     // attached already.
5927     if (!TSI)
5928       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5929 
5930     // Rebuild the type in the current instantiation.
5931     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5932     if (!TSI) return true;
5933 
5934     // Store the new type back in the decl spec.
5935     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5936     DS.UpdateTypeRep(LocType);
5937     break;
5938   }
5939 
5940   case DeclSpec::TST_decltype:
5941   case DeclSpec::TST_typeofExpr: {
5942     Expr *E = DS.getRepAsExpr();
5943     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5944     if (Result.isInvalid()) return true;
5945     DS.UpdateExprRep(Result.get());
5946     break;
5947   }
5948 
5949   default:
5950     // Nothing to do for these decl specs.
5951     break;
5952   }
5953 
5954   // It doesn't matter what order we do this in.
5955   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5956     DeclaratorChunk &Chunk = D.getTypeObject(I);
5957 
5958     // The only type information in the declarator which can come
5959     // before the declaration name is the base type of a member
5960     // pointer.
5961     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5962       continue;
5963 
5964     // Rebuild the scope specifier in-place.
5965     CXXScopeSpec &SS = Chunk.Mem.Scope();
5966     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5967       return true;
5968   }
5969 
5970   return false;
5971 }
5972 
5973 /// Returns true if the declaration is declared in a system header or from a
5974 /// system macro.
5975 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5976   return SM.isInSystemHeader(D->getLocation()) ||
5977          SM.isInSystemMacro(D->getLocation());
5978 }
5979 
5980 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5981   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5982   // of system decl.
5983   if (D->getPreviousDecl() || D->isImplicit())
5984     return;
5985   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5986   if (Status != ReservedIdentifierStatus::NotReserved &&
5987       !isFromSystemHeader(Context.getSourceManager(), D)) {
5988     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5989         << D << static_cast<int>(Status);
5990   }
5991 }
5992 
5993 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5994   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5995 
5996   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5997   // declaration only if the `bind_to_declaration` extension is set.
5998   SmallVector<FunctionDecl *, 4> Bases;
5999   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6000     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6001               implementation_extension_bind_to_declaration))
6002     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6003         S, D, MultiTemplateParamsArg(), Bases);
6004 
6005   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6006 
6007   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6008       Dcl && Dcl->getDeclContext()->isFileContext())
6009     Dcl->setTopLevelDeclInObjCContainer();
6010 
6011   if (!Bases.empty())
6012     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6013 
6014   return Dcl;
6015 }
6016 
6017 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6018 ///   If T is the name of a class, then each of the following shall have a
6019 ///   name different from T:
6020 ///     - every static data member of class T;
6021 ///     - every member function of class T
6022 ///     - every member of class T that is itself a type;
6023 /// \returns true if the declaration name violates these rules.
6024 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6025                                    DeclarationNameInfo NameInfo) {
6026   DeclarationName Name = NameInfo.getName();
6027 
6028   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6029   while (Record && Record->isAnonymousStructOrUnion())
6030     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6031   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6032     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6033     return true;
6034   }
6035 
6036   return false;
6037 }
6038 
6039 /// Diagnose a declaration whose declarator-id has the given
6040 /// nested-name-specifier.
6041 ///
6042 /// \param SS The nested-name-specifier of the declarator-id.
6043 ///
6044 /// \param DC The declaration context to which the nested-name-specifier
6045 /// resolves.
6046 ///
6047 /// \param Name The name of the entity being declared.
6048 ///
6049 /// \param Loc The location of the name of the entity being declared.
6050 ///
6051 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6052 /// we're declaring an explicit / partial specialization / instantiation.
6053 ///
6054 /// \returns true if we cannot safely recover from this error, false otherwise.
6055 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6056                                         DeclarationName Name,
6057                                         SourceLocation Loc, bool IsTemplateId) {
6058   DeclContext *Cur = CurContext;
6059   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6060     Cur = Cur->getParent();
6061 
6062   // If the user provided a superfluous scope specifier that refers back to the
6063   // class in which the entity is already declared, diagnose and ignore it.
6064   //
6065   // class X {
6066   //   void X::f();
6067   // };
6068   //
6069   // Note, it was once ill-formed to give redundant qualification in all
6070   // contexts, but that rule was removed by DR482.
6071   if (Cur->Equals(DC)) {
6072     if (Cur->isRecord()) {
6073       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6074                                       : diag::err_member_extra_qualification)
6075         << Name << FixItHint::CreateRemoval(SS.getRange());
6076       SS.clear();
6077     } else {
6078       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6079     }
6080     return false;
6081   }
6082 
6083   // Check whether the qualifying scope encloses the scope of the original
6084   // declaration. For a template-id, we perform the checks in
6085   // CheckTemplateSpecializationScope.
6086   if (!Cur->Encloses(DC) && !IsTemplateId) {
6087     if (Cur->isRecord())
6088       Diag(Loc, diag::err_member_qualification)
6089         << Name << SS.getRange();
6090     else if (isa<TranslationUnitDecl>(DC))
6091       Diag(Loc, diag::err_invalid_declarator_global_scope)
6092         << Name << SS.getRange();
6093     else if (isa<FunctionDecl>(Cur))
6094       Diag(Loc, diag::err_invalid_declarator_in_function)
6095         << Name << SS.getRange();
6096     else if (isa<BlockDecl>(Cur))
6097       Diag(Loc, diag::err_invalid_declarator_in_block)
6098         << Name << SS.getRange();
6099     else if (isa<ExportDecl>(Cur)) {
6100       if (!isa<NamespaceDecl>(DC))
6101         Diag(Loc, diag::err_export_non_namespace_scope_name)
6102             << Name << SS.getRange();
6103       else
6104         // The cases that DC is not NamespaceDecl should be handled in
6105         // CheckRedeclarationExported.
6106         return false;
6107     } else
6108       Diag(Loc, diag::err_invalid_declarator_scope)
6109       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6110 
6111     return true;
6112   }
6113 
6114   if (Cur->isRecord()) {
6115     // Cannot qualify members within a class.
6116     Diag(Loc, diag::err_member_qualification)
6117       << Name << SS.getRange();
6118     SS.clear();
6119 
6120     // C++ constructors and destructors with incorrect scopes can break
6121     // our AST invariants by having the wrong underlying types. If
6122     // that's the case, then drop this declaration entirely.
6123     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6124          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6125         !Context.hasSameType(Name.getCXXNameType(),
6126                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6127       return true;
6128 
6129     return false;
6130   }
6131 
6132   // C++11 [dcl.meaning]p1:
6133   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6134   //   not begin with a decltype-specifer"
6135   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6136   while (SpecLoc.getPrefix())
6137     SpecLoc = SpecLoc.getPrefix();
6138   if (isa_and_nonnull<DecltypeType>(
6139           SpecLoc.getNestedNameSpecifier()->getAsType()))
6140     Diag(Loc, diag::err_decltype_in_declarator)
6141       << SpecLoc.getTypeLoc().getSourceRange();
6142 
6143   return false;
6144 }
6145 
6146 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6147                                   MultiTemplateParamsArg TemplateParamLists) {
6148   // TODO: consider using NameInfo for diagnostic.
6149   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6150   DeclarationName Name = NameInfo.getName();
6151 
6152   // All of these full declarators require an identifier.  If it doesn't have
6153   // one, the ParsedFreeStandingDeclSpec action should be used.
6154   if (D.isDecompositionDeclarator()) {
6155     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6156   } else if (!Name) {
6157     if (!D.isInvalidType())  // Reject this if we think it is valid.
6158       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6159           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6160     return nullptr;
6161   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6162     return nullptr;
6163 
6164   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6165   // we find one that is.
6166   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6167          (S->getFlags() & Scope::TemplateParamScope) != 0)
6168     S = S->getParent();
6169 
6170   DeclContext *DC = CurContext;
6171   if (D.getCXXScopeSpec().isInvalid())
6172     D.setInvalidType();
6173   else if (D.getCXXScopeSpec().isSet()) {
6174     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6175                                         UPPC_DeclarationQualifier))
6176       return nullptr;
6177 
6178     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6179     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6180     if (!DC || isa<EnumDecl>(DC)) {
6181       // If we could not compute the declaration context, it's because the
6182       // declaration context is dependent but does not refer to a class,
6183       // class template, or class template partial specialization. Complain
6184       // and return early, to avoid the coming semantic disaster.
6185       Diag(D.getIdentifierLoc(),
6186            diag::err_template_qualified_declarator_no_match)
6187         << D.getCXXScopeSpec().getScopeRep()
6188         << D.getCXXScopeSpec().getRange();
6189       return nullptr;
6190     }
6191     bool IsDependentContext = DC->isDependentContext();
6192 
6193     if (!IsDependentContext &&
6194         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6195       return nullptr;
6196 
6197     // If a class is incomplete, do not parse entities inside it.
6198     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6199       Diag(D.getIdentifierLoc(),
6200            diag::err_member_def_undefined_record)
6201         << Name << DC << D.getCXXScopeSpec().getRange();
6202       return nullptr;
6203     }
6204     if (!D.getDeclSpec().isFriendSpecified()) {
6205       if (diagnoseQualifiedDeclaration(
6206               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6207               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6208         if (DC->isRecord())
6209           return nullptr;
6210 
6211         D.setInvalidType();
6212       }
6213     }
6214 
6215     // Check whether we need to rebuild the type of the given
6216     // declaration in the current instantiation.
6217     if (EnteringContext && IsDependentContext &&
6218         TemplateParamLists.size() != 0) {
6219       ContextRAII SavedContext(*this, DC);
6220       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6221         D.setInvalidType();
6222     }
6223   }
6224 
6225   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6226   QualType R = TInfo->getType();
6227 
6228   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6229                                       UPPC_DeclarationType))
6230     D.setInvalidType();
6231 
6232   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6233                         forRedeclarationInCurContext());
6234 
6235   // See if this is a redefinition of a variable in the same scope.
6236   if (!D.getCXXScopeSpec().isSet()) {
6237     bool IsLinkageLookup = false;
6238     bool CreateBuiltins = false;
6239 
6240     // If the declaration we're planning to build will be a function
6241     // or object with linkage, then look for another declaration with
6242     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6243     //
6244     // If the declaration we're planning to build will be declared with
6245     // external linkage in the translation unit, create any builtin with
6246     // the same name.
6247     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6248       /* Do nothing*/;
6249     else if (CurContext->isFunctionOrMethod() &&
6250              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6251               R->isFunctionType())) {
6252       IsLinkageLookup = true;
6253       CreateBuiltins =
6254           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6255     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6256                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6257       CreateBuiltins = true;
6258 
6259     if (IsLinkageLookup) {
6260       Previous.clear(LookupRedeclarationWithLinkage);
6261       Previous.setRedeclarationKind(ForExternalRedeclaration);
6262     }
6263 
6264     LookupName(Previous, S, CreateBuiltins);
6265   } else { // Something like "int foo::x;"
6266     LookupQualifiedName(Previous, DC);
6267 
6268     // C++ [dcl.meaning]p1:
6269     //   When the declarator-id is qualified, the declaration shall refer to a
6270     //  previously declared member of the class or namespace to which the
6271     //  qualifier refers (or, in the case of a namespace, of an element of the
6272     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6273     //  thereof; [...]
6274     //
6275     // Note that we already checked the context above, and that we do not have
6276     // enough information to make sure that Previous contains the declaration
6277     // we want to match. For example, given:
6278     //
6279     //   class X {
6280     //     void f();
6281     //     void f(float);
6282     //   };
6283     //
6284     //   void X::f(int) { } // ill-formed
6285     //
6286     // In this case, Previous will point to the overload set
6287     // containing the two f's declared in X, but neither of them
6288     // matches.
6289 
6290     // C++ [dcl.meaning]p1:
6291     //   [...] the member shall not merely have been introduced by a
6292     //   using-declaration in the scope of the class or namespace nominated by
6293     //   the nested-name-specifier of the declarator-id.
6294     RemoveUsingDecls(Previous);
6295   }
6296 
6297   if (Previous.isSingleResult() &&
6298       Previous.getFoundDecl()->isTemplateParameter()) {
6299     // Maybe we will complain about the shadowed template parameter.
6300     if (!D.isInvalidType())
6301       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6302                                       Previous.getFoundDecl());
6303 
6304     // Just pretend that we didn't see the previous declaration.
6305     Previous.clear();
6306   }
6307 
6308   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6309     // Forget that the previous declaration is the injected-class-name.
6310     Previous.clear();
6311 
6312   // In C++, the previous declaration we find might be a tag type
6313   // (class or enum). In this case, the new declaration will hide the
6314   // tag type. Note that this applies to functions, function templates, and
6315   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6316   if (Previous.isSingleTagDecl() &&
6317       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6318       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6319     Previous.clear();
6320 
6321   // Check that there are no default arguments other than in the parameters
6322   // of a function declaration (C++ only).
6323   if (getLangOpts().CPlusPlus)
6324     CheckExtraCXXDefaultArguments(D);
6325 
6326   NamedDecl *New;
6327 
6328   bool AddToScope = true;
6329   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6330     if (TemplateParamLists.size()) {
6331       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6332       return nullptr;
6333     }
6334 
6335     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6336   } else if (R->isFunctionType()) {
6337     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6338                                   TemplateParamLists,
6339                                   AddToScope);
6340   } else {
6341     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6342                                   AddToScope);
6343   }
6344 
6345   if (!New)
6346     return nullptr;
6347 
6348   // If this has an identifier and is not a function template specialization,
6349   // add it to the scope stack.
6350   if (New->getDeclName() && AddToScope)
6351     PushOnScopeChains(New, S);
6352 
6353   if (isInOpenMPDeclareTargetContext())
6354     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6355 
6356   return New;
6357 }
6358 
6359 /// Helper method to turn variable array types into constant array
6360 /// types in certain situations which would otherwise be errors (for
6361 /// GCC compatibility).
6362 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6363                                                     ASTContext &Context,
6364                                                     bool &SizeIsNegative,
6365                                                     llvm::APSInt &Oversized) {
6366   // This method tries to turn a variable array into a constant
6367   // array even when the size isn't an ICE.  This is necessary
6368   // for compatibility with code that depends on gcc's buggy
6369   // constant expression folding, like struct {char x[(int)(char*)2];}
6370   SizeIsNegative = false;
6371   Oversized = 0;
6372 
6373   if (T->isDependentType())
6374     return QualType();
6375 
6376   QualifierCollector Qs;
6377   const Type *Ty = Qs.strip(T);
6378 
6379   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6380     QualType Pointee = PTy->getPointeeType();
6381     QualType FixedType =
6382         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6383                                             Oversized);
6384     if (FixedType.isNull()) return FixedType;
6385     FixedType = Context.getPointerType(FixedType);
6386     return Qs.apply(Context, FixedType);
6387   }
6388   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6389     QualType Inner = PTy->getInnerType();
6390     QualType FixedType =
6391         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6392                                             Oversized);
6393     if (FixedType.isNull()) return FixedType;
6394     FixedType = Context.getParenType(FixedType);
6395     return Qs.apply(Context, FixedType);
6396   }
6397 
6398   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6399   if (!VLATy)
6400     return QualType();
6401 
6402   QualType ElemTy = VLATy->getElementType();
6403   if (ElemTy->isVariablyModifiedType()) {
6404     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6405                                                  SizeIsNegative, Oversized);
6406     if (ElemTy.isNull())
6407       return QualType();
6408   }
6409 
6410   Expr::EvalResult Result;
6411   if (!VLATy->getSizeExpr() ||
6412       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6413     return QualType();
6414 
6415   llvm::APSInt Res = Result.Val.getInt();
6416 
6417   // Check whether the array size is negative.
6418   if (Res.isSigned() && Res.isNegative()) {
6419     SizeIsNegative = true;
6420     return QualType();
6421   }
6422 
6423   // Check whether the array is too large to be addressed.
6424   unsigned ActiveSizeBits =
6425       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6426        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6427           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6428           : Res.getActiveBits();
6429   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6430     Oversized = Res;
6431     return QualType();
6432   }
6433 
6434   QualType FoldedArrayType = Context.getConstantArrayType(
6435       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6436   return Qs.apply(Context, FoldedArrayType);
6437 }
6438 
6439 static void
6440 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6441   SrcTL = SrcTL.getUnqualifiedLoc();
6442   DstTL = DstTL.getUnqualifiedLoc();
6443   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6444     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6445     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6446                                       DstPTL.getPointeeLoc());
6447     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6448     return;
6449   }
6450   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6451     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6452     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6453                                       DstPTL.getInnerLoc());
6454     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6455     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6456     return;
6457   }
6458   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6459   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6460   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6461   TypeLoc DstElemTL = DstATL.getElementLoc();
6462   if (VariableArrayTypeLoc SrcElemATL =
6463           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6464     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6465     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6466   } else {
6467     DstElemTL.initializeFullCopy(SrcElemTL);
6468   }
6469   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6470   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6471   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6472 }
6473 
6474 /// Helper method to turn variable array types into constant array
6475 /// types in certain situations which would otherwise be errors (for
6476 /// GCC compatibility).
6477 static TypeSourceInfo*
6478 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6479                                               ASTContext &Context,
6480                                               bool &SizeIsNegative,
6481                                               llvm::APSInt &Oversized) {
6482   QualType FixedTy
6483     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6484                                           SizeIsNegative, Oversized);
6485   if (FixedTy.isNull())
6486     return nullptr;
6487   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6488   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6489                                     FixedTInfo->getTypeLoc());
6490   return FixedTInfo;
6491 }
6492 
6493 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6494 /// true if we were successful.
6495 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6496                                            QualType &T, SourceLocation Loc,
6497                                            unsigned FailedFoldDiagID) {
6498   bool SizeIsNegative;
6499   llvm::APSInt Oversized;
6500   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6501       TInfo, Context, SizeIsNegative, Oversized);
6502   if (FixedTInfo) {
6503     Diag(Loc, diag::ext_vla_folded_to_constant);
6504     TInfo = FixedTInfo;
6505     T = FixedTInfo->getType();
6506     return true;
6507   }
6508 
6509   if (SizeIsNegative)
6510     Diag(Loc, diag::err_typecheck_negative_array_size);
6511   else if (Oversized.getBoolValue())
6512     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6513   else if (FailedFoldDiagID)
6514     Diag(Loc, FailedFoldDiagID);
6515   return false;
6516 }
6517 
6518 /// Register the given locally-scoped extern "C" declaration so
6519 /// that it can be found later for redeclarations. We include any extern "C"
6520 /// declaration that is not visible in the translation unit here, not just
6521 /// function-scope declarations.
6522 void
6523 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6524   if (!getLangOpts().CPlusPlus &&
6525       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6526     // Don't need to track declarations in the TU in C.
6527     return;
6528 
6529   // Note that we have a locally-scoped external with this name.
6530   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6531 }
6532 
6533 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6534   // FIXME: We can have multiple results via __attribute__((overloadable)).
6535   auto Result = Context.getExternCContextDecl()->lookup(Name);
6536   return Result.empty() ? nullptr : *Result.begin();
6537 }
6538 
6539 /// Diagnose function specifiers on a declaration of an identifier that
6540 /// does not identify a function.
6541 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6542   // FIXME: We should probably indicate the identifier in question to avoid
6543   // confusion for constructs like "virtual int a(), b;"
6544   if (DS.isVirtualSpecified())
6545     Diag(DS.getVirtualSpecLoc(),
6546          diag::err_virtual_non_function);
6547 
6548   if (DS.hasExplicitSpecifier())
6549     Diag(DS.getExplicitSpecLoc(),
6550          diag::err_explicit_non_function);
6551 
6552   if (DS.isNoreturnSpecified())
6553     Diag(DS.getNoreturnSpecLoc(),
6554          diag::err_noreturn_non_function);
6555 }
6556 
6557 NamedDecl*
6558 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6559                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6560   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6561   if (D.getCXXScopeSpec().isSet()) {
6562     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6563       << D.getCXXScopeSpec().getRange();
6564     D.setInvalidType();
6565     // Pretend we didn't see the scope specifier.
6566     DC = CurContext;
6567     Previous.clear();
6568   }
6569 
6570   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6571 
6572   if (D.getDeclSpec().isInlineSpecified())
6573     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6574         << getLangOpts().CPlusPlus17;
6575   if (D.getDeclSpec().hasConstexprSpecifier())
6576     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6577         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6578 
6579   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6580     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6581       Diag(D.getName().StartLocation,
6582            diag::err_deduction_guide_invalid_specifier)
6583           << "typedef";
6584     else
6585       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6586           << D.getName().getSourceRange();
6587     return nullptr;
6588   }
6589 
6590   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6591   if (!NewTD) return nullptr;
6592 
6593   // Handle attributes prior to checking for duplicates in MergeVarDecl
6594   ProcessDeclAttributes(S, NewTD, D);
6595 
6596   CheckTypedefForVariablyModifiedType(S, NewTD);
6597 
6598   bool Redeclaration = D.isRedeclaration();
6599   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6600   D.setRedeclaration(Redeclaration);
6601   return ND;
6602 }
6603 
6604 void
6605 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6606   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6607   // then it shall have block scope.
6608   // Note that variably modified types must be fixed before merging the decl so
6609   // that redeclarations will match.
6610   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6611   QualType T = TInfo->getType();
6612   if (T->isVariablyModifiedType()) {
6613     setFunctionHasBranchProtectedScope();
6614 
6615     if (S->getFnParent() == nullptr) {
6616       bool SizeIsNegative;
6617       llvm::APSInt Oversized;
6618       TypeSourceInfo *FixedTInfo =
6619         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6620                                                       SizeIsNegative,
6621                                                       Oversized);
6622       if (FixedTInfo) {
6623         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6624         NewTD->setTypeSourceInfo(FixedTInfo);
6625       } else {
6626         if (SizeIsNegative)
6627           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6628         else if (T->isVariableArrayType())
6629           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6630         else if (Oversized.getBoolValue())
6631           Diag(NewTD->getLocation(), diag::err_array_too_large)
6632             << toString(Oversized, 10);
6633         else
6634           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6635         NewTD->setInvalidDecl();
6636       }
6637     }
6638   }
6639 }
6640 
6641 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6642 /// declares a typedef-name, either using the 'typedef' type specifier or via
6643 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6644 NamedDecl*
6645 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6646                            LookupResult &Previous, bool &Redeclaration) {
6647 
6648   // Find the shadowed declaration before filtering for scope.
6649   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6650 
6651   // Merge the decl with the existing one if appropriate. If the decl is
6652   // in an outer scope, it isn't the same thing.
6653   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6654                        /*AllowInlineNamespace*/false);
6655   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6656   if (!Previous.empty()) {
6657     Redeclaration = true;
6658     MergeTypedefNameDecl(S, NewTD, Previous);
6659   } else {
6660     inferGslPointerAttribute(NewTD);
6661   }
6662 
6663   if (ShadowedDecl && !Redeclaration)
6664     CheckShadow(NewTD, ShadowedDecl, Previous);
6665 
6666   // If this is the C FILE type, notify the AST context.
6667   if (IdentifierInfo *II = NewTD->getIdentifier())
6668     if (!NewTD->isInvalidDecl() &&
6669         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6670       if (II->isStr("FILE"))
6671         Context.setFILEDecl(NewTD);
6672       else if (II->isStr("jmp_buf"))
6673         Context.setjmp_bufDecl(NewTD);
6674       else if (II->isStr("sigjmp_buf"))
6675         Context.setsigjmp_bufDecl(NewTD);
6676       else if (II->isStr("ucontext_t"))
6677         Context.setucontext_tDecl(NewTD);
6678     }
6679 
6680   return NewTD;
6681 }
6682 
6683 /// Determines whether the given declaration is an out-of-scope
6684 /// previous declaration.
6685 ///
6686 /// This routine should be invoked when name lookup has found a
6687 /// previous declaration (PrevDecl) that is not in the scope where a
6688 /// new declaration by the same name is being introduced. If the new
6689 /// declaration occurs in a local scope, previous declarations with
6690 /// linkage may still be considered previous declarations (C99
6691 /// 6.2.2p4-5, C++ [basic.link]p6).
6692 ///
6693 /// \param PrevDecl the previous declaration found by name
6694 /// lookup
6695 ///
6696 /// \param DC the context in which the new declaration is being
6697 /// declared.
6698 ///
6699 /// \returns true if PrevDecl is an out-of-scope previous declaration
6700 /// for a new delcaration with the same name.
6701 static bool
6702 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6703                                 ASTContext &Context) {
6704   if (!PrevDecl)
6705     return false;
6706 
6707   if (!PrevDecl->hasLinkage())
6708     return false;
6709 
6710   if (Context.getLangOpts().CPlusPlus) {
6711     // C++ [basic.link]p6:
6712     //   If there is a visible declaration of an entity with linkage
6713     //   having the same name and type, ignoring entities declared
6714     //   outside the innermost enclosing namespace scope, the block
6715     //   scope declaration declares that same entity and receives the
6716     //   linkage of the previous declaration.
6717     DeclContext *OuterContext = DC->getRedeclContext();
6718     if (!OuterContext->isFunctionOrMethod())
6719       // This rule only applies to block-scope declarations.
6720       return false;
6721 
6722     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6723     if (PrevOuterContext->isRecord())
6724       // We found a member function: ignore it.
6725       return false;
6726 
6727     // Find the innermost enclosing namespace for the new and
6728     // previous declarations.
6729     OuterContext = OuterContext->getEnclosingNamespaceContext();
6730     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6731 
6732     // The previous declaration is in a different namespace, so it
6733     // isn't the same function.
6734     if (!OuterContext->Equals(PrevOuterContext))
6735       return false;
6736   }
6737 
6738   return true;
6739 }
6740 
6741 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6742   CXXScopeSpec &SS = D.getCXXScopeSpec();
6743   if (!SS.isSet()) return;
6744   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6745 }
6746 
6747 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6748   QualType type = decl->getType();
6749   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6750   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6751     // Various kinds of declaration aren't allowed to be __autoreleasing.
6752     unsigned kind = -1U;
6753     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6754       if (var->hasAttr<BlocksAttr>())
6755         kind = 0; // __block
6756       else if (!var->hasLocalStorage())
6757         kind = 1; // global
6758     } else if (isa<ObjCIvarDecl>(decl)) {
6759       kind = 3; // ivar
6760     } else if (isa<FieldDecl>(decl)) {
6761       kind = 2; // field
6762     }
6763 
6764     if (kind != -1U) {
6765       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6766         << kind;
6767     }
6768   } else if (lifetime == Qualifiers::OCL_None) {
6769     // Try to infer lifetime.
6770     if (!type->isObjCLifetimeType())
6771       return false;
6772 
6773     lifetime = type->getObjCARCImplicitLifetime();
6774     type = Context.getLifetimeQualifiedType(type, lifetime);
6775     decl->setType(type);
6776   }
6777 
6778   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6779     // Thread-local variables cannot have lifetime.
6780     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6781         var->getTLSKind()) {
6782       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6783         << var->getType();
6784       return true;
6785     }
6786   }
6787 
6788   return false;
6789 }
6790 
6791 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6792   if (Decl->getType().hasAddressSpace())
6793     return;
6794   if (Decl->getType()->isDependentType())
6795     return;
6796   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6797     QualType Type = Var->getType();
6798     if (Type->isSamplerT() || Type->isVoidType())
6799       return;
6800     LangAS ImplAS = LangAS::opencl_private;
6801     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6802     // __opencl_c_program_scope_global_variables feature, the address space
6803     // for a variable at program scope or a static or extern variable inside
6804     // a function are inferred to be __global.
6805     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6806         Var->hasGlobalStorage())
6807       ImplAS = LangAS::opencl_global;
6808     // If the original type from a decayed type is an array type and that array
6809     // type has no address space yet, deduce it now.
6810     if (auto DT = dyn_cast<DecayedType>(Type)) {
6811       auto OrigTy = DT->getOriginalType();
6812       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6813         // Add the address space to the original array type and then propagate
6814         // that to the element type through `getAsArrayType`.
6815         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6816         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6817         // Re-generate the decayed type.
6818         Type = Context.getDecayedType(OrigTy);
6819       }
6820     }
6821     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6822     // Apply any qualifiers (including address space) from the array type to
6823     // the element type. This implements C99 6.7.3p8: "If the specification of
6824     // an array type includes any type qualifiers, the element type is so
6825     // qualified, not the array type."
6826     if (Type->isArrayType())
6827       Type = QualType(Context.getAsArrayType(Type), 0);
6828     Decl->setType(Type);
6829   }
6830 }
6831 
6832 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6833   // Ensure that an auto decl is deduced otherwise the checks below might cache
6834   // the wrong linkage.
6835   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6836 
6837   // 'weak' only applies to declarations with external linkage.
6838   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6839     if (!ND.isExternallyVisible()) {
6840       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6841       ND.dropAttr<WeakAttr>();
6842     }
6843   }
6844   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6845     if (ND.isExternallyVisible()) {
6846       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6847       ND.dropAttr<WeakRefAttr>();
6848       ND.dropAttr<AliasAttr>();
6849     }
6850   }
6851 
6852   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6853     if (VD->hasInit()) {
6854       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6855         assert(VD->isThisDeclarationADefinition() &&
6856                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6857         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6858         VD->dropAttr<AliasAttr>();
6859       }
6860     }
6861   }
6862 
6863   // 'selectany' only applies to externally visible variable declarations.
6864   // It does not apply to functions.
6865   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6866     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6867       S.Diag(Attr->getLocation(),
6868              diag::err_attribute_selectany_non_extern_data);
6869       ND.dropAttr<SelectAnyAttr>();
6870     }
6871   }
6872 
6873   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6874     auto *VD = dyn_cast<VarDecl>(&ND);
6875     bool IsAnonymousNS = false;
6876     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6877     if (VD) {
6878       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6879       while (NS && !IsAnonymousNS) {
6880         IsAnonymousNS = NS->isAnonymousNamespace();
6881         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6882       }
6883     }
6884     // dll attributes require external linkage. Static locals may have external
6885     // linkage but still cannot be explicitly imported or exported.
6886     // In Microsoft mode, a variable defined in anonymous namespace must have
6887     // external linkage in order to be exported.
6888     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6889     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6890         (!AnonNSInMicrosoftMode &&
6891          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6892       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6893         << &ND << Attr;
6894       ND.setInvalidDecl();
6895     }
6896   }
6897 
6898   // Check the attributes on the function type, if any.
6899   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6900     // Don't declare this variable in the second operand of the for-statement;
6901     // GCC miscompiles that by ending its lifetime before evaluating the
6902     // third operand. See gcc.gnu.org/PR86769.
6903     AttributedTypeLoc ATL;
6904     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6905          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6906          TL = ATL.getModifiedLoc()) {
6907       // The [[lifetimebound]] attribute can be applied to the implicit object
6908       // parameter of a non-static member function (other than a ctor or dtor)
6909       // by applying it to the function type.
6910       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6911         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6912         if (!MD || MD->isStatic()) {
6913           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6914               << !MD << A->getRange();
6915         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6916           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6917               << isa<CXXDestructorDecl>(MD) << A->getRange();
6918         }
6919       }
6920     }
6921   }
6922 }
6923 
6924 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6925                                            NamedDecl *NewDecl,
6926                                            bool IsSpecialization,
6927                                            bool IsDefinition) {
6928   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6929     return;
6930 
6931   bool IsTemplate = false;
6932   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6933     OldDecl = OldTD->getTemplatedDecl();
6934     IsTemplate = true;
6935     if (!IsSpecialization)
6936       IsDefinition = false;
6937   }
6938   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6939     NewDecl = NewTD->getTemplatedDecl();
6940     IsTemplate = true;
6941   }
6942 
6943   if (!OldDecl || !NewDecl)
6944     return;
6945 
6946   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6947   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6948   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6949   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6950 
6951   // dllimport and dllexport are inheritable attributes so we have to exclude
6952   // inherited attribute instances.
6953   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6954                     (NewExportAttr && !NewExportAttr->isInherited());
6955 
6956   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6957   // the only exception being explicit specializations.
6958   // Implicitly generated declarations are also excluded for now because there
6959   // is no other way to switch these to use dllimport or dllexport.
6960   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6961 
6962   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6963     // Allow with a warning for free functions and global variables.
6964     bool JustWarn = false;
6965     if (!OldDecl->isCXXClassMember()) {
6966       auto *VD = dyn_cast<VarDecl>(OldDecl);
6967       if (VD && !VD->getDescribedVarTemplate())
6968         JustWarn = true;
6969       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6970       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6971         JustWarn = true;
6972     }
6973 
6974     // We cannot change a declaration that's been used because IR has already
6975     // been emitted. Dllimported functions will still work though (modulo
6976     // address equality) as they can use the thunk.
6977     if (OldDecl->isUsed())
6978       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6979         JustWarn = false;
6980 
6981     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6982                                : diag::err_attribute_dll_redeclaration;
6983     S.Diag(NewDecl->getLocation(), DiagID)
6984         << NewDecl
6985         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6986     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6987     if (!JustWarn) {
6988       NewDecl->setInvalidDecl();
6989       return;
6990     }
6991   }
6992 
6993   // A redeclaration is not allowed to drop a dllimport attribute, the only
6994   // exceptions being inline function definitions (except for function
6995   // templates), local extern declarations, qualified friend declarations or
6996   // special MSVC extension: in the last case, the declaration is treated as if
6997   // it were marked dllexport.
6998   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6999   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7000   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7001     // Ignore static data because out-of-line definitions are diagnosed
7002     // separately.
7003     IsStaticDataMember = VD->isStaticDataMember();
7004     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7005                    VarDecl::DeclarationOnly;
7006   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7007     IsInline = FD->isInlined();
7008     IsQualifiedFriend = FD->getQualifier() &&
7009                         FD->getFriendObjectKind() == Decl::FOK_Declared;
7010   }
7011 
7012   if (OldImportAttr && !HasNewAttr &&
7013       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7014       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7015     if (IsMicrosoftABI && IsDefinition) {
7016       S.Diag(NewDecl->getLocation(),
7017              diag::warn_redeclaration_without_import_attribute)
7018           << NewDecl;
7019       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7020       NewDecl->dropAttr<DLLImportAttr>();
7021       NewDecl->addAttr(
7022           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
7023     } else {
7024       S.Diag(NewDecl->getLocation(),
7025              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7026           << NewDecl << OldImportAttr;
7027       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7028       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7029       OldDecl->dropAttr<DLLImportAttr>();
7030       NewDecl->dropAttr<DLLImportAttr>();
7031     }
7032   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7033     // In MinGW, seeing a function declared inline drops the dllimport
7034     // attribute.
7035     OldDecl->dropAttr<DLLImportAttr>();
7036     NewDecl->dropAttr<DLLImportAttr>();
7037     S.Diag(NewDecl->getLocation(),
7038            diag::warn_dllimport_dropped_from_inline_function)
7039         << NewDecl << OldImportAttr;
7040   }
7041 
7042   // A specialization of a class template member function is processed here
7043   // since it's a redeclaration. If the parent class is dllexport, the
7044   // specialization inherits that attribute. This doesn't happen automatically
7045   // since the parent class isn't instantiated until later.
7046   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7047     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7048         !NewImportAttr && !NewExportAttr) {
7049       if (const DLLExportAttr *ParentExportAttr =
7050               MD->getParent()->getAttr<DLLExportAttr>()) {
7051         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7052         NewAttr->setInherited(true);
7053         NewDecl->addAttr(NewAttr);
7054       }
7055     }
7056   }
7057 }
7058 
7059 /// Given that we are within the definition of the given function,
7060 /// will that definition behave like C99's 'inline', where the
7061 /// definition is discarded except for optimization purposes?
7062 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7063   // Try to avoid calling GetGVALinkageForFunction.
7064 
7065   // All cases of this require the 'inline' keyword.
7066   if (!FD->isInlined()) return false;
7067 
7068   // This is only possible in C++ with the gnu_inline attribute.
7069   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7070     return false;
7071 
7072   // Okay, go ahead and call the relatively-more-expensive function.
7073   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7074 }
7075 
7076 /// Determine whether a variable is extern "C" prior to attaching
7077 /// an initializer. We can't just call isExternC() here, because that
7078 /// will also compute and cache whether the declaration is externally
7079 /// visible, which might change when we attach the initializer.
7080 ///
7081 /// This can only be used if the declaration is known to not be a
7082 /// redeclaration of an internal linkage declaration.
7083 ///
7084 /// For instance:
7085 ///
7086 ///   auto x = []{};
7087 ///
7088 /// Attaching the initializer here makes this declaration not externally
7089 /// visible, because its type has internal linkage.
7090 ///
7091 /// FIXME: This is a hack.
7092 template<typename T>
7093 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7094   if (S.getLangOpts().CPlusPlus) {
7095     // In C++, the overloadable attribute negates the effects of extern "C".
7096     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7097       return false;
7098 
7099     // So do CUDA's host/device attributes.
7100     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7101                                  D->template hasAttr<CUDAHostAttr>()))
7102       return false;
7103   }
7104   return D->isExternC();
7105 }
7106 
7107 static bool shouldConsiderLinkage(const VarDecl *VD) {
7108   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7109   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7110       isa<OMPDeclareMapperDecl>(DC))
7111     return VD->hasExternalStorage();
7112   if (DC->isFileContext())
7113     return true;
7114   if (DC->isRecord())
7115     return false;
7116   if (isa<RequiresExprBodyDecl>(DC))
7117     return false;
7118   llvm_unreachable("Unexpected context");
7119 }
7120 
7121 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7122   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7123   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7124       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7125     return true;
7126   if (DC->isRecord())
7127     return false;
7128   llvm_unreachable("Unexpected context");
7129 }
7130 
7131 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7132                           ParsedAttr::Kind Kind) {
7133   // Check decl attributes on the DeclSpec.
7134   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7135     return true;
7136 
7137   // Walk the declarator structure, checking decl attributes that were in a type
7138   // position to the decl itself.
7139   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7140     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7141       return true;
7142   }
7143 
7144   // Finally, check attributes on the decl itself.
7145   return PD.getAttributes().hasAttribute(Kind) ||
7146          PD.getDeclarationAttributes().hasAttribute(Kind);
7147 }
7148 
7149 /// Adjust the \c DeclContext for a function or variable that might be a
7150 /// function-local external declaration.
7151 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7152   if (!DC->isFunctionOrMethod())
7153     return false;
7154 
7155   // If this is a local extern function or variable declared within a function
7156   // template, don't add it into the enclosing namespace scope until it is
7157   // instantiated; it might have a dependent type right now.
7158   if (DC->isDependentContext())
7159     return true;
7160 
7161   // C++11 [basic.link]p7:
7162   //   When a block scope declaration of an entity with linkage is not found to
7163   //   refer to some other declaration, then that entity is a member of the
7164   //   innermost enclosing namespace.
7165   //
7166   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7167   // semantically-enclosing namespace, not a lexically-enclosing one.
7168   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7169     DC = DC->getParent();
7170   return true;
7171 }
7172 
7173 /// Returns true if given declaration has external C language linkage.
7174 static bool isDeclExternC(const Decl *D) {
7175   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7176     return FD->isExternC();
7177   if (const auto *VD = dyn_cast<VarDecl>(D))
7178     return VD->isExternC();
7179 
7180   llvm_unreachable("Unknown type of decl!");
7181 }
7182 
7183 /// Returns true if there hasn't been any invalid type diagnosed.
7184 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7185   DeclContext *DC = NewVD->getDeclContext();
7186   QualType R = NewVD->getType();
7187 
7188   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7189   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7190   // argument.
7191   if (R->isImageType() || R->isPipeType()) {
7192     Se.Diag(NewVD->getLocation(),
7193             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7194         << R;
7195     NewVD->setInvalidDecl();
7196     return false;
7197   }
7198 
7199   // OpenCL v1.2 s6.9.r:
7200   // The event type cannot be used to declare a program scope variable.
7201   // OpenCL v2.0 s6.9.q:
7202   // The clk_event_t and reserve_id_t types cannot be declared in program
7203   // scope.
7204   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7205     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7206       Se.Diag(NewVD->getLocation(),
7207               diag::err_invalid_type_for_program_scope_var)
7208           << R;
7209       NewVD->setInvalidDecl();
7210       return false;
7211     }
7212   }
7213 
7214   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7215   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7216                                                Se.getLangOpts())) {
7217     QualType NR = R.getCanonicalType();
7218     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7219            NR->isReferenceType()) {
7220       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7221           NR->isFunctionReferenceType()) {
7222         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7223             << NR->isReferenceType();
7224         NewVD->setInvalidDecl();
7225         return false;
7226       }
7227       NR = NR->getPointeeType();
7228     }
7229   }
7230 
7231   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7232                                                Se.getLangOpts())) {
7233     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7234     // half array type (unless the cl_khr_fp16 extension is enabled).
7235     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7236       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7237       NewVD->setInvalidDecl();
7238       return false;
7239     }
7240   }
7241 
7242   // OpenCL v1.2 s6.9.r:
7243   // The event type cannot be used with the __local, __constant and __global
7244   // address space qualifiers.
7245   if (R->isEventT()) {
7246     if (R.getAddressSpace() != LangAS::opencl_private) {
7247       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7248       NewVD->setInvalidDecl();
7249       return false;
7250     }
7251   }
7252 
7253   if (R->isSamplerT()) {
7254     // OpenCL v1.2 s6.9.b p4:
7255     // The sampler type cannot be used with the __local and __global address
7256     // space qualifiers.
7257     if (R.getAddressSpace() == LangAS::opencl_local ||
7258         R.getAddressSpace() == LangAS::opencl_global) {
7259       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7260       NewVD->setInvalidDecl();
7261     }
7262 
7263     // OpenCL v1.2 s6.12.14.1:
7264     // A global sampler must be declared with either the constant address
7265     // space qualifier or with the const qualifier.
7266     if (DC->isTranslationUnit() &&
7267         !(R.getAddressSpace() == LangAS::opencl_constant ||
7268           R.isConstQualified())) {
7269       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7270       NewVD->setInvalidDecl();
7271     }
7272     if (NewVD->isInvalidDecl())
7273       return false;
7274   }
7275 
7276   return true;
7277 }
7278 
7279 template <typename AttrTy>
7280 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7281   const TypedefNameDecl *TND = TT->getDecl();
7282   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7283     AttrTy *Clone = Attribute->clone(S.Context);
7284     Clone->setInherited(true);
7285     D->addAttr(Clone);
7286   }
7287 }
7288 
7289 NamedDecl *Sema::ActOnVariableDeclarator(
7290     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7291     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7292     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7293   QualType R = TInfo->getType();
7294   DeclarationName Name = GetNameForDeclarator(D).getName();
7295 
7296   IdentifierInfo *II = Name.getAsIdentifierInfo();
7297 
7298   if (D.isDecompositionDeclarator()) {
7299     // Take the name of the first declarator as our name for diagnostic
7300     // purposes.
7301     auto &Decomp = D.getDecompositionDeclarator();
7302     if (!Decomp.bindings().empty()) {
7303       II = Decomp.bindings()[0].Name;
7304       Name = II;
7305     }
7306   } else if (!II) {
7307     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7308     return nullptr;
7309   }
7310 
7311 
7312   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7313   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7314 
7315   // dllimport globals without explicit storage class are treated as extern. We
7316   // have to change the storage class this early to get the right DeclContext.
7317   if (SC == SC_None && !DC->isRecord() &&
7318       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7319       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7320     SC = SC_Extern;
7321 
7322   DeclContext *OriginalDC = DC;
7323   bool IsLocalExternDecl = SC == SC_Extern &&
7324                            adjustContextForLocalExternDecl(DC);
7325 
7326   if (SCSpec == DeclSpec::SCS_mutable) {
7327     // mutable can only appear on non-static class members, so it's always
7328     // an error here
7329     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7330     D.setInvalidType();
7331     SC = SC_None;
7332   }
7333 
7334   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7335       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7336                               D.getDeclSpec().getStorageClassSpecLoc())) {
7337     // In C++11, the 'register' storage class specifier is deprecated.
7338     // Suppress the warning in system macros, it's used in macros in some
7339     // popular C system headers, such as in glibc's htonl() macro.
7340     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7341          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7342                                    : diag::warn_deprecated_register)
7343       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7344   }
7345 
7346   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7347 
7348   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7349     // C99 6.9p2: The storage-class specifiers auto and register shall not
7350     // appear in the declaration specifiers in an external declaration.
7351     // Global Register+Asm is a GNU extension we support.
7352     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7353       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7354       D.setInvalidType();
7355     }
7356   }
7357 
7358   // If this variable has a VLA type and an initializer, try to
7359   // fold to a constant-sized type. This is otherwise invalid.
7360   if (D.hasInitializer() && R->isVariableArrayType())
7361     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7362                                     /*DiagID=*/0);
7363 
7364   bool IsMemberSpecialization = false;
7365   bool IsVariableTemplateSpecialization = false;
7366   bool IsPartialSpecialization = false;
7367   bool IsVariableTemplate = false;
7368   VarDecl *NewVD = nullptr;
7369   VarTemplateDecl *NewTemplate = nullptr;
7370   TemplateParameterList *TemplateParams = nullptr;
7371   if (!getLangOpts().CPlusPlus) {
7372     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7373                             II, R, TInfo, SC);
7374 
7375     if (R->getContainedDeducedType())
7376       ParsingInitForAutoVars.insert(NewVD);
7377 
7378     if (D.isInvalidType())
7379       NewVD->setInvalidDecl();
7380 
7381     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7382         NewVD->hasLocalStorage())
7383       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7384                             NTCUC_AutoVar, NTCUK_Destruct);
7385   } else {
7386     bool Invalid = false;
7387 
7388     if (DC->isRecord() && !CurContext->isRecord()) {
7389       // This is an out-of-line definition of a static data member.
7390       switch (SC) {
7391       case SC_None:
7392         break;
7393       case SC_Static:
7394         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7395              diag::err_static_out_of_line)
7396           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7397         break;
7398       case SC_Auto:
7399       case SC_Register:
7400       case SC_Extern:
7401         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7402         // to names of variables declared in a block or to function parameters.
7403         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7404         // of class members
7405 
7406         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7407              diag::err_storage_class_for_static_member)
7408           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7409         break;
7410       case SC_PrivateExtern:
7411         llvm_unreachable("C storage class in c++!");
7412       }
7413     }
7414 
7415     if (SC == SC_Static && CurContext->isRecord()) {
7416       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7417         // Walk up the enclosing DeclContexts to check for any that are
7418         // incompatible with static data members.
7419         const DeclContext *FunctionOrMethod = nullptr;
7420         const CXXRecordDecl *AnonStruct = nullptr;
7421         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7422           if (Ctxt->isFunctionOrMethod()) {
7423             FunctionOrMethod = Ctxt;
7424             break;
7425           }
7426           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7427           if (ParentDecl && !ParentDecl->getDeclName()) {
7428             AnonStruct = ParentDecl;
7429             break;
7430           }
7431         }
7432         if (FunctionOrMethod) {
7433           // C++ [class.static.data]p5: A local class shall not have static data
7434           // members.
7435           Diag(D.getIdentifierLoc(),
7436                diag::err_static_data_member_not_allowed_in_local_class)
7437             << Name << RD->getDeclName() << RD->getTagKind();
7438         } else if (AnonStruct) {
7439           // C++ [class.static.data]p4: Unnamed classes and classes contained
7440           // directly or indirectly within unnamed classes shall not contain
7441           // static data members.
7442           Diag(D.getIdentifierLoc(),
7443                diag::err_static_data_member_not_allowed_in_anon_struct)
7444             << Name << AnonStruct->getTagKind();
7445           Invalid = true;
7446         } else if (RD->isUnion()) {
7447           // C++98 [class.union]p1: If a union contains a static data member,
7448           // the program is ill-formed. C++11 drops this restriction.
7449           Diag(D.getIdentifierLoc(),
7450                getLangOpts().CPlusPlus11
7451                  ? diag::warn_cxx98_compat_static_data_member_in_union
7452                  : diag::ext_static_data_member_in_union) << Name;
7453         }
7454       }
7455     }
7456 
7457     // Match up the template parameter lists with the scope specifier, then
7458     // determine whether we have a template or a template specialization.
7459     bool InvalidScope = false;
7460     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7461         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7462         D.getCXXScopeSpec(),
7463         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7464             ? D.getName().TemplateId
7465             : nullptr,
7466         TemplateParamLists,
7467         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7468     Invalid |= InvalidScope;
7469 
7470     if (TemplateParams) {
7471       if (!TemplateParams->size() &&
7472           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7473         // There is an extraneous 'template<>' for this variable. Complain
7474         // about it, but allow the declaration of the variable.
7475         Diag(TemplateParams->getTemplateLoc(),
7476              diag::err_template_variable_noparams)
7477           << II
7478           << SourceRange(TemplateParams->getTemplateLoc(),
7479                          TemplateParams->getRAngleLoc());
7480         TemplateParams = nullptr;
7481       } else {
7482         // Check that we can declare a template here.
7483         if (CheckTemplateDeclScope(S, TemplateParams))
7484           return nullptr;
7485 
7486         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7487           // This is an explicit specialization or a partial specialization.
7488           IsVariableTemplateSpecialization = true;
7489           IsPartialSpecialization = TemplateParams->size() > 0;
7490         } else { // if (TemplateParams->size() > 0)
7491           // This is a template declaration.
7492           IsVariableTemplate = true;
7493 
7494           // Only C++1y supports variable templates (N3651).
7495           Diag(D.getIdentifierLoc(),
7496                getLangOpts().CPlusPlus14
7497                    ? diag::warn_cxx11_compat_variable_template
7498                    : diag::ext_variable_template);
7499         }
7500       }
7501     } else {
7502       // Check that we can declare a member specialization here.
7503       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7504           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7505         return nullptr;
7506       assert((Invalid ||
7507               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7508              "should have a 'template<>' for this decl");
7509     }
7510 
7511     if (IsVariableTemplateSpecialization) {
7512       SourceLocation TemplateKWLoc =
7513           TemplateParamLists.size() > 0
7514               ? TemplateParamLists[0]->getTemplateLoc()
7515               : SourceLocation();
7516       DeclResult Res = ActOnVarTemplateSpecialization(
7517           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7518           IsPartialSpecialization);
7519       if (Res.isInvalid())
7520         return nullptr;
7521       NewVD = cast<VarDecl>(Res.get());
7522       AddToScope = false;
7523     } else if (D.isDecompositionDeclarator()) {
7524       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7525                                         D.getIdentifierLoc(), R, TInfo, SC,
7526                                         Bindings);
7527     } else
7528       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7529                               D.getIdentifierLoc(), II, R, TInfo, SC);
7530 
7531     // If this is supposed to be a variable template, create it as such.
7532     if (IsVariableTemplate) {
7533       NewTemplate =
7534           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7535                                   TemplateParams, NewVD);
7536       NewVD->setDescribedVarTemplate(NewTemplate);
7537     }
7538 
7539     // If this decl has an auto type in need of deduction, make a note of the
7540     // Decl so we can diagnose uses of it in its own initializer.
7541     if (R->getContainedDeducedType())
7542       ParsingInitForAutoVars.insert(NewVD);
7543 
7544     if (D.isInvalidType() || Invalid) {
7545       NewVD->setInvalidDecl();
7546       if (NewTemplate)
7547         NewTemplate->setInvalidDecl();
7548     }
7549 
7550     SetNestedNameSpecifier(*this, NewVD, D);
7551 
7552     // If we have any template parameter lists that don't directly belong to
7553     // the variable (matching the scope specifier), store them.
7554     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7555     if (TemplateParamLists.size() > VDTemplateParamLists)
7556       NewVD->setTemplateParameterListsInfo(
7557           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7558   }
7559 
7560   if (D.getDeclSpec().isInlineSpecified()) {
7561     if (!getLangOpts().CPlusPlus) {
7562       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7563           << 0;
7564     } else if (CurContext->isFunctionOrMethod()) {
7565       // 'inline' is not allowed on block scope variable declaration.
7566       Diag(D.getDeclSpec().getInlineSpecLoc(),
7567            diag::err_inline_declaration_block_scope) << Name
7568         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7569     } else {
7570       Diag(D.getDeclSpec().getInlineSpecLoc(),
7571            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7572                                      : diag::ext_inline_variable);
7573       NewVD->setInlineSpecified();
7574     }
7575   }
7576 
7577   // Set the lexical context. If the declarator has a C++ scope specifier, the
7578   // lexical context will be different from the semantic context.
7579   NewVD->setLexicalDeclContext(CurContext);
7580   if (NewTemplate)
7581     NewTemplate->setLexicalDeclContext(CurContext);
7582 
7583   if (IsLocalExternDecl) {
7584     if (D.isDecompositionDeclarator())
7585       for (auto *B : Bindings)
7586         B->setLocalExternDecl();
7587     else
7588       NewVD->setLocalExternDecl();
7589   }
7590 
7591   bool EmitTLSUnsupportedError = false;
7592   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7593     // C++11 [dcl.stc]p4:
7594     //   When thread_local is applied to a variable of block scope the
7595     //   storage-class-specifier static is implied if it does not appear
7596     //   explicitly.
7597     // Core issue: 'static' is not implied if the variable is declared
7598     //   'extern'.
7599     if (NewVD->hasLocalStorage() &&
7600         (SCSpec != DeclSpec::SCS_unspecified ||
7601          TSCS != DeclSpec::TSCS_thread_local ||
7602          !DC->isFunctionOrMethod()))
7603       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7604            diag::err_thread_non_global)
7605         << DeclSpec::getSpecifierName(TSCS);
7606     else if (!Context.getTargetInfo().isTLSSupported()) {
7607       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7608           getLangOpts().SYCLIsDevice) {
7609         // Postpone error emission until we've collected attributes required to
7610         // figure out whether it's a host or device variable and whether the
7611         // error should be ignored.
7612         EmitTLSUnsupportedError = true;
7613         // We still need to mark the variable as TLS so it shows up in AST with
7614         // proper storage class for other tools to use even if we're not going
7615         // to emit any code for it.
7616         NewVD->setTSCSpec(TSCS);
7617       } else
7618         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7619              diag::err_thread_unsupported);
7620     } else
7621       NewVD->setTSCSpec(TSCS);
7622   }
7623 
7624   switch (D.getDeclSpec().getConstexprSpecifier()) {
7625   case ConstexprSpecKind::Unspecified:
7626     break;
7627 
7628   case ConstexprSpecKind::Consteval:
7629     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7630          diag::err_constexpr_wrong_decl_kind)
7631         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7632     LLVM_FALLTHROUGH;
7633 
7634   case ConstexprSpecKind::Constexpr:
7635     NewVD->setConstexpr(true);
7636     // C++1z [dcl.spec.constexpr]p1:
7637     //   A static data member declared with the constexpr specifier is
7638     //   implicitly an inline variable.
7639     if (NewVD->isStaticDataMember() &&
7640         (getLangOpts().CPlusPlus17 ||
7641          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7642       NewVD->setImplicitlyInline();
7643     break;
7644 
7645   case ConstexprSpecKind::Constinit:
7646     if (!NewVD->hasGlobalStorage())
7647       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7648            diag::err_constinit_local_variable);
7649     else
7650       NewVD->addAttr(ConstInitAttr::Create(
7651           Context, D.getDeclSpec().getConstexprSpecLoc(),
7652           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7653     break;
7654   }
7655 
7656   // C99 6.7.4p3
7657   //   An inline definition of a function with external linkage shall
7658   //   not contain a definition of a modifiable object with static or
7659   //   thread storage duration...
7660   // We only apply this when the function is required to be defined
7661   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7662   // that a local variable with thread storage duration still has to
7663   // be marked 'static'.  Also note that it's possible to get these
7664   // semantics in C++ using __attribute__((gnu_inline)).
7665   if (SC == SC_Static && S->getFnParent() != nullptr &&
7666       !NewVD->getType().isConstQualified()) {
7667     FunctionDecl *CurFD = getCurFunctionDecl();
7668     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7669       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7670            diag::warn_static_local_in_extern_inline);
7671       MaybeSuggestAddingStaticToDecl(CurFD);
7672     }
7673   }
7674 
7675   if (D.getDeclSpec().isModulePrivateSpecified()) {
7676     if (IsVariableTemplateSpecialization)
7677       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7678           << (IsPartialSpecialization ? 1 : 0)
7679           << FixItHint::CreateRemoval(
7680                  D.getDeclSpec().getModulePrivateSpecLoc());
7681     else if (IsMemberSpecialization)
7682       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7683         << 2
7684         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7685     else if (NewVD->hasLocalStorage())
7686       Diag(NewVD->getLocation(), diag::err_module_private_local)
7687           << 0 << NewVD
7688           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7689           << FixItHint::CreateRemoval(
7690                  D.getDeclSpec().getModulePrivateSpecLoc());
7691     else {
7692       NewVD->setModulePrivate();
7693       if (NewTemplate)
7694         NewTemplate->setModulePrivate();
7695       for (auto *B : Bindings)
7696         B->setModulePrivate();
7697     }
7698   }
7699 
7700   if (getLangOpts().OpenCL) {
7701     deduceOpenCLAddressSpace(NewVD);
7702 
7703     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7704     if (TSC != TSCS_unspecified) {
7705       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7706            diag::err_opencl_unknown_type_specifier)
7707           << getLangOpts().getOpenCLVersionString()
7708           << DeclSpec::getSpecifierName(TSC) << 1;
7709       NewVD->setInvalidDecl();
7710     }
7711   }
7712 
7713   // Handle attributes prior to checking for duplicates in MergeVarDecl
7714   ProcessDeclAttributes(S, NewVD, D);
7715 
7716   // FIXME: This is probably the wrong location to be doing this and we should
7717   // probably be doing this for more attributes (especially for function
7718   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7719   // the code to copy attributes would be generated by TableGen.
7720   if (R->isFunctionPointerType())
7721     if (const auto *TT = R->getAs<TypedefType>())
7722       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7723 
7724   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7725       getLangOpts().SYCLIsDevice) {
7726     if (EmitTLSUnsupportedError &&
7727         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7728          (getLangOpts().OpenMPIsDevice &&
7729           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7730       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7731            diag::err_thread_unsupported);
7732 
7733     if (EmitTLSUnsupportedError &&
7734         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7735       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7736     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7737     // storage [duration]."
7738     if (SC == SC_None && S->getFnParent() != nullptr &&
7739         (NewVD->hasAttr<CUDASharedAttr>() ||
7740          NewVD->hasAttr<CUDAConstantAttr>())) {
7741       NewVD->setStorageClass(SC_Static);
7742     }
7743   }
7744 
7745   // Ensure that dllimport globals without explicit storage class are treated as
7746   // extern. The storage class is set above using parsed attributes. Now we can
7747   // check the VarDecl itself.
7748   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7749          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7750          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7751 
7752   // In auto-retain/release, infer strong retension for variables of
7753   // retainable type.
7754   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7755     NewVD->setInvalidDecl();
7756 
7757   // Handle GNU asm-label extension (encoded as an attribute).
7758   if (Expr *E = (Expr*)D.getAsmLabel()) {
7759     // The parser guarantees this is a string.
7760     StringLiteral *SE = cast<StringLiteral>(E);
7761     StringRef Label = SE->getString();
7762     if (S->getFnParent() != nullptr) {
7763       switch (SC) {
7764       case SC_None:
7765       case SC_Auto:
7766         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7767         break;
7768       case SC_Register:
7769         // Local Named register
7770         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7771             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7772           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7773         break;
7774       case SC_Static:
7775       case SC_Extern:
7776       case SC_PrivateExtern:
7777         break;
7778       }
7779     } else if (SC == SC_Register) {
7780       // Global Named register
7781       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7782         const auto &TI = Context.getTargetInfo();
7783         bool HasSizeMismatch;
7784 
7785         if (!TI.isValidGCCRegisterName(Label))
7786           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7787         else if (!TI.validateGlobalRegisterVariable(Label,
7788                                                     Context.getTypeSize(R),
7789                                                     HasSizeMismatch))
7790           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7791         else if (HasSizeMismatch)
7792           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7793       }
7794 
7795       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7796         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7797         NewVD->setInvalidDecl(true);
7798       }
7799     }
7800 
7801     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7802                                         /*IsLiteralLabel=*/true,
7803                                         SE->getStrTokenLoc(0)));
7804   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7805     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7806       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7807     if (I != ExtnameUndeclaredIdentifiers.end()) {
7808       if (isDeclExternC(NewVD)) {
7809         NewVD->addAttr(I->second);
7810         ExtnameUndeclaredIdentifiers.erase(I);
7811       } else
7812         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7813             << /*Variable*/1 << NewVD;
7814     }
7815   }
7816 
7817   // Find the shadowed declaration before filtering for scope.
7818   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7819                                 ? getShadowedDeclaration(NewVD, Previous)
7820                                 : nullptr;
7821 
7822   // Don't consider existing declarations that are in a different
7823   // scope and are out-of-semantic-context declarations (if the new
7824   // declaration has linkage).
7825   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7826                        D.getCXXScopeSpec().isNotEmpty() ||
7827                        IsMemberSpecialization ||
7828                        IsVariableTemplateSpecialization);
7829 
7830   // Check whether the previous declaration is in the same block scope. This
7831   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7832   if (getLangOpts().CPlusPlus &&
7833       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7834     NewVD->setPreviousDeclInSameBlockScope(
7835         Previous.isSingleResult() && !Previous.isShadowed() &&
7836         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7837 
7838   if (!getLangOpts().CPlusPlus) {
7839     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7840   } else {
7841     // If this is an explicit specialization of a static data member, check it.
7842     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7843         CheckMemberSpecialization(NewVD, Previous))
7844       NewVD->setInvalidDecl();
7845 
7846     // Merge the decl with the existing one if appropriate.
7847     if (!Previous.empty()) {
7848       if (Previous.isSingleResult() &&
7849           isa<FieldDecl>(Previous.getFoundDecl()) &&
7850           D.getCXXScopeSpec().isSet()) {
7851         // The user tried to define a non-static data member
7852         // out-of-line (C++ [dcl.meaning]p1).
7853         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7854           << D.getCXXScopeSpec().getRange();
7855         Previous.clear();
7856         NewVD->setInvalidDecl();
7857       }
7858     } else if (D.getCXXScopeSpec().isSet()) {
7859       // No previous declaration in the qualifying scope.
7860       Diag(D.getIdentifierLoc(), diag::err_no_member)
7861         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7862         << D.getCXXScopeSpec().getRange();
7863       NewVD->setInvalidDecl();
7864     }
7865 
7866     if (!IsVariableTemplateSpecialization)
7867       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7868 
7869     if (NewTemplate) {
7870       VarTemplateDecl *PrevVarTemplate =
7871           NewVD->getPreviousDecl()
7872               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7873               : nullptr;
7874 
7875       // Check the template parameter list of this declaration, possibly
7876       // merging in the template parameter list from the previous variable
7877       // template declaration.
7878       if (CheckTemplateParameterList(
7879               TemplateParams,
7880               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7881                               : nullptr,
7882               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7883                DC->isDependentContext())
7884                   ? TPC_ClassTemplateMember
7885                   : TPC_VarTemplate))
7886         NewVD->setInvalidDecl();
7887 
7888       // If we are providing an explicit specialization of a static variable
7889       // template, make a note of that.
7890       if (PrevVarTemplate &&
7891           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7892         PrevVarTemplate->setMemberSpecialization();
7893     }
7894   }
7895 
7896   // Diagnose shadowed variables iff this isn't a redeclaration.
7897   if (ShadowedDecl && !D.isRedeclaration())
7898     CheckShadow(NewVD, ShadowedDecl, Previous);
7899 
7900   ProcessPragmaWeak(S, NewVD);
7901 
7902   // If this is the first declaration of an extern C variable, update
7903   // the map of such variables.
7904   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7905       isIncompleteDeclExternC(*this, NewVD))
7906     RegisterLocallyScopedExternCDecl(NewVD, S);
7907 
7908   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7909     MangleNumberingContext *MCtx;
7910     Decl *ManglingContextDecl;
7911     std::tie(MCtx, ManglingContextDecl) =
7912         getCurrentMangleNumberContext(NewVD->getDeclContext());
7913     if (MCtx) {
7914       Context.setManglingNumber(
7915           NewVD, MCtx->getManglingNumber(
7916                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7917       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7918     }
7919   }
7920 
7921   // Special handling of variable named 'main'.
7922   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7923       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7924       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7925 
7926     // C++ [basic.start.main]p3
7927     // A program that declares a variable main at global scope is ill-formed.
7928     if (getLangOpts().CPlusPlus)
7929       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7930 
7931     // In C, and external-linkage variable named main results in undefined
7932     // behavior.
7933     else if (NewVD->hasExternalFormalLinkage())
7934       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7935   }
7936 
7937   if (D.isRedeclaration() && !Previous.empty()) {
7938     NamedDecl *Prev = Previous.getRepresentativeDecl();
7939     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7940                                    D.isFunctionDefinition());
7941   }
7942 
7943   if (NewTemplate) {
7944     if (NewVD->isInvalidDecl())
7945       NewTemplate->setInvalidDecl();
7946     ActOnDocumentableDecl(NewTemplate);
7947     return NewTemplate;
7948   }
7949 
7950   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7951     CompleteMemberSpecialization(NewVD, Previous);
7952 
7953   return NewVD;
7954 }
7955 
7956 /// Enum describing the %select options in diag::warn_decl_shadow.
7957 enum ShadowedDeclKind {
7958   SDK_Local,
7959   SDK_Global,
7960   SDK_StaticMember,
7961   SDK_Field,
7962   SDK_Typedef,
7963   SDK_Using,
7964   SDK_StructuredBinding
7965 };
7966 
7967 /// Determine what kind of declaration we're shadowing.
7968 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7969                                                 const DeclContext *OldDC) {
7970   if (isa<TypeAliasDecl>(ShadowedDecl))
7971     return SDK_Using;
7972   else if (isa<TypedefDecl>(ShadowedDecl))
7973     return SDK_Typedef;
7974   else if (isa<BindingDecl>(ShadowedDecl))
7975     return SDK_StructuredBinding;
7976   else if (isa<RecordDecl>(OldDC))
7977     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7978 
7979   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7980 }
7981 
7982 /// Return the location of the capture if the given lambda captures the given
7983 /// variable \p VD, or an invalid source location otherwise.
7984 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7985                                          const VarDecl *VD) {
7986   for (const Capture &Capture : LSI->Captures) {
7987     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7988       return Capture.getLocation();
7989   }
7990   return SourceLocation();
7991 }
7992 
7993 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7994                                      const LookupResult &R) {
7995   // Only diagnose if we're shadowing an unambiguous field or variable.
7996   if (R.getResultKind() != LookupResult::Found)
7997     return false;
7998 
7999   // Return false if warning is ignored.
8000   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8001 }
8002 
8003 /// Return the declaration shadowed by the given variable \p D, or null
8004 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8005 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8006                                         const LookupResult &R) {
8007   if (!shouldWarnIfShadowedDecl(Diags, R))
8008     return nullptr;
8009 
8010   // Don't diagnose declarations at file scope.
8011   if (D->hasGlobalStorage())
8012     return nullptr;
8013 
8014   NamedDecl *ShadowedDecl = R.getFoundDecl();
8015   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8016                                                             : nullptr;
8017 }
8018 
8019 /// Return the declaration shadowed by the given typedef \p D, or null
8020 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8021 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8022                                         const LookupResult &R) {
8023   // Don't warn if typedef declaration is part of a class
8024   if (D->getDeclContext()->isRecord())
8025     return nullptr;
8026 
8027   if (!shouldWarnIfShadowedDecl(Diags, R))
8028     return nullptr;
8029 
8030   NamedDecl *ShadowedDecl = R.getFoundDecl();
8031   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8032 }
8033 
8034 /// Return the declaration shadowed by the given variable \p D, or null
8035 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8036 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8037                                         const LookupResult &R) {
8038   if (!shouldWarnIfShadowedDecl(Diags, R))
8039     return nullptr;
8040 
8041   NamedDecl *ShadowedDecl = R.getFoundDecl();
8042   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8043                                                             : nullptr;
8044 }
8045 
8046 /// Diagnose variable or built-in function shadowing.  Implements
8047 /// -Wshadow.
8048 ///
8049 /// This method is called whenever a VarDecl is added to a "useful"
8050 /// scope.
8051 ///
8052 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8053 /// \param R the lookup of the name
8054 ///
8055 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8056                        const LookupResult &R) {
8057   DeclContext *NewDC = D->getDeclContext();
8058 
8059   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8060     // Fields are not shadowed by variables in C++ static methods.
8061     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8062       if (MD->isStatic())
8063         return;
8064 
8065     // Fields shadowed by constructor parameters are a special case. Usually
8066     // the constructor initializes the field with the parameter.
8067     if (isa<CXXConstructorDecl>(NewDC))
8068       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8069         // Remember that this was shadowed so we can either warn about its
8070         // modification or its existence depending on warning settings.
8071         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8072         return;
8073       }
8074   }
8075 
8076   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8077     if (shadowedVar->isExternC()) {
8078       // For shadowing external vars, make sure that we point to the global
8079       // declaration, not a locally scoped extern declaration.
8080       for (auto I : shadowedVar->redecls())
8081         if (I->isFileVarDecl()) {
8082           ShadowedDecl = I;
8083           break;
8084         }
8085     }
8086 
8087   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8088 
8089   unsigned WarningDiag = diag::warn_decl_shadow;
8090   SourceLocation CaptureLoc;
8091   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8092       isa<CXXMethodDecl>(NewDC)) {
8093     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8094       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8095         if (RD->getLambdaCaptureDefault() == LCD_None) {
8096           // Try to avoid warnings for lambdas with an explicit capture list.
8097           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8098           // Warn only when the lambda captures the shadowed decl explicitly.
8099           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8100           if (CaptureLoc.isInvalid())
8101             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8102         } else {
8103           // Remember that this was shadowed so we can avoid the warning if the
8104           // shadowed decl isn't captured and the warning settings allow it.
8105           cast<LambdaScopeInfo>(getCurFunction())
8106               ->ShadowingDecls.push_back(
8107                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8108           return;
8109         }
8110       }
8111 
8112       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8113         // A variable can't shadow a local variable in an enclosing scope, if
8114         // they are separated by a non-capturing declaration context.
8115         for (DeclContext *ParentDC = NewDC;
8116              ParentDC && !ParentDC->Equals(OldDC);
8117              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8118           // Only block literals, captured statements, and lambda expressions
8119           // can capture; other scopes don't.
8120           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8121               !isLambdaCallOperator(ParentDC)) {
8122             return;
8123           }
8124         }
8125       }
8126     }
8127   }
8128 
8129   // Only warn about certain kinds of shadowing for class members.
8130   if (NewDC && NewDC->isRecord()) {
8131     // In particular, don't warn about shadowing non-class members.
8132     if (!OldDC->isRecord())
8133       return;
8134 
8135     // TODO: should we warn about static data members shadowing
8136     // static data members from base classes?
8137 
8138     // TODO: don't diagnose for inaccessible shadowed members.
8139     // This is hard to do perfectly because we might friend the
8140     // shadowing context, but that's just a false negative.
8141   }
8142 
8143 
8144   DeclarationName Name = R.getLookupName();
8145 
8146   // Emit warning and note.
8147   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8148   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8149   if (!CaptureLoc.isInvalid())
8150     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8151         << Name << /*explicitly*/ 1;
8152   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8153 }
8154 
8155 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8156 /// when these variables are captured by the lambda.
8157 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8158   for (const auto &Shadow : LSI->ShadowingDecls) {
8159     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8160     // Try to avoid the warning when the shadowed decl isn't captured.
8161     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8162     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8163     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8164                                        ? diag::warn_decl_shadow_uncaptured_local
8165                                        : diag::warn_decl_shadow)
8166         << Shadow.VD->getDeclName()
8167         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8168     if (!CaptureLoc.isInvalid())
8169       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8170           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8171     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8172   }
8173 }
8174 
8175 /// Check -Wshadow without the advantage of a previous lookup.
8176 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8177   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8178     return;
8179 
8180   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8181                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8182   LookupName(R, S);
8183   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8184     CheckShadow(D, ShadowedDecl, R);
8185 }
8186 
8187 /// Check if 'E', which is an expression that is about to be modified, refers
8188 /// to a constructor parameter that shadows a field.
8189 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8190   // Quickly ignore expressions that can't be shadowing ctor parameters.
8191   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8192     return;
8193   E = E->IgnoreParenImpCasts();
8194   auto *DRE = dyn_cast<DeclRefExpr>(E);
8195   if (!DRE)
8196     return;
8197   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8198   auto I = ShadowingDecls.find(D);
8199   if (I == ShadowingDecls.end())
8200     return;
8201   const NamedDecl *ShadowedDecl = I->second;
8202   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8203   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8204   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8205   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8206 
8207   // Avoid issuing multiple warnings about the same decl.
8208   ShadowingDecls.erase(I);
8209 }
8210 
8211 /// Check for conflict between this global or extern "C" declaration and
8212 /// previous global or extern "C" declarations. This is only used in C++.
8213 template<typename T>
8214 static bool checkGlobalOrExternCConflict(
8215     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8216   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8217   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8218 
8219   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8220     // The common case: this global doesn't conflict with any extern "C"
8221     // declaration.
8222     return false;
8223   }
8224 
8225   if (Prev) {
8226     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8227       // Both the old and new declarations have C language linkage. This is a
8228       // redeclaration.
8229       Previous.clear();
8230       Previous.addDecl(Prev);
8231       return true;
8232     }
8233 
8234     // This is a global, non-extern "C" declaration, and there is a previous
8235     // non-global extern "C" declaration. Diagnose if this is a variable
8236     // declaration.
8237     if (!isa<VarDecl>(ND))
8238       return false;
8239   } else {
8240     // The declaration is extern "C". Check for any declaration in the
8241     // translation unit which might conflict.
8242     if (IsGlobal) {
8243       // We have already performed the lookup into the translation unit.
8244       IsGlobal = false;
8245       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8246            I != E; ++I) {
8247         if (isa<VarDecl>(*I)) {
8248           Prev = *I;
8249           break;
8250         }
8251       }
8252     } else {
8253       DeclContext::lookup_result R =
8254           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8255       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8256            I != E; ++I) {
8257         if (isa<VarDecl>(*I)) {
8258           Prev = *I;
8259           break;
8260         }
8261         // FIXME: If we have any other entity with this name in global scope,
8262         // the declaration is ill-formed, but that is a defect: it breaks the
8263         // 'stat' hack, for instance. Only variables can have mangled name
8264         // clashes with extern "C" declarations, so only they deserve a
8265         // diagnostic.
8266       }
8267     }
8268 
8269     if (!Prev)
8270       return false;
8271   }
8272 
8273   // Use the first declaration's location to ensure we point at something which
8274   // is lexically inside an extern "C" linkage-spec.
8275   assert(Prev && "should have found a previous declaration to diagnose");
8276   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8277     Prev = FD->getFirstDecl();
8278   else
8279     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8280 
8281   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8282     << IsGlobal << ND;
8283   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8284     << IsGlobal;
8285   return false;
8286 }
8287 
8288 /// Apply special rules for handling extern "C" declarations. Returns \c true
8289 /// if we have found that this is a redeclaration of some prior entity.
8290 ///
8291 /// Per C++ [dcl.link]p6:
8292 ///   Two declarations [for a function or variable] with C language linkage
8293 ///   with the same name that appear in different scopes refer to the same
8294 ///   [entity]. An entity with C language linkage shall not be declared with
8295 ///   the same name as an entity in global scope.
8296 template<typename T>
8297 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8298                                                   LookupResult &Previous) {
8299   if (!S.getLangOpts().CPlusPlus) {
8300     // In C, when declaring a global variable, look for a corresponding 'extern'
8301     // variable declared in function scope. We don't need this in C++, because
8302     // we find local extern decls in the surrounding file-scope DeclContext.
8303     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8304       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8305         Previous.clear();
8306         Previous.addDecl(Prev);
8307         return true;
8308       }
8309     }
8310     return false;
8311   }
8312 
8313   // A declaration in the translation unit can conflict with an extern "C"
8314   // declaration.
8315   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8316     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8317 
8318   // An extern "C" declaration can conflict with a declaration in the
8319   // translation unit or can be a redeclaration of an extern "C" declaration
8320   // in another scope.
8321   if (isIncompleteDeclExternC(S,ND))
8322     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8323 
8324   // Neither global nor extern "C": nothing to do.
8325   return false;
8326 }
8327 
8328 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8329   // If the decl is already known invalid, don't check it.
8330   if (NewVD->isInvalidDecl())
8331     return;
8332 
8333   QualType T = NewVD->getType();
8334 
8335   // Defer checking an 'auto' type until its initializer is attached.
8336   if (T->isUndeducedType())
8337     return;
8338 
8339   if (NewVD->hasAttrs())
8340     CheckAlignasUnderalignment(NewVD);
8341 
8342   if (T->isObjCObjectType()) {
8343     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8344       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8345     T = Context.getObjCObjectPointerType(T);
8346     NewVD->setType(T);
8347   }
8348 
8349   // Emit an error if an address space was applied to decl with local storage.
8350   // This includes arrays of objects with address space qualifiers, but not
8351   // automatic variables that point to other address spaces.
8352   // ISO/IEC TR 18037 S5.1.2
8353   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8354       T.getAddressSpace() != LangAS::Default) {
8355     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8356     NewVD->setInvalidDecl();
8357     return;
8358   }
8359 
8360   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8361   // scope.
8362   if (getLangOpts().OpenCLVersion == 120 &&
8363       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8364                                             getLangOpts()) &&
8365       NewVD->isStaticLocal()) {
8366     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8367     NewVD->setInvalidDecl();
8368     return;
8369   }
8370 
8371   if (getLangOpts().OpenCL) {
8372     if (!diagnoseOpenCLTypes(*this, NewVD))
8373       return;
8374 
8375     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8376     if (NewVD->hasAttr<BlocksAttr>()) {
8377       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8378       return;
8379     }
8380 
8381     if (T->isBlockPointerType()) {
8382       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8383       // can't use 'extern' storage class.
8384       if (!T.isConstQualified()) {
8385         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8386             << 0 /*const*/;
8387         NewVD->setInvalidDecl();
8388         return;
8389       }
8390       if (NewVD->hasExternalStorage()) {
8391         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8392         NewVD->setInvalidDecl();
8393         return;
8394       }
8395     }
8396 
8397     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8398     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8399         NewVD->hasExternalStorage()) {
8400       if (!T->isSamplerT() && !T->isDependentType() &&
8401           !(T.getAddressSpace() == LangAS::opencl_constant ||
8402             (T.getAddressSpace() == LangAS::opencl_global &&
8403              getOpenCLOptions().areProgramScopeVariablesSupported(
8404                  getLangOpts())))) {
8405         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8406         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8407           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8408               << Scope << "global or constant";
8409         else
8410           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8411               << Scope << "constant";
8412         NewVD->setInvalidDecl();
8413         return;
8414       }
8415     } else {
8416       if (T.getAddressSpace() == LangAS::opencl_global) {
8417         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8418             << 1 /*is any function*/ << "global";
8419         NewVD->setInvalidDecl();
8420         return;
8421       }
8422       if (T.getAddressSpace() == LangAS::opencl_constant ||
8423           T.getAddressSpace() == LangAS::opencl_local) {
8424         FunctionDecl *FD = getCurFunctionDecl();
8425         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8426         // in functions.
8427         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8428           if (T.getAddressSpace() == LangAS::opencl_constant)
8429             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8430                 << 0 /*non-kernel only*/ << "constant";
8431           else
8432             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8433                 << 0 /*non-kernel only*/ << "local";
8434           NewVD->setInvalidDecl();
8435           return;
8436         }
8437         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8438         // in the outermost scope of a kernel function.
8439         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8440           if (!getCurScope()->isFunctionScope()) {
8441             if (T.getAddressSpace() == LangAS::opencl_constant)
8442               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8443                   << "constant";
8444             else
8445               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8446                   << "local";
8447             NewVD->setInvalidDecl();
8448             return;
8449           }
8450         }
8451       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8452                  // If we are parsing a template we didn't deduce an addr
8453                  // space yet.
8454                  T.getAddressSpace() != LangAS::Default) {
8455         // Do not allow other address spaces on automatic variable.
8456         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8457         NewVD->setInvalidDecl();
8458         return;
8459       }
8460     }
8461   }
8462 
8463   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8464       && !NewVD->hasAttr<BlocksAttr>()) {
8465     if (getLangOpts().getGC() != LangOptions::NonGC)
8466       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8467     else {
8468       assert(!getLangOpts().ObjCAutoRefCount);
8469       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8470     }
8471   }
8472 
8473   bool isVM = T->isVariablyModifiedType();
8474   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8475       NewVD->hasAttr<BlocksAttr>())
8476     setFunctionHasBranchProtectedScope();
8477 
8478   if ((isVM && NewVD->hasLinkage()) ||
8479       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8480     bool SizeIsNegative;
8481     llvm::APSInt Oversized;
8482     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8483         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8484     QualType FixedT;
8485     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8486       FixedT = FixedTInfo->getType();
8487     else if (FixedTInfo) {
8488       // Type and type-as-written are canonically different. We need to fix up
8489       // both types separately.
8490       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8491                                                    Oversized);
8492     }
8493     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8494       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8495       // FIXME: This won't give the correct result for
8496       // int a[10][n];
8497       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8498 
8499       if (NewVD->isFileVarDecl())
8500         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8501         << SizeRange;
8502       else if (NewVD->isStaticLocal())
8503         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8504         << SizeRange;
8505       else
8506         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8507         << SizeRange;
8508       NewVD->setInvalidDecl();
8509       return;
8510     }
8511 
8512     if (!FixedTInfo) {
8513       if (NewVD->isFileVarDecl())
8514         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8515       else
8516         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8517       NewVD->setInvalidDecl();
8518       return;
8519     }
8520 
8521     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8522     NewVD->setType(FixedT);
8523     NewVD->setTypeSourceInfo(FixedTInfo);
8524   }
8525 
8526   if (T->isVoidType()) {
8527     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8528     //                    of objects and functions.
8529     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8530       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8531         << T;
8532       NewVD->setInvalidDecl();
8533       return;
8534     }
8535   }
8536 
8537   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8538     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8539     NewVD->setInvalidDecl();
8540     return;
8541   }
8542 
8543   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8544     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8545     NewVD->setInvalidDecl();
8546     return;
8547   }
8548 
8549   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8550     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8551     NewVD->setInvalidDecl();
8552     return;
8553   }
8554 
8555   if (NewVD->isConstexpr() && !T->isDependentType() &&
8556       RequireLiteralType(NewVD->getLocation(), T,
8557                          diag::err_constexpr_var_non_literal)) {
8558     NewVD->setInvalidDecl();
8559     return;
8560   }
8561 
8562   // PPC MMA non-pointer types are not allowed as non-local variable types.
8563   if (Context.getTargetInfo().getTriple().isPPC64() &&
8564       !NewVD->isLocalVarDecl() &&
8565       CheckPPCMMAType(T, NewVD->getLocation())) {
8566     NewVD->setInvalidDecl();
8567     return;
8568   }
8569 }
8570 
8571 /// Perform semantic checking on a newly-created variable
8572 /// declaration.
8573 ///
8574 /// This routine performs all of the type-checking required for a
8575 /// variable declaration once it has been built. It is used both to
8576 /// check variables after they have been parsed and their declarators
8577 /// have been translated into a declaration, and to check variables
8578 /// that have been instantiated from a template.
8579 ///
8580 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8581 ///
8582 /// Returns true if the variable declaration is a redeclaration.
8583 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8584   CheckVariableDeclarationType(NewVD);
8585 
8586   // If the decl is already known invalid, don't check it.
8587   if (NewVD->isInvalidDecl())
8588     return false;
8589 
8590   // If we did not find anything by this name, look for a non-visible
8591   // extern "C" declaration with the same name.
8592   if (Previous.empty() &&
8593       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8594     Previous.setShadowed();
8595 
8596   if (!Previous.empty()) {
8597     MergeVarDecl(NewVD, Previous);
8598     return true;
8599   }
8600   return false;
8601 }
8602 
8603 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8604 /// and if so, check that it's a valid override and remember it.
8605 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8606   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8607 
8608   // Look for methods in base classes that this method might override.
8609   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8610                      /*DetectVirtual=*/false);
8611   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8612     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8613     DeclarationName Name = MD->getDeclName();
8614 
8615     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8616       // We really want to find the base class destructor here.
8617       QualType T = Context.getTypeDeclType(BaseRecord);
8618       CanQualType CT = Context.getCanonicalType(T);
8619       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8620     }
8621 
8622     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8623       CXXMethodDecl *BaseMD =
8624           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8625       if (!BaseMD || !BaseMD->isVirtual() ||
8626           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8627                      /*ConsiderCudaAttrs=*/true,
8628                      // C++2a [class.virtual]p2 does not consider requires
8629                      // clauses when overriding.
8630                      /*ConsiderRequiresClauses=*/false))
8631         continue;
8632 
8633       if (Overridden.insert(BaseMD).second) {
8634         MD->addOverriddenMethod(BaseMD);
8635         CheckOverridingFunctionReturnType(MD, BaseMD);
8636         CheckOverridingFunctionAttributes(MD, BaseMD);
8637         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8638         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8639       }
8640 
8641       // A method can only override one function from each base class. We
8642       // don't track indirectly overridden methods from bases of bases.
8643       return true;
8644     }
8645 
8646     return false;
8647   };
8648 
8649   DC->lookupInBases(VisitBase, Paths);
8650   return !Overridden.empty();
8651 }
8652 
8653 namespace {
8654   // Struct for holding all of the extra arguments needed by
8655   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8656   struct ActOnFDArgs {
8657     Scope *S;
8658     Declarator &D;
8659     MultiTemplateParamsArg TemplateParamLists;
8660     bool AddToScope;
8661   };
8662 } // end anonymous namespace
8663 
8664 namespace {
8665 
8666 // Callback to only accept typo corrections that have a non-zero edit distance.
8667 // Also only accept corrections that have the same parent decl.
8668 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8669  public:
8670   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8671                             CXXRecordDecl *Parent)
8672       : Context(Context), OriginalFD(TypoFD),
8673         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8674 
8675   bool ValidateCandidate(const TypoCorrection &candidate) override {
8676     if (candidate.getEditDistance() == 0)
8677       return false;
8678 
8679     SmallVector<unsigned, 1> MismatchedParams;
8680     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8681                                           CDeclEnd = candidate.end();
8682          CDecl != CDeclEnd; ++CDecl) {
8683       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8684 
8685       if (FD && !FD->hasBody() &&
8686           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8687         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8688           CXXRecordDecl *Parent = MD->getParent();
8689           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8690             return true;
8691         } else if (!ExpectedParent) {
8692           return true;
8693         }
8694       }
8695     }
8696 
8697     return false;
8698   }
8699 
8700   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8701     return std::make_unique<DifferentNameValidatorCCC>(*this);
8702   }
8703 
8704  private:
8705   ASTContext &Context;
8706   FunctionDecl *OriginalFD;
8707   CXXRecordDecl *ExpectedParent;
8708 };
8709 
8710 } // end anonymous namespace
8711 
8712 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8713   TypoCorrectedFunctionDefinitions.insert(F);
8714 }
8715 
8716 /// Generate diagnostics for an invalid function redeclaration.
8717 ///
8718 /// This routine handles generating the diagnostic messages for an invalid
8719 /// function redeclaration, including finding possible similar declarations
8720 /// or performing typo correction if there are no previous declarations with
8721 /// the same name.
8722 ///
8723 /// Returns a NamedDecl iff typo correction was performed and substituting in
8724 /// the new declaration name does not cause new errors.
8725 static NamedDecl *DiagnoseInvalidRedeclaration(
8726     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8727     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8728   DeclarationName Name = NewFD->getDeclName();
8729   DeclContext *NewDC = NewFD->getDeclContext();
8730   SmallVector<unsigned, 1> MismatchedParams;
8731   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8732   TypoCorrection Correction;
8733   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8734   unsigned DiagMsg =
8735     IsLocalFriend ? diag::err_no_matching_local_friend :
8736     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8737     diag::err_member_decl_does_not_match;
8738   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8739                     IsLocalFriend ? Sema::LookupLocalFriendName
8740                                   : Sema::LookupOrdinaryName,
8741                     Sema::ForVisibleRedeclaration);
8742 
8743   NewFD->setInvalidDecl();
8744   if (IsLocalFriend)
8745     SemaRef.LookupName(Prev, S);
8746   else
8747     SemaRef.LookupQualifiedName(Prev, NewDC);
8748   assert(!Prev.isAmbiguous() &&
8749          "Cannot have an ambiguity in previous-declaration lookup");
8750   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8751   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8752                                 MD ? MD->getParent() : nullptr);
8753   if (!Prev.empty()) {
8754     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8755          Func != FuncEnd; ++Func) {
8756       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8757       if (FD &&
8758           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8759         // Add 1 to the index so that 0 can mean the mismatch didn't
8760         // involve a parameter
8761         unsigned ParamNum =
8762             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8763         NearMatches.push_back(std::make_pair(FD, ParamNum));
8764       }
8765     }
8766   // If the qualified name lookup yielded nothing, try typo correction
8767   } else if ((Correction = SemaRef.CorrectTypo(
8768                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8769                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8770                   IsLocalFriend ? nullptr : NewDC))) {
8771     // Set up everything for the call to ActOnFunctionDeclarator
8772     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8773                               ExtraArgs.D.getIdentifierLoc());
8774     Previous.clear();
8775     Previous.setLookupName(Correction.getCorrection());
8776     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8777                                     CDeclEnd = Correction.end();
8778          CDecl != CDeclEnd; ++CDecl) {
8779       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8780       if (FD && !FD->hasBody() &&
8781           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8782         Previous.addDecl(FD);
8783       }
8784     }
8785     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8786 
8787     NamedDecl *Result;
8788     // Retry building the function declaration with the new previous
8789     // declarations, and with errors suppressed.
8790     {
8791       // Trap errors.
8792       Sema::SFINAETrap Trap(SemaRef);
8793 
8794       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8795       // pieces need to verify the typo-corrected C++ declaration and hopefully
8796       // eliminate the need for the parameter pack ExtraArgs.
8797       Result = SemaRef.ActOnFunctionDeclarator(
8798           ExtraArgs.S, ExtraArgs.D,
8799           Correction.getCorrectionDecl()->getDeclContext(),
8800           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8801           ExtraArgs.AddToScope);
8802 
8803       if (Trap.hasErrorOccurred())
8804         Result = nullptr;
8805     }
8806 
8807     if (Result) {
8808       // Determine which correction we picked.
8809       Decl *Canonical = Result->getCanonicalDecl();
8810       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8811            I != E; ++I)
8812         if ((*I)->getCanonicalDecl() == Canonical)
8813           Correction.setCorrectionDecl(*I);
8814 
8815       // Let Sema know about the correction.
8816       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8817       SemaRef.diagnoseTypo(
8818           Correction,
8819           SemaRef.PDiag(IsLocalFriend
8820                           ? diag::err_no_matching_local_friend_suggest
8821                           : diag::err_member_decl_does_not_match_suggest)
8822             << Name << NewDC << IsDefinition);
8823       return Result;
8824     }
8825 
8826     // Pretend the typo correction never occurred
8827     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8828                               ExtraArgs.D.getIdentifierLoc());
8829     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8830     Previous.clear();
8831     Previous.setLookupName(Name);
8832   }
8833 
8834   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8835       << Name << NewDC << IsDefinition << NewFD->getLocation();
8836 
8837   bool NewFDisConst = false;
8838   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8839     NewFDisConst = NewMD->isConst();
8840 
8841   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8842        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8843        NearMatch != NearMatchEnd; ++NearMatch) {
8844     FunctionDecl *FD = NearMatch->first;
8845     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8846     bool FDisConst = MD && MD->isConst();
8847     bool IsMember = MD || !IsLocalFriend;
8848 
8849     // FIXME: These notes are poorly worded for the local friend case.
8850     if (unsigned Idx = NearMatch->second) {
8851       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8852       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8853       if (Loc.isInvalid()) Loc = FD->getLocation();
8854       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8855                                  : diag::note_local_decl_close_param_match)
8856         << Idx << FDParam->getType()
8857         << NewFD->getParamDecl(Idx - 1)->getType();
8858     } else if (FDisConst != NewFDisConst) {
8859       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8860           << NewFDisConst << FD->getSourceRange().getEnd()
8861           << (NewFDisConst
8862                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8863                                                  .getConstQualifierLoc())
8864                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8865                                                    .getRParenLoc()
8866                                                    .getLocWithOffset(1),
8867                                                " const"));
8868     } else
8869       SemaRef.Diag(FD->getLocation(),
8870                    IsMember ? diag::note_member_def_close_match
8871                             : diag::note_local_decl_close_match);
8872   }
8873   return nullptr;
8874 }
8875 
8876 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8877   switch (D.getDeclSpec().getStorageClassSpec()) {
8878   default: llvm_unreachable("Unknown storage class!");
8879   case DeclSpec::SCS_auto:
8880   case DeclSpec::SCS_register:
8881   case DeclSpec::SCS_mutable:
8882     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8883                  diag::err_typecheck_sclass_func);
8884     D.getMutableDeclSpec().ClearStorageClassSpecs();
8885     D.setInvalidType();
8886     break;
8887   case DeclSpec::SCS_unspecified: break;
8888   case DeclSpec::SCS_extern:
8889     if (D.getDeclSpec().isExternInLinkageSpec())
8890       return SC_None;
8891     return SC_Extern;
8892   case DeclSpec::SCS_static: {
8893     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8894       // C99 6.7.1p5:
8895       //   The declaration of an identifier for a function that has
8896       //   block scope shall have no explicit storage-class specifier
8897       //   other than extern
8898       // See also (C++ [dcl.stc]p4).
8899       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8900                    diag::err_static_block_func);
8901       break;
8902     } else
8903       return SC_Static;
8904   }
8905   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8906   }
8907 
8908   // No explicit storage class has already been returned
8909   return SC_None;
8910 }
8911 
8912 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8913                                            DeclContext *DC, QualType &R,
8914                                            TypeSourceInfo *TInfo,
8915                                            StorageClass SC,
8916                                            bool &IsVirtualOkay) {
8917   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8918   DeclarationName Name = NameInfo.getName();
8919 
8920   FunctionDecl *NewFD = nullptr;
8921   bool isInline = D.getDeclSpec().isInlineSpecified();
8922 
8923   if (!SemaRef.getLangOpts().CPlusPlus) {
8924     // Determine whether the function was written with a prototype. This is
8925     // true when:
8926     //   - there is a prototype in the declarator, or
8927     //   - the type R of the function is some kind of typedef or other non-
8928     //     attributed reference to a type name (which eventually refers to a
8929     //     function type). Note, we can't always look at the adjusted type to
8930     //     check this case because attributes may cause a non-function
8931     //     declarator to still have a function type. e.g.,
8932     //       typedef void func(int a);
8933     //       __attribute__((noreturn)) func other_func; // This has a prototype
8934     bool HasPrototype =
8935         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8936         (D.getDeclSpec().isTypeRep() &&
8937          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8938         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8939     assert(
8940         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8941         "Strict prototypes are required");
8942 
8943     NewFD = FunctionDecl::Create(
8944         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8945         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8946         ConstexprSpecKind::Unspecified,
8947         /*TrailingRequiresClause=*/nullptr);
8948     if (D.isInvalidType())
8949       NewFD->setInvalidDecl();
8950 
8951     return NewFD;
8952   }
8953 
8954   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8955 
8956   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8957   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8958     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8959                  diag::err_constexpr_wrong_decl_kind)
8960         << static_cast<int>(ConstexprKind);
8961     ConstexprKind = ConstexprSpecKind::Unspecified;
8962     D.getMutableDeclSpec().ClearConstexprSpec();
8963   }
8964   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8965 
8966   // Check that the return type is not an abstract class type.
8967   // For record types, this is done by the AbstractClassUsageDiagnoser once
8968   // the class has been completely parsed.
8969   if (!DC->isRecord() &&
8970       SemaRef.RequireNonAbstractType(
8971           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8972           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8973     D.setInvalidType();
8974 
8975   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8976     // This is a C++ constructor declaration.
8977     assert(DC->isRecord() &&
8978            "Constructors can only be declared in a member context");
8979 
8980     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8981     return CXXConstructorDecl::Create(
8982         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8983         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8984         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8985         InheritedConstructor(), TrailingRequiresClause);
8986 
8987   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8988     // This is a C++ destructor declaration.
8989     if (DC->isRecord()) {
8990       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8991       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8992       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8993           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8994           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8995           /*isImplicitlyDeclared=*/false, ConstexprKind,
8996           TrailingRequiresClause);
8997       // User defined destructors start as not selected if the class definition is still
8998       // not done.
8999       if (Record->isBeingDefined())
9000         NewDD->setIneligibleOrNotSelected(true);
9001 
9002       // If the destructor needs an implicit exception specification, set it
9003       // now. FIXME: It'd be nice to be able to create the right type to start
9004       // with, but the type needs to reference the destructor declaration.
9005       if (SemaRef.getLangOpts().CPlusPlus11)
9006         SemaRef.AdjustDestructorExceptionSpec(NewDD);
9007 
9008       IsVirtualOkay = true;
9009       return NewDD;
9010 
9011     } else {
9012       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9013       D.setInvalidType();
9014 
9015       // Create a FunctionDecl to satisfy the function definition parsing
9016       // code path.
9017       return FunctionDecl::Create(
9018           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9019           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9020           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9021     }
9022 
9023   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9024     if (!DC->isRecord()) {
9025       SemaRef.Diag(D.getIdentifierLoc(),
9026            diag::err_conv_function_not_member);
9027       return nullptr;
9028     }
9029 
9030     SemaRef.CheckConversionDeclarator(D, R, SC);
9031     if (D.isInvalidType())
9032       return nullptr;
9033 
9034     IsVirtualOkay = true;
9035     return CXXConversionDecl::Create(
9036         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9037         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9038         ExplicitSpecifier, ConstexprKind, SourceLocation(),
9039         TrailingRequiresClause);
9040 
9041   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9042     if (TrailingRequiresClause)
9043       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9044                    diag::err_trailing_requires_clause_on_deduction_guide)
9045           << TrailingRequiresClause->getSourceRange();
9046     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
9047 
9048     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9049                                          ExplicitSpecifier, NameInfo, R, TInfo,
9050                                          D.getEndLoc());
9051   } else if (DC->isRecord()) {
9052     // If the name of the function is the same as the name of the record,
9053     // then this must be an invalid constructor that has a return type.
9054     // (The parser checks for a return type and makes the declarator a
9055     // constructor if it has no return type).
9056     if (Name.getAsIdentifierInfo() &&
9057         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9058       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9059         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9060         << SourceRange(D.getIdentifierLoc());
9061       return nullptr;
9062     }
9063 
9064     // This is a C++ method declaration.
9065     CXXMethodDecl *Ret = CXXMethodDecl::Create(
9066         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9067         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9068         ConstexprKind, SourceLocation(), TrailingRequiresClause);
9069     IsVirtualOkay = !Ret->isStatic();
9070     return Ret;
9071   } else {
9072     bool isFriend =
9073         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9074     if (!isFriend && SemaRef.CurContext->isRecord())
9075       return nullptr;
9076 
9077     // Determine whether the function was written with a
9078     // prototype. This true when:
9079     //   - we're in C++ (where every function has a prototype),
9080     return FunctionDecl::Create(
9081         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9082         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9083         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9084   }
9085 }
9086 
9087 enum OpenCLParamType {
9088   ValidKernelParam,
9089   PtrPtrKernelParam,
9090   PtrKernelParam,
9091   InvalidAddrSpacePtrKernelParam,
9092   InvalidKernelParam,
9093   RecordKernelParam
9094 };
9095 
9096 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9097   // Size dependent types are just typedefs to normal integer types
9098   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9099   // integers other than by their names.
9100   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9101 
9102   // Remove typedefs one by one until we reach a typedef
9103   // for a size dependent type.
9104   QualType DesugaredTy = Ty;
9105   do {
9106     ArrayRef<StringRef> Names(SizeTypeNames);
9107     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9108     if (Names.end() != Match)
9109       return true;
9110 
9111     Ty = DesugaredTy;
9112     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9113   } while (DesugaredTy != Ty);
9114 
9115   return false;
9116 }
9117 
9118 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9119   if (PT->isDependentType())
9120     return InvalidKernelParam;
9121 
9122   if (PT->isPointerType() || PT->isReferenceType()) {
9123     QualType PointeeType = PT->getPointeeType();
9124     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9125         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9126         PointeeType.getAddressSpace() == LangAS::Default)
9127       return InvalidAddrSpacePtrKernelParam;
9128 
9129     if (PointeeType->isPointerType()) {
9130       // This is a pointer to pointer parameter.
9131       // Recursively check inner type.
9132       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9133       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9134           ParamKind == InvalidKernelParam)
9135         return ParamKind;
9136 
9137       return PtrPtrKernelParam;
9138     }
9139 
9140     // C++ for OpenCL v1.0 s2.4:
9141     // Moreover the types used in parameters of the kernel functions must be:
9142     // Standard layout types for pointer parameters. The same applies to
9143     // reference if an implementation supports them in kernel parameters.
9144     if (S.getLangOpts().OpenCLCPlusPlus &&
9145         !S.getOpenCLOptions().isAvailableOption(
9146             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9147         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9148         !PointeeType->isStandardLayoutType())
9149       return InvalidKernelParam;
9150 
9151     return PtrKernelParam;
9152   }
9153 
9154   // OpenCL v1.2 s6.9.k:
9155   // Arguments to kernel functions in a program cannot be declared with the
9156   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9157   // uintptr_t or a struct and/or union that contain fields declared to be one
9158   // of these built-in scalar types.
9159   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9160     return InvalidKernelParam;
9161 
9162   if (PT->isImageType())
9163     return PtrKernelParam;
9164 
9165   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9166     return InvalidKernelParam;
9167 
9168   // OpenCL extension spec v1.2 s9.5:
9169   // This extension adds support for half scalar and vector types as built-in
9170   // types that can be used for arithmetic operations, conversions etc.
9171   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9172       PT->isHalfType())
9173     return InvalidKernelParam;
9174 
9175   // Look into an array argument to check if it has a forbidden type.
9176   if (PT->isArrayType()) {
9177     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9178     // Call ourself to check an underlying type of an array. Since the
9179     // getPointeeOrArrayElementType returns an innermost type which is not an
9180     // array, this recursive call only happens once.
9181     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9182   }
9183 
9184   // C++ for OpenCL v1.0 s2.4:
9185   // Moreover the types used in parameters of the kernel functions must be:
9186   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9187   // types) for parameters passed by value;
9188   if (S.getLangOpts().OpenCLCPlusPlus &&
9189       !S.getOpenCLOptions().isAvailableOption(
9190           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9191       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9192     return InvalidKernelParam;
9193 
9194   if (PT->isRecordType())
9195     return RecordKernelParam;
9196 
9197   return ValidKernelParam;
9198 }
9199 
9200 static void checkIsValidOpenCLKernelParameter(
9201   Sema &S,
9202   Declarator &D,
9203   ParmVarDecl *Param,
9204   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9205   QualType PT = Param->getType();
9206 
9207   // Cache the valid types we encounter to avoid rechecking structs that are
9208   // used again
9209   if (ValidTypes.count(PT.getTypePtr()))
9210     return;
9211 
9212   switch (getOpenCLKernelParameterType(S, PT)) {
9213   case PtrPtrKernelParam:
9214     // OpenCL v3.0 s6.11.a:
9215     // A kernel function argument cannot be declared as a pointer to a pointer
9216     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9217     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9218       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9219       D.setInvalidType();
9220       return;
9221     }
9222 
9223     ValidTypes.insert(PT.getTypePtr());
9224     return;
9225 
9226   case InvalidAddrSpacePtrKernelParam:
9227     // OpenCL v1.0 s6.5:
9228     // __kernel function arguments declared to be a pointer of a type can point
9229     // to one of the following address spaces only : __global, __local or
9230     // __constant.
9231     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9232     D.setInvalidType();
9233     return;
9234 
9235     // OpenCL v1.2 s6.9.k:
9236     // Arguments to kernel functions in a program cannot be declared with the
9237     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9238     // uintptr_t or a struct and/or union that contain fields declared to be
9239     // one of these built-in scalar types.
9240 
9241   case InvalidKernelParam:
9242     // OpenCL v1.2 s6.8 n:
9243     // A kernel function argument cannot be declared
9244     // of event_t type.
9245     // Do not diagnose half type since it is diagnosed as invalid argument
9246     // type for any function elsewhere.
9247     if (!PT->isHalfType()) {
9248       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9249 
9250       // Explain what typedefs are involved.
9251       const TypedefType *Typedef = nullptr;
9252       while ((Typedef = PT->getAs<TypedefType>())) {
9253         SourceLocation Loc = Typedef->getDecl()->getLocation();
9254         // SourceLocation may be invalid for a built-in type.
9255         if (Loc.isValid())
9256           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9257         PT = Typedef->desugar();
9258       }
9259     }
9260 
9261     D.setInvalidType();
9262     return;
9263 
9264   case PtrKernelParam:
9265   case ValidKernelParam:
9266     ValidTypes.insert(PT.getTypePtr());
9267     return;
9268 
9269   case RecordKernelParam:
9270     break;
9271   }
9272 
9273   // Track nested structs we will inspect
9274   SmallVector<const Decl *, 4> VisitStack;
9275 
9276   // Track where we are in the nested structs. Items will migrate from
9277   // VisitStack to HistoryStack as we do the DFS for bad field.
9278   SmallVector<const FieldDecl *, 4> HistoryStack;
9279   HistoryStack.push_back(nullptr);
9280 
9281   // At this point we already handled everything except of a RecordType or
9282   // an ArrayType of a RecordType.
9283   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9284   const RecordType *RecTy =
9285       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9286   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9287 
9288   VisitStack.push_back(RecTy->getDecl());
9289   assert(VisitStack.back() && "First decl null?");
9290 
9291   do {
9292     const Decl *Next = VisitStack.pop_back_val();
9293     if (!Next) {
9294       assert(!HistoryStack.empty());
9295       // Found a marker, we have gone up a level
9296       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9297         ValidTypes.insert(Hist->getType().getTypePtr());
9298 
9299       continue;
9300     }
9301 
9302     // Adds everything except the original parameter declaration (which is not a
9303     // field itself) to the history stack.
9304     const RecordDecl *RD;
9305     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9306       HistoryStack.push_back(Field);
9307 
9308       QualType FieldTy = Field->getType();
9309       // Other field types (known to be valid or invalid) are handled while we
9310       // walk around RecordDecl::fields().
9311       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9312              "Unexpected type.");
9313       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9314 
9315       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9316     } else {
9317       RD = cast<RecordDecl>(Next);
9318     }
9319 
9320     // Add a null marker so we know when we've gone back up a level
9321     VisitStack.push_back(nullptr);
9322 
9323     for (const auto *FD : RD->fields()) {
9324       QualType QT = FD->getType();
9325 
9326       if (ValidTypes.count(QT.getTypePtr()))
9327         continue;
9328 
9329       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9330       if (ParamType == ValidKernelParam)
9331         continue;
9332 
9333       if (ParamType == RecordKernelParam) {
9334         VisitStack.push_back(FD);
9335         continue;
9336       }
9337 
9338       // OpenCL v1.2 s6.9.p:
9339       // Arguments to kernel functions that are declared to be a struct or union
9340       // do not allow OpenCL objects to be passed as elements of the struct or
9341       // union.
9342       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9343           ParamType == InvalidAddrSpacePtrKernelParam) {
9344         S.Diag(Param->getLocation(),
9345                diag::err_record_with_pointers_kernel_param)
9346           << PT->isUnionType()
9347           << PT;
9348       } else {
9349         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9350       }
9351 
9352       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9353           << OrigRecDecl->getDeclName();
9354 
9355       // We have an error, now let's go back up through history and show where
9356       // the offending field came from
9357       for (ArrayRef<const FieldDecl *>::const_iterator
9358                I = HistoryStack.begin() + 1,
9359                E = HistoryStack.end();
9360            I != E; ++I) {
9361         const FieldDecl *OuterField = *I;
9362         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9363           << OuterField->getType();
9364       }
9365 
9366       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9367         << QT->isPointerType()
9368         << QT;
9369       D.setInvalidType();
9370       return;
9371     }
9372   } while (!VisitStack.empty());
9373 }
9374 
9375 /// Find the DeclContext in which a tag is implicitly declared if we see an
9376 /// elaborated type specifier in the specified context, and lookup finds
9377 /// nothing.
9378 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9379   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9380     DC = DC->getParent();
9381   return DC;
9382 }
9383 
9384 /// Find the Scope in which a tag is implicitly declared if we see an
9385 /// elaborated type specifier in the specified context, and lookup finds
9386 /// nothing.
9387 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9388   while (S->isClassScope() ||
9389          (LangOpts.CPlusPlus &&
9390           S->isFunctionPrototypeScope()) ||
9391          ((S->getFlags() & Scope::DeclScope) == 0) ||
9392          (S->getEntity() && S->getEntity()->isTransparentContext()))
9393     S = S->getParent();
9394   return S;
9395 }
9396 
9397 /// Determine whether a declaration matches a known function in namespace std.
9398 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9399                          unsigned BuiltinID) {
9400   switch (BuiltinID) {
9401   case Builtin::BI__GetExceptionInfo:
9402     // No type checking whatsoever.
9403     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9404 
9405   case Builtin::BIaddressof:
9406   case Builtin::BI__addressof:
9407   case Builtin::BIforward:
9408   case Builtin::BImove:
9409   case Builtin::BImove_if_noexcept:
9410   case Builtin::BIas_const: {
9411     // Ensure that we don't treat the algorithm
9412     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9413     // as the builtin std::move.
9414     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9415     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9416   }
9417 
9418   default:
9419     return false;
9420   }
9421 }
9422 
9423 NamedDecl*
9424 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9425                               TypeSourceInfo *TInfo, LookupResult &Previous,
9426                               MultiTemplateParamsArg TemplateParamListsRef,
9427                               bool &AddToScope) {
9428   QualType R = TInfo->getType();
9429 
9430   assert(R->isFunctionType());
9431   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9432     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9433 
9434   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9435   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9436   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9437     if (!TemplateParamLists.empty() &&
9438         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9439       TemplateParamLists.back() = Invented;
9440     else
9441       TemplateParamLists.push_back(Invented);
9442   }
9443 
9444   // TODO: consider using NameInfo for diagnostic.
9445   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9446   DeclarationName Name = NameInfo.getName();
9447   StorageClass SC = getFunctionStorageClass(*this, D);
9448 
9449   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9450     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9451          diag::err_invalid_thread)
9452       << DeclSpec::getSpecifierName(TSCS);
9453 
9454   if (D.isFirstDeclarationOfMember())
9455     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9456                            D.getIdentifierLoc());
9457 
9458   bool isFriend = false;
9459   FunctionTemplateDecl *FunctionTemplate = nullptr;
9460   bool isMemberSpecialization = false;
9461   bool isFunctionTemplateSpecialization = false;
9462 
9463   bool isDependentClassScopeExplicitSpecialization = false;
9464   bool HasExplicitTemplateArgs = false;
9465   TemplateArgumentListInfo TemplateArgs;
9466 
9467   bool isVirtualOkay = false;
9468 
9469   DeclContext *OriginalDC = DC;
9470   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9471 
9472   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9473                                               isVirtualOkay);
9474   if (!NewFD) return nullptr;
9475 
9476   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9477     NewFD->setTopLevelDeclInObjCContainer();
9478 
9479   // Set the lexical context. If this is a function-scope declaration, or has a
9480   // C++ scope specifier, or is the object of a friend declaration, the lexical
9481   // context will be different from the semantic context.
9482   NewFD->setLexicalDeclContext(CurContext);
9483 
9484   if (IsLocalExternDecl)
9485     NewFD->setLocalExternDecl();
9486 
9487   if (getLangOpts().CPlusPlus) {
9488     // The rules for implicit inlines changed in C++20 for methods and friends
9489     // with an in-class definition (when such a definition is not attached to
9490     // the global module).  User-specified 'inline' overrides this (set when
9491     // the function decl is created above).
9492     // FIXME: We need a better way to separate C++ standard and clang modules.
9493     bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9494                                !NewFD->getOwningModule() ||
9495                                NewFD->getOwningModule()->isGlobalModule() ||
9496                                NewFD->getOwningModule()->isModuleMapModule();
9497     bool isInline = D.getDeclSpec().isInlineSpecified();
9498     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9499     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9500     isFriend = D.getDeclSpec().isFriendSpecified();
9501     if (isFriend && !isInline && D.isFunctionDefinition()) {
9502       // Pre-C++20 [class.friend]p5
9503       //   A function can be defined in a friend declaration of a
9504       //   class . . . . Such a function is implicitly inline.
9505       // Post C++20 [class.friend]p7
9506       //   Such a function is implicitly an inline function if it is attached
9507       //   to the global module.
9508       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9509     }
9510 
9511     // If this is a method defined in an __interface, and is not a constructor
9512     // or an overloaded operator, then set the pure flag (isVirtual will already
9513     // return true).
9514     if (const CXXRecordDecl *Parent =
9515           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9516       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9517         NewFD->setPure(true);
9518 
9519       // C++ [class.union]p2
9520       //   A union can have member functions, but not virtual functions.
9521       if (isVirtual && Parent->isUnion()) {
9522         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9523         NewFD->setInvalidDecl();
9524       }
9525       if ((Parent->isClass() || Parent->isStruct()) &&
9526           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9527           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9528           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9529         if (auto *Def = Parent->getDefinition())
9530           Def->setInitMethod(true);
9531       }
9532     }
9533 
9534     SetNestedNameSpecifier(*this, NewFD, D);
9535     isMemberSpecialization = false;
9536     isFunctionTemplateSpecialization = false;
9537     if (D.isInvalidType())
9538       NewFD->setInvalidDecl();
9539 
9540     // Match up the template parameter lists with the scope specifier, then
9541     // determine whether we have a template or a template specialization.
9542     bool Invalid = false;
9543     TemplateParameterList *TemplateParams =
9544         MatchTemplateParametersToScopeSpecifier(
9545             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9546             D.getCXXScopeSpec(),
9547             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9548                 ? D.getName().TemplateId
9549                 : nullptr,
9550             TemplateParamLists, isFriend, isMemberSpecialization,
9551             Invalid);
9552     if (TemplateParams) {
9553       // Check that we can declare a template here.
9554       if (CheckTemplateDeclScope(S, TemplateParams))
9555         NewFD->setInvalidDecl();
9556 
9557       if (TemplateParams->size() > 0) {
9558         // This is a function template
9559 
9560         // A destructor cannot be a template.
9561         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9562           Diag(NewFD->getLocation(), diag::err_destructor_template);
9563           NewFD->setInvalidDecl();
9564         }
9565 
9566         // If we're adding a template to a dependent context, we may need to
9567         // rebuilding some of the types used within the template parameter list,
9568         // now that we know what the current instantiation is.
9569         if (DC->isDependentContext()) {
9570           ContextRAII SavedContext(*this, DC);
9571           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9572             Invalid = true;
9573         }
9574 
9575         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9576                                                         NewFD->getLocation(),
9577                                                         Name, TemplateParams,
9578                                                         NewFD);
9579         FunctionTemplate->setLexicalDeclContext(CurContext);
9580         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9581 
9582         // For source fidelity, store the other template param lists.
9583         if (TemplateParamLists.size() > 1) {
9584           NewFD->setTemplateParameterListsInfo(Context,
9585               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9586                   .drop_back(1));
9587         }
9588       } else {
9589         // This is a function template specialization.
9590         isFunctionTemplateSpecialization = true;
9591         // For source fidelity, store all the template param lists.
9592         if (TemplateParamLists.size() > 0)
9593           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9594 
9595         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9596         if (isFriend) {
9597           // We want to remove the "template<>", found here.
9598           SourceRange RemoveRange = TemplateParams->getSourceRange();
9599 
9600           // If we remove the template<> and the name is not a
9601           // template-id, we're actually silently creating a problem:
9602           // the friend declaration will refer to an untemplated decl,
9603           // and clearly the user wants a template specialization.  So
9604           // we need to insert '<>' after the name.
9605           SourceLocation InsertLoc;
9606           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9607             InsertLoc = D.getName().getSourceRange().getEnd();
9608             InsertLoc = getLocForEndOfToken(InsertLoc);
9609           }
9610 
9611           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9612             << Name << RemoveRange
9613             << FixItHint::CreateRemoval(RemoveRange)
9614             << FixItHint::CreateInsertion(InsertLoc, "<>");
9615           Invalid = true;
9616         }
9617       }
9618     } else {
9619       // Check that we can declare a template here.
9620       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9621           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9622         NewFD->setInvalidDecl();
9623 
9624       // All template param lists were matched against the scope specifier:
9625       // this is NOT (an explicit specialization of) a template.
9626       if (TemplateParamLists.size() > 0)
9627         // For source fidelity, store all the template param lists.
9628         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9629     }
9630 
9631     if (Invalid) {
9632       NewFD->setInvalidDecl();
9633       if (FunctionTemplate)
9634         FunctionTemplate->setInvalidDecl();
9635     }
9636 
9637     // C++ [dcl.fct.spec]p5:
9638     //   The virtual specifier shall only be used in declarations of
9639     //   nonstatic class member functions that appear within a
9640     //   member-specification of a class declaration; see 10.3.
9641     //
9642     if (isVirtual && !NewFD->isInvalidDecl()) {
9643       if (!isVirtualOkay) {
9644         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9645              diag::err_virtual_non_function);
9646       } else if (!CurContext->isRecord()) {
9647         // 'virtual' was specified outside of the class.
9648         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9649              diag::err_virtual_out_of_class)
9650           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9651       } else if (NewFD->getDescribedFunctionTemplate()) {
9652         // C++ [temp.mem]p3:
9653         //  A member function template shall not be virtual.
9654         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9655              diag::err_virtual_member_function_template)
9656           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9657       } else {
9658         // Okay: Add virtual to the method.
9659         NewFD->setVirtualAsWritten(true);
9660       }
9661 
9662       if (getLangOpts().CPlusPlus14 &&
9663           NewFD->getReturnType()->isUndeducedType())
9664         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9665     }
9666 
9667     if (getLangOpts().CPlusPlus14 &&
9668         (NewFD->isDependentContext() ||
9669          (isFriend && CurContext->isDependentContext())) &&
9670         NewFD->getReturnType()->isUndeducedType()) {
9671       // If the function template is referenced directly (for instance, as a
9672       // member of the current instantiation), pretend it has a dependent type.
9673       // This is not really justified by the standard, but is the only sane
9674       // thing to do.
9675       // FIXME: For a friend function, we have not marked the function as being
9676       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9677       const FunctionProtoType *FPT =
9678           NewFD->getType()->castAs<FunctionProtoType>();
9679       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9680       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9681                                              FPT->getExtProtoInfo()));
9682     }
9683 
9684     // C++ [dcl.fct.spec]p3:
9685     //  The inline specifier shall not appear on a block scope function
9686     //  declaration.
9687     if (isInline && !NewFD->isInvalidDecl()) {
9688       if (CurContext->isFunctionOrMethod()) {
9689         // 'inline' is not allowed on block scope function declaration.
9690         Diag(D.getDeclSpec().getInlineSpecLoc(),
9691              diag::err_inline_declaration_block_scope) << Name
9692           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9693       }
9694     }
9695 
9696     // C++ [dcl.fct.spec]p6:
9697     //  The explicit specifier shall be used only in the declaration of a
9698     //  constructor or conversion function within its class definition;
9699     //  see 12.3.1 and 12.3.2.
9700     if (hasExplicit && !NewFD->isInvalidDecl() &&
9701         !isa<CXXDeductionGuideDecl>(NewFD)) {
9702       if (!CurContext->isRecord()) {
9703         // 'explicit' was specified outside of the class.
9704         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9705              diag::err_explicit_out_of_class)
9706             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9707       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9708                  !isa<CXXConversionDecl>(NewFD)) {
9709         // 'explicit' was specified on a function that wasn't a constructor
9710         // or conversion function.
9711         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9712              diag::err_explicit_non_ctor_or_conv_function)
9713             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9714       }
9715     }
9716 
9717     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9718     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9719       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9720       // are implicitly inline.
9721       NewFD->setImplicitlyInline();
9722 
9723       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9724       // be either constructors or to return a literal type. Therefore,
9725       // destructors cannot be declared constexpr.
9726       if (isa<CXXDestructorDecl>(NewFD) &&
9727           (!getLangOpts().CPlusPlus20 ||
9728            ConstexprKind == ConstexprSpecKind::Consteval)) {
9729         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9730             << static_cast<int>(ConstexprKind);
9731         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9732                                     ? ConstexprSpecKind::Unspecified
9733                                     : ConstexprSpecKind::Constexpr);
9734       }
9735       // C++20 [dcl.constexpr]p2: An allocation function, or a
9736       // deallocation function shall not be declared with the consteval
9737       // specifier.
9738       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9739           (NewFD->getOverloadedOperator() == OO_New ||
9740            NewFD->getOverloadedOperator() == OO_Array_New ||
9741            NewFD->getOverloadedOperator() == OO_Delete ||
9742            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9743         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9744              diag::err_invalid_consteval_decl_kind)
9745             << NewFD;
9746         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9747       }
9748     }
9749 
9750     // If __module_private__ was specified, mark the function accordingly.
9751     if (D.getDeclSpec().isModulePrivateSpecified()) {
9752       if (isFunctionTemplateSpecialization) {
9753         SourceLocation ModulePrivateLoc
9754           = D.getDeclSpec().getModulePrivateSpecLoc();
9755         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9756           << 0
9757           << FixItHint::CreateRemoval(ModulePrivateLoc);
9758       } else {
9759         NewFD->setModulePrivate();
9760         if (FunctionTemplate)
9761           FunctionTemplate->setModulePrivate();
9762       }
9763     }
9764 
9765     if (isFriend) {
9766       if (FunctionTemplate) {
9767         FunctionTemplate->setObjectOfFriendDecl();
9768         FunctionTemplate->setAccess(AS_public);
9769       }
9770       NewFD->setObjectOfFriendDecl();
9771       NewFD->setAccess(AS_public);
9772     }
9773 
9774     // If a function is defined as defaulted or deleted, mark it as such now.
9775     // We'll do the relevant checks on defaulted / deleted functions later.
9776     switch (D.getFunctionDefinitionKind()) {
9777     case FunctionDefinitionKind::Declaration:
9778     case FunctionDefinitionKind::Definition:
9779       break;
9780 
9781     case FunctionDefinitionKind::Defaulted:
9782       NewFD->setDefaulted();
9783       break;
9784 
9785     case FunctionDefinitionKind::Deleted:
9786       NewFD->setDeletedAsWritten();
9787       break;
9788     }
9789 
9790     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9791         D.isFunctionDefinition() && !isInline) {
9792       // Pre C++20 [class.mfct]p2:
9793       //   A member function may be defined (8.4) in its class definition, in
9794       //   which case it is an inline member function (7.1.2)
9795       // Post C++20 [class.mfct]p1:
9796       //   If a member function is attached to the global module and is defined
9797       //   in its class definition, it is inline.
9798       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9799     }
9800 
9801     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9802         !CurContext->isRecord()) {
9803       // C++ [class.static]p1:
9804       //   A data or function member of a class may be declared static
9805       //   in a class definition, in which case it is a static member of
9806       //   the class.
9807 
9808       // Complain about the 'static' specifier if it's on an out-of-line
9809       // member function definition.
9810 
9811       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9812       // member function template declaration and class member template
9813       // declaration (MSVC versions before 2015), warn about this.
9814       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9815            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9816              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9817            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9818            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9819         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9820     }
9821 
9822     // C++11 [except.spec]p15:
9823     //   A deallocation function with no exception-specification is treated
9824     //   as if it were specified with noexcept(true).
9825     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9826     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9827          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9828         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9829       NewFD->setType(Context.getFunctionType(
9830           FPT->getReturnType(), FPT->getParamTypes(),
9831           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9832   }
9833 
9834   // Filter out previous declarations that don't match the scope.
9835   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9836                        D.getCXXScopeSpec().isNotEmpty() ||
9837                        isMemberSpecialization ||
9838                        isFunctionTemplateSpecialization);
9839 
9840   // Handle GNU asm-label extension (encoded as an attribute).
9841   if (Expr *E = (Expr*) D.getAsmLabel()) {
9842     // The parser guarantees this is a string.
9843     StringLiteral *SE = cast<StringLiteral>(E);
9844     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9845                                         /*IsLiteralLabel=*/true,
9846                                         SE->getStrTokenLoc(0)));
9847   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9848     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9849       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9850     if (I != ExtnameUndeclaredIdentifiers.end()) {
9851       if (isDeclExternC(NewFD)) {
9852         NewFD->addAttr(I->second);
9853         ExtnameUndeclaredIdentifiers.erase(I);
9854       } else
9855         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9856             << /*Variable*/0 << NewFD;
9857     }
9858   }
9859 
9860   // Copy the parameter declarations from the declarator D to the function
9861   // declaration NewFD, if they are available.  First scavenge them into Params.
9862   SmallVector<ParmVarDecl*, 16> Params;
9863   unsigned FTIIdx;
9864   if (D.isFunctionDeclarator(FTIIdx)) {
9865     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9866 
9867     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9868     // function that takes no arguments, not a function that takes a
9869     // single void argument.
9870     // We let through "const void" here because Sema::GetTypeForDeclarator
9871     // already checks for that case.
9872     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9873       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9874         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9875         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9876         Param->setDeclContext(NewFD);
9877         Params.push_back(Param);
9878 
9879         if (Param->isInvalidDecl())
9880           NewFD->setInvalidDecl();
9881       }
9882     }
9883 
9884     if (!getLangOpts().CPlusPlus) {
9885       // In C, find all the tag declarations from the prototype and move them
9886       // into the function DeclContext. Remove them from the surrounding tag
9887       // injection context of the function, which is typically but not always
9888       // the TU.
9889       DeclContext *PrototypeTagContext =
9890           getTagInjectionContext(NewFD->getLexicalDeclContext());
9891       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9892         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9893 
9894         // We don't want to reparent enumerators. Look at their parent enum
9895         // instead.
9896         if (!TD) {
9897           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9898             TD = cast<EnumDecl>(ECD->getDeclContext());
9899         }
9900         if (!TD)
9901           continue;
9902         DeclContext *TagDC = TD->getLexicalDeclContext();
9903         if (!TagDC->containsDecl(TD))
9904           continue;
9905         TagDC->removeDecl(TD);
9906         TD->setDeclContext(NewFD);
9907         NewFD->addDecl(TD);
9908 
9909         // Preserve the lexical DeclContext if it is not the surrounding tag
9910         // injection context of the FD. In this example, the semantic context of
9911         // E will be f and the lexical context will be S, while both the
9912         // semantic and lexical contexts of S will be f:
9913         //   void f(struct S { enum E { a } f; } s);
9914         if (TagDC != PrototypeTagContext)
9915           TD->setLexicalDeclContext(TagDC);
9916       }
9917     }
9918   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9919     // When we're declaring a function with a typedef, typeof, etc as in the
9920     // following example, we'll need to synthesize (unnamed)
9921     // parameters for use in the declaration.
9922     //
9923     // @code
9924     // typedef void fn(int);
9925     // fn f;
9926     // @endcode
9927 
9928     // Synthesize a parameter for each argument type.
9929     for (const auto &AI : FT->param_types()) {
9930       ParmVarDecl *Param =
9931           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9932       Param->setScopeInfo(0, Params.size());
9933       Params.push_back(Param);
9934     }
9935   } else {
9936     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9937            "Should not need args for typedef of non-prototype fn");
9938   }
9939 
9940   // Finally, we know we have the right number of parameters, install them.
9941   NewFD->setParams(Params);
9942 
9943   if (D.getDeclSpec().isNoreturnSpecified())
9944     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9945                                            D.getDeclSpec().getNoreturnSpecLoc(),
9946                                            AttributeCommonInfo::AS_Keyword));
9947 
9948   // Functions returning a variably modified type violate C99 6.7.5.2p2
9949   // because all functions have linkage.
9950   if (!NewFD->isInvalidDecl() &&
9951       NewFD->getReturnType()->isVariablyModifiedType()) {
9952     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9953     NewFD->setInvalidDecl();
9954   }
9955 
9956   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9957   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9958       !NewFD->hasAttr<SectionAttr>())
9959     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9960         Context, PragmaClangTextSection.SectionName,
9961         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9962 
9963   // Apply an implicit SectionAttr if #pragma code_seg is active.
9964   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9965       !NewFD->hasAttr<SectionAttr>()) {
9966     NewFD->addAttr(SectionAttr::CreateImplicit(
9967         Context, CodeSegStack.CurrentValue->getString(),
9968         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9969         SectionAttr::Declspec_allocate));
9970     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9971                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9972                          ASTContext::PSF_Read,
9973                      NewFD))
9974       NewFD->dropAttr<SectionAttr>();
9975   }
9976 
9977   // Apply an implicit CodeSegAttr from class declspec or
9978   // apply an implicit SectionAttr from #pragma code_seg if active.
9979   if (!NewFD->hasAttr<CodeSegAttr>()) {
9980     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9981                                                                  D.isFunctionDefinition())) {
9982       NewFD->addAttr(SAttr);
9983     }
9984   }
9985 
9986   // Handle attributes.
9987   ProcessDeclAttributes(S, NewFD, D);
9988 
9989   if (getLangOpts().OpenCL) {
9990     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9991     // type declaration will generate a compilation error.
9992     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9993     if (AddressSpace != LangAS::Default) {
9994       Diag(NewFD->getLocation(),
9995            diag::err_opencl_return_value_with_address_space);
9996       NewFD->setInvalidDecl();
9997     }
9998   }
9999 
10000   if (!getLangOpts().CPlusPlus) {
10001     // Perform semantic checking on the function declaration.
10002     if (!NewFD->isInvalidDecl() && NewFD->isMain())
10003       CheckMain(NewFD, D.getDeclSpec());
10004 
10005     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10006       CheckMSVCRTEntryPoint(NewFD);
10007 
10008     if (!NewFD->isInvalidDecl())
10009       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10010                                                   isMemberSpecialization,
10011                                                   D.isFunctionDefinition()));
10012     else if (!Previous.empty())
10013       // Recover gracefully from an invalid redeclaration.
10014       D.setRedeclaration(true);
10015     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10016             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10017            "previous declaration set still overloaded");
10018 
10019     // Diagnose no-prototype function declarations with calling conventions that
10020     // don't support variadic calls. Only do this in C and do it after merging
10021     // possibly prototyped redeclarations.
10022     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10023     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10024       CallingConv CC = FT->getExtInfo().getCC();
10025       if (!supportsVariadicCall(CC)) {
10026         // Windows system headers sometimes accidentally use stdcall without
10027         // (void) parameters, so we relax this to a warning.
10028         int DiagID =
10029             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10030         Diag(NewFD->getLocation(), DiagID)
10031             << FunctionType::getNameForCallConv(CC);
10032       }
10033     }
10034 
10035    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10036        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10037      checkNonTrivialCUnion(NewFD->getReturnType(),
10038                            NewFD->getReturnTypeSourceRange().getBegin(),
10039                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10040   } else {
10041     // C++11 [replacement.functions]p3:
10042     //  The program's definitions shall not be specified as inline.
10043     //
10044     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10045     //
10046     // Suppress the diagnostic if the function is __attribute__((used)), since
10047     // that forces an external definition to be emitted.
10048     if (D.getDeclSpec().isInlineSpecified() &&
10049         NewFD->isReplaceableGlobalAllocationFunction() &&
10050         !NewFD->hasAttr<UsedAttr>())
10051       Diag(D.getDeclSpec().getInlineSpecLoc(),
10052            diag::ext_operator_new_delete_declared_inline)
10053         << NewFD->getDeclName();
10054 
10055     // If the declarator is a template-id, translate the parser's template
10056     // argument list into our AST format.
10057     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10058       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10059       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10060       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10061       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10062                                          TemplateId->NumArgs);
10063       translateTemplateArguments(TemplateArgsPtr,
10064                                  TemplateArgs);
10065 
10066       HasExplicitTemplateArgs = true;
10067 
10068       if (NewFD->isInvalidDecl()) {
10069         HasExplicitTemplateArgs = false;
10070       } else if (FunctionTemplate) {
10071         // Function template with explicit template arguments.
10072         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10073           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10074 
10075         HasExplicitTemplateArgs = false;
10076       } else {
10077         assert((isFunctionTemplateSpecialization ||
10078                 D.getDeclSpec().isFriendSpecified()) &&
10079                "should have a 'template<>' for this decl");
10080         // "friend void foo<>(int);" is an implicit specialization decl.
10081         isFunctionTemplateSpecialization = true;
10082       }
10083     } else if (isFriend && isFunctionTemplateSpecialization) {
10084       // This combination is only possible in a recovery case;  the user
10085       // wrote something like:
10086       //   template <> friend void foo(int);
10087       // which we're recovering from as if the user had written:
10088       //   friend void foo<>(int);
10089       // Go ahead and fake up a template id.
10090       HasExplicitTemplateArgs = true;
10091       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10092       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10093     }
10094 
10095     // We do not add HD attributes to specializations here because
10096     // they may have different constexpr-ness compared to their
10097     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10098     // may end up with different effective targets. Instead, a
10099     // specialization inherits its target attributes from its template
10100     // in the CheckFunctionTemplateSpecialization() call below.
10101     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10102       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10103 
10104     // If it's a friend (and only if it's a friend), it's possible
10105     // that either the specialized function type or the specialized
10106     // template is dependent, and therefore matching will fail.  In
10107     // this case, don't check the specialization yet.
10108     if (isFunctionTemplateSpecialization && isFriend &&
10109         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10110          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10111              TemplateArgs.arguments()))) {
10112       assert(HasExplicitTemplateArgs &&
10113              "friend function specialization without template args");
10114       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10115                                                        Previous))
10116         NewFD->setInvalidDecl();
10117     } else if (isFunctionTemplateSpecialization) {
10118       if (CurContext->isDependentContext() && CurContext->isRecord()
10119           && !isFriend) {
10120         isDependentClassScopeExplicitSpecialization = true;
10121       } else if (!NewFD->isInvalidDecl() &&
10122                  CheckFunctionTemplateSpecialization(
10123                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10124                      Previous))
10125         NewFD->setInvalidDecl();
10126 
10127       // C++ [dcl.stc]p1:
10128       //   A storage-class-specifier shall not be specified in an explicit
10129       //   specialization (14.7.3)
10130       FunctionTemplateSpecializationInfo *Info =
10131           NewFD->getTemplateSpecializationInfo();
10132       if (Info && SC != SC_None) {
10133         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10134           Diag(NewFD->getLocation(),
10135                diag::err_explicit_specialization_inconsistent_storage_class)
10136             << SC
10137             << FixItHint::CreateRemoval(
10138                                       D.getDeclSpec().getStorageClassSpecLoc());
10139 
10140         else
10141           Diag(NewFD->getLocation(),
10142                diag::ext_explicit_specialization_storage_class)
10143             << FixItHint::CreateRemoval(
10144                                       D.getDeclSpec().getStorageClassSpecLoc());
10145       }
10146     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10147       if (CheckMemberSpecialization(NewFD, Previous))
10148           NewFD->setInvalidDecl();
10149     }
10150 
10151     // Perform semantic checking on the function declaration.
10152     if (!isDependentClassScopeExplicitSpecialization) {
10153       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10154         CheckMain(NewFD, D.getDeclSpec());
10155 
10156       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10157         CheckMSVCRTEntryPoint(NewFD);
10158 
10159       if (!NewFD->isInvalidDecl())
10160         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10161                                                     isMemberSpecialization,
10162                                                     D.isFunctionDefinition()));
10163       else if (!Previous.empty())
10164         // Recover gracefully from an invalid redeclaration.
10165         D.setRedeclaration(true);
10166     }
10167 
10168     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10169             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10170            "previous declaration set still overloaded");
10171 
10172     NamedDecl *PrincipalDecl = (FunctionTemplate
10173                                 ? cast<NamedDecl>(FunctionTemplate)
10174                                 : NewFD);
10175 
10176     if (isFriend && NewFD->getPreviousDecl()) {
10177       AccessSpecifier Access = AS_public;
10178       if (!NewFD->isInvalidDecl())
10179         Access = NewFD->getPreviousDecl()->getAccess();
10180 
10181       NewFD->setAccess(Access);
10182       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10183     }
10184 
10185     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10186         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10187       PrincipalDecl->setNonMemberOperator();
10188 
10189     // If we have a function template, check the template parameter
10190     // list. This will check and merge default template arguments.
10191     if (FunctionTemplate) {
10192       FunctionTemplateDecl *PrevTemplate =
10193                                      FunctionTemplate->getPreviousDecl();
10194       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10195                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10196                                     : nullptr,
10197                             D.getDeclSpec().isFriendSpecified()
10198                               ? (D.isFunctionDefinition()
10199                                    ? TPC_FriendFunctionTemplateDefinition
10200                                    : TPC_FriendFunctionTemplate)
10201                               : (D.getCXXScopeSpec().isSet() &&
10202                                  DC && DC->isRecord() &&
10203                                  DC->isDependentContext())
10204                                   ? TPC_ClassTemplateMember
10205                                   : TPC_FunctionTemplate);
10206     }
10207 
10208     if (NewFD->isInvalidDecl()) {
10209       // Ignore all the rest of this.
10210     } else if (!D.isRedeclaration()) {
10211       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10212                                        AddToScope };
10213       // Fake up an access specifier if it's supposed to be a class member.
10214       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10215         NewFD->setAccess(AS_public);
10216 
10217       // Qualified decls generally require a previous declaration.
10218       if (D.getCXXScopeSpec().isSet()) {
10219         // ...with the major exception of templated-scope or
10220         // dependent-scope friend declarations.
10221 
10222         // TODO: we currently also suppress this check in dependent
10223         // contexts because (1) the parameter depth will be off when
10224         // matching friend templates and (2) we might actually be
10225         // selecting a friend based on a dependent factor.  But there
10226         // are situations where these conditions don't apply and we
10227         // can actually do this check immediately.
10228         //
10229         // Unless the scope is dependent, it's always an error if qualified
10230         // redeclaration lookup found nothing at all. Diagnose that now;
10231         // nothing will diagnose that error later.
10232         if (isFriend &&
10233             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10234              (!Previous.empty() && CurContext->isDependentContext()))) {
10235           // ignore these
10236         } else if (NewFD->isCPUDispatchMultiVersion() ||
10237                    NewFD->isCPUSpecificMultiVersion()) {
10238           // ignore this, we allow the redeclaration behavior here to create new
10239           // versions of the function.
10240         } else {
10241           // The user tried to provide an out-of-line definition for a
10242           // function that is a member of a class or namespace, but there
10243           // was no such member function declared (C++ [class.mfct]p2,
10244           // C++ [namespace.memdef]p2). For example:
10245           //
10246           // class X {
10247           //   void f() const;
10248           // };
10249           //
10250           // void X::f() { } // ill-formed
10251           //
10252           // Complain about this problem, and attempt to suggest close
10253           // matches (e.g., those that differ only in cv-qualifiers and
10254           // whether the parameter types are references).
10255 
10256           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10257                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10258             AddToScope = ExtraArgs.AddToScope;
10259             return Result;
10260           }
10261         }
10262 
10263         // Unqualified local friend declarations are required to resolve
10264         // to something.
10265       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10266         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10267                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10268           AddToScope = ExtraArgs.AddToScope;
10269           return Result;
10270         }
10271       }
10272     } else if (!D.isFunctionDefinition() &&
10273                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10274                !isFriend && !isFunctionTemplateSpecialization &&
10275                !isMemberSpecialization) {
10276       // An out-of-line member function declaration must also be a
10277       // definition (C++ [class.mfct]p2).
10278       // Note that this is not the case for explicit specializations of
10279       // function templates or member functions of class templates, per
10280       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10281       // extension for compatibility with old SWIG code which likes to
10282       // generate them.
10283       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10284         << D.getCXXScopeSpec().getRange();
10285     }
10286   }
10287 
10288   // If this is the first declaration of a library builtin function, add
10289   // attributes as appropriate.
10290   if (!D.isRedeclaration()) {
10291     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10292       if (unsigned BuiltinID = II->getBuiltinID()) {
10293         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10294         if (!InStdNamespace &&
10295             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10296           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10297             // Validate the type matches unless this builtin is specified as
10298             // matching regardless of its declared type.
10299             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10300               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10301             } else {
10302               ASTContext::GetBuiltinTypeError Error;
10303               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10304               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10305 
10306               if (!Error && !BuiltinType.isNull() &&
10307                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10308                       NewFD->getType(), BuiltinType))
10309                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10310             }
10311           }
10312         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10313                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10314           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10315         }
10316       }
10317     }
10318   }
10319 
10320   ProcessPragmaWeak(S, NewFD);
10321   checkAttributesAfterMerging(*this, *NewFD);
10322 
10323   AddKnownFunctionAttributes(NewFD);
10324 
10325   if (NewFD->hasAttr<OverloadableAttr>() &&
10326       !NewFD->getType()->getAs<FunctionProtoType>()) {
10327     Diag(NewFD->getLocation(),
10328          diag::err_attribute_overloadable_no_prototype)
10329       << NewFD;
10330 
10331     // Turn this into a variadic function with no parameters.
10332     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10333     FunctionProtoType::ExtProtoInfo EPI(
10334         Context.getDefaultCallingConvention(true, false));
10335     EPI.Variadic = true;
10336     EPI.ExtInfo = FT->getExtInfo();
10337 
10338     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10339     NewFD->setType(R);
10340   }
10341 
10342   // If there's a #pragma GCC visibility in scope, and this isn't a class
10343   // member, set the visibility of this function.
10344   if (!DC->isRecord() && NewFD->isExternallyVisible())
10345     AddPushedVisibilityAttribute(NewFD);
10346 
10347   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10348   // marking the function.
10349   AddCFAuditedAttribute(NewFD);
10350 
10351   // If this is a function definition, check if we have to apply any
10352   // attributes (i.e. optnone and no_builtin) due to a pragma.
10353   if (D.isFunctionDefinition()) {
10354     AddRangeBasedOptnone(NewFD);
10355     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10356     AddSectionMSAllocText(NewFD);
10357     ModifyFnAttributesMSPragmaOptimize(NewFD);
10358   }
10359 
10360   // If this is the first declaration of an extern C variable, update
10361   // the map of such variables.
10362   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10363       isIncompleteDeclExternC(*this, NewFD))
10364     RegisterLocallyScopedExternCDecl(NewFD, S);
10365 
10366   // Set this FunctionDecl's range up to the right paren.
10367   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10368 
10369   if (D.isRedeclaration() && !Previous.empty()) {
10370     NamedDecl *Prev = Previous.getRepresentativeDecl();
10371     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10372                                    isMemberSpecialization ||
10373                                        isFunctionTemplateSpecialization,
10374                                    D.isFunctionDefinition());
10375   }
10376 
10377   if (getLangOpts().CUDA) {
10378     IdentifierInfo *II = NewFD->getIdentifier();
10379     if (II && II->isStr(getCudaConfigureFuncName()) &&
10380         !NewFD->isInvalidDecl() &&
10381         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10382       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10383         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10384             << getCudaConfigureFuncName();
10385       Context.setcudaConfigureCallDecl(NewFD);
10386     }
10387 
10388     // Variadic functions, other than a *declaration* of printf, are not allowed
10389     // in device-side CUDA code, unless someone passed
10390     // -fcuda-allow-variadic-functions.
10391     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10392         (NewFD->hasAttr<CUDADeviceAttr>() ||
10393          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10394         !(II && II->isStr("printf") && NewFD->isExternC() &&
10395           !D.isFunctionDefinition())) {
10396       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10397     }
10398   }
10399 
10400   MarkUnusedFileScopedDecl(NewFD);
10401 
10402 
10403 
10404   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10405     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10406     if (SC == SC_Static) {
10407       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10408       D.setInvalidType();
10409     }
10410 
10411     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10412     if (!NewFD->getReturnType()->isVoidType()) {
10413       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10414       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10415           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10416                                 : FixItHint());
10417       D.setInvalidType();
10418     }
10419 
10420     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10421     for (auto Param : NewFD->parameters())
10422       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10423 
10424     if (getLangOpts().OpenCLCPlusPlus) {
10425       if (DC->isRecord()) {
10426         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10427         D.setInvalidType();
10428       }
10429       if (FunctionTemplate) {
10430         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10431         D.setInvalidType();
10432       }
10433     }
10434   }
10435 
10436   if (getLangOpts().CPlusPlus) {
10437     if (FunctionTemplate) {
10438       if (NewFD->isInvalidDecl())
10439         FunctionTemplate->setInvalidDecl();
10440       return FunctionTemplate;
10441     }
10442 
10443     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10444       CompleteMemberSpecialization(NewFD, Previous);
10445   }
10446 
10447   for (const ParmVarDecl *Param : NewFD->parameters()) {
10448     QualType PT = Param->getType();
10449 
10450     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10451     // types.
10452     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10453       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10454         QualType ElemTy = PipeTy->getElementType();
10455           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10456             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10457             D.setInvalidType();
10458           }
10459       }
10460     }
10461   }
10462 
10463   // Here we have an function template explicit specialization at class scope.
10464   // The actual specialization will be postponed to template instatiation
10465   // time via the ClassScopeFunctionSpecializationDecl node.
10466   if (isDependentClassScopeExplicitSpecialization) {
10467     ClassScopeFunctionSpecializationDecl *NewSpec =
10468                          ClassScopeFunctionSpecializationDecl::Create(
10469                                 Context, CurContext, NewFD->getLocation(),
10470                                 cast<CXXMethodDecl>(NewFD),
10471                                 HasExplicitTemplateArgs, TemplateArgs);
10472     CurContext->addDecl(NewSpec);
10473     AddToScope = false;
10474   }
10475 
10476   // Diagnose availability attributes. Availability cannot be used on functions
10477   // that are run during load/unload.
10478   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10479     if (NewFD->hasAttr<ConstructorAttr>()) {
10480       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10481           << 1;
10482       NewFD->dropAttr<AvailabilityAttr>();
10483     }
10484     if (NewFD->hasAttr<DestructorAttr>()) {
10485       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10486           << 2;
10487       NewFD->dropAttr<AvailabilityAttr>();
10488     }
10489   }
10490 
10491   // Diagnose no_builtin attribute on function declaration that are not a
10492   // definition.
10493   // FIXME: We should really be doing this in
10494   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10495   // the FunctionDecl and at this point of the code
10496   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10497   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10498   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10499     switch (D.getFunctionDefinitionKind()) {
10500     case FunctionDefinitionKind::Defaulted:
10501     case FunctionDefinitionKind::Deleted:
10502       Diag(NBA->getLocation(),
10503            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10504           << NBA->getSpelling();
10505       break;
10506     case FunctionDefinitionKind::Declaration:
10507       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10508           << NBA->getSpelling();
10509       break;
10510     case FunctionDefinitionKind::Definition:
10511       break;
10512     }
10513 
10514   return NewFD;
10515 }
10516 
10517 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10518 /// when __declspec(code_seg) "is applied to a class, all member functions of
10519 /// the class and nested classes -- this includes compiler-generated special
10520 /// member functions -- are put in the specified segment."
10521 /// The actual behavior is a little more complicated. The Microsoft compiler
10522 /// won't check outer classes if there is an active value from #pragma code_seg.
10523 /// The CodeSeg is always applied from the direct parent but only from outer
10524 /// classes when the #pragma code_seg stack is empty. See:
10525 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10526 /// available since MS has removed the page.
10527 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10528   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10529   if (!Method)
10530     return nullptr;
10531   const CXXRecordDecl *Parent = Method->getParent();
10532   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10533     Attr *NewAttr = SAttr->clone(S.getASTContext());
10534     NewAttr->setImplicit(true);
10535     return NewAttr;
10536   }
10537 
10538   // The Microsoft compiler won't check outer classes for the CodeSeg
10539   // when the #pragma code_seg stack is active.
10540   if (S.CodeSegStack.CurrentValue)
10541    return nullptr;
10542 
10543   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10544     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10545       Attr *NewAttr = SAttr->clone(S.getASTContext());
10546       NewAttr->setImplicit(true);
10547       return NewAttr;
10548     }
10549   }
10550   return nullptr;
10551 }
10552 
10553 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10554 /// containing class. Otherwise it will return implicit SectionAttr if the
10555 /// function is a definition and there is an active value on CodeSegStack
10556 /// (from the current #pragma code-seg value).
10557 ///
10558 /// \param FD Function being declared.
10559 /// \param IsDefinition Whether it is a definition or just a declarartion.
10560 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10561 ///          nullptr if no attribute should be added.
10562 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10563                                                        bool IsDefinition) {
10564   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10565     return A;
10566   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10567       CodeSegStack.CurrentValue)
10568     return SectionAttr::CreateImplicit(
10569         getASTContext(), CodeSegStack.CurrentValue->getString(),
10570         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10571         SectionAttr::Declspec_allocate);
10572   return nullptr;
10573 }
10574 
10575 /// Determines if we can perform a correct type check for \p D as a
10576 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10577 /// best-effort check.
10578 ///
10579 /// \param NewD The new declaration.
10580 /// \param OldD The old declaration.
10581 /// \param NewT The portion of the type of the new declaration to check.
10582 /// \param OldT The portion of the type of the old declaration to check.
10583 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10584                                           QualType NewT, QualType OldT) {
10585   if (!NewD->getLexicalDeclContext()->isDependentContext())
10586     return true;
10587 
10588   // For dependently-typed local extern declarations and friends, we can't
10589   // perform a correct type check in general until instantiation:
10590   //
10591   //   int f();
10592   //   template<typename T> void g() { T f(); }
10593   //
10594   // (valid if g() is only instantiated with T = int).
10595   if (NewT->isDependentType() &&
10596       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10597     return false;
10598 
10599   // Similarly, if the previous declaration was a dependent local extern
10600   // declaration, we don't really know its type yet.
10601   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10602     return false;
10603 
10604   return true;
10605 }
10606 
10607 /// Checks if the new declaration declared in dependent context must be
10608 /// put in the same redeclaration chain as the specified declaration.
10609 ///
10610 /// \param D Declaration that is checked.
10611 /// \param PrevDecl Previous declaration found with proper lookup method for the
10612 ///                 same declaration name.
10613 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10614 ///          belongs to.
10615 ///
10616 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10617   if (!D->getLexicalDeclContext()->isDependentContext())
10618     return true;
10619 
10620   // Don't chain dependent friend function definitions until instantiation, to
10621   // permit cases like
10622   //
10623   //   void func();
10624   //   template<typename T> class C1 { friend void func() {} };
10625   //   template<typename T> class C2 { friend void func() {} };
10626   //
10627   // ... which is valid if only one of C1 and C2 is ever instantiated.
10628   //
10629   // FIXME: This need only apply to function definitions. For now, we proxy
10630   // this by checking for a file-scope function. We do not want this to apply
10631   // to friend declarations nominating member functions, because that gets in
10632   // the way of access checks.
10633   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10634     return false;
10635 
10636   auto *VD = dyn_cast<ValueDecl>(D);
10637   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10638   return !VD || !PrevVD ||
10639          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10640                                         PrevVD->getType());
10641 }
10642 
10643 /// Check the target attribute of the function for MultiVersion
10644 /// validity.
10645 ///
10646 /// Returns true if there was an error, false otherwise.
10647 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10648   const auto *TA = FD->getAttr<TargetAttr>();
10649   assert(TA && "MultiVersion Candidate requires a target attribute");
10650   ParsedTargetAttr ParseInfo = TA->parse();
10651   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10652   enum ErrType { Feature = 0, Architecture = 1 };
10653 
10654   if (!ParseInfo.Architecture.empty() &&
10655       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10656     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10657         << Architecture << ParseInfo.Architecture;
10658     return true;
10659   }
10660 
10661   for (const auto &Feat : ParseInfo.Features) {
10662     auto BareFeat = StringRef{Feat}.substr(1);
10663     if (Feat[0] == '-') {
10664       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10665           << Feature << ("no-" + BareFeat).str();
10666       return true;
10667     }
10668 
10669     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10670         !TargetInfo.isValidFeatureName(BareFeat)) {
10671       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10672           << Feature << BareFeat;
10673       return true;
10674     }
10675   }
10676   return false;
10677 }
10678 
10679 // Provide a white-list of attributes that are allowed to be combined with
10680 // multiversion functions.
10681 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10682                                            MultiVersionKind MVKind) {
10683   // Note: this list/diagnosis must match the list in
10684   // checkMultiversionAttributesAllSame.
10685   switch (Kind) {
10686   default:
10687     return false;
10688   case attr::Used:
10689     return MVKind == MultiVersionKind::Target;
10690   case attr::NonNull:
10691   case attr::NoThrow:
10692     return true;
10693   }
10694 }
10695 
10696 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10697                                                  const FunctionDecl *FD,
10698                                                  const FunctionDecl *CausedFD,
10699                                                  MultiVersionKind MVKind) {
10700   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10701     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10702         << static_cast<unsigned>(MVKind) << A;
10703     if (CausedFD)
10704       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10705     return true;
10706   };
10707 
10708   for (const Attr *A : FD->attrs()) {
10709     switch (A->getKind()) {
10710     case attr::CPUDispatch:
10711     case attr::CPUSpecific:
10712       if (MVKind != MultiVersionKind::CPUDispatch &&
10713           MVKind != MultiVersionKind::CPUSpecific)
10714         return Diagnose(S, A);
10715       break;
10716     case attr::Target:
10717       if (MVKind != MultiVersionKind::Target)
10718         return Diagnose(S, A);
10719       break;
10720     case attr::TargetClones:
10721       if (MVKind != MultiVersionKind::TargetClones)
10722         return Diagnose(S, A);
10723       break;
10724     default:
10725       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10726         return Diagnose(S, A);
10727       break;
10728     }
10729   }
10730   return false;
10731 }
10732 
10733 bool Sema::areMultiversionVariantFunctionsCompatible(
10734     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10735     const PartialDiagnostic &NoProtoDiagID,
10736     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10737     const PartialDiagnosticAt &NoSupportDiagIDAt,
10738     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10739     bool ConstexprSupported, bool CLinkageMayDiffer) {
10740   enum DoesntSupport {
10741     FuncTemplates = 0,
10742     VirtFuncs = 1,
10743     DeducedReturn = 2,
10744     Constructors = 3,
10745     Destructors = 4,
10746     DeletedFuncs = 5,
10747     DefaultedFuncs = 6,
10748     ConstexprFuncs = 7,
10749     ConstevalFuncs = 8,
10750     Lambda = 9,
10751   };
10752   enum Different {
10753     CallingConv = 0,
10754     ReturnType = 1,
10755     ConstexprSpec = 2,
10756     InlineSpec = 3,
10757     Linkage = 4,
10758     LanguageLinkage = 5,
10759   };
10760 
10761   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10762       !OldFD->getType()->getAs<FunctionProtoType>()) {
10763     Diag(OldFD->getLocation(), NoProtoDiagID);
10764     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10765     return true;
10766   }
10767 
10768   if (NoProtoDiagID.getDiagID() != 0 &&
10769       !NewFD->getType()->getAs<FunctionProtoType>())
10770     return Diag(NewFD->getLocation(), NoProtoDiagID);
10771 
10772   if (!TemplatesSupported &&
10773       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10774     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10775            << FuncTemplates;
10776 
10777   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10778     if (NewCXXFD->isVirtual())
10779       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10780              << VirtFuncs;
10781 
10782     if (isa<CXXConstructorDecl>(NewCXXFD))
10783       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10784              << Constructors;
10785 
10786     if (isa<CXXDestructorDecl>(NewCXXFD))
10787       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10788              << Destructors;
10789   }
10790 
10791   if (NewFD->isDeleted())
10792     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10793            << DeletedFuncs;
10794 
10795   if (NewFD->isDefaulted())
10796     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10797            << DefaultedFuncs;
10798 
10799   if (!ConstexprSupported && NewFD->isConstexpr())
10800     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10801            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10802 
10803   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10804   const auto *NewType = cast<FunctionType>(NewQType);
10805   QualType NewReturnType = NewType->getReturnType();
10806 
10807   if (NewReturnType->isUndeducedType())
10808     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10809            << DeducedReturn;
10810 
10811   // Ensure the return type is identical.
10812   if (OldFD) {
10813     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10814     const auto *OldType = cast<FunctionType>(OldQType);
10815     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10816     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10817 
10818     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10819       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10820 
10821     QualType OldReturnType = OldType->getReturnType();
10822 
10823     if (OldReturnType != NewReturnType)
10824       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10825 
10826     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10827       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10828 
10829     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10830       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10831 
10832     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10833       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10834 
10835     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10836       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10837 
10838     if (CheckEquivalentExceptionSpec(
10839             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10840             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10841       return true;
10842   }
10843   return false;
10844 }
10845 
10846 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10847                                              const FunctionDecl *NewFD,
10848                                              bool CausesMV,
10849                                              MultiVersionKind MVKind) {
10850   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10851     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10852     if (OldFD)
10853       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10854     return true;
10855   }
10856 
10857   bool IsCPUSpecificCPUDispatchMVKind =
10858       MVKind == MultiVersionKind::CPUDispatch ||
10859       MVKind == MultiVersionKind::CPUSpecific;
10860 
10861   if (CausesMV && OldFD &&
10862       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10863     return true;
10864 
10865   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10866     return true;
10867 
10868   // Only allow transition to MultiVersion if it hasn't been used.
10869   if (OldFD && CausesMV && OldFD->isUsed(false))
10870     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10871 
10872   return S.areMultiversionVariantFunctionsCompatible(
10873       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10874       PartialDiagnosticAt(NewFD->getLocation(),
10875                           S.PDiag(diag::note_multiversioning_caused_here)),
10876       PartialDiagnosticAt(NewFD->getLocation(),
10877                           S.PDiag(diag::err_multiversion_doesnt_support)
10878                               << static_cast<unsigned>(MVKind)),
10879       PartialDiagnosticAt(NewFD->getLocation(),
10880                           S.PDiag(diag::err_multiversion_diff)),
10881       /*TemplatesSupported=*/false,
10882       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10883       /*CLinkageMayDiffer=*/false);
10884 }
10885 
10886 /// Check the validity of a multiversion function declaration that is the
10887 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10888 ///
10889 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10890 ///
10891 /// Returns true if there was an error, false otherwise.
10892 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10893                                            MultiVersionKind MVKind,
10894                                            const TargetAttr *TA) {
10895   assert(MVKind != MultiVersionKind::None &&
10896          "Function lacks multiversion attribute");
10897 
10898   // Target only causes MV if it is default, otherwise this is a normal
10899   // function.
10900   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10901     return false;
10902 
10903   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10904     FD->setInvalidDecl();
10905     return true;
10906   }
10907 
10908   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10909     FD->setInvalidDecl();
10910     return true;
10911   }
10912 
10913   FD->setIsMultiVersion();
10914   return false;
10915 }
10916 
10917 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10918   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10919     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10920       return true;
10921   }
10922 
10923   return false;
10924 }
10925 
10926 static bool CheckTargetCausesMultiVersioning(
10927     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10928     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10929   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10930   ParsedTargetAttr NewParsed = NewTA->parse();
10931   // Sort order doesn't matter, it just needs to be consistent.
10932   llvm::sort(NewParsed.Features);
10933 
10934   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10935   // to change, this is a simple redeclaration.
10936   if (!NewTA->isDefaultVersion() &&
10937       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10938     return false;
10939 
10940   // Otherwise, this decl causes MultiVersioning.
10941   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10942                                        MultiVersionKind::Target)) {
10943     NewFD->setInvalidDecl();
10944     return true;
10945   }
10946 
10947   if (CheckMultiVersionValue(S, NewFD)) {
10948     NewFD->setInvalidDecl();
10949     return true;
10950   }
10951 
10952   // If this is 'default', permit the forward declaration.
10953   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10954     Redeclaration = true;
10955     OldDecl = OldFD;
10956     OldFD->setIsMultiVersion();
10957     NewFD->setIsMultiVersion();
10958     return false;
10959   }
10960 
10961   if (CheckMultiVersionValue(S, OldFD)) {
10962     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10963     NewFD->setInvalidDecl();
10964     return true;
10965   }
10966 
10967   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10968 
10969   if (OldParsed == NewParsed) {
10970     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10971     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10972     NewFD->setInvalidDecl();
10973     return true;
10974   }
10975 
10976   for (const auto *FD : OldFD->redecls()) {
10977     const auto *CurTA = FD->getAttr<TargetAttr>();
10978     // We allow forward declarations before ANY multiversioning attributes, but
10979     // nothing after the fact.
10980     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10981         (!CurTA || CurTA->isInherited())) {
10982       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10983           << 0;
10984       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10985       NewFD->setInvalidDecl();
10986       return true;
10987     }
10988   }
10989 
10990   OldFD->setIsMultiVersion();
10991   NewFD->setIsMultiVersion();
10992   Redeclaration = false;
10993   OldDecl = nullptr;
10994   Previous.clear();
10995   return false;
10996 }
10997 
10998 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10999                                         MultiVersionKind New) {
11000   if (Old == New || Old == MultiVersionKind::None ||
11001       New == MultiVersionKind::None)
11002     return true;
11003 
11004   return (Old == MultiVersionKind::CPUDispatch &&
11005           New == MultiVersionKind::CPUSpecific) ||
11006          (Old == MultiVersionKind::CPUSpecific &&
11007           New == MultiVersionKind::CPUDispatch);
11008 }
11009 
11010 /// Check the validity of a new function declaration being added to an existing
11011 /// multiversioned declaration collection.
11012 static bool CheckMultiVersionAdditionalDecl(
11013     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11014     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
11015     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11016     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11017     LookupResult &Previous) {
11018 
11019   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11020   // Disallow mixing of multiversioning types.
11021   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11022     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11023     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11024     NewFD->setInvalidDecl();
11025     return true;
11026   }
11027 
11028   ParsedTargetAttr NewParsed;
11029   if (NewTA) {
11030     NewParsed = NewTA->parse();
11031     llvm::sort(NewParsed.Features);
11032   }
11033 
11034   bool UseMemberUsingDeclRules =
11035       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11036 
11037   bool MayNeedOverloadableChecks =
11038       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11039 
11040   // Next, check ALL non-overloads to see if this is a redeclaration of a
11041   // previous member of the MultiVersion set.
11042   for (NamedDecl *ND : Previous) {
11043     FunctionDecl *CurFD = ND->getAsFunction();
11044     if (!CurFD)
11045       continue;
11046     if (MayNeedOverloadableChecks &&
11047         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11048       continue;
11049 
11050     switch (NewMVKind) {
11051     case MultiVersionKind::None:
11052       assert(OldMVKind == MultiVersionKind::TargetClones &&
11053              "Only target_clones can be omitted in subsequent declarations");
11054       break;
11055     case MultiVersionKind::Target: {
11056       const auto *CurTA = CurFD->getAttr<TargetAttr>();
11057       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11058         NewFD->setIsMultiVersion();
11059         Redeclaration = true;
11060         OldDecl = ND;
11061         return false;
11062       }
11063 
11064       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
11065       if (CurParsed == NewParsed) {
11066         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11067         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11068         NewFD->setInvalidDecl();
11069         return true;
11070       }
11071       break;
11072     }
11073     case MultiVersionKind::TargetClones: {
11074       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11075       Redeclaration = true;
11076       OldDecl = CurFD;
11077       NewFD->setIsMultiVersion();
11078 
11079       if (CurClones && NewClones &&
11080           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11081            !std::equal(CurClones->featuresStrs_begin(),
11082                        CurClones->featuresStrs_end(),
11083                        NewClones->featuresStrs_begin()))) {
11084         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11085         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11086         NewFD->setInvalidDecl();
11087         return true;
11088       }
11089 
11090       return false;
11091     }
11092     case MultiVersionKind::CPUSpecific:
11093     case MultiVersionKind::CPUDispatch: {
11094       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11095       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11096       // Handle CPUDispatch/CPUSpecific versions.
11097       // Only 1 CPUDispatch function is allowed, this will make it go through
11098       // the redeclaration errors.
11099       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11100           CurFD->hasAttr<CPUDispatchAttr>()) {
11101         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11102             std::equal(
11103                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11104                 NewCPUDisp->cpus_begin(),
11105                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11106                   return Cur->getName() == New->getName();
11107                 })) {
11108           NewFD->setIsMultiVersion();
11109           Redeclaration = true;
11110           OldDecl = ND;
11111           return false;
11112         }
11113 
11114         // If the declarations don't match, this is an error condition.
11115         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11116         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11117         NewFD->setInvalidDecl();
11118         return true;
11119       }
11120       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11121         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11122             std::equal(
11123                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11124                 NewCPUSpec->cpus_begin(),
11125                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11126                   return Cur->getName() == New->getName();
11127                 })) {
11128           NewFD->setIsMultiVersion();
11129           Redeclaration = true;
11130           OldDecl = ND;
11131           return false;
11132         }
11133 
11134         // Only 1 version of CPUSpecific is allowed for each CPU.
11135         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11136           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11137             if (CurII == NewII) {
11138               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11139                   << NewII;
11140               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11141               NewFD->setInvalidDecl();
11142               return true;
11143             }
11144           }
11145         }
11146       }
11147       break;
11148     }
11149     }
11150   }
11151 
11152   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11153   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11154   // handled in the attribute adding step.
11155   if (NewMVKind == MultiVersionKind::Target &&
11156       CheckMultiVersionValue(S, NewFD)) {
11157     NewFD->setInvalidDecl();
11158     return true;
11159   }
11160 
11161   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11162                                        !OldFD->isMultiVersion(), NewMVKind)) {
11163     NewFD->setInvalidDecl();
11164     return true;
11165   }
11166 
11167   // Permit forward declarations in the case where these two are compatible.
11168   if (!OldFD->isMultiVersion()) {
11169     OldFD->setIsMultiVersion();
11170     NewFD->setIsMultiVersion();
11171     Redeclaration = true;
11172     OldDecl = OldFD;
11173     return false;
11174   }
11175 
11176   NewFD->setIsMultiVersion();
11177   Redeclaration = false;
11178   OldDecl = nullptr;
11179   Previous.clear();
11180   return false;
11181 }
11182 
11183 /// Check the validity of a mulitversion function declaration.
11184 /// Also sets the multiversion'ness' of the function itself.
11185 ///
11186 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11187 ///
11188 /// Returns true if there was an error, false otherwise.
11189 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11190                                       bool &Redeclaration, NamedDecl *&OldDecl,
11191                                       LookupResult &Previous) {
11192   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11193   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11194   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11195   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11196   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11197 
11198   // Main isn't allowed to become a multiversion function, however it IS
11199   // permitted to have 'main' be marked with the 'target' optimization hint.
11200   if (NewFD->isMain()) {
11201     if (MVKind != MultiVersionKind::None &&
11202         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11203       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11204       NewFD->setInvalidDecl();
11205       return true;
11206     }
11207     return false;
11208   }
11209 
11210   if (!OldDecl || !OldDecl->getAsFunction() ||
11211       OldDecl->getDeclContext()->getRedeclContext() !=
11212           NewFD->getDeclContext()->getRedeclContext()) {
11213     // If there's no previous declaration, AND this isn't attempting to cause
11214     // multiversioning, this isn't an error condition.
11215     if (MVKind == MultiVersionKind::None)
11216       return false;
11217     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11218   }
11219 
11220   FunctionDecl *OldFD = OldDecl->getAsFunction();
11221 
11222   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11223     return false;
11224 
11225   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11226   // for target_clones.
11227   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11228       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11229     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11230         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11231     NewFD->setInvalidDecl();
11232     return true;
11233   }
11234 
11235   if (!OldFD->isMultiVersion()) {
11236     switch (MVKind) {
11237     case MultiVersionKind::Target:
11238       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11239                                               Redeclaration, OldDecl, Previous);
11240     case MultiVersionKind::TargetClones:
11241       if (OldFD->isUsed(false)) {
11242         NewFD->setInvalidDecl();
11243         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11244       }
11245       OldFD->setIsMultiVersion();
11246       break;
11247     case MultiVersionKind::CPUDispatch:
11248     case MultiVersionKind::CPUSpecific:
11249     case MultiVersionKind::None:
11250       break;
11251     }
11252   }
11253 
11254   // At this point, we have a multiversion function decl (in OldFD) AND an
11255   // appropriate attribute in the current function decl.  Resolve that these are
11256   // still compatible with previous declarations.
11257   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11258                                          NewCPUDisp, NewCPUSpec, NewClones,
11259                                          Redeclaration, OldDecl, Previous);
11260 }
11261 
11262 /// Perform semantic checking of a new function declaration.
11263 ///
11264 /// Performs semantic analysis of the new function declaration
11265 /// NewFD. This routine performs all semantic checking that does not
11266 /// require the actual declarator involved in the declaration, and is
11267 /// used both for the declaration of functions as they are parsed
11268 /// (called via ActOnDeclarator) and for the declaration of functions
11269 /// that have been instantiated via C++ template instantiation (called
11270 /// via InstantiateDecl).
11271 ///
11272 /// \param IsMemberSpecialization whether this new function declaration is
11273 /// a member specialization (that replaces any definition provided by the
11274 /// previous declaration).
11275 ///
11276 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11277 ///
11278 /// \returns true if the function declaration is a redeclaration.
11279 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11280                                     LookupResult &Previous,
11281                                     bool IsMemberSpecialization,
11282                                     bool DeclIsDefn) {
11283   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11284          "Variably modified return types are not handled here");
11285 
11286   // Determine whether the type of this function should be merged with
11287   // a previous visible declaration. This never happens for functions in C++,
11288   // and always happens in C if the previous declaration was visible.
11289   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11290                                !Previous.isShadowed();
11291 
11292   bool Redeclaration = false;
11293   NamedDecl *OldDecl = nullptr;
11294   bool MayNeedOverloadableChecks = false;
11295 
11296   // Merge or overload the declaration with an existing declaration of
11297   // the same name, if appropriate.
11298   if (!Previous.empty()) {
11299     // Determine whether NewFD is an overload of PrevDecl or
11300     // a declaration that requires merging. If it's an overload,
11301     // there's no more work to do here; we'll just add the new
11302     // function to the scope.
11303     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11304       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11305       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11306         Redeclaration = true;
11307         OldDecl = Candidate;
11308       }
11309     } else {
11310       MayNeedOverloadableChecks = true;
11311       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11312                             /*NewIsUsingDecl*/ false)) {
11313       case Ovl_Match:
11314         Redeclaration = true;
11315         break;
11316 
11317       case Ovl_NonFunction:
11318         Redeclaration = true;
11319         break;
11320 
11321       case Ovl_Overload:
11322         Redeclaration = false;
11323         break;
11324       }
11325     }
11326   }
11327 
11328   // Check for a previous extern "C" declaration with this name.
11329   if (!Redeclaration &&
11330       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11331     if (!Previous.empty()) {
11332       // This is an extern "C" declaration with the same name as a previous
11333       // declaration, and thus redeclares that entity...
11334       Redeclaration = true;
11335       OldDecl = Previous.getFoundDecl();
11336       MergeTypeWithPrevious = false;
11337 
11338       // ... except in the presence of __attribute__((overloadable)).
11339       if (OldDecl->hasAttr<OverloadableAttr>() ||
11340           NewFD->hasAttr<OverloadableAttr>()) {
11341         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11342           MayNeedOverloadableChecks = true;
11343           Redeclaration = false;
11344           OldDecl = nullptr;
11345         }
11346       }
11347     }
11348   }
11349 
11350   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11351     return Redeclaration;
11352 
11353   // PPC MMA non-pointer types are not allowed as function return types.
11354   if (Context.getTargetInfo().getTriple().isPPC64() &&
11355       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11356     NewFD->setInvalidDecl();
11357   }
11358 
11359   // C++11 [dcl.constexpr]p8:
11360   //   A constexpr specifier for a non-static member function that is not
11361   //   a constructor declares that member function to be const.
11362   //
11363   // This needs to be delayed until we know whether this is an out-of-line
11364   // definition of a static member function.
11365   //
11366   // This rule is not present in C++1y, so we produce a backwards
11367   // compatibility warning whenever it happens in C++11.
11368   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11369   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11370       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11371       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11372     CXXMethodDecl *OldMD = nullptr;
11373     if (OldDecl)
11374       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11375     if (!OldMD || !OldMD->isStatic()) {
11376       const FunctionProtoType *FPT =
11377         MD->getType()->castAs<FunctionProtoType>();
11378       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11379       EPI.TypeQuals.addConst();
11380       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11381                                           FPT->getParamTypes(), EPI));
11382 
11383       // Warn that we did this, if we're not performing template instantiation.
11384       // In that case, we'll have warned already when the template was defined.
11385       if (!inTemplateInstantiation()) {
11386         SourceLocation AddConstLoc;
11387         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11388                 .IgnoreParens().getAs<FunctionTypeLoc>())
11389           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11390 
11391         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11392           << FixItHint::CreateInsertion(AddConstLoc, " const");
11393       }
11394     }
11395   }
11396 
11397   if (Redeclaration) {
11398     // NewFD and OldDecl represent declarations that need to be
11399     // merged.
11400     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11401                           DeclIsDefn)) {
11402       NewFD->setInvalidDecl();
11403       return Redeclaration;
11404     }
11405 
11406     Previous.clear();
11407     Previous.addDecl(OldDecl);
11408 
11409     if (FunctionTemplateDecl *OldTemplateDecl =
11410             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11411       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11412       FunctionTemplateDecl *NewTemplateDecl
11413         = NewFD->getDescribedFunctionTemplate();
11414       assert(NewTemplateDecl && "Template/non-template mismatch");
11415 
11416       // The call to MergeFunctionDecl above may have created some state in
11417       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11418       // can add it as a redeclaration.
11419       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11420 
11421       NewFD->setPreviousDeclaration(OldFD);
11422       if (NewFD->isCXXClassMember()) {
11423         NewFD->setAccess(OldTemplateDecl->getAccess());
11424         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11425       }
11426 
11427       // If this is an explicit specialization of a member that is a function
11428       // template, mark it as a member specialization.
11429       if (IsMemberSpecialization &&
11430           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11431         NewTemplateDecl->setMemberSpecialization();
11432         assert(OldTemplateDecl->isMemberSpecialization());
11433         // Explicit specializations of a member template do not inherit deleted
11434         // status from the parent member template that they are specializing.
11435         if (OldFD->isDeleted()) {
11436           // FIXME: This assert will not hold in the presence of modules.
11437           assert(OldFD->getCanonicalDecl() == OldFD);
11438           // FIXME: We need an update record for this AST mutation.
11439           OldFD->setDeletedAsWritten(false);
11440         }
11441       }
11442 
11443     } else {
11444       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11445         auto *OldFD = cast<FunctionDecl>(OldDecl);
11446         // This needs to happen first so that 'inline' propagates.
11447         NewFD->setPreviousDeclaration(OldFD);
11448         if (NewFD->isCXXClassMember())
11449           NewFD->setAccess(OldFD->getAccess());
11450       }
11451     }
11452   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11453              !NewFD->getAttr<OverloadableAttr>()) {
11454     assert((Previous.empty() ||
11455             llvm::any_of(Previous,
11456                          [](const NamedDecl *ND) {
11457                            return ND->hasAttr<OverloadableAttr>();
11458                          })) &&
11459            "Non-redecls shouldn't happen without overloadable present");
11460 
11461     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11462       const auto *FD = dyn_cast<FunctionDecl>(ND);
11463       return FD && !FD->hasAttr<OverloadableAttr>();
11464     });
11465 
11466     if (OtherUnmarkedIter != Previous.end()) {
11467       Diag(NewFD->getLocation(),
11468            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11469       Diag((*OtherUnmarkedIter)->getLocation(),
11470            diag::note_attribute_overloadable_prev_overload)
11471           << false;
11472 
11473       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11474     }
11475   }
11476 
11477   if (LangOpts.OpenMP)
11478     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11479 
11480   // Semantic checking for this function declaration (in isolation).
11481 
11482   if (getLangOpts().CPlusPlus) {
11483     // C++-specific checks.
11484     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11485       CheckConstructor(Constructor);
11486     } else if (CXXDestructorDecl *Destructor =
11487                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11488       CXXRecordDecl *Record = Destructor->getParent();
11489       QualType ClassType = Context.getTypeDeclType(Record);
11490 
11491       // FIXME: Shouldn't we be able to perform this check even when the class
11492       // type is dependent? Both gcc and edg can handle that.
11493       if (!ClassType->isDependentType()) {
11494         DeclarationName Name
11495           = Context.DeclarationNames.getCXXDestructorName(
11496                                         Context.getCanonicalType(ClassType));
11497         if (NewFD->getDeclName() != Name) {
11498           Diag(NewFD->getLocation(), diag::err_destructor_name);
11499           NewFD->setInvalidDecl();
11500           return Redeclaration;
11501         }
11502       }
11503     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11504       if (auto *TD = Guide->getDescribedFunctionTemplate())
11505         CheckDeductionGuideTemplate(TD);
11506 
11507       // A deduction guide is not on the list of entities that can be
11508       // explicitly specialized.
11509       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11510         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11511             << /*explicit specialization*/ 1;
11512     }
11513 
11514     // Find any virtual functions that this function overrides.
11515     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11516       if (!Method->isFunctionTemplateSpecialization() &&
11517           !Method->getDescribedFunctionTemplate() &&
11518           Method->isCanonicalDecl()) {
11519         AddOverriddenMethods(Method->getParent(), Method);
11520       }
11521       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11522         // C++2a [class.virtual]p6
11523         // A virtual method shall not have a requires-clause.
11524         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11525              diag::err_constrained_virtual_method);
11526 
11527       if (Method->isStatic())
11528         checkThisInStaticMemberFunctionType(Method);
11529     }
11530 
11531     // C++20: dcl.decl.general p4:
11532     // The optional requires-clause ([temp.pre]) in an init-declarator or
11533     // member-declarator shall be present only if the declarator declares a
11534     // templated function ([dcl.fct]).
11535     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11536       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11537         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11538     }
11539 
11540     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11541       ActOnConversionDeclarator(Conversion);
11542 
11543     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11544     if (NewFD->isOverloadedOperator() &&
11545         CheckOverloadedOperatorDeclaration(NewFD)) {
11546       NewFD->setInvalidDecl();
11547       return Redeclaration;
11548     }
11549 
11550     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11551     if (NewFD->getLiteralIdentifier() &&
11552         CheckLiteralOperatorDeclaration(NewFD)) {
11553       NewFD->setInvalidDecl();
11554       return Redeclaration;
11555     }
11556 
11557     // In C++, check default arguments now that we have merged decls. Unless
11558     // the lexical context is the class, because in this case this is done
11559     // during delayed parsing anyway.
11560     if (!CurContext->isRecord())
11561       CheckCXXDefaultArguments(NewFD);
11562 
11563     // If this function is declared as being extern "C", then check to see if
11564     // the function returns a UDT (class, struct, or union type) that is not C
11565     // compatible, and if it does, warn the user.
11566     // But, issue any diagnostic on the first declaration only.
11567     if (Previous.empty() && NewFD->isExternC()) {
11568       QualType R = NewFD->getReturnType();
11569       if (R->isIncompleteType() && !R->isVoidType())
11570         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11571             << NewFD << R;
11572       else if (!R.isPODType(Context) && !R->isVoidType() &&
11573                !R->isObjCObjectPointerType())
11574         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11575     }
11576 
11577     // C++1z [dcl.fct]p6:
11578     //   [...] whether the function has a non-throwing exception-specification
11579     //   [is] part of the function type
11580     //
11581     // This results in an ABI break between C++14 and C++17 for functions whose
11582     // declared type includes an exception-specification in a parameter or
11583     // return type. (Exception specifications on the function itself are OK in
11584     // most cases, and exception specifications are not permitted in most other
11585     // contexts where they could make it into a mangling.)
11586     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11587       auto HasNoexcept = [&](QualType T) -> bool {
11588         // Strip off declarator chunks that could be between us and a function
11589         // type. We don't need to look far, exception specifications are very
11590         // restricted prior to C++17.
11591         if (auto *RT = T->getAs<ReferenceType>())
11592           T = RT->getPointeeType();
11593         else if (T->isAnyPointerType())
11594           T = T->getPointeeType();
11595         else if (auto *MPT = T->getAs<MemberPointerType>())
11596           T = MPT->getPointeeType();
11597         if (auto *FPT = T->getAs<FunctionProtoType>())
11598           if (FPT->isNothrow())
11599             return true;
11600         return false;
11601       };
11602 
11603       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11604       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11605       for (QualType T : FPT->param_types())
11606         AnyNoexcept |= HasNoexcept(T);
11607       if (AnyNoexcept)
11608         Diag(NewFD->getLocation(),
11609              diag::warn_cxx17_compat_exception_spec_in_signature)
11610             << NewFD;
11611     }
11612 
11613     if (!Redeclaration && LangOpts.CUDA)
11614       checkCUDATargetOverload(NewFD, Previous);
11615   }
11616   return Redeclaration;
11617 }
11618 
11619 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11620   // C++11 [basic.start.main]p3:
11621   //   A program that [...] declares main to be inline, static or
11622   //   constexpr is ill-formed.
11623   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11624   //   appear in a declaration of main.
11625   // static main is not an error under C99, but we should warn about it.
11626   // We accept _Noreturn main as an extension.
11627   if (FD->getStorageClass() == SC_Static)
11628     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11629          ? diag::err_static_main : diag::warn_static_main)
11630       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11631   if (FD->isInlineSpecified())
11632     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11633       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11634   if (DS.isNoreturnSpecified()) {
11635     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11636     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11637     Diag(NoreturnLoc, diag::ext_noreturn_main);
11638     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11639       << FixItHint::CreateRemoval(NoreturnRange);
11640   }
11641   if (FD->isConstexpr()) {
11642     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11643         << FD->isConsteval()
11644         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11645     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11646   }
11647 
11648   if (getLangOpts().OpenCL) {
11649     Diag(FD->getLocation(), diag::err_opencl_no_main)
11650         << FD->hasAttr<OpenCLKernelAttr>();
11651     FD->setInvalidDecl();
11652     return;
11653   }
11654 
11655   // Functions named main in hlsl are default entries, but don't have specific
11656   // signatures they are required to conform to.
11657   if (getLangOpts().HLSL)
11658     return;
11659 
11660   QualType T = FD->getType();
11661   assert(T->isFunctionType() && "function decl is not of function type");
11662   const FunctionType* FT = T->castAs<FunctionType>();
11663 
11664   // Set default calling convention for main()
11665   if (FT->getCallConv() != CC_C) {
11666     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11667     FD->setType(QualType(FT, 0));
11668     T = Context.getCanonicalType(FD->getType());
11669   }
11670 
11671   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11672     // In C with GNU extensions we allow main() to have non-integer return
11673     // type, but we should warn about the extension, and we disable the
11674     // implicit-return-zero rule.
11675 
11676     // GCC in C mode accepts qualified 'int'.
11677     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11678       FD->setHasImplicitReturnZero(true);
11679     else {
11680       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11681       SourceRange RTRange = FD->getReturnTypeSourceRange();
11682       if (RTRange.isValid())
11683         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11684             << FixItHint::CreateReplacement(RTRange, "int");
11685     }
11686   } else {
11687     // In C and C++, main magically returns 0 if you fall off the end;
11688     // set the flag which tells us that.
11689     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11690 
11691     // All the standards say that main() should return 'int'.
11692     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11693       FD->setHasImplicitReturnZero(true);
11694     else {
11695       // Otherwise, this is just a flat-out error.
11696       SourceRange RTRange = FD->getReturnTypeSourceRange();
11697       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11698           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11699                                 : FixItHint());
11700       FD->setInvalidDecl(true);
11701     }
11702   }
11703 
11704   // Treat protoless main() as nullary.
11705   if (isa<FunctionNoProtoType>(FT)) return;
11706 
11707   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11708   unsigned nparams = FTP->getNumParams();
11709   assert(FD->getNumParams() == nparams);
11710 
11711   bool HasExtraParameters = (nparams > 3);
11712 
11713   if (FTP->isVariadic()) {
11714     Diag(FD->getLocation(), diag::ext_variadic_main);
11715     // FIXME: if we had information about the location of the ellipsis, we
11716     // could add a FixIt hint to remove it as a parameter.
11717   }
11718 
11719   // Darwin passes an undocumented fourth argument of type char**.  If
11720   // other platforms start sprouting these, the logic below will start
11721   // getting shifty.
11722   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11723     HasExtraParameters = false;
11724 
11725   if (HasExtraParameters) {
11726     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11727     FD->setInvalidDecl(true);
11728     nparams = 3;
11729   }
11730 
11731   // FIXME: a lot of the following diagnostics would be improved
11732   // if we had some location information about types.
11733 
11734   QualType CharPP =
11735     Context.getPointerType(Context.getPointerType(Context.CharTy));
11736   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11737 
11738   for (unsigned i = 0; i < nparams; ++i) {
11739     QualType AT = FTP->getParamType(i);
11740 
11741     bool mismatch = true;
11742 
11743     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11744       mismatch = false;
11745     else if (Expected[i] == CharPP) {
11746       // As an extension, the following forms are okay:
11747       //   char const **
11748       //   char const * const *
11749       //   char * const *
11750 
11751       QualifierCollector qs;
11752       const PointerType* PT;
11753       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11754           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11755           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11756                               Context.CharTy)) {
11757         qs.removeConst();
11758         mismatch = !qs.empty();
11759       }
11760     }
11761 
11762     if (mismatch) {
11763       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11764       // TODO: suggest replacing given type with expected type
11765       FD->setInvalidDecl(true);
11766     }
11767   }
11768 
11769   if (nparams == 1 && !FD->isInvalidDecl()) {
11770     Diag(FD->getLocation(), diag::warn_main_one_arg);
11771   }
11772 
11773   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11774     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11775     FD->setInvalidDecl();
11776   }
11777 }
11778 
11779 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11780 
11781   // Default calling convention for main and wmain is __cdecl
11782   if (FD->getName() == "main" || FD->getName() == "wmain")
11783     return false;
11784 
11785   // Default calling convention for MinGW is __cdecl
11786   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11787   if (T.isWindowsGNUEnvironment())
11788     return false;
11789 
11790   // Default calling convention for WinMain, wWinMain and DllMain
11791   // is __stdcall on 32 bit Windows
11792   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11793     return true;
11794 
11795   return false;
11796 }
11797 
11798 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11799   QualType T = FD->getType();
11800   assert(T->isFunctionType() && "function decl is not of function type");
11801   const FunctionType *FT = T->castAs<FunctionType>();
11802 
11803   // Set an implicit return of 'zero' if the function can return some integral,
11804   // enumeration, pointer or nullptr type.
11805   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11806       FT->getReturnType()->isAnyPointerType() ||
11807       FT->getReturnType()->isNullPtrType())
11808     // DllMain is exempt because a return value of zero means it failed.
11809     if (FD->getName() != "DllMain")
11810       FD->setHasImplicitReturnZero(true);
11811 
11812   // Explicity specified calling conventions are applied to MSVC entry points
11813   if (!hasExplicitCallingConv(T)) {
11814     if (isDefaultStdCall(FD, *this)) {
11815       if (FT->getCallConv() != CC_X86StdCall) {
11816         FT = Context.adjustFunctionType(
11817             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11818         FD->setType(QualType(FT, 0));
11819       }
11820     } else if (FT->getCallConv() != CC_C) {
11821       FT = Context.adjustFunctionType(FT,
11822                                       FT->getExtInfo().withCallingConv(CC_C));
11823       FD->setType(QualType(FT, 0));
11824     }
11825   }
11826 
11827   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11828     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11829     FD->setInvalidDecl();
11830   }
11831 }
11832 
11833 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11834   // FIXME: Need strict checking.  In C89, we need to check for
11835   // any assignment, increment, decrement, function-calls, or
11836   // commas outside of a sizeof.  In C99, it's the same list,
11837   // except that the aforementioned are allowed in unevaluated
11838   // expressions.  Everything else falls under the
11839   // "may accept other forms of constant expressions" exception.
11840   //
11841   // Regular C++ code will not end up here (exceptions: language extensions,
11842   // OpenCL C++ etc), so the constant expression rules there don't matter.
11843   if (Init->isValueDependent()) {
11844     assert(Init->containsErrors() &&
11845            "Dependent code should only occur in error-recovery path.");
11846     return true;
11847   }
11848   const Expr *Culprit;
11849   if (Init->isConstantInitializer(Context, false, &Culprit))
11850     return false;
11851   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11852     << Culprit->getSourceRange();
11853   return true;
11854 }
11855 
11856 namespace {
11857   // Visits an initialization expression to see if OrigDecl is evaluated in
11858   // its own initialization and throws a warning if it does.
11859   class SelfReferenceChecker
11860       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11861     Sema &S;
11862     Decl *OrigDecl;
11863     bool isRecordType;
11864     bool isPODType;
11865     bool isReferenceType;
11866 
11867     bool isInitList;
11868     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11869 
11870   public:
11871     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11872 
11873     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11874                                                     S(S), OrigDecl(OrigDecl) {
11875       isPODType = false;
11876       isRecordType = false;
11877       isReferenceType = false;
11878       isInitList = false;
11879       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11880         isPODType = VD->getType().isPODType(S.Context);
11881         isRecordType = VD->getType()->isRecordType();
11882         isReferenceType = VD->getType()->isReferenceType();
11883       }
11884     }
11885 
11886     // For most expressions, just call the visitor.  For initializer lists,
11887     // track the index of the field being initialized since fields are
11888     // initialized in order allowing use of previously initialized fields.
11889     void CheckExpr(Expr *E) {
11890       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11891       if (!InitList) {
11892         Visit(E);
11893         return;
11894       }
11895 
11896       // Track and increment the index here.
11897       isInitList = true;
11898       InitFieldIndex.push_back(0);
11899       for (auto Child : InitList->children()) {
11900         CheckExpr(cast<Expr>(Child));
11901         ++InitFieldIndex.back();
11902       }
11903       InitFieldIndex.pop_back();
11904     }
11905 
11906     // Returns true if MemberExpr is checked and no further checking is needed.
11907     // Returns false if additional checking is required.
11908     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11909       llvm::SmallVector<FieldDecl*, 4> Fields;
11910       Expr *Base = E;
11911       bool ReferenceField = false;
11912 
11913       // Get the field members used.
11914       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11915         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11916         if (!FD)
11917           return false;
11918         Fields.push_back(FD);
11919         if (FD->getType()->isReferenceType())
11920           ReferenceField = true;
11921         Base = ME->getBase()->IgnoreParenImpCasts();
11922       }
11923 
11924       // Keep checking only if the base Decl is the same.
11925       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11926       if (!DRE || DRE->getDecl() != OrigDecl)
11927         return false;
11928 
11929       // A reference field can be bound to an unininitialized field.
11930       if (CheckReference && !ReferenceField)
11931         return true;
11932 
11933       // Convert FieldDecls to their index number.
11934       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11935       for (const FieldDecl *I : llvm::reverse(Fields))
11936         UsedFieldIndex.push_back(I->getFieldIndex());
11937 
11938       // See if a warning is needed by checking the first difference in index
11939       // numbers.  If field being used has index less than the field being
11940       // initialized, then the use is safe.
11941       for (auto UsedIter = UsedFieldIndex.begin(),
11942                 UsedEnd = UsedFieldIndex.end(),
11943                 OrigIter = InitFieldIndex.begin(),
11944                 OrigEnd = InitFieldIndex.end();
11945            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11946         if (*UsedIter < *OrigIter)
11947           return true;
11948         if (*UsedIter > *OrigIter)
11949           break;
11950       }
11951 
11952       // TODO: Add a different warning which will print the field names.
11953       HandleDeclRefExpr(DRE);
11954       return true;
11955     }
11956 
11957     // For most expressions, the cast is directly above the DeclRefExpr.
11958     // For conditional operators, the cast can be outside the conditional
11959     // operator if both expressions are DeclRefExpr's.
11960     void HandleValue(Expr *E) {
11961       E = E->IgnoreParens();
11962       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11963         HandleDeclRefExpr(DRE);
11964         return;
11965       }
11966 
11967       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11968         Visit(CO->getCond());
11969         HandleValue(CO->getTrueExpr());
11970         HandleValue(CO->getFalseExpr());
11971         return;
11972       }
11973 
11974       if (BinaryConditionalOperator *BCO =
11975               dyn_cast<BinaryConditionalOperator>(E)) {
11976         Visit(BCO->getCond());
11977         HandleValue(BCO->getFalseExpr());
11978         return;
11979       }
11980 
11981       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11982         HandleValue(OVE->getSourceExpr());
11983         return;
11984       }
11985 
11986       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11987         if (BO->getOpcode() == BO_Comma) {
11988           Visit(BO->getLHS());
11989           HandleValue(BO->getRHS());
11990           return;
11991         }
11992       }
11993 
11994       if (isa<MemberExpr>(E)) {
11995         if (isInitList) {
11996           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11997                                       false /*CheckReference*/))
11998             return;
11999         }
12000 
12001         Expr *Base = E->IgnoreParenImpCasts();
12002         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12003           // Check for static member variables and don't warn on them.
12004           if (!isa<FieldDecl>(ME->getMemberDecl()))
12005             return;
12006           Base = ME->getBase()->IgnoreParenImpCasts();
12007         }
12008         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12009           HandleDeclRefExpr(DRE);
12010         return;
12011       }
12012 
12013       Visit(E);
12014     }
12015 
12016     // Reference types not handled in HandleValue are handled here since all
12017     // uses of references are bad, not just r-value uses.
12018     void VisitDeclRefExpr(DeclRefExpr *E) {
12019       if (isReferenceType)
12020         HandleDeclRefExpr(E);
12021     }
12022 
12023     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12024       if (E->getCastKind() == CK_LValueToRValue) {
12025         HandleValue(E->getSubExpr());
12026         return;
12027       }
12028 
12029       Inherited::VisitImplicitCastExpr(E);
12030     }
12031 
12032     void VisitMemberExpr(MemberExpr *E) {
12033       if (isInitList) {
12034         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12035           return;
12036       }
12037 
12038       // Don't warn on arrays since they can be treated as pointers.
12039       if (E->getType()->canDecayToPointerType()) return;
12040 
12041       // Warn when a non-static method call is followed by non-static member
12042       // field accesses, which is followed by a DeclRefExpr.
12043       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12044       bool Warn = (MD && !MD->isStatic());
12045       Expr *Base = E->getBase()->IgnoreParenImpCasts();
12046       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12047         if (!isa<FieldDecl>(ME->getMemberDecl()))
12048           Warn = false;
12049         Base = ME->getBase()->IgnoreParenImpCasts();
12050       }
12051 
12052       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12053         if (Warn)
12054           HandleDeclRefExpr(DRE);
12055         return;
12056       }
12057 
12058       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12059       // Visit that expression.
12060       Visit(Base);
12061     }
12062 
12063     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12064       Expr *Callee = E->getCallee();
12065 
12066       if (isa<UnresolvedLookupExpr>(Callee))
12067         return Inherited::VisitCXXOperatorCallExpr(E);
12068 
12069       Visit(Callee);
12070       for (auto Arg: E->arguments())
12071         HandleValue(Arg->IgnoreParenImpCasts());
12072     }
12073 
12074     void VisitUnaryOperator(UnaryOperator *E) {
12075       // For POD record types, addresses of its own members are well-defined.
12076       if (E->getOpcode() == UO_AddrOf && isRecordType &&
12077           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12078         if (!isPODType)
12079           HandleValue(E->getSubExpr());
12080         return;
12081       }
12082 
12083       if (E->isIncrementDecrementOp()) {
12084         HandleValue(E->getSubExpr());
12085         return;
12086       }
12087 
12088       Inherited::VisitUnaryOperator(E);
12089     }
12090 
12091     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12092 
12093     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12094       if (E->getConstructor()->isCopyConstructor()) {
12095         Expr *ArgExpr = E->getArg(0);
12096         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12097           if (ILE->getNumInits() == 1)
12098             ArgExpr = ILE->getInit(0);
12099         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12100           if (ICE->getCastKind() == CK_NoOp)
12101             ArgExpr = ICE->getSubExpr();
12102         HandleValue(ArgExpr);
12103         return;
12104       }
12105       Inherited::VisitCXXConstructExpr(E);
12106     }
12107 
12108     void VisitCallExpr(CallExpr *E) {
12109       // Treat std::move as a use.
12110       if (E->isCallToStdMove()) {
12111         HandleValue(E->getArg(0));
12112         return;
12113       }
12114 
12115       Inherited::VisitCallExpr(E);
12116     }
12117 
12118     void VisitBinaryOperator(BinaryOperator *E) {
12119       if (E->isCompoundAssignmentOp()) {
12120         HandleValue(E->getLHS());
12121         Visit(E->getRHS());
12122         return;
12123       }
12124 
12125       Inherited::VisitBinaryOperator(E);
12126     }
12127 
12128     // A custom visitor for BinaryConditionalOperator is needed because the
12129     // regular visitor would check the condition and true expression separately
12130     // but both point to the same place giving duplicate diagnostics.
12131     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12132       Visit(E->getCond());
12133       Visit(E->getFalseExpr());
12134     }
12135 
12136     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12137       Decl* ReferenceDecl = DRE->getDecl();
12138       if (OrigDecl != ReferenceDecl) return;
12139       unsigned diag;
12140       if (isReferenceType) {
12141         diag = diag::warn_uninit_self_reference_in_reference_init;
12142       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12143         diag = diag::warn_static_self_reference_in_init;
12144       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12145                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12146                  DRE->getDecl()->getType()->isRecordType()) {
12147         diag = diag::warn_uninit_self_reference_in_init;
12148       } else {
12149         // Local variables will be handled by the CFG analysis.
12150         return;
12151       }
12152 
12153       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12154                             S.PDiag(diag)
12155                                 << DRE->getDecl() << OrigDecl->getLocation()
12156                                 << DRE->getSourceRange());
12157     }
12158   };
12159 
12160   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12161   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12162                                  bool DirectInit) {
12163     // Parameters arguments are occassionially constructed with itself,
12164     // for instance, in recursive functions.  Skip them.
12165     if (isa<ParmVarDecl>(OrigDecl))
12166       return;
12167 
12168     E = E->IgnoreParens();
12169 
12170     // Skip checking T a = a where T is not a record or reference type.
12171     // Doing so is a way to silence uninitialized warnings.
12172     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12173       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12174         if (ICE->getCastKind() == CK_LValueToRValue)
12175           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12176             if (DRE->getDecl() == OrigDecl)
12177               return;
12178 
12179     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12180   }
12181 } // end anonymous namespace
12182 
12183 namespace {
12184   // Simple wrapper to add the name of a variable or (if no variable is
12185   // available) a DeclarationName into a diagnostic.
12186   struct VarDeclOrName {
12187     VarDecl *VDecl;
12188     DeclarationName Name;
12189 
12190     friend const Sema::SemaDiagnosticBuilder &
12191     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12192       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12193     }
12194   };
12195 } // end anonymous namespace
12196 
12197 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12198                                             DeclarationName Name, QualType Type,
12199                                             TypeSourceInfo *TSI,
12200                                             SourceRange Range, bool DirectInit,
12201                                             Expr *Init) {
12202   bool IsInitCapture = !VDecl;
12203   assert((!VDecl || !VDecl->isInitCapture()) &&
12204          "init captures are expected to be deduced prior to initialization");
12205 
12206   VarDeclOrName VN{VDecl, Name};
12207 
12208   DeducedType *Deduced = Type->getContainedDeducedType();
12209   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12210 
12211   // C++11 [dcl.spec.auto]p3
12212   if (!Init) {
12213     assert(VDecl && "no init for init capture deduction?");
12214 
12215     // Except for class argument deduction, and then for an initializing
12216     // declaration only, i.e. no static at class scope or extern.
12217     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12218         VDecl->hasExternalStorage() ||
12219         VDecl->isStaticDataMember()) {
12220       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12221         << VDecl->getDeclName() << Type;
12222       return QualType();
12223     }
12224   }
12225 
12226   ArrayRef<Expr*> DeduceInits;
12227   if (Init)
12228     DeduceInits = Init;
12229 
12230   if (DirectInit) {
12231     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12232       DeduceInits = PL->exprs();
12233   }
12234 
12235   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12236     assert(VDecl && "non-auto type for init capture deduction?");
12237     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12238     InitializationKind Kind = InitializationKind::CreateForInit(
12239         VDecl->getLocation(), DirectInit, Init);
12240     // FIXME: Initialization should not be taking a mutable list of inits.
12241     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12242     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12243                                                        InitsCopy);
12244   }
12245 
12246   if (DirectInit) {
12247     if (auto *IL = dyn_cast<InitListExpr>(Init))
12248       DeduceInits = IL->inits();
12249   }
12250 
12251   // Deduction only works if we have exactly one source expression.
12252   if (DeduceInits.empty()) {
12253     // It isn't possible to write this directly, but it is possible to
12254     // end up in this situation with "auto x(some_pack...);"
12255     Diag(Init->getBeginLoc(), IsInitCapture
12256                                   ? diag::err_init_capture_no_expression
12257                                   : diag::err_auto_var_init_no_expression)
12258         << VN << Type << Range;
12259     return QualType();
12260   }
12261 
12262   if (DeduceInits.size() > 1) {
12263     Diag(DeduceInits[1]->getBeginLoc(),
12264          IsInitCapture ? diag::err_init_capture_multiple_expressions
12265                        : diag::err_auto_var_init_multiple_expressions)
12266         << VN << Type << Range;
12267     return QualType();
12268   }
12269 
12270   Expr *DeduceInit = DeduceInits[0];
12271   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12272     Diag(Init->getBeginLoc(), IsInitCapture
12273                                   ? diag::err_init_capture_paren_braces
12274                                   : diag::err_auto_var_init_paren_braces)
12275         << isa<InitListExpr>(Init) << VN << Type << Range;
12276     return QualType();
12277   }
12278 
12279   // Expressions default to 'id' when we're in a debugger.
12280   bool DefaultedAnyToId = false;
12281   if (getLangOpts().DebuggerCastResultToId &&
12282       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12283     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12284     if (Result.isInvalid()) {
12285       return QualType();
12286     }
12287     Init = Result.get();
12288     DefaultedAnyToId = true;
12289   }
12290 
12291   // C++ [dcl.decomp]p1:
12292   //   If the assignment-expression [...] has array type A and no ref-qualifier
12293   //   is present, e has type cv A
12294   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12295       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12296       DeduceInit->getType()->isConstantArrayType())
12297     return Context.getQualifiedType(DeduceInit->getType(),
12298                                     Type.getQualifiers());
12299 
12300   QualType DeducedType;
12301   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12302     if (!IsInitCapture)
12303       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12304     else if (isa<InitListExpr>(Init))
12305       Diag(Range.getBegin(),
12306            diag::err_init_capture_deduction_failure_from_init_list)
12307           << VN
12308           << (DeduceInit->getType().isNull() ? TSI->getType()
12309                                              : DeduceInit->getType())
12310           << DeduceInit->getSourceRange();
12311     else
12312       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12313           << VN << TSI->getType()
12314           << (DeduceInit->getType().isNull() ? TSI->getType()
12315                                              : DeduceInit->getType())
12316           << DeduceInit->getSourceRange();
12317   }
12318 
12319   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12320   // 'id' instead of a specific object type prevents most of our usual
12321   // checks.
12322   // We only want to warn outside of template instantiations, though:
12323   // inside a template, the 'id' could have come from a parameter.
12324   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12325       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12326     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12327     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12328   }
12329 
12330   return DeducedType;
12331 }
12332 
12333 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12334                                          Expr *Init) {
12335   assert(!Init || !Init->containsErrors());
12336   QualType DeducedType = deduceVarTypeFromInitializer(
12337       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12338       VDecl->getSourceRange(), DirectInit, Init);
12339   if (DeducedType.isNull()) {
12340     VDecl->setInvalidDecl();
12341     return true;
12342   }
12343 
12344   VDecl->setType(DeducedType);
12345   assert(VDecl->isLinkageValid());
12346 
12347   // In ARC, infer lifetime.
12348   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12349     VDecl->setInvalidDecl();
12350 
12351   if (getLangOpts().OpenCL)
12352     deduceOpenCLAddressSpace(VDecl);
12353 
12354   // If this is a redeclaration, check that the type we just deduced matches
12355   // the previously declared type.
12356   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12357     // We never need to merge the type, because we cannot form an incomplete
12358     // array of auto, nor deduce such a type.
12359     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12360   }
12361 
12362   // Check the deduced type is valid for a variable declaration.
12363   CheckVariableDeclarationType(VDecl);
12364   return VDecl->isInvalidDecl();
12365 }
12366 
12367 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12368                                               SourceLocation Loc) {
12369   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12370     Init = EWC->getSubExpr();
12371 
12372   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12373     Init = CE->getSubExpr();
12374 
12375   QualType InitType = Init->getType();
12376   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12377           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12378          "shouldn't be called if type doesn't have a non-trivial C struct");
12379   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12380     for (auto I : ILE->inits()) {
12381       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12382           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12383         continue;
12384       SourceLocation SL = I->getExprLoc();
12385       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12386     }
12387     return;
12388   }
12389 
12390   if (isa<ImplicitValueInitExpr>(Init)) {
12391     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12392       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12393                             NTCUK_Init);
12394   } else {
12395     // Assume all other explicit initializers involving copying some existing
12396     // object.
12397     // TODO: ignore any explicit initializers where we can guarantee
12398     // copy-elision.
12399     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12400       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12401   }
12402 }
12403 
12404 namespace {
12405 
12406 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12407   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12408   // in the source code or implicitly by the compiler if it is in a union
12409   // defined in a system header and has non-trivial ObjC ownership
12410   // qualifications. We don't want those fields to participate in determining
12411   // whether the containing union is non-trivial.
12412   return FD->hasAttr<UnavailableAttr>();
12413 }
12414 
12415 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12416     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12417                                     void> {
12418   using Super =
12419       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12420                                     void>;
12421 
12422   DiagNonTrivalCUnionDefaultInitializeVisitor(
12423       QualType OrigTy, SourceLocation OrigLoc,
12424       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12425       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12426 
12427   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12428                      const FieldDecl *FD, bool InNonTrivialUnion) {
12429     if (const auto *AT = S.Context.getAsArrayType(QT))
12430       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12431                                      InNonTrivialUnion);
12432     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12433   }
12434 
12435   void visitARCStrong(QualType QT, const FieldDecl *FD,
12436                       bool InNonTrivialUnion) {
12437     if (InNonTrivialUnion)
12438       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12439           << 1 << 0 << QT << FD->getName();
12440   }
12441 
12442   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12443     if (InNonTrivialUnion)
12444       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12445           << 1 << 0 << QT << FD->getName();
12446   }
12447 
12448   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12449     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12450     if (RD->isUnion()) {
12451       if (OrigLoc.isValid()) {
12452         bool IsUnion = false;
12453         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12454           IsUnion = OrigRD->isUnion();
12455         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12456             << 0 << OrigTy << IsUnion << UseContext;
12457         // Reset OrigLoc so that this diagnostic is emitted only once.
12458         OrigLoc = SourceLocation();
12459       }
12460       InNonTrivialUnion = true;
12461     }
12462 
12463     if (InNonTrivialUnion)
12464       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12465           << 0 << 0 << QT.getUnqualifiedType() << "";
12466 
12467     for (const FieldDecl *FD : RD->fields())
12468       if (!shouldIgnoreForRecordTriviality(FD))
12469         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12470   }
12471 
12472   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12473 
12474   // The non-trivial C union type or the struct/union type that contains a
12475   // non-trivial C union.
12476   QualType OrigTy;
12477   SourceLocation OrigLoc;
12478   Sema::NonTrivialCUnionContext UseContext;
12479   Sema &S;
12480 };
12481 
12482 struct DiagNonTrivalCUnionDestructedTypeVisitor
12483     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12484   using Super =
12485       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12486 
12487   DiagNonTrivalCUnionDestructedTypeVisitor(
12488       QualType OrigTy, SourceLocation OrigLoc,
12489       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12490       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12491 
12492   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12493                      const FieldDecl *FD, bool InNonTrivialUnion) {
12494     if (const auto *AT = S.Context.getAsArrayType(QT))
12495       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12496                                      InNonTrivialUnion);
12497     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12498   }
12499 
12500   void visitARCStrong(QualType QT, const FieldDecl *FD,
12501                       bool InNonTrivialUnion) {
12502     if (InNonTrivialUnion)
12503       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12504           << 1 << 1 << QT << FD->getName();
12505   }
12506 
12507   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12508     if (InNonTrivialUnion)
12509       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12510           << 1 << 1 << QT << FD->getName();
12511   }
12512 
12513   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12514     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12515     if (RD->isUnion()) {
12516       if (OrigLoc.isValid()) {
12517         bool IsUnion = false;
12518         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12519           IsUnion = OrigRD->isUnion();
12520         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12521             << 1 << OrigTy << IsUnion << UseContext;
12522         // Reset OrigLoc so that this diagnostic is emitted only once.
12523         OrigLoc = SourceLocation();
12524       }
12525       InNonTrivialUnion = true;
12526     }
12527 
12528     if (InNonTrivialUnion)
12529       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12530           << 0 << 1 << QT.getUnqualifiedType() << "";
12531 
12532     for (const FieldDecl *FD : RD->fields())
12533       if (!shouldIgnoreForRecordTriviality(FD))
12534         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12535   }
12536 
12537   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12538   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12539                           bool InNonTrivialUnion) {}
12540 
12541   // The non-trivial C union type or the struct/union type that contains a
12542   // non-trivial C union.
12543   QualType OrigTy;
12544   SourceLocation OrigLoc;
12545   Sema::NonTrivialCUnionContext UseContext;
12546   Sema &S;
12547 };
12548 
12549 struct DiagNonTrivalCUnionCopyVisitor
12550     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12551   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12552 
12553   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12554                                  Sema::NonTrivialCUnionContext UseContext,
12555                                  Sema &S)
12556       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12557 
12558   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12559                      const FieldDecl *FD, bool InNonTrivialUnion) {
12560     if (const auto *AT = S.Context.getAsArrayType(QT))
12561       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12562                                      InNonTrivialUnion);
12563     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12564   }
12565 
12566   void visitARCStrong(QualType QT, const FieldDecl *FD,
12567                       bool InNonTrivialUnion) {
12568     if (InNonTrivialUnion)
12569       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12570           << 1 << 2 << QT << FD->getName();
12571   }
12572 
12573   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12574     if (InNonTrivialUnion)
12575       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12576           << 1 << 2 << QT << FD->getName();
12577   }
12578 
12579   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12580     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12581     if (RD->isUnion()) {
12582       if (OrigLoc.isValid()) {
12583         bool IsUnion = false;
12584         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12585           IsUnion = OrigRD->isUnion();
12586         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12587             << 2 << OrigTy << IsUnion << UseContext;
12588         // Reset OrigLoc so that this diagnostic is emitted only once.
12589         OrigLoc = SourceLocation();
12590       }
12591       InNonTrivialUnion = true;
12592     }
12593 
12594     if (InNonTrivialUnion)
12595       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12596           << 0 << 2 << QT.getUnqualifiedType() << "";
12597 
12598     for (const FieldDecl *FD : RD->fields())
12599       if (!shouldIgnoreForRecordTriviality(FD))
12600         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12601   }
12602 
12603   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12604                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12605   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12606   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12607                             bool InNonTrivialUnion) {}
12608 
12609   // The non-trivial C union type or the struct/union type that contains a
12610   // non-trivial C union.
12611   QualType OrigTy;
12612   SourceLocation OrigLoc;
12613   Sema::NonTrivialCUnionContext UseContext;
12614   Sema &S;
12615 };
12616 
12617 } // namespace
12618 
12619 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12620                                  NonTrivialCUnionContext UseContext,
12621                                  unsigned NonTrivialKind) {
12622   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12623           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12624           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12625          "shouldn't be called if type doesn't have a non-trivial C union");
12626 
12627   if ((NonTrivialKind & NTCUK_Init) &&
12628       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12629     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12630         .visit(QT, nullptr, false);
12631   if ((NonTrivialKind & NTCUK_Destruct) &&
12632       QT.hasNonTrivialToPrimitiveDestructCUnion())
12633     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12634         .visit(QT, nullptr, false);
12635   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12636     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12637         .visit(QT, nullptr, false);
12638 }
12639 
12640 /// AddInitializerToDecl - Adds the initializer Init to the
12641 /// declaration dcl. If DirectInit is true, this is C++ direct
12642 /// initialization rather than copy initialization.
12643 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12644   // If there is no declaration, there was an error parsing it.  Just ignore
12645   // the initializer.
12646   if (!RealDecl || RealDecl->isInvalidDecl()) {
12647     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12648     return;
12649   }
12650 
12651   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12652     // Pure-specifiers are handled in ActOnPureSpecifier.
12653     Diag(Method->getLocation(), diag::err_member_function_initialization)
12654       << Method->getDeclName() << Init->getSourceRange();
12655     Method->setInvalidDecl();
12656     return;
12657   }
12658 
12659   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12660   if (!VDecl) {
12661     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12662     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12663     RealDecl->setInvalidDecl();
12664     return;
12665   }
12666 
12667   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12668   if (VDecl->getType()->isUndeducedType()) {
12669     // Attempt typo correction early so that the type of the init expression can
12670     // be deduced based on the chosen correction if the original init contains a
12671     // TypoExpr.
12672     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12673     if (!Res.isUsable()) {
12674       // There are unresolved typos in Init, just drop them.
12675       // FIXME: improve the recovery strategy to preserve the Init.
12676       RealDecl->setInvalidDecl();
12677       return;
12678     }
12679     if (Res.get()->containsErrors()) {
12680       // Invalidate the decl as we don't know the type for recovery-expr yet.
12681       RealDecl->setInvalidDecl();
12682       VDecl->setInit(Res.get());
12683       return;
12684     }
12685     Init = Res.get();
12686 
12687     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12688       return;
12689   }
12690 
12691   // dllimport cannot be used on variable definitions.
12692   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12693     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12694     VDecl->setInvalidDecl();
12695     return;
12696   }
12697 
12698   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12699     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12700     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12701     VDecl->setInvalidDecl();
12702     return;
12703   }
12704 
12705   if (!VDecl->getType()->isDependentType()) {
12706     // A definition must end up with a complete type, which means it must be
12707     // complete with the restriction that an array type might be completed by
12708     // the initializer; note that later code assumes this restriction.
12709     QualType BaseDeclType = VDecl->getType();
12710     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12711       BaseDeclType = Array->getElementType();
12712     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12713                             diag::err_typecheck_decl_incomplete_type)) {
12714       RealDecl->setInvalidDecl();
12715       return;
12716     }
12717 
12718     // The variable can not have an abstract class type.
12719     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12720                                diag::err_abstract_type_in_decl,
12721                                AbstractVariableType))
12722       VDecl->setInvalidDecl();
12723   }
12724 
12725   // If adding the initializer will turn this declaration into a definition,
12726   // and we already have a definition for this variable, diagnose or otherwise
12727   // handle the situation.
12728   if (VarDecl *Def = VDecl->getDefinition())
12729     if (Def != VDecl &&
12730         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12731         !VDecl->isThisDeclarationADemotedDefinition() &&
12732         checkVarDeclRedefinition(Def, VDecl))
12733       return;
12734 
12735   if (getLangOpts().CPlusPlus) {
12736     // C++ [class.static.data]p4
12737     //   If a static data member is of const integral or const
12738     //   enumeration type, its declaration in the class definition can
12739     //   specify a constant-initializer which shall be an integral
12740     //   constant expression (5.19). In that case, the member can appear
12741     //   in integral constant expressions. The member shall still be
12742     //   defined in a namespace scope if it is used in the program and the
12743     //   namespace scope definition shall not contain an initializer.
12744     //
12745     // We already performed a redefinition check above, but for static
12746     // data members we also need to check whether there was an in-class
12747     // declaration with an initializer.
12748     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12749       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12750           << VDecl->getDeclName();
12751       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12752            diag::note_previous_initializer)
12753           << 0;
12754       return;
12755     }
12756 
12757     if (VDecl->hasLocalStorage())
12758       setFunctionHasBranchProtectedScope();
12759 
12760     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12761       VDecl->setInvalidDecl();
12762       return;
12763     }
12764   }
12765 
12766   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12767   // a kernel function cannot be initialized."
12768   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12769     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12770     VDecl->setInvalidDecl();
12771     return;
12772   }
12773 
12774   // The LoaderUninitialized attribute acts as a definition (of undef).
12775   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12776     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12777     VDecl->setInvalidDecl();
12778     return;
12779   }
12780 
12781   // Get the decls type and save a reference for later, since
12782   // CheckInitializerTypes may change it.
12783   QualType DclT = VDecl->getType(), SavT = DclT;
12784 
12785   // Expressions default to 'id' when we're in a debugger
12786   // and we are assigning it to a variable of Objective-C pointer type.
12787   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12788       Init->getType() == Context.UnknownAnyTy) {
12789     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12790     if (Result.isInvalid()) {
12791       VDecl->setInvalidDecl();
12792       return;
12793     }
12794     Init = Result.get();
12795   }
12796 
12797   // Perform the initialization.
12798   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12799   if (!VDecl->isInvalidDecl()) {
12800     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12801     InitializationKind Kind = InitializationKind::CreateForInit(
12802         VDecl->getLocation(), DirectInit, Init);
12803 
12804     MultiExprArg Args = Init;
12805     if (CXXDirectInit)
12806       Args = MultiExprArg(CXXDirectInit->getExprs(),
12807                           CXXDirectInit->getNumExprs());
12808 
12809     // Try to correct any TypoExprs in the initialization arguments.
12810     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12811       ExprResult Res = CorrectDelayedTyposInExpr(
12812           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12813           [this, Entity, Kind](Expr *E) {
12814             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12815             return Init.Failed() ? ExprError() : E;
12816           });
12817       if (Res.isInvalid()) {
12818         VDecl->setInvalidDecl();
12819       } else if (Res.get() != Args[Idx]) {
12820         Args[Idx] = Res.get();
12821       }
12822     }
12823     if (VDecl->isInvalidDecl())
12824       return;
12825 
12826     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12827                                    /*TopLevelOfInitList=*/false,
12828                                    /*TreatUnavailableAsInvalid=*/false);
12829     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12830     if (Result.isInvalid()) {
12831       // If the provided initializer fails to initialize the var decl,
12832       // we attach a recovery expr for better recovery.
12833       auto RecoveryExpr =
12834           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12835       if (RecoveryExpr.get())
12836         VDecl->setInit(RecoveryExpr.get());
12837       return;
12838     }
12839 
12840     Init = Result.getAs<Expr>();
12841   }
12842 
12843   // Check for self-references within variable initializers.
12844   // Variables declared within a function/method body (except for references)
12845   // are handled by a dataflow analysis.
12846   // This is undefined behavior in C++, but valid in C.
12847   if (getLangOpts().CPlusPlus)
12848     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12849         VDecl->getType()->isReferenceType())
12850       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12851 
12852   // If the type changed, it means we had an incomplete type that was
12853   // completed by the initializer. For example:
12854   //   int ary[] = { 1, 3, 5 };
12855   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12856   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12857     VDecl->setType(DclT);
12858 
12859   if (!VDecl->isInvalidDecl()) {
12860     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12861 
12862     if (VDecl->hasAttr<BlocksAttr>())
12863       checkRetainCycles(VDecl, Init);
12864 
12865     // It is safe to assign a weak reference into a strong variable.
12866     // Although this code can still have problems:
12867     //   id x = self.weakProp;
12868     //   id y = self.weakProp;
12869     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12870     // paths through the function. This should be revisited if
12871     // -Wrepeated-use-of-weak is made flow-sensitive.
12872     if (FunctionScopeInfo *FSI = getCurFunction())
12873       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12874            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12875           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12876                            Init->getBeginLoc()))
12877         FSI->markSafeWeakUse(Init);
12878   }
12879 
12880   // The initialization is usually a full-expression.
12881   //
12882   // FIXME: If this is a braced initialization of an aggregate, it is not
12883   // an expression, and each individual field initializer is a separate
12884   // full-expression. For instance, in:
12885   //
12886   //   struct Temp { ~Temp(); };
12887   //   struct S { S(Temp); };
12888   //   struct T { S a, b; } t = { Temp(), Temp() }
12889   //
12890   // we should destroy the first Temp before constructing the second.
12891   ExprResult Result =
12892       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12893                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12894   if (Result.isInvalid()) {
12895     VDecl->setInvalidDecl();
12896     return;
12897   }
12898   Init = Result.get();
12899 
12900   // Attach the initializer to the decl.
12901   VDecl->setInit(Init);
12902 
12903   if (VDecl->isLocalVarDecl()) {
12904     // Don't check the initializer if the declaration is malformed.
12905     if (VDecl->isInvalidDecl()) {
12906       // do nothing
12907 
12908     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12909     // This is true even in C++ for OpenCL.
12910     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12911       CheckForConstantInitializer(Init, DclT);
12912 
12913     // Otherwise, C++ does not restrict the initializer.
12914     } else if (getLangOpts().CPlusPlus) {
12915       // do nothing
12916 
12917     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12918     // static storage duration shall be constant expressions or string literals.
12919     } else if (VDecl->getStorageClass() == SC_Static) {
12920       CheckForConstantInitializer(Init, DclT);
12921 
12922     // C89 is stricter than C99 for aggregate initializers.
12923     // C89 6.5.7p3: All the expressions [...] in an initializer list
12924     // for an object that has aggregate or union type shall be
12925     // constant expressions.
12926     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12927                isa<InitListExpr>(Init)) {
12928       const Expr *Culprit;
12929       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12930         Diag(Culprit->getExprLoc(),
12931              diag::ext_aggregate_init_not_constant)
12932           << Culprit->getSourceRange();
12933       }
12934     }
12935 
12936     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12937       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12938         if (VDecl->hasLocalStorage())
12939           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12940   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12941              VDecl->getLexicalDeclContext()->isRecord()) {
12942     // This is an in-class initialization for a static data member, e.g.,
12943     //
12944     // struct S {
12945     //   static const int value = 17;
12946     // };
12947 
12948     // C++ [class.mem]p4:
12949     //   A member-declarator can contain a constant-initializer only
12950     //   if it declares a static member (9.4) of const integral or
12951     //   const enumeration type, see 9.4.2.
12952     //
12953     // C++11 [class.static.data]p3:
12954     //   If a non-volatile non-inline const static data member is of integral
12955     //   or enumeration type, its declaration in the class definition can
12956     //   specify a brace-or-equal-initializer in which every initializer-clause
12957     //   that is an assignment-expression is a constant expression. A static
12958     //   data member of literal type can be declared in the class definition
12959     //   with the constexpr specifier; if so, its declaration shall specify a
12960     //   brace-or-equal-initializer in which every initializer-clause that is
12961     //   an assignment-expression is a constant expression.
12962 
12963     // Do nothing on dependent types.
12964     if (DclT->isDependentType()) {
12965 
12966     // Allow any 'static constexpr' members, whether or not they are of literal
12967     // type. We separately check that every constexpr variable is of literal
12968     // type.
12969     } else if (VDecl->isConstexpr()) {
12970 
12971     // Require constness.
12972     } else if (!DclT.isConstQualified()) {
12973       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12974         << Init->getSourceRange();
12975       VDecl->setInvalidDecl();
12976 
12977     // We allow integer constant expressions in all cases.
12978     } else if (DclT->isIntegralOrEnumerationType()) {
12979       // Check whether the expression is a constant expression.
12980       SourceLocation Loc;
12981       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12982         // In C++11, a non-constexpr const static data member with an
12983         // in-class initializer cannot be volatile.
12984         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12985       else if (Init->isValueDependent())
12986         ; // Nothing to check.
12987       else if (Init->isIntegerConstantExpr(Context, &Loc))
12988         ; // Ok, it's an ICE!
12989       else if (Init->getType()->isScopedEnumeralType() &&
12990                Init->isCXX11ConstantExpr(Context))
12991         ; // Ok, it is a scoped-enum constant expression.
12992       else if (Init->isEvaluatable(Context)) {
12993         // If we can constant fold the initializer through heroics, accept it,
12994         // but report this as a use of an extension for -pedantic.
12995         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12996           << Init->getSourceRange();
12997       } else {
12998         // Otherwise, this is some crazy unknown case.  Report the issue at the
12999         // location provided by the isIntegerConstantExpr failed check.
13000         Diag(Loc, diag::err_in_class_initializer_non_constant)
13001           << Init->getSourceRange();
13002         VDecl->setInvalidDecl();
13003       }
13004 
13005     // We allow foldable floating-point constants as an extension.
13006     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13007       // In C++98, this is a GNU extension. In C++11, it is not, but we support
13008       // it anyway and provide a fixit to add the 'constexpr'.
13009       if (getLangOpts().CPlusPlus11) {
13010         Diag(VDecl->getLocation(),
13011              diag::ext_in_class_initializer_float_type_cxx11)
13012             << DclT << Init->getSourceRange();
13013         Diag(VDecl->getBeginLoc(),
13014              diag::note_in_class_initializer_float_type_cxx11)
13015             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13016       } else {
13017         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13018           << DclT << Init->getSourceRange();
13019 
13020         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13021           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13022             << Init->getSourceRange();
13023           VDecl->setInvalidDecl();
13024         }
13025       }
13026 
13027     // Suggest adding 'constexpr' in C++11 for literal types.
13028     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13029       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13030           << DclT << Init->getSourceRange()
13031           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13032       VDecl->setConstexpr(true);
13033 
13034     } else {
13035       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13036         << DclT << Init->getSourceRange();
13037       VDecl->setInvalidDecl();
13038     }
13039   } else if (VDecl->isFileVarDecl()) {
13040     // In C, extern is typically used to avoid tentative definitions when
13041     // declaring variables in headers, but adding an intializer makes it a
13042     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13043     // In C++, extern is often used to give implictly static const variables
13044     // external linkage, so don't warn in that case. If selectany is present,
13045     // this might be header code intended for C and C++ inclusion, so apply the
13046     // C++ rules.
13047     if (VDecl->getStorageClass() == SC_Extern &&
13048         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13049          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13050         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13051         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13052       Diag(VDecl->getLocation(), diag::warn_extern_init);
13053 
13054     // In Microsoft C++ mode, a const variable defined in namespace scope has
13055     // external linkage by default if the variable is declared with
13056     // __declspec(dllexport).
13057     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13058         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13059         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13060       VDecl->setStorageClass(SC_Extern);
13061 
13062     // C99 6.7.8p4. All file scoped initializers need to be constant.
13063     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13064       CheckForConstantInitializer(Init, DclT);
13065   }
13066 
13067   QualType InitType = Init->getType();
13068   if (!InitType.isNull() &&
13069       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13070        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13071     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13072 
13073   // We will represent direct-initialization similarly to copy-initialization:
13074   //    int x(1);  -as-> int x = 1;
13075   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13076   //
13077   // Clients that want to distinguish between the two forms, can check for
13078   // direct initializer using VarDecl::getInitStyle().
13079   // A major benefit is that clients that don't particularly care about which
13080   // exactly form was it (like the CodeGen) can handle both cases without
13081   // special case code.
13082 
13083   // C++ 8.5p11:
13084   // The form of initialization (using parentheses or '=') is generally
13085   // insignificant, but does matter when the entity being initialized has a
13086   // class type.
13087   if (CXXDirectInit) {
13088     assert(DirectInit && "Call-style initializer must be direct init.");
13089     VDecl->setInitStyle(VarDecl::CallInit);
13090   } else if (DirectInit) {
13091     // This must be list-initialization. No other way is direct-initialization.
13092     VDecl->setInitStyle(VarDecl::ListInit);
13093   }
13094 
13095   if (LangOpts.OpenMP &&
13096       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13097       VDecl->isFileVarDecl())
13098     DeclsToCheckForDeferredDiags.insert(VDecl);
13099   CheckCompleteVariableDeclaration(VDecl);
13100 }
13101 
13102 /// ActOnInitializerError - Given that there was an error parsing an
13103 /// initializer for the given declaration, try to at least re-establish
13104 /// invariants such as whether a variable's type is either dependent or
13105 /// complete.
13106 void Sema::ActOnInitializerError(Decl *D) {
13107   // Our main concern here is re-establishing invariants like "a
13108   // variable's type is either dependent or complete".
13109   if (!D || D->isInvalidDecl()) return;
13110 
13111   VarDecl *VD = dyn_cast<VarDecl>(D);
13112   if (!VD) return;
13113 
13114   // Bindings are not usable if we can't make sense of the initializer.
13115   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13116     for (auto *BD : DD->bindings())
13117       BD->setInvalidDecl();
13118 
13119   // Auto types are meaningless if we can't make sense of the initializer.
13120   if (VD->getType()->isUndeducedType()) {
13121     D->setInvalidDecl();
13122     return;
13123   }
13124 
13125   QualType Ty = VD->getType();
13126   if (Ty->isDependentType()) return;
13127 
13128   // Require a complete type.
13129   if (RequireCompleteType(VD->getLocation(),
13130                           Context.getBaseElementType(Ty),
13131                           diag::err_typecheck_decl_incomplete_type)) {
13132     VD->setInvalidDecl();
13133     return;
13134   }
13135 
13136   // Require a non-abstract type.
13137   if (RequireNonAbstractType(VD->getLocation(), Ty,
13138                              diag::err_abstract_type_in_decl,
13139                              AbstractVariableType)) {
13140     VD->setInvalidDecl();
13141     return;
13142   }
13143 
13144   // Don't bother complaining about constructors or destructors,
13145   // though.
13146 }
13147 
13148 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13149   // If there is no declaration, there was an error parsing it. Just ignore it.
13150   if (!RealDecl)
13151     return;
13152 
13153   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13154     QualType Type = Var->getType();
13155 
13156     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13157     if (isa<DecompositionDecl>(RealDecl)) {
13158       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13159       Var->setInvalidDecl();
13160       return;
13161     }
13162 
13163     if (Type->isUndeducedType() &&
13164         DeduceVariableDeclarationType(Var, false, nullptr))
13165       return;
13166 
13167     // C++11 [class.static.data]p3: A static data member can be declared with
13168     // the constexpr specifier; if so, its declaration shall specify
13169     // a brace-or-equal-initializer.
13170     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13171     // the definition of a variable [...] or the declaration of a static data
13172     // member.
13173     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13174         !Var->isThisDeclarationADemotedDefinition()) {
13175       if (Var->isStaticDataMember()) {
13176         // C++1z removes the relevant rule; the in-class declaration is always
13177         // a definition there.
13178         if (!getLangOpts().CPlusPlus17 &&
13179             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13180           Diag(Var->getLocation(),
13181                diag::err_constexpr_static_mem_var_requires_init)
13182               << Var;
13183           Var->setInvalidDecl();
13184           return;
13185         }
13186       } else {
13187         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13188         Var->setInvalidDecl();
13189         return;
13190       }
13191     }
13192 
13193     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13194     // be initialized.
13195     if (!Var->isInvalidDecl() &&
13196         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13197         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13198       bool HasConstExprDefaultConstructor = false;
13199       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13200         for (auto *Ctor : RD->ctors()) {
13201           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13202               Ctor->getMethodQualifiers().getAddressSpace() ==
13203                   LangAS::opencl_constant) {
13204             HasConstExprDefaultConstructor = true;
13205           }
13206         }
13207       }
13208       if (!HasConstExprDefaultConstructor) {
13209         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13210         Var->setInvalidDecl();
13211         return;
13212       }
13213     }
13214 
13215     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13216       if (Var->getStorageClass() == SC_Extern) {
13217         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13218             << Var;
13219         Var->setInvalidDecl();
13220         return;
13221       }
13222       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13223                               diag::err_typecheck_decl_incomplete_type)) {
13224         Var->setInvalidDecl();
13225         return;
13226       }
13227       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13228         if (!RD->hasTrivialDefaultConstructor()) {
13229           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13230           Var->setInvalidDecl();
13231           return;
13232         }
13233       }
13234       // The declaration is unitialized, no need for further checks.
13235       return;
13236     }
13237 
13238     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13239     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13240         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13241       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13242                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13243 
13244 
13245     switch (DefKind) {
13246     case VarDecl::Definition:
13247       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13248         break;
13249 
13250       // We have an out-of-line definition of a static data member
13251       // that has an in-class initializer, so we type-check this like
13252       // a declaration.
13253       //
13254       LLVM_FALLTHROUGH;
13255 
13256     case VarDecl::DeclarationOnly:
13257       // It's only a declaration.
13258 
13259       // Block scope. C99 6.7p7: If an identifier for an object is
13260       // declared with no linkage (C99 6.2.2p6), the type for the
13261       // object shall be complete.
13262       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13263           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13264           RequireCompleteType(Var->getLocation(), Type,
13265                               diag::err_typecheck_decl_incomplete_type))
13266         Var->setInvalidDecl();
13267 
13268       // Make sure that the type is not abstract.
13269       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13270           RequireNonAbstractType(Var->getLocation(), Type,
13271                                  diag::err_abstract_type_in_decl,
13272                                  AbstractVariableType))
13273         Var->setInvalidDecl();
13274       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13275           Var->getStorageClass() == SC_PrivateExtern) {
13276         Diag(Var->getLocation(), diag::warn_private_extern);
13277         Diag(Var->getLocation(), diag::note_private_extern);
13278       }
13279 
13280       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13281           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13282         ExternalDeclarations.push_back(Var);
13283 
13284       return;
13285 
13286     case VarDecl::TentativeDefinition:
13287       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13288       // object that has file scope without an initializer, and without a
13289       // storage-class specifier or with the storage-class specifier "static",
13290       // constitutes a tentative definition. Note: A tentative definition with
13291       // external linkage is valid (C99 6.2.2p5).
13292       if (!Var->isInvalidDecl()) {
13293         if (const IncompleteArrayType *ArrayT
13294                                     = Context.getAsIncompleteArrayType(Type)) {
13295           if (RequireCompleteSizedType(
13296                   Var->getLocation(), ArrayT->getElementType(),
13297                   diag::err_array_incomplete_or_sizeless_type))
13298             Var->setInvalidDecl();
13299         } else if (Var->getStorageClass() == SC_Static) {
13300           // C99 6.9.2p3: If the declaration of an identifier for an object is
13301           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13302           // declared type shall not be an incomplete type.
13303           // NOTE: code such as the following
13304           //     static struct s;
13305           //     struct s { int a; };
13306           // is accepted by gcc. Hence here we issue a warning instead of
13307           // an error and we do not invalidate the static declaration.
13308           // NOTE: to avoid multiple warnings, only check the first declaration.
13309           if (Var->isFirstDecl())
13310             RequireCompleteType(Var->getLocation(), Type,
13311                                 diag::ext_typecheck_decl_incomplete_type);
13312         }
13313       }
13314 
13315       // Record the tentative definition; we're done.
13316       if (!Var->isInvalidDecl())
13317         TentativeDefinitions.push_back(Var);
13318       return;
13319     }
13320 
13321     // Provide a specific diagnostic for uninitialized variable
13322     // definitions with incomplete array type.
13323     if (Type->isIncompleteArrayType()) {
13324       Diag(Var->getLocation(),
13325            diag::err_typecheck_incomplete_array_needs_initializer);
13326       Var->setInvalidDecl();
13327       return;
13328     }
13329 
13330     // Provide a specific diagnostic for uninitialized variable
13331     // definitions with reference type.
13332     if (Type->isReferenceType()) {
13333       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13334           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13335       return;
13336     }
13337 
13338     // Do not attempt to type-check the default initializer for a
13339     // variable with dependent type.
13340     if (Type->isDependentType())
13341       return;
13342 
13343     if (Var->isInvalidDecl())
13344       return;
13345 
13346     if (!Var->hasAttr<AliasAttr>()) {
13347       if (RequireCompleteType(Var->getLocation(),
13348                               Context.getBaseElementType(Type),
13349                               diag::err_typecheck_decl_incomplete_type)) {
13350         Var->setInvalidDecl();
13351         return;
13352       }
13353     } else {
13354       return;
13355     }
13356 
13357     // The variable can not have an abstract class type.
13358     if (RequireNonAbstractType(Var->getLocation(), Type,
13359                                diag::err_abstract_type_in_decl,
13360                                AbstractVariableType)) {
13361       Var->setInvalidDecl();
13362       return;
13363     }
13364 
13365     // Check for jumps past the implicit initializer.  C++0x
13366     // clarifies that this applies to a "variable with automatic
13367     // storage duration", not a "local variable".
13368     // C++11 [stmt.dcl]p3
13369     //   A program that jumps from a point where a variable with automatic
13370     //   storage duration is not in scope to a point where it is in scope is
13371     //   ill-formed unless the variable has scalar type, class type with a
13372     //   trivial default constructor and a trivial destructor, a cv-qualified
13373     //   version of one of these types, or an array of one of the preceding
13374     //   types and is declared without an initializer.
13375     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13376       if (const RecordType *Record
13377             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13378         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13379         // Mark the function (if we're in one) for further checking even if the
13380         // looser rules of C++11 do not require such checks, so that we can
13381         // diagnose incompatibilities with C++98.
13382         if (!CXXRecord->isPOD())
13383           setFunctionHasBranchProtectedScope();
13384       }
13385     }
13386     // In OpenCL, we can't initialize objects in the __local address space,
13387     // even implicitly, so don't synthesize an implicit initializer.
13388     if (getLangOpts().OpenCL &&
13389         Var->getType().getAddressSpace() == LangAS::opencl_local)
13390       return;
13391     // C++03 [dcl.init]p9:
13392     //   If no initializer is specified for an object, and the
13393     //   object is of (possibly cv-qualified) non-POD class type (or
13394     //   array thereof), the object shall be default-initialized; if
13395     //   the object is of const-qualified type, the underlying class
13396     //   type shall have a user-declared default
13397     //   constructor. Otherwise, if no initializer is specified for
13398     //   a non- static object, the object and its subobjects, if
13399     //   any, have an indeterminate initial value); if the object
13400     //   or any of its subobjects are of const-qualified type, the
13401     //   program is ill-formed.
13402     // C++0x [dcl.init]p11:
13403     //   If no initializer is specified for an object, the object is
13404     //   default-initialized; [...].
13405     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13406     InitializationKind Kind
13407       = InitializationKind::CreateDefault(Var->getLocation());
13408 
13409     InitializationSequence InitSeq(*this, Entity, Kind, None);
13410     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13411 
13412     if (Init.get()) {
13413       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13414       // This is important for template substitution.
13415       Var->setInitStyle(VarDecl::CallInit);
13416     } else if (Init.isInvalid()) {
13417       // If default-init fails, attach a recovery-expr initializer to track
13418       // that initialization was attempted and failed.
13419       auto RecoveryExpr =
13420           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13421       if (RecoveryExpr.get())
13422         Var->setInit(RecoveryExpr.get());
13423     }
13424 
13425     CheckCompleteVariableDeclaration(Var);
13426   }
13427 }
13428 
13429 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13430   // If there is no declaration, there was an error parsing it. Ignore it.
13431   if (!D)
13432     return;
13433 
13434   VarDecl *VD = dyn_cast<VarDecl>(D);
13435   if (!VD) {
13436     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13437     D->setInvalidDecl();
13438     return;
13439   }
13440 
13441   VD->setCXXForRangeDecl(true);
13442 
13443   // for-range-declaration cannot be given a storage class specifier.
13444   int Error = -1;
13445   switch (VD->getStorageClass()) {
13446   case SC_None:
13447     break;
13448   case SC_Extern:
13449     Error = 0;
13450     break;
13451   case SC_Static:
13452     Error = 1;
13453     break;
13454   case SC_PrivateExtern:
13455     Error = 2;
13456     break;
13457   case SC_Auto:
13458     Error = 3;
13459     break;
13460   case SC_Register:
13461     Error = 4;
13462     break;
13463   }
13464 
13465   // for-range-declaration cannot be given a storage class specifier con't.
13466   switch (VD->getTSCSpec()) {
13467   case TSCS_thread_local:
13468     Error = 6;
13469     break;
13470   case TSCS___thread:
13471   case TSCS__Thread_local:
13472   case TSCS_unspecified:
13473     break;
13474   }
13475 
13476   if (Error != -1) {
13477     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13478         << VD << Error;
13479     D->setInvalidDecl();
13480   }
13481 }
13482 
13483 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13484                                             IdentifierInfo *Ident,
13485                                             ParsedAttributes &Attrs) {
13486   // C++1y [stmt.iter]p1:
13487   //   A range-based for statement of the form
13488   //      for ( for-range-identifier : for-range-initializer ) statement
13489   //   is equivalent to
13490   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13491   DeclSpec DS(Attrs.getPool().getFactory());
13492 
13493   const char *PrevSpec;
13494   unsigned DiagID;
13495   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13496                      getPrintingPolicy());
13497 
13498   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13499   D.SetIdentifier(Ident, IdentLoc);
13500   D.takeAttributes(Attrs);
13501 
13502   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13503                 IdentLoc);
13504   Decl *Var = ActOnDeclarator(S, D);
13505   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13506   FinalizeDeclaration(Var);
13507   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13508                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13509                                                       : IdentLoc);
13510 }
13511 
13512 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13513   if (var->isInvalidDecl()) return;
13514 
13515   MaybeAddCUDAConstantAttr(var);
13516 
13517   if (getLangOpts().OpenCL) {
13518     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13519     // initialiser
13520     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13521         !var->hasInit()) {
13522       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13523           << 1 /*Init*/;
13524       var->setInvalidDecl();
13525       return;
13526     }
13527   }
13528 
13529   // In Objective-C, don't allow jumps past the implicit initialization of a
13530   // local retaining variable.
13531   if (getLangOpts().ObjC &&
13532       var->hasLocalStorage()) {
13533     switch (var->getType().getObjCLifetime()) {
13534     case Qualifiers::OCL_None:
13535     case Qualifiers::OCL_ExplicitNone:
13536     case Qualifiers::OCL_Autoreleasing:
13537       break;
13538 
13539     case Qualifiers::OCL_Weak:
13540     case Qualifiers::OCL_Strong:
13541       setFunctionHasBranchProtectedScope();
13542       break;
13543     }
13544   }
13545 
13546   if (var->hasLocalStorage() &&
13547       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13548     setFunctionHasBranchProtectedScope();
13549 
13550   // Warn about externally-visible variables being defined without a
13551   // prior declaration.  We only want to do this for global
13552   // declarations, but we also specifically need to avoid doing it for
13553   // class members because the linkage of an anonymous class can
13554   // change if it's later given a typedef name.
13555   if (var->isThisDeclarationADefinition() &&
13556       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13557       var->isExternallyVisible() && var->hasLinkage() &&
13558       !var->isInline() && !var->getDescribedVarTemplate() &&
13559       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13560       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13561       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13562                                   var->getLocation())) {
13563     // Find a previous declaration that's not a definition.
13564     VarDecl *prev = var->getPreviousDecl();
13565     while (prev && prev->isThisDeclarationADefinition())
13566       prev = prev->getPreviousDecl();
13567 
13568     if (!prev) {
13569       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13570       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13571           << /* variable */ 0;
13572     }
13573   }
13574 
13575   // Cache the result of checking for constant initialization.
13576   Optional<bool> CacheHasConstInit;
13577   const Expr *CacheCulprit = nullptr;
13578   auto checkConstInit = [&]() mutable {
13579     if (!CacheHasConstInit)
13580       CacheHasConstInit = var->getInit()->isConstantInitializer(
13581             Context, var->getType()->isReferenceType(), &CacheCulprit);
13582     return *CacheHasConstInit;
13583   };
13584 
13585   if (var->getTLSKind() == VarDecl::TLS_Static) {
13586     if (var->getType().isDestructedType()) {
13587       // GNU C++98 edits for __thread, [basic.start.term]p3:
13588       //   The type of an object with thread storage duration shall not
13589       //   have a non-trivial destructor.
13590       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13591       if (getLangOpts().CPlusPlus11)
13592         Diag(var->getLocation(), diag::note_use_thread_local);
13593     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13594       if (!checkConstInit()) {
13595         // GNU C++98 edits for __thread, [basic.start.init]p4:
13596         //   An object of thread storage duration shall not require dynamic
13597         //   initialization.
13598         // FIXME: Need strict checking here.
13599         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13600           << CacheCulprit->getSourceRange();
13601         if (getLangOpts().CPlusPlus11)
13602           Diag(var->getLocation(), diag::note_use_thread_local);
13603       }
13604     }
13605   }
13606 
13607 
13608   if (!var->getType()->isStructureType() && var->hasInit() &&
13609       isa<InitListExpr>(var->getInit())) {
13610     const auto *ILE = cast<InitListExpr>(var->getInit());
13611     unsigned NumInits = ILE->getNumInits();
13612     if (NumInits > 2)
13613       for (unsigned I = 0; I < NumInits; ++I) {
13614         const auto *Init = ILE->getInit(I);
13615         if (!Init)
13616           break;
13617         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13618         if (!SL)
13619           break;
13620 
13621         unsigned NumConcat = SL->getNumConcatenated();
13622         // Diagnose missing comma in string array initialization.
13623         // Do not warn when all the elements in the initializer are concatenated
13624         // together. Do not warn for macros too.
13625         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13626           bool OnlyOneMissingComma = true;
13627           for (unsigned J = I + 1; J < NumInits; ++J) {
13628             const auto *Init = ILE->getInit(J);
13629             if (!Init)
13630               break;
13631             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13632             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13633               OnlyOneMissingComma = false;
13634               break;
13635             }
13636           }
13637 
13638           if (OnlyOneMissingComma) {
13639             SmallVector<FixItHint, 1> Hints;
13640             for (unsigned i = 0; i < NumConcat - 1; ++i)
13641               Hints.push_back(FixItHint::CreateInsertion(
13642                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13643 
13644             Diag(SL->getStrTokenLoc(1),
13645                  diag::warn_concatenated_literal_array_init)
13646                 << Hints;
13647             Diag(SL->getBeginLoc(),
13648                  diag::note_concatenated_string_literal_silence);
13649           }
13650           // In any case, stop now.
13651           break;
13652         }
13653       }
13654   }
13655 
13656 
13657   QualType type = var->getType();
13658 
13659   if (var->hasAttr<BlocksAttr>())
13660     getCurFunction()->addByrefBlockVar(var);
13661 
13662   Expr *Init = var->getInit();
13663   bool GlobalStorage = var->hasGlobalStorage();
13664   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13665   QualType baseType = Context.getBaseElementType(type);
13666   bool HasConstInit = true;
13667 
13668   // Check whether the initializer is sufficiently constant.
13669   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13670       !Init->isValueDependent() &&
13671       (GlobalStorage || var->isConstexpr() ||
13672        var->mightBeUsableInConstantExpressions(Context))) {
13673     // If this variable might have a constant initializer or might be usable in
13674     // constant expressions, check whether or not it actually is now.  We can't
13675     // do this lazily, because the result might depend on things that change
13676     // later, such as which constexpr functions happen to be defined.
13677     SmallVector<PartialDiagnosticAt, 8> Notes;
13678     if (!getLangOpts().CPlusPlus11) {
13679       // Prior to C++11, in contexts where a constant initializer is required,
13680       // the set of valid constant initializers is described by syntactic rules
13681       // in [expr.const]p2-6.
13682       // FIXME: Stricter checking for these rules would be useful for constinit /
13683       // -Wglobal-constructors.
13684       HasConstInit = checkConstInit();
13685 
13686       // Compute and cache the constant value, and remember that we have a
13687       // constant initializer.
13688       if (HasConstInit) {
13689         (void)var->checkForConstantInitialization(Notes);
13690         Notes.clear();
13691       } else if (CacheCulprit) {
13692         Notes.emplace_back(CacheCulprit->getExprLoc(),
13693                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13694         Notes.back().second << CacheCulprit->getSourceRange();
13695       }
13696     } else {
13697       // Evaluate the initializer to see if it's a constant initializer.
13698       HasConstInit = var->checkForConstantInitialization(Notes);
13699     }
13700 
13701     if (HasConstInit) {
13702       // FIXME: Consider replacing the initializer with a ConstantExpr.
13703     } else if (var->isConstexpr()) {
13704       SourceLocation DiagLoc = var->getLocation();
13705       // If the note doesn't add any useful information other than a source
13706       // location, fold it into the primary diagnostic.
13707       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13708                                    diag::note_invalid_subexpr_in_const_expr) {
13709         DiagLoc = Notes[0].first;
13710         Notes.clear();
13711       }
13712       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13713           << var << Init->getSourceRange();
13714       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13715         Diag(Notes[I].first, Notes[I].second);
13716     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13717       auto *Attr = var->getAttr<ConstInitAttr>();
13718       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13719           << Init->getSourceRange();
13720       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13721           << Attr->getRange() << Attr->isConstinit();
13722       for (auto &it : Notes)
13723         Diag(it.first, it.second);
13724     } else if (IsGlobal &&
13725                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13726                                            var->getLocation())) {
13727       // Warn about globals which don't have a constant initializer.  Don't
13728       // warn about globals with a non-trivial destructor because we already
13729       // warned about them.
13730       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13731       if (!(RD && !RD->hasTrivialDestructor())) {
13732         // checkConstInit() here permits trivial default initialization even in
13733         // C++11 onwards, where such an initializer is not a constant initializer
13734         // but nonetheless doesn't require a global constructor.
13735         if (!checkConstInit())
13736           Diag(var->getLocation(), diag::warn_global_constructor)
13737               << Init->getSourceRange();
13738       }
13739     }
13740   }
13741 
13742   // Apply section attributes and pragmas to global variables.
13743   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13744       !inTemplateInstantiation()) {
13745     PragmaStack<StringLiteral *> *Stack = nullptr;
13746     int SectionFlags = ASTContext::PSF_Read;
13747     if (var->getType().isConstQualified()) {
13748       if (HasConstInit)
13749         Stack = &ConstSegStack;
13750       else {
13751         Stack = &BSSSegStack;
13752         SectionFlags |= ASTContext::PSF_Write;
13753       }
13754     } else if (var->hasInit() && HasConstInit) {
13755       Stack = &DataSegStack;
13756       SectionFlags |= ASTContext::PSF_Write;
13757     } else {
13758       Stack = &BSSSegStack;
13759       SectionFlags |= ASTContext::PSF_Write;
13760     }
13761     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13762       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13763         SectionFlags |= ASTContext::PSF_Implicit;
13764       UnifySection(SA->getName(), SectionFlags, var);
13765     } else if (Stack->CurrentValue) {
13766       SectionFlags |= ASTContext::PSF_Implicit;
13767       auto SectionName = Stack->CurrentValue->getString();
13768       var->addAttr(SectionAttr::CreateImplicit(
13769           Context, SectionName, Stack->CurrentPragmaLocation,
13770           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13771       if (UnifySection(SectionName, SectionFlags, var))
13772         var->dropAttr<SectionAttr>();
13773     }
13774 
13775     // Apply the init_seg attribute if this has an initializer.  If the
13776     // initializer turns out to not be dynamic, we'll end up ignoring this
13777     // attribute.
13778     if (CurInitSeg && var->getInit())
13779       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13780                                                CurInitSegLoc,
13781                                                AttributeCommonInfo::AS_Pragma));
13782   }
13783 
13784   // All the following checks are C++ only.
13785   if (!getLangOpts().CPlusPlus) {
13786     // If this variable must be emitted, add it as an initializer for the
13787     // current module.
13788     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13789       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13790     return;
13791   }
13792 
13793   // Require the destructor.
13794   if (!type->isDependentType())
13795     if (const RecordType *recordType = baseType->getAs<RecordType>())
13796       FinalizeVarWithDestructor(var, recordType);
13797 
13798   // If this variable must be emitted, add it as an initializer for the current
13799   // module.
13800   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13801     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13802 
13803   // Build the bindings if this is a structured binding declaration.
13804   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13805     CheckCompleteDecompositionDeclaration(DD);
13806 }
13807 
13808 /// Check if VD needs to be dllexport/dllimport due to being in a
13809 /// dllexport/import function.
13810 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13811   assert(VD->isStaticLocal());
13812 
13813   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13814 
13815   // Find outermost function when VD is in lambda function.
13816   while (FD && !getDLLAttr(FD) &&
13817          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13818          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13819     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13820   }
13821 
13822   if (!FD)
13823     return;
13824 
13825   // Static locals inherit dll attributes from their function.
13826   if (Attr *A = getDLLAttr(FD)) {
13827     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13828     NewAttr->setInherited(true);
13829     VD->addAttr(NewAttr);
13830   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13831     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13832     NewAttr->setInherited(true);
13833     VD->addAttr(NewAttr);
13834 
13835     // Export this function to enforce exporting this static variable even
13836     // if it is not used in this compilation unit.
13837     if (!FD->hasAttr<DLLExportAttr>())
13838       FD->addAttr(NewAttr);
13839 
13840   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13841     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13842     NewAttr->setInherited(true);
13843     VD->addAttr(NewAttr);
13844   }
13845 }
13846 
13847 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13848 /// any semantic actions necessary after any initializer has been attached.
13849 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13850   // Note that we are no longer parsing the initializer for this declaration.
13851   ParsingInitForAutoVars.erase(ThisDecl);
13852 
13853   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13854   if (!VD)
13855     return;
13856 
13857   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13858   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13859       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13860     if (PragmaClangBSSSection.Valid)
13861       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13862           Context, PragmaClangBSSSection.SectionName,
13863           PragmaClangBSSSection.PragmaLocation,
13864           AttributeCommonInfo::AS_Pragma));
13865     if (PragmaClangDataSection.Valid)
13866       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13867           Context, PragmaClangDataSection.SectionName,
13868           PragmaClangDataSection.PragmaLocation,
13869           AttributeCommonInfo::AS_Pragma));
13870     if (PragmaClangRodataSection.Valid)
13871       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13872           Context, PragmaClangRodataSection.SectionName,
13873           PragmaClangRodataSection.PragmaLocation,
13874           AttributeCommonInfo::AS_Pragma));
13875     if (PragmaClangRelroSection.Valid)
13876       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13877           Context, PragmaClangRelroSection.SectionName,
13878           PragmaClangRelroSection.PragmaLocation,
13879           AttributeCommonInfo::AS_Pragma));
13880   }
13881 
13882   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13883     for (auto *BD : DD->bindings()) {
13884       FinalizeDeclaration(BD);
13885     }
13886   }
13887 
13888   checkAttributesAfterMerging(*this, *VD);
13889 
13890   // Perform TLS alignment check here after attributes attached to the variable
13891   // which may affect the alignment have been processed. Only perform the check
13892   // if the target has a maximum TLS alignment (zero means no constraints).
13893   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13894     // Protect the check so that it's not performed on dependent types and
13895     // dependent alignments (we can't determine the alignment in that case).
13896     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13897       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13898       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13899         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13900           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13901           << (unsigned)MaxAlignChars.getQuantity();
13902       }
13903     }
13904   }
13905 
13906   if (VD->isStaticLocal())
13907     CheckStaticLocalForDllExport(VD);
13908 
13909   // Perform check for initializers of device-side global variables.
13910   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13911   // 7.5). We must also apply the same checks to all __shared__
13912   // variables whether they are local or not. CUDA also allows
13913   // constant initializers for __constant__ and __device__ variables.
13914   if (getLangOpts().CUDA)
13915     checkAllowedCUDAInitializer(VD);
13916 
13917   // Grab the dllimport or dllexport attribute off of the VarDecl.
13918   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13919 
13920   // Imported static data members cannot be defined out-of-line.
13921   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13922     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13923         VD->isThisDeclarationADefinition()) {
13924       // We allow definitions of dllimport class template static data members
13925       // with a warning.
13926       CXXRecordDecl *Context =
13927         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13928       bool IsClassTemplateMember =
13929           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13930           Context->getDescribedClassTemplate();
13931 
13932       Diag(VD->getLocation(),
13933            IsClassTemplateMember
13934                ? diag::warn_attribute_dllimport_static_field_definition
13935                : diag::err_attribute_dllimport_static_field_definition);
13936       Diag(IA->getLocation(), diag::note_attribute);
13937       if (!IsClassTemplateMember)
13938         VD->setInvalidDecl();
13939     }
13940   }
13941 
13942   // dllimport/dllexport variables cannot be thread local, their TLS index
13943   // isn't exported with the variable.
13944   if (DLLAttr && VD->getTLSKind()) {
13945     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13946     if (F && getDLLAttr(F)) {
13947       assert(VD->isStaticLocal());
13948       // But if this is a static local in a dlimport/dllexport function, the
13949       // function will never be inlined, which means the var would never be
13950       // imported, so having it marked import/export is safe.
13951     } else {
13952       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13953                                                                     << DLLAttr;
13954       VD->setInvalidDecl();
13955     }
13956   }
13957 
13958   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13959     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13960       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13961           << Attr;
13962       VD->dropAttr<UsedAttr>();
13963     }
13964   }
13965   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13966     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13967       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13968           << Attr;
13969       VD->dropAttr<RetainAttr>();
13970     }
13971   }
13972 
13973   const DeclContext *DC = VD->getDeclContext();
13974   // If there's a #pragma GCC visibility in scope, and this isn't a class
13975   // member, set the visibility of this variable.
13976   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13977     AddPushedVisibilityAttribute(VD);
13978 
13979   // FIXME: Warn on unused var template partial specializations.
13980   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13981     MarkUnusedFileScopedDecl(VD);
13982 
13983   // Now we have parsed the initializer and can update the table of magic
13984   // tag values.
13985   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13986       !VD->getType()->isIntegralOrEnumerationType())
13987     return;
13988 
13989   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13990     const Expr *MagicValueExpr = VD->getInit();
13991     if (!MagicValueExpr) {
13992       continue;
13993     }
13994     Optional<llvm::APSInt> MagicValueInt;
13995     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13996       Diag(I->getRange().getBegin(),
13997            diag::err_type_tag_for_datatype_not_ice)
13998         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13999       continue;
14000     }
14001     if (MagicValueInt->getActiveBits() > 64) {
14002       Diag(I->getRange().getBegin(),
14003            diag::err_type_tag_for_datatype_too_large)
14004         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14005       continue;
14006     }
14007     uint64_t MagicValue = MagicValueInt->getZExtValue();
14008     RegisterTypeTagForDatatype(I->getArgumentKind(),
14009                                MagicValue,
14010                                I->getMatchingCType(),
14011                                I->getLayoutCompatible(),
14012                                I->getMustBeNull());
14013   }
14014 }
14015 
14016 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14017   auto *VD = dyn_cast<VarDecl>(DD);
14018   return VD && !VD->getType()->hasAutoForTrailingReturnType();
14019 }
14020 
14021 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14022                                                    ArrayRef<Decl *> Group) {
14023   SmallVector<Decl*, 8> Decls;
14024 
14025   if (DS.isTypeSpecOwned())
14026     Decls.push_back(DS.getRepAsDecl());
14027 
14028   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14029   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14030   bool DiagnosedMultipleDecomps = false;
14031   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14032   bool DiagnosedNonDeducedAuto = false;
14033 
14034   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14035     if (Decl *D = Group[i]) {
14036       // For declarators, there are some additional syntactic-ish checks we need
14037       // to perform.
14038       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14039         if (!FirstDeclaratorInGroup)
14040           FirstDeclaratorInGroup = DD;
14041         if (!FirstDecompDeclaratorInGroup)
14042           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14043         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14044             !hasDeducedAuto(DD))
14045           FirstNonDeducedAutoInGroup = DD;
14046 
14047         if (FirstDeclaratorInGroup != DD) {
14048           // A decomposition declaration cannot be combined with any other
14049           // declaration in the same group.
14050           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14051             Diag(FirstDecompDeclaratorInGroup->getLocation(),
14052                  diag::err_decomp_decl_not_alone)
14053                 << FirstDeclaratorInGroup->getSourceRange()
14054                 << DD->getSourceRange();
14055             DiagnosedMultipleDecomps = true;
14056           }
14057 
14058           // A declarator that uses 'auto' in any way other than to declare a
14059           // variable with a deduced type cannot be combined with any other
14060           // declarator in the same group.
14061           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14062             Diag(FirstNonDeducedAutoInGroup->getLocation(),
14063                  diag::err_auto_non_deduced_not_alone)
14064                 << FirstNonDeducedAutoInGroup->getType()
14065                        ->hasAutoForTrailingReturnType()
14066                 << FirstDeclaratorInGroup->getSourceRange()
14067                 << DD->getSourceRange();
14068             DiagnosedNonDeducedAuto = true;
14069           }
14070         }
14071       }
14072 
14073       Decls.push_back(D);
14074     }
14075   }
14076 
14077   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14078     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14079       handleTagNumbering(Tag, S);
14080       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14081           getLangOpts().CPlusPlus)
14082         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14083     }
14084   }
14085 
14086   return BuildDeclaratorGroup(Decls);
14087 }
14088 
14089 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14090 /// group, performing any necessary semantic checking.
14091 Sema::DeclGroupPtrTy
14092 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14093   // C++14 [dcl.spec.auto]p7: (DR1347)
14094   //   If the type that replaces the placeholder type is not the same in each
14095   //   deduction, the program is ill-formed.
14096   if (Group.size() > 1) {
14097     QualType Deduced;
14098     VarDecl *DeducedDecl = nullptr;
14099     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14100       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14101       if (!D || D->isInvalidDecl())
14102         break;
14103       DeducedType *DT = D->getType()->getContainedDeducedType();
14104       if (!DT || DT->getDeducedType().isNull())
14105         continue;
14106       if (Deduced.isNull()) {
14107         Deduced = DT->getDeducedType();
14108         DeducedDecl = D;
14109       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14110         auto *AT = dyn_cast<AutoType>(DT);
14111         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14112                         diag::err_auto_different_deductions)
14113                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14114                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14115                    << D->getDeclName();
14116         if (DeducedDecl->hasInit())
14117           Dia << DeducedDecl->getInit()->getSourceRange();
14118         if (D->getInit())
14119           Dia << D->getInit()->getSourceRange();
14120         D->setInvalidDecl();
14121         break;
14122       }
14123     }
14124   }
14125 
14126   ActOnDocumentableDecls(Group);
14127 
14128   return DeclGroupPtrTy::make(
14129       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14130 }
14131 
14132 void Sema::ActOnDocumentableDecl(Decl *D) {
14133   ActOnDocumentableDecls(D);
14134 }
14135 
14136 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14137   // Don't parse the comment if Doxygen diagnostics are ignored.
14138   if (Group.empty() || !Group[0])
14139     return;
14140 
14141   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14142                       Group[0]->getLocation()) &&
14143       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14144                       Group[0]->getLocation()))
14145     return;
14146 
14147   if (Group.size() >= 2) {
14148     // This is a decl group.  Normally it will contain only declarations
14149     // produced from declarator list.  But in case we have any definitions or
14150     // additional declaration references:
14151     //   'typedef struct S {} S;'
14152     //   'typedef struct S *S;'
14153     //   'struct S *pS;'
14154     // FinalizeDeclaratorGroup adds these as separate declarations.
14155     Decl *MaybeTagDecl = Group[0];
14156     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14157       Group = Group.slice(1);
14158     }
14159   }
14160 
14161   // FIMXE: We assume every Decl in the group is in the same file.
14162   // This is false when preprocessor constructs the group from decls in
14163   // different files (e. g. macros or #include).
14164   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14165 }
14166 
14167 /// Common checks for a parameter-declaration that should apply to both function
14168 /// parameters and non-type template parameters.
14169 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14170   // Check that there are no default arguments inside the type of this
14171   // parameter.
14172   if (getLangOpts().CPlusPlus)
14173     CheckExtraCXXDefaultArguments(D);
14174 
14175   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14176   if (D.getCXXScopeSpec().isSet()) {
14177     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14178       << D.getCXXScopeSpec().getRange();
14179   }
14180 
14181   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14182   // simple identifier except [...irrelevant cases...].
14183   switch (D.getName().getKind()) {
14184   case UnqualifiedIdKind::IK_Identifier:
14185     break;
14186 
14187   case UnqualifiedIdKind::IK_OperatorFunctionId:
14188   case UnqualifiedIdKind::IK_ConversionFunctionId:
14189   case UnqualifiedIdKind::IK_LiteralOperatorId:
14190   case UnqualifiedIdKind::IK_ConstructorName:
14191   case UnqualifiedIdKind::IK_DestructorName:
14192   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14193   case UnqualifiedIdKind::IK_DeductionGuideName:
14194     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14195       << GetNameForDeclarator(D).getName();
14196     break;
14197 
14198   case UnqualifiedIdKind::IK_TemplateId:
14199   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14200     // GetNameForDeclarator would not produce a useful name in this case.
14201     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14202     break;
14203   }
14204 }
14205 
14206 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14207 /// to introduce parameters into function prototype scope.
14208 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14209   const DeclSpec &DS = D.getDeclSpec();
14210 
14211   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14212 
14213   // C++03 [dcl.stc]p2 also permits 'auto'.
14214   StorageClass SC = SC_None;
14215   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14216     SC = SC_Register;
14217     // In C++11, the 'register' storage class specifier is deprecated.
14218     // In C++17, it is not allowed, but we tolerate it as an extension.
14219     if (getLangOpts().CPlusPlus11) {
14220       Diag(DS.getStorageClassSpecLoc(),
14221            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14222                                      : diag::warn_deprecated_register)
14223         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14224     }
14225   } else if (getLangOpts().CPlusPlus &&
14226              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14227     SC = SC_Auto;
14228   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14229     Diag(DS.getStorageClassSpecLoc(),
14230          diag::err_invalid_storage_class_in_func_decl);
14231     D.getMutableDeclSpec().ClearStorageClassSpecs();
14232   }
14233 
14234   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14235     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14236       << DeclSpec::getSpecifierName(TSCS);
14237   if (DS.isInlineSpecified())
14238     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14239         << getLangOpts().CPlusPlus17;
14240   if (DS.hasConstexprSpecifier())
14241     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14242         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14243 
14244   DiagnoseFunctionSpecifiers(DS);
14245 
14246   CheckFunctionOrTemplateParamDeclarator(S, D);
14247 
14248   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14249   QualType parmDeclType = TInfo->getType();
14250 
14251   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14252   IdentifierInfo *II = D.getIdentifier();
14253   if (II) {
14254     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14255                    ForVisibleRedeclaration);
14256     LookupName(R, S);
14257     if (R.isSingleResult()) {
14258       NamedDecl *PrevDecl = R.getFoundDecl();
14259       if (PrevDecl->isTemplateParameter()) {
14260         // Maybe we will complain about the shadowed template parameter.
14261         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14262         // Just pretend that we didn't see the previous declaration.
14263         PrevDecl = nullptr;
14264       } else if (S->isDeclScope(PrevDecl)) {
14265         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14266         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14267 
14268         // Recover by removing the name
14269         II = nullptr;
14270         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14271         D.setInvalidType(true);
14272       }
14273     }
14274   }
14275 
14276   // Temporarily put parameter variables in the translation unit, not
14277   // the enclosing context.  This prevents them from accidentally
14278   // looking like class members in C++.
14279   ParmVarDecl *New =
14280       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14281                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14282 
14283   if (D.isInvalidType())
14284     New->setInvalidDecl();
14285 
14286   assert(S->isFunctionPrototypeScope());
14287   assert(S->getFunctionPrototypeDepth() >= 1);
14288   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14289                     S->getNextFunctionPrototypeIndex());
14290 
14291   // Add the parameter declaration into this scope.
14292   S->AddDecl(New);
14293   if (II)
14294     IdResolver.AddDecl(New);
14295 
14296   ProcessDeclAttributes(S, New, D);
14297 
14298   if (D.getDeclSpec().isModulePrivateSpecified())
14299     Diag(New->getLocation(), diag::err_module_private_local)
14300         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14301         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14302 
14303   if (New->hasAttr<BlocksAttr>()) {
14304     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14305   }
14306 
14307   if (getLangOpts().OpenCL)
14308     deduceOpenCLAddressSpace(New);
14309 
14310   return New;
14311 }
14312 
14313 /// Synthesizes a variable for a parameter arising from a
14314 /// typedef.
14315 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14316                                               SourceLocation Loc,
14317                                               QualType T) {
14318   /* FIXME: setting StartLoc == Loc.
14319      Would it be worth to modify callers so as to provide proper source
14320      location for the unnamed parameters, embedding the parameter's type? */
14321   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14322                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14323                                            SC_None, nullptr);
14324   Param->setImplicit();
14325   return Param;
14326 }
14327 
14328 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14329   // Don't diagnose unused-parameter errors in template instantiations; we
14330   // will already have done so in the template itself.
14331   if (inTemplateInstantiation())
14332     return;
14333 
14334   for (const ParmVarDecl *Parameter : Parameters) {
14335     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14336         !Parameter->hasAttr<UnusedAttr>()) {
14337       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14338         << Parameter->getDeclName();
14339     }
14340   }
14341 }
14342 
14343 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14344     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14345   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14346     return;
14347 
14348   // Warn if the return value is pass-by-value and larger than the specified
14349   // threshold.
14350   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14351     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14352     if (Size > LangOpts.NumLargeByValueCopy)
14353       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14354   }
14355 
14356   // Warn if any parameter is pass-by-value and larger than the specified
14357   // threshold.
14358   for (const ParmVarDecl *Parameter : Parameters) {
14359     QualType T = Parameter->getType();
14360     if (T->isDependentType() || !T.isPODType(Context))
14361       continue;
14362     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14363     if (Size > LangOpts.NumLargeByValueCopy)
14364       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14365           << Parameter << Size;
14366   }
14367 }
14368 
14369 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14370                                   SourceLocation NameLoc, IdentifierInfo *Name,
14371                                   QualType T, TypeSourceInfo *TSInfo,
14372                                   StorageClass SC) {
14373   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14374   if (getLangOpts().ObjCAutoRefCount &&
14375       T.getObjCLifetime() == Qualifiers::OCL_None &&
14376       T->isObjCLifetimeType()) {
14377 
14378     Qualifiers::ObjCLifetime lifetime;
14379 
14380     // Special cases for arrays:
14381     //   - if it's const, use __unsafe_unretained
14382     //   - otherwise, it's an error
14383     if (T->isArrayType()) {
14384       if (!T.isConstQualified()) {
14385         if (DelayedDiagnostics.shouldDelayDiagnostics())
14386           DelayedDiagnostics.add(
14387               sema::DelayedDiagnostic::makeForbiddenType(
14388               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14389         else
14390           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14391               << TSInfo->getTypeLoc().getSourceRange();
14392       }
14393       lifetime = Qualifiers::OCL_ExplicitNone;
14394     } else {
14395       lifetime = T->getObjCARCImplicitLifetime();
14396     }
14397     T = Context.getLifetimeQualifiedType(T, lifetime);
14398   }
14399 
14400   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14401                                          Context.getAdjustedParameterType(T),
14402                                          TSInfo, SC, nullptr);
14403 
14404   // Make a note if we created a new pack in the scope of a lambda, so that
14405   // we know that references to that pack must also be expanded within the
14406   // lambda scope.
14407   if (New->isParameterPack())
14408     if (auto *LSI = getEnclosingLambda())
14409       LSI->LocalPacks.push_back(New);
14410 
14411   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14412       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14413     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14414                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14415 
14416   // Parameters can not be abstract class types.
14417   // For record types, this is done by the AbstractClassUsageDiagnoser once
14418   // the class has been completely parsed.
14419   if (!CurContext->isRecord() &&
14420       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14421                              AbstractParamType))
14422     New->setInvalidDecl();
14423 
14424   // Parameter declarators cannot be interface types. All ObjC objects are
14425   // passed by reference.
14426   if (T->isObjCObjectType()) {
14427     SourceLocation TypeEndLoc =
14428         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14429     Diag(NameLoc,
14430          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14431       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14432     T = Context.getObjCObjectPointerType(T);
14433     New->setType(T);
14434   }
14435 
14436   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14437   // duration shall not be qualified by an address-space qualifier."
14438   // Since all parameters have automatic store duration, they can not have
14439   // an address space.
14440   if (T.getAddressSpace() != LangAS::Default &&
14441       // OpenCL allows function arguments declared to be an array of a type
14442       // to be qualified with an address space.
14443       !(getLangOpts().OpenCL &&
14444         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14445     Diag(NameLoc, diag::err_arg_with_address_space);
14446     New->setInvalidDecl();
14447   }
14448 
14449   // PPC MMA non-pointer types are not allowed as function argument types.
14450   if (Context.getTargetInfo().getTriple().isPPC64() &&
14451       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14452     New->setInvalidDecl();
14453   }
14454 
14455   return New;
14456 }
14457 
14458 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14459                                            SourceLocation LocAfterDecls) {
14460   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14461 
14462   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14463   // in the declaration list shall have at least one declarator, those
14464   // declarators shall only declare identifiers from the identifier list, and
14465   // every identifier in the identifier list shall be declared.
14466   //
14467   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14468   // identifiers it names shall be declared in the declaration list."
14469   //
14470   // This is why we only diagnose in C99 and later. Note, the other conditions
14471   // listed are checked elsewhere.
14472   if (!FTI.hasPrototype) {
14473     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14474       --i;
14475       if (FTI.Params[i].Param == nullptr) {
14476         if (getLangOpts().C99) {
14477           SmallString<256> Code;
14478           llvm::raw_svector_ostream(Code)
14479               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14480           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14481               << FTI.Params[i].Ident
14482               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14483         }
14484 
14485         // Implicitly declare the argument as type 'int' for lack of a better
14486         // type.
14487         AttributeFactory attrs;
14488         DeclSpec DS(attrs);
14489         const char* PrevSpec; // unused
14490         unsigned DiagID; // unused
14491         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14492                            DiagID, Context.getPrintingPolicy());
14493         // Use the identifier location for the type source range.
14494         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14495         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14496         Declarator ParamD(DS, ParsedAttributesView::none(),
14497                           DeclaratorContext::KNRTypeList);
14498         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14499         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14500       }
14501     }
14502   }
14503 }
14504 
14505 Decl *
14506 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14507                               MultiTemplateParamsArg TemplateParameterLists,
14508                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14509   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14510   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14511   Scope *ParentScope = FnBodyScope->getParent();
14512 
14513   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14514   // we define a non-templated function definition, we will create a declaration
14515   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14516   // The base function declaration will have the equivalent of an `omp declare
14517   // variant` annotation which specifies the mangled definition as a
14518   // specialization function under the OpenMP context defined as part of the
14519   // `omp begin declare variant`.
14520   SmallVector<FunctionDecl *, 4> Bases;
14521   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14522     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14523         ParentScope, D, TemplateParameterLists, Bases);
14524 
14525   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14526   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14527   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14528 
14529   if (!Bases.empty())
14530     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14531 
14532   return Dcl;
14533 }
14534 
14535 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14536   Consumer.HandleInlineFunctionDefinition(D);
14537 }
14538 
14539 static bool
14540 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14541                                 const FunctionDecl *&PossiblePrototype) {
14542   // Don't warn about invalid declarations.
14543   if (FD->isInvalidDecl())
14544     return false;
14545 
14546   // Or declarations that aren't global.
14547   if (!FD->isGlobal())
14548     return false;
14549 
14550   // Don't warn about C++ member functions.
14551   if (isa<CXXMethodDecl>(FD))
14552     return false;
14553 
14554   // Don't warn about 'main'.
14555   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14556     if (IdentifierInfo *II = FD->getIdentifier())
14557       if (II->isStr("main") || II->isStr("efi_main"))
14558         return false;
14559 
14560   // Don't warn about inline functions.
14561   if (FD->isInlined())
14562     return false;
14563 
14564   // Don't warn about function templates.
14565   if (FD->getDescribedFunctionTemplate())
14566     return false;
14567 
14568   // Don't warn about function template specializations.
14569   if (FD->isFunctionTemplateSpecialization())
14570     return false;
14571 
14572   // Don't warn for OpenCL kernels.
14573   if (FD->hasAttr<OpenCLKernelAttr>())
14574     return false;
14575 
14576   // Don't warn on explicitly deleted functions.
14577   if (FD->isDeleted())
14578     return false;
14579 
14580   // Don't warn on implicitly local functions (such as having local-typed
14581   // parameters).
14582   if (!FD->isExternallyVisible())
14583     return false;
14584 
14585   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14586        Prev; Prev = Prev->getPreviousDecl()) {
14587     // Ignore any declarations that occur in function or method
14588     // scope, because they aren't visible from the header.
14589     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14590       continue;
14591 
14592     PossiblePrototype = Prev;
14593     return Prev->getType()->isFunctionNoProtoType();
14594   }
14595 
14596   return true;
14597 }
14598 
14599 void
14600 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14601                                    const FunctionDecl *EffectiveDefinition,
14602                                    SkipBodyInfo *SkipBody) {
14603   const FunctionDecl *Definition = EffectiveDefinition;
14604   if (!Definition &&
14605       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14606     return;
14607 
14608   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14609     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14610       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14611         // A merged copy of the same function, instantiated as a member of
14612         // the same class, is OK.
14613         if (declaresSameEntity(OrigFD, OrigDef) &&
14614             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14615                                cast<Decl>(FD->getLexicalDeclContext())))
14616           return;
14617       }
14618     }
14619   }
14620 
14621   if (canRedefineFunction(Definition, getLangOpts()))
14622     return;
14623 
14624   // Don't emit an error when this is redefinition of a typo-corrected
14625   // definition.
14626   if (TypoCorrectedFunctionDefinitions.count(Definition))
14627     return;
14628 
14629   // If we don't have a visible definition of the function, and it's inline or
14630   // a template, skip the new definition.
14631   if (SkipBody && !hasVisibleDefinition(Definition) &&
14632       (Definition->getFormalLinkage() == InternalLinkage ||
14633        Definition->isInlined() ||
14634        Definition->getDescribedFunctionTemplate() ||
14635        Definition->getNumTemplateParameterLists())) {
14636     SkipBody->ShouldSkip = true;
14637     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14638     if (auto *TD = Definition->getDescribedFunctionTemplate())
14639       makeMergedDefinitionVisible(TD);
14640     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14641     return;
14642   }
14643 
14644   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14645       Definition->getStorageClass() == SC_Extern)
14646     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14647         << FD << getLangOpts().CPlusPlus;
14648   else
14649     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14650 
14651   Diag(Definition->getLocation(), diag::note_previous_definition);
14652   FD->setInvalidDecl();
14653 }
14654 
14655 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14656                                    Sema &S) {
14657   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14658 
14659   LambdaScopeInfo *LSI = S.PushLambdaScope();
14660   LSI->CallOperator = CallOperator;
14661   LSI->Lambda = LambdaClass;
14662   LSI->ReturnType = CallOperator->getReturnType();
14663   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14664 
14665   if (LCD == LCD_None)
14666     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14667   else if (LCD == LCD_ByCopy)
14668     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14669   else if (LCD == LCD_ByRef)
14670     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14671   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14672 
14673   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14674   LSI->Mutable = !CallOperator->isConst();
14675 
14676   // Add the captures to the LSI so they can be noted as already
14677   // captured within tryCaptureVar.
14678   auto I = LambdaClass->field_begin();
14679   for (const auto &C : LambdaClass->captures()) {
14680     if (C.capturesVariable()) {
14681       VarDecl *VD = C.getCapturedVar();
14682       if (VD->isInitCapture())
14683         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14684       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14685       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14686           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14687           /*EllipsisLoc*/C.isPackExpansion()
14688                          ? C.getEllipsisLoc() : SourceLocation(),
14689           I->getType(), /*Invalid*/false);
14690 
14691     } else if (C.capturesThis()) {
14692       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14693                           C.getCaptureKind() == LCK_StarThis);
14694     } else {
14695       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14696                              I->getType());
14697     }
14698     ++I;
14699   }
14700 }
14701 
14702 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14703                                     SkipBodyInfo *SkipBody,
14704                                     FnBodyKind BodyKind) {
14705   if (!D) {
14706     // Parsing the function declaration failed in some way. Push on a fake scope
14707     // anyway so we can try to parse the function body.
14708     PushFunctionScope();
14709     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14710     return D;
14711   }
14712 
14713   FunctionDecl *FD = nullptr;
14714 
14715   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14716     FD = FunTmpl->getTemplatedDecl();
14717   else
14718     FD = cast<FunctionDecl>(D);
14719 
14720   // Do not push if it is a lambda because one is already pushed when building
14721   // the lambda in ActOnStartOfLambdaDefinition().
14722   if (!isLambdaCallOperator(FD))
14723     PushExpressionEvaluationContext(
14724         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14725                           : ExprEvalContexts.back().Context);
14726 
14727   // Check for defining attributes before the check for redefinition.
14728   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14729     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14730     FD->dropAttr<AliasAttr>();
14731     FD->setInvalidDecl();
14732   }
14733   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14734     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14735     FD->dropAttr<IFuncAttr>();
14736     FD->setInvalidDecl();
14737   }
14738 
14739   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14740     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14741         Ctor->isDefaultConstructor() &&
14742         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14743       // If this is an MS ABI dllexport default constructor, instantiate any
14744       // default arguments.
14745       InstantiateDefaultCtorDefaultArgs(Ctor);
14746     }
14747   }
14748 
14749   // See if this is a redefinition. If 'will have body' (or similar) is already
14750   // set, then these checks were already performed when it was set.
14751   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14752       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14753     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14754 
14755     // If we're skipping the body, we're done. Don't enter the scope.
14756     if (SkipBody && SkipBody->ShouldSkip)
14757       return D;
14758   }
14759 
14760   // Mark this function as "will have a body eventually".  This lets users to
14761   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14762   // this function.
14763   FD->setWillHaveBody();
14764 
14765   // If we are instantiating a generic lambda call operator, push
14766   // a LambdaScopeInfo onto the function stack.  But use the information
14767   // that's already been calculated (ActOnLambdaExpr) to prime the current
14768   // LambdaScopeInfo.
14769   // When the template operator is being specialized, the LambdaScopeInfo,
14770   // has to be properly restored so that tryCaptureVariable doesn't try
14771   // and capture any new variables. In addition when calculating potential
14772   // captures during transformation of nested lambdas, it is necessary to
14773   // have the LSI properly restored.
14774   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14775     assert(inTemplateInstantiation() &&
14776            "There should be an active template instantiation on the stack "
14777            "when instantiating a generic lambda!");
14778     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14779   } else {
14780     // Enter a new function scope
14781     PushFunctionScope();
14782   }
14783 
14784   // Builtin functions cannot be defined.
14785   if (unsigned BuiltinID = FD->getBuiltinID()) {
14786     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14787         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14788       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14789       FD->setInvalidDecl();
14790     }
14791   }
14792 
14793   // The return type of a function definition must be complete (C99 6.9.1p3),
14794   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14795   QualType ResultType = FD->getReturnType();
14796   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14797       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14798       RequireCompleteType(FD->getLocation(), ResultType,
14799                           diag::err_func_def_incomplete_result))
14800     FD->setInvalidDecl();
14801 
14802   if (FnBodyScope)
14803     PushDeclContext(FnBodyScope, FD);
14804 
14805   // Check the validity of our function parameters
14806   if (BodyKind != FnBodyKind::Delete)
14807     CheckParmsForFunctionDef(FD->parameters(),
14808                              /*CheckParameterNames=*/true);
14809 
14810   // Add non-parameter declarations already in the function to the current
14811   // scope.
14812   if (FnBodyScope) {
14813     for (Decl *NPD : FD->decls()) {
14814       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14815       if (!NonParmDecl)
14816         continue;
14817       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14818              "parameters should not be in newly created FD yet");
14819 
14820       // If the decl has a name, make it accessible in the current scope.
14821       if (NonParmDecl->getDeclName())
14822         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14823 
14824       // Similarly, dive into enums and fish their constants out, making them
14825       // accessible in this scope.
14826       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14827         for (auto *EI : ED->enumerators())
14828           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14829       }
14830     }
14831   }
14832 
14833   // Introduce our parameters into the function scope
14834   for (auto Param : FD->parameters()) {
14835     Param->setOwningFunction(FD);
14836 
14837     // If this has an identifier, add it to the scope stack.
14838     if (Param->getIdentifier() && FnBodyScope) {
14839       CheckShadow(FnBodyScope, Param);
14840 
14841       PushOnScopeChains(Param, FnBodyScope);
14842     }
14843   }
14844 
14845   // Ensure that the function's exception specification is instantiated.
14846   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14847     ResolveExceptionSpec(D->getLocation(), FPT);
14848 
14849   // dllimport cannot be applied to non-inline function definitions.
14850   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14851       !FD->isTemplateInstantiation()) {
14852     assert(!FD->hasAttr<DLLExportAttr>());
14853     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14854     FD->setInvalidDecl();
14855     return D;
14856   }
14857   // We want to attach documentation to original Decl (which might be
14858   // a function template).
14859   ActOnDocumentableDecl(D);
14860   if (getCurLexicalContext()->isObjCContainer() &&
14861       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14862       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14863     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14864 
14865   return D;
14866 }
14867 
14868 /// Given the set of return statements within a function body,
14869 /// compute the variables that are subject to the named return value
14870 /// optimization.
14871 ///
14872 /// Each of the variables that is subject to the named return value
14873 /// optimization will be marked as NRVO variables in the AST, and any
14874 /// return statement that has a marked NRVO variable as its NRVO candidate can
14875 /// use the named return value optimization.
14876 ///
14877 /// This function applies a very simplistic algorithm for NRVO: if every return
14878 /// statement in the scope of a variable has the same NRVO candidate, that
14879 /// candidate is an NRVO variable.
14880 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14881   ReturnStmt **Returns = Scope->Returns.data();
14882 
14883   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14884     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14885       if (!NRVOCandidate->isNRVOVariable())
14886         Returns[I]->setNRVOCandidate(nullptr);
14887     }
14888   }
14889 }
14890 
14891 bool Sema::canDelayFunctionBody(const Declarator &D) {
14892   // We can't delay parsing the body of a constexpr function template (yet).
14893   if (D.getDeclSpec().hasConstexprSpecifier())
14894     return false;
14895 
14896   // We can't delay parsing the body of a function template with a deduced
14897   // return type (yet).
14898   if (D.getDeclSpec().hasAutoTypeSpec()) {
14899     // If the placeholder introduces a non-deduced trailing return type,
14900     // we can still delay parsing it.
14901     if (D.getNumTypeObjects()) {
14902       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14903       if (Outer.Kind == DeclaratorChunk::Function &&
14904           Outer.Fun.hasTrailingReturnType()) {
14905         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14906         return Ty.isNull() || !Ty->isUndeducedType();
14907       }
14908     }
14909     return false;
14910   }
14911 
14912   return true;
14913 }
14914 
14915 bool Sema::canSkipFunctionBody(Decl *D) {
14916   // We cannot skip the body of a function (or function template) which is
14917   // constexpr, since we may need to evaluate its body in order to parse the
14918   // rest of the file.
14919   // We cannot skip the body of a function with an undeduced return type,
14920   // because any callers of that function need to know the type.
14921   if (const FunctionDecl *FD = D->getAsFunction()) {
14922     if (FD->isConstexpr())
14923       return false;
14924     // We can't simply call Type::isUndeducedType here, because inside template
14925     // auto can be deduced to a dependent type, which is not considered
14926     // "undeduced".
14927     if (FD->getReturnType()->getContainedDeducedType())
14928       return false;
14929   }
14930   return Consumer.shouldSkipFunctionBody(D);
14931 }
14932 
14933 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14934   if (!Decl)
14935     return nullptr;
14936   if (FunctionDecl *FD = Decl->getAsFunction())
14937     FD->setHasSkippedBody();
14938   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14939     MD->setHasSkippedBody();
14940   return Decl;
14941 }
14942 
14943 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14944   return ActOnFinishFunctionBody(D, BodyArg, false);
14945 }
14946 
14947 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14948 /// body.
14949 class ExitFunctionBodyRAII {
14950 public:
14951   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14952   ~ExitFunctionBodyRAII() {
14953     if (!IsLambda)
14954       S.PopExpressionEvaluationContext();
14955   }
14956 
14957 private:
14958   Sema &S;
14959   bool IsLambda = false;
14960 };
14961 
14962 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14963   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14964 
14965   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14966     if (EscapeInfo.count(BD))
14967       return EscapeInfo[BD];
14968 
14969     bool R = false;
14970     const BlockDecl *CurBD = BD;
14971 
14972     do {
14973       R = !CurBD->doesNotEscape();
14974       if (R)
14975         break;
14976       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14977     } while (CurBD);
14978 
14979     return EscapeInfo[BD] = R;
14980   };
14981 
14982   // If the location where 'self' is implicitly retained is inside a escaping
14983   // block, emit a diagnostic.
14984   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14985        S.ImplicitlyRetainedSelfLocs)
14986     if (IsOrNestedInEscapingBlock(P.second))
14987       S.Diag(P.first, diag::warn_implicitly_retains_self)
14988           << FixItHint::CreateInsertion(P.first, "self->");
14989 }
14990 
14991 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14992                                     bool IsInstantiation) {
14993   FunctionScopeInfo *FSI = getCurFunction();
14994   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14995 
14996   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14997     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14998 
14999   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15000   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15001 
15002   if (getLangOpts().Coroutines && FSI->isCoroutine())
15003     CheckCompletedCoroutineBody(FD, Body);
15004 
15005   {
15006     // Do not call PopExpressionEvaluationContext() if it is a lambda because
15007     // one is already popped when finishing the lambda in BuildLambdaExpr().
15008     // This is meant to pop the context added in ActOnStartOfFunctionDef().
15009     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15010 
15011     if (FD) {
15012       FD->setBody(Body);
15013       FD->setWillHaveBody(false);
15014 
15015       if (getLangOpts().CPlusPlus14) {
15016         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15017             FD->getReturnType()->isUndeducedType()) {
15018           // For a function with a deduced result type to return void,
15019           // the result type as written must be 'auto' or 'decltype(auto)',
15020           // possibly cv-qualified or constrained, but not ref-qualified.
15021           if (!FD->getReturnType()->getAs<AutoType>()) {
15022             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15023                 << FD->getReturnType();
15024             FD->setInvalidDecl();
15025           } else {
15026             // Falling off the end of the function is the same as 'return;'.
15027             Expr *Dummy = nullptr;
15028             if (DeduceFunctionTypeFromReturnExpr(
15029                     FD, dcl->getLocation(), Dummy,
15030                     FD->getReturnType()->getAs<AutoType>()))
15031               FD->setInvalidDecl();
15032           }
15033         }
15034       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15035         // In C++11, we don't use 'auto' deduction rules for lambda call
15036         // operators because we don't support return type deduction.
15037         auto *LSI = getCurLambda();
15038         if (LSI->HasImplicitReturnType) {
15039           deduceClosureReturnType(*LSI);
15040 
15041           // C++11 [expr.prim.lambda]p4:
15042           //   [...] if there are no return statements in the compound-statement
15043           //   [the deduced type is] the type void
15044           QualType RetType =
15045               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15046 
15047           // Update the return type to the deduced type.
15048           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15049           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15050                                               Proto->getExtProtoInfo()));
15051         }
15052       }
15053 
15054       // If the function implicitly returns zero (like 'main') or is naked,
15055       // don't complain about missing return statements.
15056       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15057         WP.disableCheckFallThrough();
15058 
15059       // MSVC permits the use of pure specifier (=0) on function definition,
15060       // defined at class scope, warn about this non-standard construct.
15061       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15062         Diag(FD->getLocation(), diag::ext_pure_function_definition);
15063 
15064       if (!FD->isInvalidDecl()) {
15065         // Don't diagnose unused parameters of defaulted, deleted or naked
15066         // functions.
15067         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15068             !FD->hasAttr<NakedAttr>())
15069           DiagnoseUnusedParameters(FD->parameters());
15070         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15071                                                FD->getReturnType(), FD);
15072 
15073         // If this is a structor, we need a vtable.
15074         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15075           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15076         else if (CXXDestructorDecl *Destructor =
15077                      dyn_cast<CXXDestructorDecl>(FD))
15078           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15079 
15080         // Try to apply the named return value optimization. We have to check
15081         // if we can do this here because lambdas keep return statements around
15082         // to deduce an implicit return type.
15083         if (FD->getReturnType()->isRecordType() &&
15084             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15085           computeNRVO(Body, FSI);
15086       }
15087 
15088       // GNU warning -Wmissing-prototypes:
15089       //   Warn if a global function is defined without a previous
15090       //   prototype declaration. This warning is issued even if the
15091       //   definition itself provides a prototype. The aim is to detect
15092       //   global functions that fail to be declared in header files.
15093       const FunctionDecl *PossiblePrototype = nullptr;
15094       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15095         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15096 
15097         if (PossiblePrototype) {
15098           // We found a declaration that is not a prototype,
15099           // but that could be a zero-parameter prototype
15100           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15101             TypeLoc TL = TI->getTypeLoc();
15102             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15103               Diag(PossiblePrototype->getLocation(),
15104                    diag::note_declaration_not_a_prototype)
15105                   << (FD->getNumParams() != 0)
15106                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15107                                                     FTL.getRParenLoc(), "void")
15108                                               : FixItHint{});
15109           }
15110         } else {
15111           // Returns true if the token beginning at this Loc is `const`.
15112           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15113                                   const LangOptions &LangOpts) {
15114             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15115             if (LocInfo.first.isInvalid())
15116               return false;
15117 
15118             bool Invalid = false;
15119             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15120             if (Invalid)
15121               return false;
15122 
15123             if (LocInfo.second > Buffer.size())
15124               return false;
15125 
15126             const char *LexStart = Buffer.data() + LocInfo.second;
15127             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15128 
15129             return StartTok.consume_front("const") &&
15130                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15131                     StartTok.startswith("/*") || StartTok.startswith("//"));
15132           };
15133 
15134           auto findBeginLoc = [&]() {
15135             // If the return type has `const` qualifier, we want to insert
15136             // `static` before `const` (and not before the typename).
15137             if ((FD->getReturnType()->isAnyPointerType() &&
15138                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15139                 FD->getReturnType().isConstQualified()) {
15140               // But only do this if we can determine where the `const` is.
15141 
15142               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15143                                getLangOpts()))
15144 
15145                 return FD->getBeginLoc();
15146             }
15147             return FD->getTypeSpecStartLoc();
15148           };
15149           Diag(FD->getTypeSpecStartLoc(),
15150                diag::note_static_for_internal_linkage)
15151               << /* function */ 1
15152               << (FD->getStorageClass() == SC_None
15153                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15154                       : FixItHint{});
15155         }
15156       }
15157 
15158       // If the function being defined does not have a prototype, then we may
15159       // need to diagnose it as changing behavior in C2x because we now know
15160       // whether the function accepts arguments or not. This only handles the
15161       // case where the definition has no prototype but does have parameters
15162       // and either there is no previous potential prototype, or the previous
15163       // potential prototype also has no actual prototype. This handles cases
15164       // like:
15165       //   void f(); void f(a) int a; {}
15166       //   void g(a) int a; {}
15167       // See MergeFunctionDecl() for other cases of the behavior change
15168       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15169       // type without a prototype.
15170       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15171           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15172                                   !PossiblePrototype->isImplicit()))) {
15173         // The function definition has parameters, so this will change behavior
15174         // in C2x. If there is a possible prototype, it comes before the
15175         // function definition.
15176         // FIXME: The declaration may have already been diagnosed as being
15177         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15178         // there's no way to test for the "changes behavior" condition in
15179         // SemaType.cpp when forming the declaration's function type. So, we do
15180         // this awkward dance instead.
15181         //
15182         // If we have a possible prototype and it declares a function with a
15183         // prototype, we don't want to diagnose it; if we have a possible
15184         // prototype and it has no prototype, it may have already been
15185         // diagnosed in SemaType.cpp as deprecated depending on whether
15186         // -Wstrict-prototypes is enabled. If we already warned about it being
15187         // deprecated, add a note that it also changes behavior. If we didn't
15188         // warn about it being deprecated (because the diagnostic is not
15189         // enabled), warn now that it is deprecated and changes behavior.
15190 
15191         // This K&R C function definition definitely changes behavior in C2x,
15192         // so diagnose it.
15193         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15194             << /*definition*/ 1 << /* not supported in C2x */ 0;
15195 
15196         // If we have a possible prototype for the function which is a user-
15197         // visible declaration, we already tested that it has no prototype.
15198         // This will change behavior in C2x. This gets a warning rather than a
15199         // note because it's the same behavior-changing problem as with the
15200         // definition.
15201         if (PossiblePrototype)
15202           Diag(PossiblePrototype->getLocation(),
15203                diag::warn_non_prototype_changes_behavior)
15204               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15205               << /*definition*/ 1;
15206       }
15207 
15208       // Warn on CPUDispatch with an actual body.
15209       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15210         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15211           if (!CmpndBody->body_empty())
15212             Diag(CmpndBody->body_front()->getBeginLoc(),
15213                  diag::warn_dispatch_body_ignored);
15214 
15215       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15216         const CXXMethodDecl *KeyFunction;
15217         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15218             MD->isVirtual() &&
15219             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15220             MD == KeyFunction->getCanonicalDecl()) {
15221           // Update the key-function state if necessary for this ABI.
15222           if (FD->isInlined() &&
15223               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15224             Context.setNonKeyFunction(MD);
15225 
15226             // If the newly-chosen key function is already defined, then we
15227             // need to mark the vtable as used retroactively.
15228             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15229             const FunctionDecl *Definition;
15230             if (KeyFunction && KeyFunction->isDefined(Definition))
15231               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15232           } else {
15233             // We just defined they key function; mark the vtable as used.
15234             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15235           }
15236         }
15237       }
15238 
15239       assert(
15240           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15241           "Function parsing confused");
15242     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15243       assert(MD == getCurMethodDecl() && "Method parsing confused");
15244       MD->setBody(Body);
15245       if (!MD->isInvalidDecl()) {
15246         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15247                                                MD->getReturnType(), MD);
15248 
15249         if (Body)
15250           computeNRVO(Body, FSI);
15251       }
15252       if (FSI->ObjCShouldCallSuper) {
15253         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15254             << MD->getSelector().getAsString();
15255         FSI->ObjCShouldCallSuper = false;
15256       }
15257       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15258         const ObjCMethodDecl *InitMethod = nullptr;
15259         bool isDesignated =
15260             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15261         assert(isDesignated && InitMethod);
15262         (void)isDesignated;
15263 
15264         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15265           auto IFace = MD->getClassInterface();
15266           if (!IFace)
15267             return false;
15268           auto SuperD = IFace->getSuperClass();
15269           if (!SuperD)
15270             return false;
15271           return SuperD->getIdentifier() ==
15272                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15273         };
15274         // Don't issue this warning for unavailable inits or direct subclasses
15275         // of NSObject.
15276         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15277           Diag(MD->getLocation(),
15278                diag::warn_objc_designated_init_missing_super_call);
15279           Diag(InitMethod->getLocation(),
15280                diag::note_objc_designated_init_marked_here);
15281         }
15282         FSI->ObjCWarnForNoDesignatedInitChain = false;
15283       }
15284       if (FSI->ObjCWarnForNoInitDelegation) {
15285         // Don't issue this warning for unavaialable inits.
15286         if (!MD->isUnavailable())
15287           Diag(MD->getLocation(),
15288                diag::warn_objc_secondary_init_missing_init_call);
15289         FSI->ObjCWarnForNoInitDelegation = false;
15290       }
15291 
15292       diagnoseImplicitlyRetainedSelf(*this);
15293     } else {
15294       // Parsing the function declaration failed in some way. Pop the fake scope
15295       // we pushed on.
15296       PopFunctionScopeInfo(ActivePolicy, dcl);
15297       return nullptr;
15298     }
15299 
15300     if (Body && FSI->HasPotentialAvailabilityViolations)
15301       DiagnoseUnguardedAvailabilityViolations(dcl);
15302 
15303     assert(!FSI->ObjCShouldCallSuper &&
15304            "This should only be set for ObjC methods, which should have been "
15305            "handled in the block above.");
15306 
15307     // Verify and clean out per-function state.
15308     if (Body && (!FD || !FD->isDefaulted())) {
15309       // C++ constructors that have function-try-blocks can't have return
15310       // statements in the handlers of that block. (C++ [except.handle]p14)
15311       // Verify this.
15312       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15313         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15314 
15315       // Verify that gotos and switch cases don't jump into scopes illegally.
15316       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15317         DiagnoseInvalidJumps(Body);
15318 
15319       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15320         if (!Destructor->getParent()->isDependentType())
15321           CheckDestructor(Destructor);
15322 
15323         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15324                                                Destructor->getParent());
15325       }
15326 
15327       // If any errors have occurred, clear out any temporaries that may have
15328       // been leftover. This ensures that these temporaries won't be picked up
15329       // for deletion in some later function.
15330       if (hasUncompilableErrorOccurred() ||
15331           getDiagnostics().getSuppressAllDiagnostics()) {
15332         DiscardCleanupsInEvaluationContext();
15333       }
15334       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15335         // Since the body is valid, issue any analysis-based warnings that are
15336         // enabled.
15337         ActivePolicy = &WP;
15338       }
15339 
15340       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15341           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15342         FD->setInvalidDecl();
15343 
15344       if (FD && FD->hasAttr<NakedAttr>()) {
15345         for (const Stmt *S : Body->children()) {
15346           // Allow local register variables without initializer as they don't
15347           // require prologue.
15348           bool RegisterVariables = false;
15349           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15350             for (const auto *Decl : DS->decls()) {
15351               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15352                 RegisterVariables =
15353                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15354                 if (!RegisterVariables)
15355                   break;
15356               }
15357             }
15358           }
15359           if (RegisterVariables)
15360             continue;
15361           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15362             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15363             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15364             FD->setInvalidDecl();
15365             break;
15366           }
15367         }
15368       }
15369 
15370       assert(ExprCleanupObjects.size() ==
15371                  ExprEvalContexts.back().NumCleanupObjects &&
15372              "Leftover temporaries in function");
15373       assert(!Cleanup.exprNeedsCleanups() &&
15374              "Unaccounted cleanups in function");
15375       assert(MaybeODRUseExprs.empty() &&
15376              "Leftover expressions for odr-use checking");
15377     }
15378   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15379     // the declaration context below. Otherwise, we're unable to transform
15380     // 'this' expressions when transforming immediate context functions.
15381 
15382   if (!IsInstantiation)
15383     PopDeclContext();
15384 
15385   PopFunctionScopeInfo(ActivePolicy, dcl);
15386   // If any errors have occurred, clear out any temporaries that may have
15387   // been leftover. This ensures that these temporaries won't be picked up for
15388   // deletion in some later function.
15389   if (hasUncompilableErrorOccurred()) {
15390     DiscardCleanupsInEvaluationContext();
15391   }
15392 
15393   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15394                                   !LangOpts.OMPTargetTriples.empty())) ||
15395              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15396     auto ES = getEmissionStatus(FD);
15397     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15398         ES == Sema::FunctionEmissionStatus::Unknown)
15399       DeclsToCheckForDeferredDiags.insert(FD);
15400   }
15401 
15402   if (FD && !FD->isDeleted())
15403     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15404 
15405   return dcl;
15406 }
15407 
15408 /// When we finish delayed parsing of an attribute, we must attach it to the
15409 /// relevant Decl.
15410 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15411                                        ParsedAttributes &Attrs) {
15412   // Always attach attributes to the underlying decl.
15413   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15414     D = TD->getTemplatedDecl();
15415   ProcessDeclAttributeList(S, D, Attrs);
15416 
15417   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15418     if (Method->isStatic())
15419       checkThisInStaticMemberFunctionAttributes(Method);
15420 }
15421 
15422 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15423 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15424 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15425                                           IdentifierInfo &II, Scope *S) {
15426   // It is not valid to implicitly define a function in C2x.
15427   assert(LangOpts.implicitFunctionsAllowed() &&
15428          "Implicit function declarations aren't allowed in this language mode");
15429 
15430   // Find the scope in which the identifier is injected and the corresponding
15431   // DeclContext.
15432   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15433   // In that case, we inject the declaration into the translation unit scope
15434   // instead.
15435   Scope *BlockScope = S;
15436   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15437     BlockScope = BlockScope->getParent();
15438 
15439   Scope *ContextScope = BlockScope;
15440   while (!ContextScope->getEntity())
15441     ContextScope = ContextScope->getParent();
15442   ContextRAII SavedContext(*this, ContextScope->getEntity());
15443 
15444   // Before we produce a declaration for an implicitly defined
15445   // function, see whether there was a locally-scoped declaration of
15446   // this name as a function or variable. If so, use that
15447   // (non-visible) declaration, and complain about it.
15448   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15449   if (ExternCPrev) {
15450     // We still need to inject the function into the enclosing block scope so
15451     // that later (non-call) uses can see it.
15452     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15453 
15454     // C89 footnote 38:
15455     //   If in fact it is not defined as having type "function returning int",
15456     //   the behavior is undefined.
15457     if (!isa<FunctionDecl>(ExternCPrev) ||
15458         !Context.typesAreCompatible(
15459             cast<FunctionDecl>(ExternCPrev)->getType(),
15460             Context.getFunctionNoProtoType(Context.IntTy))) {
15461       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15462           << ExternCPrev << !getLangOpts().C99;
15463       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15464       return ExternCPrev;
15465     }
15466   }
15467 
15468   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15469   unsigned diag_id;
15470   if (II.getName().startswith("__builtin_"))
15471     diag_id = diag::warn_builtin_unknown;
15472   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15473   else if (getLangOpts().C99)
15474     diag_id = diag::ext_implicit_function_decl_c99;
15475   else
15476     diag_id = diag::warn_implicit_function_decl;
15477 
15478   TypoCorrection Corrected;
15479   // Because typo correction is expensive, only do it if the implicit
15480   // function declaration is going to be treated as an error.
15481   //
15482   // Perform the corection before issuing the main diagnostic, as some consumers
15483   // use typo-correction callbacks to enhance the main diagnostic.
15484   if (S && !ExternCPrev &&
15485       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15486     DeclFilterCCC<FunctionDecl> CCC{};
15487     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15488                             S, nullptr, CCC, CTK_NonError);
15489   }
15490 
15491   Diag(Loc, diag_id) << &II;
15492   if (Corrected) {
15493     // If the correction is going to suggest an implicitly defined function,
15494     // skip the correction as not being a particularly good idea.
15495     bool Diagnose = true;
15496     if (const auto *D = Corrected.getCorrectionDecl())
15497       Diagnose = !D->isImplicit();
15498     if (Diagnose)
15499       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15500                    /*ErrorRecovery*/ false);
15501   }
15502 
15503   // If we found a prior declaration of this function, don't bother building
15504   // another one. We've already pushed that one into scope, so there's nothing
15505   // more to do.
15506   if (ExternCPrev)
15507     return ExternCPrev;
15508 
15509   // Set a Declarator for the implicit definition: int foo();
15510   const char *Dummy;
15511   AttributeFactory attrFactory;
15512   DeclSpec DS(attrFactory);
15513   unsigned DiagID;
15514   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15515                                   Context.getPrintingPolicy());
15516   (void)Error; // Silence warning.
15517   assert(!Error && "Error setting up implicit decl!");
15518   SourceLocation NoLoc;
15519   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15520   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15521                                              /*IsAmbiguous=*/false,
15522                                              /*LParenLoc=*/NoLoc,
15523                                              /*Params=*/nullptr,
15524                                              /*NumParams=*/0,
15525                                              /*EllipsisLoc=*/NoLoc,
15526                                              /*RParenLoc=*/NoLoc,
15527                                              /*RefQualifierIsLvalueRef=*/true,
15528                                              /*RefQualifierLoc=*/NoLoc,
15529                                              /*MutableLoc=*/NoLoc, EST_None,
15530                                              /*ESpecRange=*/SourceRange(),
15531                                              /*Exceptions=*/nullptr,
15532                                              /*ExceptionRanges=*/nullptr,
15533                                              /*NumExceptions=*/0,
15534                                              /*NoexceptExpr=*/nullptr,
15535                                              /*ExceptionSpecTokens=*/nullptr,
15536                                              /*DeclsInPrototype=*/None, Loc,
15537                                              Loc, D),
15538                 std::move(DS.getAttributes()), SourceLocation());
15539   D.SetIdentifier(&II, Loc);
15540 
15541   // Insert this function into the enclosing block scope.
15542   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15543   FD->setImplicit();
15544 
15545   AddKnownFunctionAttributes(FD);
15546 
15547   return FD;
15548 }
15549 
15550 /// If this function is a C++ replaceable global allocation function
15551 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15552 /// adds any function attributes that we know a priori based on the standard.
15553 ///
15554 /// We need to check for duplicate attributes both here and where user-written
15555 /// attributes are applied to declarations.
15556 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15557     FunctionDecl *FD) {
15558   if (FD->isInvalidDecl())
15559     return;
15560 
15561   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15562       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15563     return;
15564 
15565   Optional<unsigned> AlignmentParam;
15566   bool IsNothrow = false;
15567   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15568     return;
15569 
15570   // C++2a [basic.stc.dynamic.allocation]p4:
15571   //   An allocation function that has a non-throwing exception specification
15572   //   indicates failure by returning a null pointer value. Any other allocation
15573   //   function never returns a null pointer value and indicates failure only by
15574   //   throwing an exception [...]
15575   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15576     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15577 
15578   // C++2a [basic.stc.dynamic.allocation]p2:
15579   //   An allocation function attempts to allocate the requested amount of
15580   //   storage. [...] If the request succeeds, the value returned by a
15581   //   replaceable allocation function is a [...] pointer value p0 different
15582   //   from any previously returned value p1 [...]
15583   //
15584   // However, this particular information is being added in codegen,
15585   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15586 
15587   // C++2a [basic.stc.dynamic.allocation]p2:
15588   //   An allocation function attempts to allocate the requested amount of
15589   //   storage. If it is successful, it returns the address of the start of a
15590   //   block of storage whose length in bytes is at least as large as the
15591   //   requested size.
15592   if (!FD->hasAttr<AllocSizeAttr>()) {
15593     FD->addAttr(AllocSizeAttr::CreateImplicit(
15594         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15595         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15596   }
15597 
15598   // C++2a [basic.stc.dynamic.allocation]p3:
15599   //   For an allocation function [...], the pointer returned on a successful
15600   //   call shall represent the address of storage that is aligned as follows:
15601   //   (3.1) If the allocation function takes an argument of type
15602   //         std​::​align_­val_­t, the storage will have the alignment
15603   //         specified by the value of this argument.
15604   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15605     FD->addAttr(AllocAlignAttr::CreateImplicit(
15606         Context, ParamIdx(AlignmentParam.value(), FD), FD->getLocation()));
15607   }
15608 
15609   // FIXME:
15610   // C++2a [basic.stc.dynamic.allocation]p3:
15611   //   For an allocation function [...], the pointer returned on a successful
15612   //   call shall represent the address of storage that is aligned as follows:
15613   //   (3.2) Otherwise, if the allocation function is named operator new[],
15614   //         the storage is aligned for any object that does not have
15615   //         new-extended alignment ([basic.align]) and is no larger than the
15616   //         requested size.
15617   //   (3.3) Otherwise, the storage is aligned for any object that does not
15618   //         have new-extended alignment and is of the requested size.
15619 }
15620 
15621 /// Adds any function attributes that we know a priori based on
15622 /// the declaration of this function.
15623 ///
15624 /// These attributes can apply both to implicitly-declared builtins
15625 /// (like __builtin___printf_chk) or to library-declared functions
15626 /// like NSLog or printf.
15627 ///
15628 /// We need to check for duplicate attributes both here and where user-written
15629 /// attributes are applied to declarations.
15630 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15631   if (FD->isInvalidDecl())
15632     return;
15633 
15634   // If this is a built-in function, map its builtin attributes to
15635   // actual attributes.
15636   if (unsigned BuiltinID = FD->getBuiltinID()) {
15637     // Handle printf-formatting attributes.
15638     unsigned FormatIdx;
15639     bool HasVAListArg;
15640     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15641       if (!FD->hasAttr<FormatAttr>()) {
15642         const char *fmt = "printf";
15643         unsigned int NumParams = FD->getNumParams();
15644         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15645             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15646           fmt = "NSString";
15647         FD->addAttr(FormatAttr::CreateImplicit(Context,
15648                                                &Context.Idents.get(fmt),
15649                                                FormatIdx+1,
15650                                                HasVAListArg ? 0 : FormatIdx+2,
15651                                                FD->getLocation()));
15652       }
15653     }
15654     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15655                                              HasVAListArg)) {
15656      if (!FD->hasAttr<FormatAttr>())
15657        FD->addAttr(FormatAttr::CreateImplicit(Context,
15658                                               &Context.Idents.get("scanf"),
15659                                               FormatIdx+1,
15660                                               HasVAListArg ? 0 : FormatIdx+2,
15661                                               FD->getLocation()));
15662     }
15663 
15664     // Handle automatically recognized callbacks.
15665     SmallVector<int, 4> Encoding;
15666     if (!FD->hasAttr<CallbackAttr>() &&
15667         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15668       FD->addAttr(CallbackAttr::CreateImplicit(
15669           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15670 
15671     // Mark const if we don't care about errno and that is the only thing
15672     // preventing the function from being const. This allows IRgen to use LLVM
15673     // intrinsics for such functions.
15674     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15675         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15676       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15677 
15678     // We make "fma" on GNU or Windows const because we know it does not set
15679     // errno in those environments even though it could set errno based on the
15680     // C standard.
15681     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15682     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15683         !FD->hasAttr<ConstAttr>()) {
15684       switch (BuiltinID) {
15685       case Builtin::BI__builtin_fma:
15686       case Builtin::BI__builtin_fmaf:
15687       case Builtin::BI__builtin_fmal:
15688       case Builtin::BIfma:
15689       case Builtin::BIfmaf:
15690       case Builtin::BIfmal:
15691         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15692         break;
15693       default:
15694         break;
15695       }
15696     }
15697 
15698     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15699         !FD->hasAttr<ReturnsTwiceAttr>())
15700       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15701                                          FD->getLocation()));
15702     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15703       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15704     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15705       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15706     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15707       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15708     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15709         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15710       // Add the appropriate attribute, depending on the CUDA compilation mode
15711       // and which target the builtin belongs to. For example, during host
15712       // compilation, aux builtins are __device__, while the rest are __host__.
15713       if (getLangOpts().CUDAIsDevice !=
15714           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15715         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15716       else
15717         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15718     }
15719 
15720     // Add known guaranteed alignment for allocation functions.
15721     switch (BuiltinID) {
15722     case Builtin::BImemalign:
15723     case Builtin::BIaligned_alloc:
15724       if (!FD->hasAttr<AllocAlignAttr>())
15725         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15726                                                    FD->getLocation()));
15727       break;
15728     default:
15729       break;
15730     }
15731 
15732     // Add allocsize attribute for allocation functions.
15733     switch (BuiltinID) {
15734     case Builtin::BIcalloc:
15735       FD->addAttr(AllocSizeAttr::CreateImplicit(
15736           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15737       break;
15738     case Builtin::BImemalign:
15739     case Builtin::BIaligned_alloc:
15740     case Builtin::BIrealloc:
15741       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15742                                                 ParamIdx(), FD->getLocation()));
15743       break;
15744     case Builtin::BImalloc:
15745       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15746                                                 ParamIdx(), FD->getLocation()));
15747       break;
15748     default:
15749       break;
15750     }
15751   }
15752 
15753   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15754 
15755   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15756   // throw, add an implicit nothrow attribute to any extern "C" function we come
15757   // across.
15758   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15759       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15760     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15761     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15762       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15763   }
15764 
15765   IdentifierInfo *Name = FD->getIdentifier();
15766   if (!Name)
15767     return;
15768   if ((!getLangOpts().CPlusPlus &&
15769        FD->getDeclContext()->isTranslationUnit()) ||
15770       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15771        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15772        LinkageSpecDecl::lang_c)) {
15773     // Okay: this could be a libc/libm/Objective-C function we know
15774     // about.
15775   } else
15776     return;
15777 
15778   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15779     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15780     // target-specific builtins, perhaps?
15781     if (!FD->hasAttr<FormatAttr>())
15782       FD->addAttr(FormatAttr::CreateImplicit(Context,
15783                                              &Context.Idents.get("printf"), 2,
15784                                              Name->isStr("vasprintf") ? 0 : 3,
15785                                              FD->getLocation()));
15786   }
15787 
15788   if (Name->isStr("__CFStringMakeConstantString")) {
15789     // We already have a __builtin___CFStringMakeConstantString,
15790     // but builds that use -fno-constant-cfstrings don't go through that.
15791     if (!FD->hasAttr<FormatArgAttr>())
15792       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15793                                                 FD->getLocation()));
15794   }
15795 }
15796 
15797 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15798                                     TypeSourceInfo *TInfo) {
15799   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15800   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15801 
15802   if (!TInfo) {
15803     assert(D.isInvalidType() && "no declarator info for valid type");
15804     TInfo = Context.getTrivialTypeSourceInfo(T);
15805   }
15806 
15807   // Scope manipulation handled by caller.
15808   TypedefDecl *NewTD =
15809       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15810                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15811 
15812   // Bail out immediately if we have an invalid declaration.
15813   if (D.isInvalidType()) {
15814     NewTD->setInvalidDecl();
15815     return NewTD;
15816   }
15817 
15818   if (D.getDeclSpec().isModulePrivateSpecified()) {
15819     if (CurContext->isFunctionOrMethod())
15820       Diag(NewTD->getLocation(), diag::err_module_private_local)
15821           << 2 << NewTD
15822           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15823           << FixItHint::CreateRemoval(
15824                  D.getDeclSpec().getModulePrivateSpecLoc());
15825     else
15826       NewTD->setModulePrivate();
15827   }
15828 
15829   // C++ [dcl.typedef]p8:
15830   //   If the typedef declaration defines an unnamed class (or
15831   //   enum), the first typedef-name declared by the declaration
15832   //   to be that class type (or enum type) is used to denote the
15833   //   class type (or enum type) for linkage purposes only.
15834   // We need to check whether the type was declared in the declaration.
15835   switch (D.getDeclSpec().getTypeSpecType()) {
15836   case TST_enum:
15837   case TST_struct:
15838   case TST_interface:
15839   case TST_union:
15840   case TST_class: {
15841     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15842     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15843     break;
15844   }
15845 
15846   default:
15847     break;
15848   }
15849 
15850   return NewTD;
15851 }
15852 
15853 /// Check that this is a valid underlying type for an enum declaration.
15854 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15855   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15856   QualType T = TI->getType();
15857 
15858   if (T->isDependentType())
15859     return false;
15860 
15861   // This doesn't use 'isIntegralType' despite the error message mentioning
15862   // integral type because isIntegralType would also allow enum types in C.
15863   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15864     if (BT->isInteger())
15865       return false;
15866 
15867   if (T->isBitIntType())
15868     return false;
15869 
15870   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15871 }
15872 
15873 /// Check whether this is a valid redeclaration of a previous enumeration.
15874 /// \return true if the redeclaration was invalid.
15875 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15876                                   QualType EnumUnderlyingTy, bool IsFixed,
15877                                   const EnumDecl *Prev) {
15878   if (IsScoped != Prev->isScoped()) {
15879     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15880       << Prev->isScoped();
15881     Diag(Prev->getLocation(), diag::note_previous_declaration);
15882     return true;
15883   }
15884 
15885   if (IsFixed && Prev->isFixed()) {
15886     if (!EnumUnderlyingTy->isDependentType() &&
15887         !Prev->getIntegerType()->isDependentType() &&
15888         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15889                                         Prev->getIntegerType())) {
15890       // TODO: Highlight the underlying type of the redeclaration.
15891       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15892         << EnumUnderlyingTy << Prev->getIntegerType();
15893       Diag(Prev->getLocation(), diag::note_previous_declaration)
15894           << Prev->getIntegerTypeRange();
15895       return true;
15896     }
15897   } else if (IsFixed != Prev->isFixed()) {
15898     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15899       << Prev->isFixed();
15900     Diag(Prev->getLocation(), diag::note_previous_declaration);
15901     return true;
15902   }
15903 
15904   return false;
15905 }
15906 
15907 /// Get diagnostic %select index for tag kind for
15908 /// redeclaration diagnostic message.
15909 /// WARNING: Indexes apply to particular diagnostics only!
15910 ///
15911 /// \returns diagnostic %select index.
15912 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15913   switch (Tag) {
15914   case TTK_Struct: return 0;
15915   case TTK_Interface: return 1;
15916   case TTK_Class:  return 2;
15917   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15918   }
15919 }
15920 
15921 /// Determine if tag kind is a class-key compatible with
15922 /// class for redeclaration (class, struct, or __interface).
15923 ///
15924 /// \returns true iff the tag kind is compatible.
15925 static bool isClassCompatTagKind(TagTypeKind Tag)
15926 {
15927   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15928 }
15929 
15930 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15931                                              TagTypeKind TTK) {
15932   if (isa<TypedefDecl>(PrevDecl))
15933     return NTK_Typedef;
15934   else if (isa<TypeAliasDecl>(PrevDecl))
15935     return NTK_TypeAlias;
15936   else if (isa<ClassTemplateDecl>(PrevDecl))
15937     return NTK_Template;
15938   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15939     return NTK_TypeAliasTemplate;
15940   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15941     return NTK_TemplateTemplateArgument;
15942   switch (TTK) {
15943   case TTK_Struct:
15944   case TTK_Interface:
15945   case TTK_Class:
15946     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15947   case TTK_Union:
15948     return NTK_NonUnion;
15949   case TTK_Enum:
15950     return NTK_NonEnum;
15951   }
15952   llvm_unreachable("invalid TTK");
15953 }
15954 
15955 /// Determine whether a tag with a given kind is acceptable
15956 /// as a redeclaration of the given tag declaration.
15957 ///
15958 /// \returns true if the new tag kind is acceptable, false otherwise.
15959 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15960                                         TagTypeKind NewTag, bool isDefinition,
15961                                         SourceLocation NewTagLoc,
15962                                         const IdentifierInfo *Name) {
15963   // C++ [dcl.type.elab]p3:
15964   //   The class-key or enum keyword present in the
15965   //   elaborated-type-specifier shall agree in kind with the
15966   //   declaration to which the name in the elaborated-type-specifier
15967   //   refers. This rule also applies to the form of
15968   //   elaborated-type-specifier that declares a class-name or
15969   //   friend class since it can be construed as referring to the
15970   //   definition of the class. Thus, in any
15971   //   elaborated-type-specifier, the enum keyword shall be used to
15972   //   refer to an enumeration (7.2), the union class-key shall be
15973   //   used to refer to a union (clause 9), and either the class or
15974   //   struct class-key shall be used to refer to a class (clause 9)
15975   //   declared using the class or struct class-key.
15976   TagTypeKind OldTag = Previous->getTagKind();
15977   if (OldTag != NewTag &&
15978       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15979     return false;
15980 
15981   // Tags are compatible, but we might still want to warn on mismatched tags.
15982   // Non-class tags can't be mismatched at this point.
15983   if (!isClassCompatTagKind(NewTag))
15984     return true;
15985 
15986   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15987   // by our warning analysis. We don't want to warn about mismatches with (eg)
15988   // declarations in system headers that are designed to be specialized, but if
15989   // a user asks us to warn, we should warn if their code contains mismatched
15990   // declarations.
15991   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15992     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15993                                       Loc);
15994   };
15995   if (IsIgnoredLoc(NewTagLoc))
15996     return true;
15997 
15998   auto IsIgnored = [&](const TagDecl *Tag) {
15999     return IsIgnoredLoc(Tag->getLocation());
16000   };
16001   while (IsIgnored(Previous)) {
16002     Previous = Previous->getPreviousDecl();
16003     if (!Previous)
16004       return true;
16005     OldTag = Previous->getTagKind();
16006   }
16007 
16008   bool isTemplate = false;
16009   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16010     isTemplate = Record->getDescribedClassTemplate();
16011 
16012   if (inTemplateInstantiation()) {
16013     if (OldTag != NewTag) {
16014       // In a template instantiation, do not offer fix-its for tag mismatches
16015       // since they usually mess up the template instead of fixing the problem.
16016       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16017         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16018         << getRedeclDiagFromTagKind(OldTag);
16019       // FIXME: Note previous location?
16020     }
16021     return true;
16022   }
16023 
16024   if (isDefinition) {
16025     // On definitions, check all previous tags and issue a fix-it for each
16026     // one that doesn't match the current tag.
16027     if (Previous->getDefinition()) {
16028       // Don't suggest fix-its for redefinitions.
16029       return true;
16030     }
16031 
16032     bool previousMismatch = false;
16033     for (const TagDecl *I : Previous->redecls()) {
16034       if (I->getTagKind() != NewTag) {
16035         // Ignore previous declarations for which the warning was disabled.
16036         if (IsIgnored(I))
16037           continue;
16038 
16039         if (!previousMismatch) {
16040           previousMismatch = true;
16041           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16042             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16043             << getRedeclDiagFromTagKind(I->getTagKind());
16044         }
16045         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16046           << getRedeclDiagFromTagKind(NewTag)
16047           << FixItHint::CreateReplacement(I->getInnerLocStart(),
16048                TypeWithKeyword::getTagTypeKindName(NewTag));
16049       }
16050     }
16051     return true;
16052   }
16053 
16054   // Identify the prevailing tag kind: this is the kind of the definition (if
16055   // there is a non-ignored definition), or otherwise the kind of the prior
16056   // (non-ignored) declaration.
16057   const TagDecl *PrevDef = Previous->getDefinition();
16058   if (PrevDef && IsIgnored(PrevDef))
16059     PrevDef = nullptr;
16060   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16061   if (Redecl->getTagKind() != NewTag) {
16062     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16063       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16064       << getRedeclDiagFromTagKind(OldTag);
16065     Diag(Redecl->getLocation(), diag::note_previous_use);
16066 
16067     // If there is a previous definition, suggest a fix-it.
16068     if (PrevDef) {
16069       Diag(NewTagLoc, diag::note_struct_class_suggestion)
16070         << getRedeclDiagFromTagKind(Redecl->getTagKind())
16071         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16072              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16073     }
16074   }
16075 
16076   return true;
16077 }
16078 
16079 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16080 /// from an outer enclosing namespace or file scope inside a friend declaration.
16081 /// This should provide the commented out code in the following snippet:
16082 ///   namespace N {
16083 ///     struct X;
16084 ///     namespace M {
16085 ///       struct Y { friend struct /*N::*/ X; };
16086 ///     }
16087 ///   }
16088 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16089                                          SourceLocation NameLoc) {
16090   // While the decl is in a namespace, do repeated lookup of that name and see
16091   // if we get the same namespace back.  If we do not, continue until
16092   // translation unit scope, at which point we have a fully qualified NNS.
16093   SmallVector<IdentifierInfo *, 4> Namespaces;
16094   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16095   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16096     // This tag should be declared in a namespace, which can only be enclosed by
16097     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16098     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16099     if (!Namespace || Namespace->isAnonymousNamespace())
16100       return FixItHint();
16101     IdentifierInfo *II = Namespace->getIdentifier();
16102     Namespaces.push_back(II);
16103     NamedDecl *Lookup = SemaRef.LookupSingleName(
16104         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16105     if (Lookup == Namespace)
16106       break;
16107   }
16108 
16109   // Once we have all the namespaces, reverse them to go outermost first, and
16110   // build an NNS.
16111   SmallString<64> Insertion;
16112   llvm::raw_svector_ostream OS(Insertion);
16113   if (DC->isTranslationUnit())
16114     OS << "::";
16115   std::reverse(Namespaces.begin(), Namespaces.end());
16116   for (auto *II : Namespaces)
16117     OS << II->getName() << "::";
16118   return FixItHint::CreateInsertion(NameLoc, Insertion);
16119 }
16120 
16121 /// Determine whether a tag originally declared in context \p OldDC can
16122 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16123 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16124 /// using-declaration).
16125 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16126                                          DeclContext *NewDC) {
16127   OldDC = OldDC->getRedeclContext();
16128   NewDC = NewDC->getRedeclContext();
16129 
16130   if (OldDC->Equals(NewDC))
16131     return true;
16132 
16133   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16134   // encloses the other).
16135   if (S.getLangOpts().MSVCCompat &&
16136       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16137     return true;
16138 
16139   return false;
16140 }
16141 
16142 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16143 /// former case, Name will be non-null.  In the later case, Name will be null.
16144 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16145 /// reference/declaration/definition of a tag.
16146 ///
16147 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16148 /// trailing-type-specifier) other than one in an alias-declaration.
16149 ///
16150 /// \param SkipBody If non-null, will be set to indicate if the caller should
16151 /// skip the definition of this tag and treat it as if it were a declaration.
16152 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16153                      SourceLocation KWLoc, CXXScopeSpec &SS,
16154                      IdentifierInfo *Name, SourceLocation NameLoc,
16155                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16156                      SourceLocation ModulePrivateLoc,
16157                      MultiTemplateParamsArg TemplateParameterLists,
16158                      bool &OwnedDecl, bool &IsDependent,
16159                      SourceLocation ScopedEnumKWLoc,
16160                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16161                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16162                      SkipBodyInfo *SkipBody) {
16163   // If this is not a definition, it must have a name.
16164   IdentifierInfo *OrigName = Name;
16165   assert((Name != nullptr || TUK == TUK_Definition) &&
16166          "Nameless record must be a definition!");
16167   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16168 
16169   OwnedDecl = false;
16170   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16171   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16172 
16173   // FIXME: Check member specializations more carefully.
16174   bool isMemberSpecialization = false;
16175   bool Invalid = false;
16176 
16177   // We only need to do this matching if we have template parameters
16178   // or a scope specifier, which also conveniently avoids this work
16179   // for non-C++ cases.
16180   if (TemplateParameterLists.size() > 0 ||
16181       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16182     if (TemplateParameterList *TemplateParams =
16183             MatchTemplateParametersToScopeSpecifier(
16184                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16185                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16186       if (Kind == TTK_Enum) {
16187         Diag(KWLoc, diag::err_enum_template);
16188         return nullptr;
16189       }
16190 
16191       if (TemplateParams->size() > 0) {
16192         // This is a declaration or definition of a class template (which may
16193         // be a member of another template).
16194 
16195         if (Invalid)
16196           return nullptr;
16197 
16198         OwnedDecl = false;
16199         DeclResult Result = CheckClassTemplate(
16200             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16201             AS, ModulePrivateLoc,
16202             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16203             TemplateParameterLists.data(), SkipBody);
16204         return Result.get();
16205       } else {
16206         // The "template<>" header is extraneous.
16207         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16208           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16209         isMemberSpecialization = true;
16210       }
16211     }
16212 
16213     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16214         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16215       return nullptr;
16216   }
16217 
16218   // Figure out the underlying type if this a enum declaration. We need to do
16219   // this early, because it's needed to detect if this is an incompatible
16220   // redeclaration.
16221   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16222   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16223 
16224   if (Kind == TTK_Enum) {
16225     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16226       // No underlying type explicitly specified, or we failed to parse the
16227       // type, default to int.
16228       EnumUnderlying = Context.IntTy.getTypePtr();
16229     } else if (UnderlyingType.get()) {
16230       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16231       // integral type; any cv-qualification is ignored.
16232       TypeSourceInfo *TI = nullptr;
16233       GetTypeFromParser(UnderlyingType.get(), &TI);
16234       EnumUnderlying = TI;
16235 
16236       if (CheckEnumUnderlyingType(TI))
16237         // Recover by falling back to int.
16238         EnumUnderlying = Context.IntTy.getTypePtr();
16239 
16240       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16241                                           UPPC_FixedUnderlyingType))
16242         EnumUnderlying = Context.IntTy.getTypePtr();
16243 
16244     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16245       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16246       // of 'int'. However, if this is an unfixed forward declaration, don't set
16247       // the underlying type unless the user enables -fms-compatibility. This
16248       // makes unfixed forward declared enums incomplete and is more conforming.
16249       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16250         EnumUnderlying = Context.IntTy.getTypePtr();
16251     }
16252   }
16253 
16254   DeclContext *SearchDC = CurContext;
16255   DeclContext *DC = CurContext;
16256   bool isStdBadAlloc = false;
16257   bool isStdAlignValT = false;
16258 
16259   RedeclarationKind Redecl = forRedeclarationInCurContext();
16260   if (TUK == TUK_Friend || TUK == TUK_Reference)
16261     Redecl = NotForRedeclaration;
16262 
16263   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16264   /// implemented asks for structural equivalence checking, the returned decl
16265   /// here is passed back to the parser, allowing the tag body to be parsed.
16266   auto createTagFromNewDecl = [&]() -> TagDecl * {
16267     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16268     // If there is an identifier, use the location of the identifier as the
16269     // location of the decl, otherwise use the location of the struct/union
16270     // keyword.
16271     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16272     TagDecl *New = nullptr;
16273 
16274     if (Kind == TTK_Enum) {
16275       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16276                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16277       // If this is an undefined enum, bail.
16278       if (TUK != TUK_Definition && !Invalid)
16279         return nullptr;
16280       if (EnumUnderlying) {
16281         EnumDecl *ED = cast<EnumDecl>(New);
16282         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16283           ED->setIntegerTypeSourceInfo(TI);
16284         else
16285           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16286         QualType EnumTy = ED->getIntegerType();
16287         ED->setPromotionType(EnumTy->isPromotableIntegerType()
16288                                  ? Context.getPromotedIntegerType(EnumTy)
16289                                  : EnumTy);
16290       }
16291     } else { // struct/union
16292       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16293                                nullptr);
16294     }
16295 
16296     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16297       // Add alignment attributes if necessary; these attributes are checked
16298       // when the ASTContext lays out the structure.
16299       //
16300       // It is important for implementing the correct semantics that this
16301       // happen here (in ActOnTag). The #pragma pack stack is
16302       // maintained as a result of parser callbacks which can occur at
16303       // many points during the parsing of a struct declaration (because
16304       // the #pragma tokens are effectively skipped over during the
16305       // parsing of the struct).
16306       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16307         AddAlignmentAttributesForRecord(RD);
16308         AddMsStructLayoutForRecord(RD);
16309       }
16310     }
16311     New->setLexicalDeclContext(CurContext);
16312     return New;
16313   };
16314 
16315   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16316   if (Name && SS.isNotEmpty()) {
16317     // We have a nested-name tag ('struct foo::bar').
16318 
16319     // Check for invalid 'foo::'.
16320     if (SS.isInvalid()) {
16321       Name = nullptr;
16322       goto CreateNewDecl;
16323     }
16324 
16325     // If this is a friend or a reference to a class in a dependent
16326     // context, don't try to make a decl for it.
16327     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16328       DC = computeDeclContext(SS, false);
16329       if (!DC) {
16330         IsDependent = true;
16331         return nullptr;
16332       }
16333     } else {
16334       DC = computeDeclContext(SS, true);
16335       if (!DC) {
16336         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16337           << SS.getRange();
16338         return nullptr;
16339       }
16340     }
16341 
16342     if (RequireCompleteDeclContext(SS, DC))
16343       return nullptr;
16344 
16345     SearchDC = DC;
16346     // Look-up name inside 'foo::'.
16347     LookupQualifiedName(Previous, DC);
16348 
16349     if (Previous.isAmbiguous())
16350       return nullptr;
16351 
16352     if (Previous.empty()) {
16353       // Name lookup did not find anything. However, if the
16354       // nested-name-specifier refers to the current instantiation,
16355       // and that current instantiation has any dependent base
16356       // classes, we might find something at instantiation time: treat
16357       // this as a dependent elaborated-type-specifier.
16358       // But this only makes any sense for reference-like lookups.
16359       if (Previous.wasNotFoundInCurrentInstantiation() &&
16360           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16361         IsDependent = true;
16362         return nullptr;
16363       }
16364 
16365       // A tag 'foo::bar' must already exist.
16366       Diag(NameLoc, diag::err_not_tag_in_scope)
16367         << Kind << Name << DC << SS.getRange();
16368       Name = nullptr;
16369       Invalid = true;
16370       goto CreateNewDecl;
16371     }
16372   } else if (Name) {
16373     // C++14 [class.mem]p14:
16374     //   If T is the name of a class, then each of the following shall have a
16375     //   name different from T:
16376     //    -- every member of class T that is itself a type
16377     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16378         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16379       return nullptr;
16380 
16381     // If this is a named struct, check to see if there was a previous forward
16382     // declaration or definition.
16383     // FIXME: We're looking into outer scopes here, even when we
16384     // shouldn't be. Doing so can result in ambiguities that we
16385     // shouldn't be diagnosing.
16386     LookupName(Previous, S);
16387 
16388     // When declaring or defining a tag, ignore ambiguities introduced
16389     // by types using'ed into this scope.
16390     if (Previous.isAmbiguous() &&
16391         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16392       LookupResult::Filter F = Previous.makeFilter();
16393       while (F.hasNext()) {
16394         NamedDecl *ND = F.next();
16395         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16396                 SearchDC->getRedeclContext()))
16397           F.erase();
16398       }
16399       F.done();
16400     }
16401 
16402     // C++11 [namespace.memdef]p3:
16403     //   If the name in a friend declaration is neither qualified nor
16404     //   a template-id and the declaration is a function or an
16405     //   elaborated-type-specifier, the lookup to determine whether
16406     //   the entity has been previously declared shall not consider
16407     //   any scopes outside the innermost enclosing namespace.
16408     //
16409     // MSVC doesn't implement the above rule for types, so a friend tag
16410     // declaration may be a redeclaration of a type declared in an enclosing
16411     // scope.  They do implement this rule for friend functions.
16412     //
16413     // Does it matter that this should be by scope instead of by
16414     // semantic context?
16415     if (!Previous.empty() && TUK == TUK_Friend) {
16416       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16417       LookupResult::Filter F = Previous.makeFilter();
16418       bool FriendSawTagOutsideEnclosingNamespace = false;
16419       while (F.hasNext()) {
16420         NamedDecl *ND = F.next();
16421         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16422         if (DC->isFileContext() &&
16423             !EnclosingNS->Encloses(ND->getDeclContext())) {
16424           if (getLangOpts().MSVCCompat)
16425             FriendSawTagOutsideEnclosingNamespace = true;
16426           else
16427             F.erase();
16428         }
16429       }
16430       F.done();
16431 
16432       // Diagnose this MSVC extension in the easy case where lookup would have
16433       // unambiguously found something outside the enclosing namespace.
16434       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16435         NamedDecl *ND = Previous.getFoundDecl();
16436         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16437             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16438       }
16439     }
16440 
16441     // Note:  there used to be some attempt at recovery here.
16442     if (Previous.isAmbiguous())
16443       return nullptr;
16444 
16445     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16446       // FIXME: This makes sure that we ignore the contexts associated
16447       // with C structs, unions, and enums when looking for a matching
16448       // tag declaration or definition. See the similar lookup tweak
16449       // in Sema::LookupName; is there a better way to deal with this?
16450       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16451         SearchDC = SearchDC->getParent();
16452     } else if (getLangOpts().CPlusPlus) {
16453       // Inside ObjCContainer want to keep it as a lexical decl context but go
16454       // past it (most often to TranslationUnit) to find the semantic decl
16455       // context.
16456       while (isa<ObjCContainerDecl>(SearchDC))
16457         SearchDC = SearchDC->getParent();
16458     }
16459   } else if (getLangOpts().CPlusPlus) {
16460     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16461     // TagDecl the same way as we skip it for named TagDecl.
16462     while (isa<ObjCContainerDecl>(SearchDC))
16463       SearchDC = SearchDC->getParent();
16464   }
16465 
16466   if (Previous.isSingleResult() &&
16467       Previous.getFoundDecl()->isTemplateParameter()) {
16468     // Maybe we will complain about the shadowed template parameter.
16469     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16470     // Just pretend that we didn't see the previous declaration.
16471     Previous.clear();
16472   }
16473 
16474   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16475       DC->Equals(getStdNamespace())) {
16476     if (Name->isStr("bad_alloc")) {
16477       // This is a declaration of or a reference to "std::bad_alloc".
16478       isStdBadAlloc = true;
16479 
16480       // If std::bad_alloc has been implicitly declared (but made invisible to
16481       // name lookup), fill in this implicit declaration as the previous
16482       // declaration, so that the declarations get chained appropriately.
16483       if (Previous.empty() && StdBadAlloc)
16484         Previous.addDecl(getStdBadAlloc());
16485     } else if (Name->isStr("align_val_t")) {
16486       isStdAlignValT = true;
16487       if (Previous.empty() && StdAlignValT)
16488         Previous.addDecl(getStdAlignValT());
16489     }
16490   }
16491 
16492   // If we didn't find a previous declaration, and this is a reference
16493   // (or friend reference), move to the correct scope.  In C++, we
16494   // also need to do a redeclaration lookup there, just in case
16495   // there's a shadow friend decl.
16496   if (Name && Previous.empty() &&
16497       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16498     if (Invalid) goto CreateNewDecl;
16499     assert(SS.isEmpty());
16500 
16501     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16502       // C++ [basic.scope.pdecl]p5:
16503       //   -- for an elaborated-type-specifier of the form
16504       //
16505       //          class-key identifier
16506       //
16507       //      if the elaborated-type-specifier is used in the
16508       //      decl-specifier-seq or parameter-declaration-clause of a
16509       //      function defined in namespace scope, the identifier is
16510       //      declared as a class-name in the namespace that contains
16511       //      the declaration; otherwise, except as a friend
16512       //      declaration, the identifier is declared in the smallest
16513       //      non-class, non-function-prototype scope that contains the
16514       //      declaration.
16515       //
16516       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16517       // C structs and unions.
16518       //
16519       // It is an error in C++ to declare (rather than define) an enum
16520       // type, including via an elaborated type specifier.  We'll
16521       // diagnose that later; for now, declare the enum in the same
16522       // scope as we would have picked for any other tag type.
16523       //
16524       // GNU C also supports this behavior as part of its incomplete
16525       // enum types extension, while GNU C++ does not.
16526       //
16527       // Find the context where we'll be declaring the tag.
16528       // FIXME: We would like to maintain the current DeclContext as the
16529       // lexical context,
16530       SearchDC = getTagInjectionContext(SearchDC);
16531 
16532       // Find the scope where we'll be declaring the tag.
16533       S = getTagInjectionScope(S, getLangOpts());
16534     } else {
16535       assert(TUK == TUK_Friend);
16536       // C++ [namespace.memdef]p3:
16537       //   If a friend declaration in a non-local class first declares a
16538       //   class or function, the friend class or function is a member of
16539       //   the innermost enclosing namespace.
16540       SearchDC = SearchDC->getEnclosingNamespaceContext();
16541     }
16542 
16543     // In C++, we need to do a redeclaration lookup to properly
16544     // diagnose some problems.
16545     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16546     // hidden declaration so that we don't get ambiguity errors when using a
16547     // type declared by an elaborated-type-specifier.  In C that is not correct
16548     // and we should instead merge compatible types found by lookup.
16549     if (getLangOpts().CPlusPlus) {
16550       // FIXME: This can perform qualified lookups into function contexts,
16551       // which are meaningless.
16552       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16553       LookupQualifiedName(Previous, SearchDC);
16554     } else {
16555       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16556       LookupName(Previous, S);
16557     }
16558   }
16559 
16560   // If we have a known previous declaration to use, then use it.
16561   if (Previous.empty() && SkipBody && SkipBody->Previous)
16562     Previous.addDecl(SkipBody->Previous);
16563 
16564   if (!Previous.empty()) {
16565     NamedDecl *PrevDecl = Previous.getFoundDecl();
16566     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16567 
16568     // It's okay to have a tag decl in the same scope as a typedef
16569     // which hides a tag decl in the same scope.  Finding this
16570     // with a redeclaration lookup can only actually happen in C++.
16571     //
16572     // This is also okay for elaborated-type-specifiers, which is
16573     // technically forbidden by the current standard but which is
16574     // okay according to the likely resolution of an open issue;
16575     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16576     if (getLangOpts().CPlusPlus) {
16577       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16578         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16579           TagDecl *Tag = TT->getDecl();
16580           if (Tag->getDeclName() == Name &&
16581               Tag->getDeclContext()->getRedeclContext()
16582                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16583             PrevDecl = Tag;
16584             Previous.clear();
16585             Previous.addDecl(Tag);
16586             Previous.resolveKind();
16587           }
16588         }
16589       }
16590     }
16591 
16592     // If this is a redeclaration of a using shadow declaration, it must
16593     // declare a tag in the same context. In MSVC mode, we allow a
16594     // redefinition if either context is within the other.
16595     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16596       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16597       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16598           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16599           !(OldTag && isAcceptableTagRedeclContext(
16600                           *this, OldTag->getDeclContext(), SearchDC))) {
16601         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16602         Diag(Shadow->getTargetDecl()->getLocation(),
16603              diag::note_using_decl_target);
16604         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16605             << 0;
16606         // Recover by ignoring the old declaration.
16607         Previous.clear();
16608         goto CreateNewDecl;
16609       }
16610     }
16611 
16612     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16613       // If this is a use of a previous tag, or if the tag is already declared
16614       // in the same scope (so that the definition/declaration completes or
16615       // rementions the tag), reuse the decl.
16616       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16617           isDeclInScope(DirectPrevDecl, SearchDC, S,
16618                         SS.isNotEmpty() || isMemberSpecialization)) {
16619         // Make sure that this wasn't declared as an enum and now used as a
16620         // struct or something similar.
16621         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16622                                           TUK == TUK_Definition, KWLoc,
16623                                           Name)) {
16624           bool SafeToContinue
16625             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16626                Kind != TTK_Enum);
16627           if (SafeToContinue)
16628             Diag(KWLoc, diag::err_use_with_wrong_tag)
16629               << Name
16630               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16631                                               PrevTagDecl->getKindName());
16632           else
16633             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16634           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16635 
16636           if (SafeToContinue)
16637             Kind = PrevTagDecl->getTagKind();
16638           else {
16639             // Recover by making this an anonymous redefinition.
16640             Name = nullptr;
16641             Previous.clear();
16642             Invalid = true;
16643           }
16644         }
16645 
16646         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16647           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16648           if (TUK == TUK_Reference || TUK == TUK_Friend)
16649             return PrevTagDecl;
16650 
16651           QualType EnumUnderlyingTy;
16652           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16653             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16654           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16655             EnumUnderlyingTy = QualType(T, 0);
16656 
16657           // All conflicts with previous declarations are recovered by
16658           // returning the previous declaration, unless this is a definition,
16659           // in which case we want the caller to bail out.
16660           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16661                                      ScopedEnum, EnumUnderlyingTy,
16662                                      IsFixed, PrevEnum))
16663             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16664         }
16665 
16666         // C++11 [class.mem]p1:
16667         //   A member shall not be declared twice in the member-specification,
16668         //   except that a nested class or member class template can be declared
16669         //   and then later defined.
16670         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16671             S->isDeclScope(PrevDecl)) {
16672           Diag(NameLoc, diag::ext_member_redeclared);
16673           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16674         }
16675 
16676         if (!Invalid) {
16677           // If this is a use, just return the declaration we found, unless
16678           // we have attributes.
16679           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16680             if (!Attrs.empty()) {
16681               // FIXME: Diagnose these attributes. For now, we create a new
16682               // declaration to hold them.
16683             } else if (TUK == TUK_Reference &&
16684                        (PrevTagDecl->getFriendObjectKind() ==
16685                             Decl::FOK_Undeclared ||
16686                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16687                        SS.isEmpty()) {
16688               // This declaration is a reference to an existing entity, but
16689               // has different visibility from that entity: it either makes
16690               // a friend visible or it makes a type visible in a new module.
16691               // In either case, create a new declaration. We only do this if
16692               // the declaration would have meant the same thing if no prior
16693               // declaration were found, that is, if it was found in the same
16694               // scope where we would have injected a declaration.
16695               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16696                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16697                 return PrevTagDecl;
16698               // This is in the injected scope, create a new declaration in
16699               // that scope.
16700               S = getTagInjectionScope(S, getLangOpts());
16701             } else {
16702               return PrevTagDecl;
16703             }
16704           }
16705 
16706           // Diagnose attempts to redefine a tag.
16707           if (TUK == TUK_Definition) {
16708             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16709               // If we're defining a specialization and the previous definition
16710               // is from an implicit instantiation, don't emit an error
16711               // here; we'll catch this in the general case below.
16712               bool IsExplicitSpecializationAfterInstantiation = false;
16713               if (isMemberSpecialization) {
16714                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16715                   IsExplicitSpecializationAfterInstantiation =
16716                     RD->getTemplateSpecializationKind() !=
16717                     TSK_ExplicitSpecialization;
16718                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16719                   IsExplicitSpecializationAfterInstantiation =
16720                     ED->getTemplateSpecializationKind() !=
16721                     TSK_ExplicitSpecialization;
16722               }
16723 
16724               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16725               // not keep more that one definition around (merge them). However,
16726               // ensure the decl passes the structural compatibility check in
16727               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16728               NamedDecl *Hidden = nullptr;
16729               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16730                 // There is a definition of this tag, but it is not visible. We
16731                 // explicitly make use of C++'s one definition rule here, and
16732                 // assume that this definition is identical to the hidden one
16733                 // we already have. Make the existing definition visible and
16734                 // use it in place of this one.
16735                 if (!getLangOpts().CPlusPlus) {
16736                   // Postpone making the old definition visible until after we
16737                   // complete parsing the new one and do the structural
16738                   // comparison.
16739                   SkipBody->CheckSameAsPrevious = true;
16740                   SkipBody->New = createTagFromNewDecl();
16741                   SkipBody->Previous = Def;
16742                   return Def;
16743                 } else {
16744                   SkipBody->ShouldSkip = true;
16745                   SkipBody->Previous = Def;
16746                   makeMergedDefinitionVisible(Hidden);
16747                   // Carry on and handle it like a normal definition. We'll
16748                   // skip starting the definitiion later.
16749                 }
16750               } else if (!IsExplicitSpecializationAfterInstantiation) {
16751                 // A redeclaration in function prototype scope in C isn't
16752                 // visible elsewhere, so merely issue a warning.
16753                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16754                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16755                 else
16756                   Diag(NameLoc, diag::err_redefinition) << Name;
16757                 notePreviousDefinition(Def,
16758                                        NameLoc.isValid() ? NameLoc : KWLoc);
16759                 // If this is a redefinition, recover by making this
16760                 // struct be anonymous, which will make any later
16761                 // references get the previous definition.
16762                 Name = nullptr;
16763                 Previous.clear();
16764                 Invalid = true;
16765               }
16766             } else {
16767               // If the type is currently being defined, complain
16768               // about a nested redefinition.
16769               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16770               if (TD->isBeingDefined()) {
16771                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16772                 Diag(PrevTagDecl->getLocation(),
16773                      diag::note_previous_definition);
16774                 Name = nullptr;
16775                 Previous.clear();
16776                 Invalid = true;
16777               }
16778             }
16779 
16780             // Okay, this is definition of a previously declared or referenced
16781             // tag. We're going to create a new Decl for it.
16782           }
16783 
16784           // Okay, we're going to make a redeclaration.  If this is some kind
16785           // of reference, make sure we build the redeclaration in the same DC
16786           // as the original, and ignore the current access specifier.
16787           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16788             SearchDC = PrevTagDecl->getDeclContext();
16789             AS = AS_none;
16790           }
16791         }
16792         // If we get here we have (another) forward declaration or we
16793         // have a definition.  Just create a new decl.
16794 
16795       } else {
16796         // If we get here, this is a definition of a new tag type in a nested
16797         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16798         // new decl/type.  We set PrevDecl to NULL so that the entities
16799         // have distinct types.
16800         Previous.clear();
16801       }
16802       // If we get here, we're going to create a new Decl. If PrevDecl
16803       // is non-NULL, it's a definition of the tag declared by
16804       // PrevDecl. If it's NULL, we have a new definition.
16805 
16806     // Otherwise, PrevDecl is not a tag, but was found with tag
16807     // lookup.  This is only actually possible in C++, where a few
16808     // things like templates still live in the tag namespace.
16809     } else {
16810       // Use a better diagnostic if an elaborated-type-specifier
16811       // found the wrong kind of type on the first
16812       // (non-redeclaration) lookup.
16813       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16814           !Previous.isForRedeclaration()) {
16815         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16816         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16817                                                        << Kind;
16818         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16819         Invalid = true;
16820 
16821       // Otherwise, only diagnose if the declaration is in scope.
16822       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16823                                 SS.isNotEmpty() || isMemberSpecialization)) {
16824         // do nothing
16825 
16826       // Diagnose implicit declarations introduced by elaborated types.
16827       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16828         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16829         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16830         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16831         Invalid = true;
16832 
16833       // Otherwise it's a declaration.  Call out a particularly common
16834       // case here.
16835       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16836         unsigned Kind = 0;
16837         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16838         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16839           << Name << Kind << TND->getUnderlyingType();
16840         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16841         Invalid = true;
16842 
16843       // Otherwise, diagnose.
16844       } else {
16845         // The tag name clashes with something else in the target scope,
16846         // issue an error and recover by making this tag be anonymous.
16847         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16848         notePreviousDefinition(PrevDecl, NameLoc);
16849         Name = nullptr;
16850         Invalid = true;
16851       }
16852 
16853       // The existing declaration isn't relevant to us; we're in a
16854       // new scope, so clear out the previous declaration.
16855       Previous.clear();
16856     }
16857   }
16858 
16859 CreateNewDecl:
16860 
16861   TagDecl *PrevDecl = nullptr;
16862   if (Previous.isSingleResult())
16863     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16864 
16865   // If there is an identifier, use the location of the identifier as the
16866   // location of the decl, otherwise use the location of the struct/union
16867   // keyword.
16868   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16869 
16870   // Otherwise, create a new declaration. If there is a previous
16871   // declaration of the same entity, the two will be linked via
16872   // PrevDecl.
16873   TagDecl *New;
16874 
16875   if (Kind == TTK_Enum) {
16876     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16877     // enum X { A, B, C } D;    D should chain to X.
16878     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16879                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16880                            ScopedEnumUsesClassTag, IsFixed);
16881 
16882     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16883       StdAlignValT = cast<EnumDecl>(New);
16884 
16885     // If this is an undefined enum, warn.
16886     if (TUK != TUK_Definition && !Invalid) {
16887       TagDecl *Def;
16888       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16889         // C++0x: 7.2p2: opaque-enum-declaration.
16890         // Conflicts are diagnosed above. Do nothing.
16891       }
16892       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16893         Diag(Loc, diag::ext_forward_ref_enum_def)
16894           << New;
16895         Diag(Def->getLocation(), diag::note_previous_definition);
16896       } else {
16897         unsigned DiagID = diag::ext_forward_ref_enum;
16898         if (getLangOpts().MSVCCompat)
16899           DiagID = diag::ext_ms_forward_ref_enum;
16900         else if (getLangOpts().CPlusPlus)
16901           DiagID = diag::err_forward_ref_enum;
16902         Diag(Loc, DiagID);
16903       }
16904     }
16905 
16906     if (EnumUnderlying) {
16907       EnumDecl *ED = cast<EnumDecl>(New);
16908       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16909         ED->setIntegerTypeSourceInfo(TI);
16910       else
16911         ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16912       QualType EnumTy = ED->getIntegerType();
16913       ED->setPromotionType(EnumTy->isPromotableIntegerType()
16914                                ? Context.getPromotedIntegerType(EnumTy)
16915                                : EnumTy);
16916       assert(ED->isComplete() && "enum with type should be complete");
16917     }
16918   } else {
16919     // struct/union/class
16920 
16921     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16922     // struct X { int A; } D;    D should chain to X.
16923     if (getLangOpts().CPlusPlus) {
16924       // FIXME: Look for a way to use RecordDecl for simple structs.
16925       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16926                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16927 
16928       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16929         StdBadAlloc = cast<CXXRecordDecl>(New);
16930     } else
16931       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16932                                cast_or_null<RecordDecl>(PrevDecl));
16933   }
16934 
16935   // C++11 [dcl.type]p3:
16936   //   A type-specifier-seq shall not define a class or enumeration [...].
16937   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16938       TUK == TUK_Definition) {
16939     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16940       << Context.getTagDeclType(New);
16941     Invalid = true;
16942   }
16943 
16944   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16945       DC->getDeclKind() == Decl::Enum) {
16946     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16947       << Context.getTagDeclType(New);
16948     Invalid = true;
16949   }
16950 
16951   // Maybe add qualifier info.
16952   if (SS.isNotEmpty()) {
16953     if (SS.isSet()) {
16954       // If this is either a declaration or a definition, check the
16955       // nested-name-specifier against the current context.
16956       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16957           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16958                                        isMemberSpecialization))
16959         Invalid = true;
16960 
16961       New->setQualifierInfo(SS.getWithLocInContext(Context));
16962       if (TemplateParameterLists.size() > 0) {
16963         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16964       }
16965     }
16966     else
16967       Invalid = true;
16968   }
16969 
16970   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16971     // Add alignment attributes if necessary; these attributes are checked when
16972     // the ASTContext lays out the structure.
16973     //
16974     // It is important for implementing the correct semantics that this
16975     // happen here (in ActOnTag). The #pragma pack stack is
16976     // maintained as a result of parser callbacks which can occur at
16977     // many points during the parsing of a struct declaration (because
16978     // the #pragma tokens are effectively skipped over during the
16979     // parsing of the struct).
16980     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16981       AddAlignmentAttributesForRecord(RD);
16982       AddMsStructLayoutForRecord(RD);
16983     }
16984   }
16985 
16986   if (ModulePrivateLoc.isValid()) {
16987     if (isMemberSpecialization)
16988       Diag(New->getLocation(), diag::err_module_private_specialization)
16989         << 2
16990         << FixItHint::CreateRemoval(ModulePrivateLoc);
16991     // __module_private__ does not apply to local classes. However, we only
16992     // diagnose this as an error when the declaration specifiers are
16993     // freestanding. Here, we just ignore the __module_private__.
16994     else if (!SearchDC->isFunctionOrMethod())
16995       New->setModulePrivate();
16996   }
16997 
16998   // If this is a specialization of a member class (of a class template),
16999   // check the specialization.
17000   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17001     Invalid = true;
17002 
17003   // If we're declaring or defining a tag in function prototype scope in C,
17004   // note that this type can only be used within the function and add it to
17005   // the list of decls to inject into the function definition scope.
17006   if ((Name || Kind == TTK_Enum) &&
17007       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17008     if (getLangOpts().CPlusPlus) {
17009       // C++ [dcl.fct]p6:
17010       //   Types shall not be defined in return or parameter types.
17011       if (TUK == TUK_Definition && !IsTypeSpecifier) {
17012         Diag(Loc, diag::err_type_defined_in_param_type)
17013             << Name;
17014         Invalid = true;
17015       }
17016     } else if (!PrevDecl) {
17017       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17018     }
17019   }
17020 
17021   if (Invalid)
17022     New->setInvalidDecl();
17023 
17024   // Set the lexical context. If the tag has a C++ scope specifier, the
17025   // lexical context will be different from the semantic context.
17026   New->setLexicalDeclContext(CurContext);
17027 
17028   // Mark this as a friend decl if applicable.
17029   // In Microsoft mode, a friend declaration also acts as a forward
17030   // declaration so we always pass true to setObjectOfFriendDecl to make
17031   // the tag name visible.
17032   if (TUK == TUK_Friend)
17033     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17034 
17035   // Set the access specifier.
17036   if (!Invalid && SearchDC->isRecord())
17037     SetMemberAccessSpecifier(New, PrevDecl, AS);
17038 
17039   if (PrevDecl)
17040     CheckRedeclarationInModule(New, PrevDecl);
17041 
17042   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17043     New->startDefinition();
17044 
17045   ProcessDeclAttributeList(S, New, Attrs);
17046   AddPragmaAttributes(S, New);
17047 
17048   // If this has an identifier, add it to the scope stack.
17049   if (TUK == TUK_Friend) {
17050     // We might be replacing an existing declaration in the lookup tables;
17051     // if so, borrow its access specifier.
17052     if (PrevDecl)
17053       New->setAccess(PrevDecl->getAccess());
17054 
17055     DeclContext *DC = New->getDeclContext()->getRedeclContext();
17056     DC->makeDeclVisibleInContext(New);
17057     if (Name) // can be null along some error paths
17058       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17059         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17060   } else if (Name) {
17061     S = getNonFieldDeclScope(S);
17062     PushOnScopeChains(New, S, true);
17063   } else {
17064     CurContext->addDecl(New);
17065   }
17066 
17067   // If this is the C FILE type, notify the AST context.
17068   if (IdentifierInfo *II = New->getIdentifier())
17069     if (!New->isInvalidDecl() &&
17070         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17071         II->isStr("FILE"))
17072       Context.setFILEDecl(New);
17073 
17074   if (PrevDecl)
17075     mergeDeclAttributes(New, PrevDecl);
17076 
17077   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17078     inferGslOwnerPointerAttribute(CXXRD);
17079 
17080   // If there's a #pragma GCC visibility in scope, set the visibility of this
17081   // record.
17082   AddPushedVisibilityAttribute(New);
17083 
17084   if (isMemberSpecialization && !New->isInvalidDecl())
17085     CompleteMemberSpecialization(New, Previous);
17086 
17087   OwnedDecl = true;
17088   // In C++, don't return an invalid declaration. We can't recover well from
17089   // the cases where we make the type anonymous.
17090   if (Invalid && getLangOpts().CPlusPlus) {
17091     if (New->isBeingDefined())
17092       if (auto RD = dyn_cast<RecordDecl>(New))
17093         RD->completeDefinition();
17094     return nullptr;
17095   } else if (SkipBody && SkipBody->ShouldSkip) {
17096     return SkipBody->Previous;
17097   } else {
17098     return New;
17099   }
17100 }
17101 
17102 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17103   AdjustDeclIfTemplate(TagD);
17104   TagDecl *Tag = cast<TagDecl>(TagD);
17105 
17106   // Enter the tag context.
17107   PushDeclContext(S, Tag);
17108 
17109   ActOnDocumentableDecl(TagD);
17110 
17111   // If there's a #pragma GCC visibility in scope, set the visibility of this
17112   // record.
17113   AddPushedVisibilityAttribute(Tag);
17114 }
17115 
17116 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17117   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17118     return false;
17119 
17120   // Make the previous decl visible.
17121   makeMergedDefinitionVisible(SkipBody.Previous);
17122   return true;
17123 }
17124 
17125 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17126   assert(IDecl->getLexicalParent() == CurContext &&
17127       "The next DeclContext should be lexically contained in the current one.");
17128   CurContext = IDecl;
17129 }
17130 
17131 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17132                                            SourceLocation FinalLoc,
17133                                            bool IsFinalSpelledSealed,
17134                                            bool IsAbstract,
17135                                            SourceLocation LBraceLoc) {
17136   AdjustDeclIfTemplate(TagD);
17137   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17138 
17139   FieldCollector->StartClass();
17140 
17141   if (!Record->getIdentifier())
17142     return;
17143 
17144   if (IsAbstract)
17145     Record->markAbstract();
17146 
17147   if (FinalLoc.isValid()) {
17148     Record->addAttr(FinalAttr::Create(
17149         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17150         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17151   }
17152   // C++ [class]p2:
17153   //   [...] The class-name is also inserted into the scope of the
17154   //   class itself; this is known as the injected-class-name. For
17155   //   purposes of access checking, the injected-class-name is treated
17156   //   as if it were a public member name.
17157   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17158       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17159       Record->getLocation(), Record->getIdentifier(),
17160       /*PrevDecl=*/nullptr,
17161       /*DelayTypeCreation=*/true);
17162   Context.getTypeDeclType(InjectedClassName, Record);
17163   InjectedClassName->setImplicit();
17164   InjectedClassName->setAccess(AS_public);
17165   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17166       InjectedClassName->setDescribedClassTemplate(Template);
17167   PushOnScopeChains(InjectedClassName, S);
17168   assert(InjectedClassName->isInjectedClassName() &&
17169          "Broken injected-class-name");
17170 }
17171 
17172 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17173                                     SourceRange BraceRange) {
17174   AdjustDeclIfTemplate(TagD);
17175   TagDecl *Tag = cast<TagDecl>(TagD);
17176   Tag->setBraceRange(BraceRange);
17177 
17178   // Make sure we "complete" the definition even it is invalid.
17179   if (Tag->isBeingDefined()) {
17180     assert(Tag->isInvalidDecl() && "We should already have completed it");
17181     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17182       RD->completeDefinition();
17183   }
17184 
17185   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17186     FieldCollector->FinishClass();
17187     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17188       auto *Def = RD->getDefinition();
17189       assert(Def && "The record is expected to have a completed definition");
17190       unsigned NumInitMethods = 0;
17191       for (auto *Method : Def->methods()) {
17192         if (!Method->getIdentifier())
17193             continue;
17194         if (Method->getName() == "__init")
17195           NumInitMethods++;
17196       }
17197       if (NumInitMethods > 1 || !Def->hasInitMethod())
17198         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17199     }
17200   }
17201 
17202   // Exit this scope of this tag's definition.
17203   PopDeclContext();
17204 
17205   if (getCurLexicalContext()->isObjCContainer() &&
17206       Tag->getDeclContext()->isFileContext())
17207     Tag->setTopLevelDeclInObjCContainer();
17208 
17209   // Notify the consumer that we've defined a tag.
17210   if (!Tag->isInvalidDecl())
17211     Consumer.HandleTagDeclDefinition(Tag);
17212 
17213   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17214   // from XLs and instead matches the XL #pragma pack(1) behavior.
17215   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17216       AlignPackStack.hasValue()) {
17217     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17218     // Only diagnose #pragma align(packed).
17219     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17220       return;
17221     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17222     if (!RD)
17223       return;
17224     // Only warn if there is at least 1 bitfield member.
17225     if (llvm::any_of(RD->fields(),
17226                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17227       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17228   }
17229 }
17230 
17231 void Sema::ActOnObjCContainerFinishDefinition() {
17232   // Exit this scope of this interface definition.
17233   PopDeclContext();
17234 }
17235 
17236 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17237   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17238   OriginalLexicalContext = ObjCCtx;
17239   ActOnObjCContainerFinishDefinition();
17240 }
17241 
17242 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17243   ActOnObjCContainerStartDefinition(ObjCCtx);
17244   OriginalLexicalContext = nullptr;
17245 }
17246 
17247 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17248   AdjustDeclIfTemplate(TagD);
17249   TagDecl *Tag = cast<TagDecl>(TagD);
17250   Tag->setInvalidDecl();
17251 
17252   // Make sure we "complete" the definition even it is invalid.
17253   if (Tag->isBeingDefined()) {
17254     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17255       RD->completeDefinition();
17256   }
17257 
17258   // We're undoing ActOnTagStartDefinition here, not
17259   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17260   // the FieldCollector.
17261 
17262   PopDeclContext();
17263 }
17264 
17265 // Note that FieldName may be null for anonymous bitfields.
17266 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17267                                 IdentifierInfo *FieldName, QualType FieldTy,
17268                                 bool IsMsStruct, Expr *BitWidth) {
17269   assert(BitWidth);
17270   if (BitWidth->containsErrors())
17271     return ExprError();
17272 
17273   // C99 6.7.2.1p4 - verify the field type.
17274   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17275   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17276     // Handle incomplete and sizeless types with a specific error.
17277     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17278                                  diag::err_field_incomplete_or_sizeless))
17279       return ExprError();
17280     if (FieldName)
17281       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17282         << FieldName << FieldTy << BitWidth->getSourceRange();
17283     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17284       << FieldTy << BitWidth->getSourceRange();
17285   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17286                                              UPPC_BitFieldWidth))
17287     return ExprError();
17288 
17289   // If the bit-width is type- or value-dependent, don't try to check
17290   // it now.
17291   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17292     return BitWidth;
17293 
17294   llvm::APSInt Value;
17295   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17296   if (ICE.isInvalid())
17297     return ICE;
17298   BitWidth = ICE.get();
17299 
17300   // Zero-width bitfield is ok for anonymous field.
17301   if (Value == 0 && FieldName)
17302     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17303 
17304   if (Value.isSigned() && Value.isNegative()) {
17305     if (FieldName)
17306       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17307                << FieldName << toString(Value, 10);
17308     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17309       << toString(Value, 10);
17310   }
17311 
17312   // The size of the bit-field must not exceed our maximum permitted object
17313   // size.
17314   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17315     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17316            << !FieldName << FieldName << toString(Value, 10);
17317   }
17318 
17319   if (!FieldTy->isDependentType()) {
17320     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17321     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17322     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17323 
17324     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17325     // ABI.
17326     bool CStdConstraintViolation =
17327         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17328     bool MSBitfieldViolation =
17329         Value.ugt(TypeStorageSize) &&
17330         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17331     if (CStdConstraintViolation || MSBitfieldViolation) {
17332       unsigned DiagWidth =
17333           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17334       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17335              << (bool)FieldName << FieldName << toString(Value, 10)
17336              << !CStdConstraintViolation << DiagWidth;
17337     }
17338 
17339     // Warn on types where the user might conceivably expect to get all
17340     // specified bits as value bits: that's all integral types other than
17341     // 'bool'.
17342     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17343       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17344           << FieldName << toString(Value, 10)
17345           << (unsigned)TypeWidth;
17346     }
17347   }
17348 
17349   return BitWidth;
17350 }
17351 
17352 /// ActOnField - Each field of a C struct/union is passed into this in order
17353 /// to create a FieldDecl object for it.
17354 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17355                        Declarator &D, Expr *BitfieldWidth) {
17356   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17357                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17358                                /*InitStyle=*/ICIS_NoInit, AS_public);
17359   return Res;
17360 }
17361 
17362 /// HandleField - Analyze a field of a C struct or a C++ data member.
17363 ///
17364 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17365                              SourceLocation DeclStart,
17366                              Declarator &D, Expr *BitWidth,
17367                              InClassInitStyle InitStyle,
17368                              AccessSpecifier AS) {
17369   if (D.isDecompositionDeclarator()) {
17370     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17371     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17372       << Decomp.getSourceRange();
17373     return nullptr;
17374   }
17375 
17376   IdentifierInfo *II = D.getIdentifier();
17377   SourceLocation Loc = DeclStart;
17378   if (II) Loc = D.getIdentifierLoc();
17379 
17380   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17381   QualType T = TInfo->getType();
17382   if (getLangOpts().CPlusPlus) {
17383     CheckExtraCXXDefaultArguments(D);
17384 
17385     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17386                                         UPPC_DataMemberType)) {
17387       D.setInvalidType();
17388       T = Context.IntTy;
17389       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17390     }
17391   }
17392 
17393   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17394 
17395   if (D.getDeclSpec().isInlineSpecified())
17396     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17397         << getLangOpts().CPlusPlus17;
17398   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17399     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17400          diag::err_invalid_thread)
17401       << DeclSpec::getSpecifierName(TSCS);
17402 
17403   // Check to see if this name was declared as a member previously
17404   NamedDecl *PrevDecl = nullptr;
17405   LookupResult Previous(*this, II, Loc, LookupMemberName,
17406                         ForVisibleRedeclaration);
17407   LookupName(Previous, S);
17408   switch (Previous.getResultKind()) {
17409     case LookupResult::Found:
17410     case LookupResult::FoundUnresolvedValue:
17411       PrevDecl = Previous.getAsSingle<NamedDecl>();
17412       break;
17413 
17414     case LookupResult::FoundOverloaded:
17415       PrevDecl = Previous.getRepresentativeDecl();
17416       break;
17417 
17418     case LookupResult::NotFound:
17419     case LookupResult::NotFoundInCurrentInstantiation:
17420     case LookupResult::Ambiguous:
17421       break;
17422   }
17423   Previous.suppressDiagnostics();
17424 
17425   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17426     // Maybe we will complain about the shadowed template parameter.
17427     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17428     // Just pretend that we didn't see the previous declaration.
17429     PrevDecl = nullptr;
17430   }
17431 
17432   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17433     PrevDecl = nullptr;
17434 
17435   bool Mutable
17436     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17437   SourceLocation TSSL = D.getBeginLoc();
17438   FieldDecl *NewFD
17439     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17440                      TSSL, AS, PrevDecl, &D);
17441 
17442   if (NewFD->isInvalidDecl())
17443     Record->setInvalidDecl();
17444 
17445   if (D.getDeclSpec().isModulePrivateSpecified())
17446     NewFD->setModulePrivate();
17447 
17448   if (NewFD->isInvalidDecl() && PrevDecl) {
17449     // Don't introduce NewFD into scope; there's already something
17450     // with the same name in the same scope.
17451   } else if (II) {
17452     PushOnScopeChains(NewFD, S);
17453   } else
17454     Record->addDecl(NewFD);
17455 
17456   return NewFD;
17457 }
17458 
17459 /// Build a new FieldDecl and check its well-formedness.
17460 ///
17461 /// This routine builds a new FieldDecl given the fields name, type,
17462 /// record, etc. \p PrevDecl should refer to any previous declaration
17463 /// with the same name and in the same scope as the field to be
17464 /// created.
17465 ///
17466 /// \returns a new FieldDecl.
17467 ///
17468 /// \todo The Declarator argument is a hack. It will be removed once
17469 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17470                                 TypeSourceInfo *TInfo,
17471                                 RecordDecl *Record, SourceLocation Loc,
17472                                 bool Mutable, Expr *BitWidth,
17473                                 InClassInitStyle InitStyle,
17474                                 SourceLocation TSSL,
17475                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17476                                 Declarator *D) {
17477   IdentifierInfo *II = Name.getAsIdentifierInfo();
17478   bool InvalidDecl = false;
17479   if (D) InvalidDecl = D->isInvalidType();
17480 
17481   // If we receive a broken type, recover by assuming 'int' and
17482   // marking this declaration as invalid.
17483   if (T.isNull() || T->containsErrors()) {
17484     InvalidDecl = true;
17485     T = Context.IntTy;
17486   }
17487 
17488   QualType EltTy = Context.getBaseElementType(T);
17489   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17490     if (RequireCompleteSizedType(Loc, EltTy,
17491                                  diag::err_field_incomplete_or_sizeless)) {
17492       // Fields of incomplete type force their record to be invalid.
17493       Record->setInvalidDecl();
17494       InvalidDecl = true;
17495     } else {
17496       NamedDecl *Def;
17497       EltTy->isIncompleteType(&Def);
17498       if (Def && Def->isInvalidDecl()) {
17499         Record->setInvalidDecl();
17500         InvalidDecl = true;
17501       }
17502     }
17503   }
17504 
17505   // TR 18037 does not allow fields to be declared with address space
17506   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17507       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17508     Diag(Loc, diag::err_field_with_address_space);
17509     Record->setInvalidDecl();
17510     InvalidDecl = true;
17511   }
17512 
17513   if (LangOpts.OpenCL) {
17514     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17515     // used as structure or union field: image, sampler, event or block types.
17516     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17517         T->isBlockPointerType()) {
17518       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17519       Record->setInvalidDecl();
17520       InvalidDecl = true;
17521     }
17522     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17523     // is enabled.
17524     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17525                         "__cl_clang_bitfields", LangOpts)) {
17526       Diag(Loc, diag::err_opencl_bitfields);
17527       InvalidDecl = true;
17528     }
17529   }
17530 
17531   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17532   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17533       T.hasQualifiers()) {
17534     InvalidDecl = true;
17535     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17536   }
17537 
17538   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17539   // than a variably modified type.
17540   if (!InvalidDecl && T->isVariablyModifiedType()) {
17541     if (!tryToFixVariablyModifiedVarType(
17542             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17543       InvalidDecl = true;
17544   }
17545 
17546   // Fields can not have abstract class types
17547   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17548                                              diag::err_abstract_type_in_decl,
17549                                              AbstractFieldType))
17550     InvalidDecl = true;
17551 
17552   if (InvalidDecl)
17553     BitWidth = nullptr;
17554   // If this is declared as a bit-field, check the bit-field.
17555   if (BitWidth) {
17556     BitWidth =
17557         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17558     if (!BitWidth) {
17559       InvalidDecl = true;
17560       BitWidth = nullptr;
17561     }
17562   }
17563 
17564   // Check that 'mutable' is consistent with the type of the declaration.
17565   if (!InvalidDecl && Mutable) {
17566     unsigned DiagID = 0;
17567     if (T->isReferenceType())
17568       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17569                                         : diag::err_mutable_reference;
17570     else if (T.isConstQualified())
17571       DiagID = diag::err_mutable_const;
17572 
17573     if (DiagID) {
17574       SourceLocation ErrLoc = Loc;
17575       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17576         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17577       Diag(ErrLoc, DiagID);
17578       if (DiagID != diag::ext_mutable_reference) {
17579         Mutable = false;
17580         InvalidDecl = true;
17581       }
17582     }
17583   }
17584 
17585   // C++11 [class.union]p8 (DR1460):
17586   //   At most one variant member of a union may have a
17587   //   brace-or-equal-initializer.
17588   if (InitStyle != ICIS_NoInit)
17589     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17590 
17591   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17592                                        BitWidth, Mutable, InitStyle);
17593   if (InvalidDecl)
17594     NewFD->setInvalidDecl();
17595 
17596   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17597     Diag(Loc, diag::err_duplicate_member) << II;
17598     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17599     NewFD->setInvalidDecl();
17600   }
17601 
17602   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17603     if (Record->isUnion()) {
17604       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17605         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17606         if (RDecl->getDefinition()) {
17607           // C++ [class.union]p1: An object of a class with a non-trivial
17608           // constructor, a non-trivial copy constructor, a non-trivial
17609           // destructor, or a non-trivial copy assignment operator
17610           // cannot be a member of a union, nor can an array of such
17611           // objects.
17612           if (CheckNontrivialField(NewFD))
17613             NewFD->setInvalidDecl();
17614         }
17615       }
17616 
17617       // C++ [class.union]p1: If a union contains a member of reference type,
17618       // the program is ill-formed, except when compiling with MSVC extensions
17619       // enabled.
17620       if (EltTy->isReferenceType()) {
17621         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17622                                     diag::ext_union_member_of_reference_type :
17623                                     diag::err_union_member_of_reference_type)
17624           << NewFD->getDeclName() << EltTy;
17625         if (!getLangOpts().MicrosoftExt)
17626           NewFD->setInvalidDecl();
17627       }
17628     }
17629   }
17630 
17631   // FIXME: We need to pass in the attributes given an AST
17632   // representation, not a parser representation.
17633   if (D) {
17634     // FIXME: The current scope is almost... but not entirely... correct here.
17635     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17636 
17637     if (NewFD->hasAttrs())
17638       CheckAlignasUnderalignment(NewFD);
17639   }
17640 
17641   // In auto-retain/release, infer strong retension for fields of
17642   // retainable type.
17643   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17644     NewFD->setInvalidDecl();
17645 
17646   if (T.isObjCGCWeak())
17647     Diag(Loc, diag::warn_attribute_weak_on_field);
17648 
17649   // PPC MMA non-pointer types are not allowed as field types.
17650   if (Context.getTargetInfo().getTriple().isPPC64() &&
17651       CheckPPCMMAType(T, NewFD->getLocation()))
17652     NewFD->setInvalidDecl();
17653 
17654   NewFD->setAccess(AS);
17655   return NewFD;
17656 }
17657 
17658 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17659   assert(FD);
17660   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17661 
17662   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17663     return false;
17664 
17665   QualType EltTy = Context.getBaseElementType(FD->getType());
17666   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17667     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17668     if (RDecl->getDefinition()) {
17669       // We check for copy constructors before constructors
17670       // because otherwise we'll never get complaints about
17671       // copy constructors.
17672 
17673       CXXSpecialMember member = CXXInvalid;
17674       // We're required to check for any non-trivial constructors. Since the
17675       // implicit default constructor is suppressed if there are any
17676       // user-declared constructors, we just need to check that there is a
17677       // trivial default constructor and a trivial copy constructor. (We don't
17678       // worry about move constructors here, since this is a C++98 check.)
17679       if (RDecl->hasNonTrivialCopyConstructor())
17680         member = CXXCopyConstructor;
17681       else if (!RDecl->hasTrivialDefaultConstructor())
17682         member = CXXDefaultConstructor;
17683       else if (RDecl->hasNonTrivialCopyAssignment())
17684         member = CXXCopyAssignment;
17685       else if (RDecl->hasNonTrivialDestructor())
17686         member = CXXDestructor;
17687 
17688       if (member != CXXInvalid) {
17689         if (!getLangOpts().CPlusPlus11 &&
17690             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17691           // Objective-C++ ARC: it is an error to have a non-trivial field of
17692           // a union. However, system headers in Objective-C programs
17693           // occasionally have Objective-C lifetime objects within unions,
17694           // and rather than cause the program to fail, we make those
17695           // members unavailable.
17696           SourceLocation Loc = FD->getLocation();
17697           if (getSourceManager().isInSystemHeader(Loc)) {
17698             if (!FD->hasAttr<UnavailableAttr>())
17699               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17700                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17701             return false;
17702           }
17703         }
17704 
17705         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17706                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17707                diag::err_illegal_union_or_anon_struct_member)
17708           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17709         DiagnoseNontrivial(RDecl, member);
17710         return !getLangOpts().CPlusPlus11;
17711       }
17712     }
17713   }
17714 
17715   return false;
17716 }
17717 
17718 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17719 ///  AST enum value.
17720 static ObjCIvarDecl::AccessControl
17721 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17722   switch (ivarVisibility) {
17723   default: llvm_unreachable("Unknown visitibility kind");
17724   case tok::objc_private: return ObjCIvarDecl::Private;
17725   case tok::objc_public: return ObjCIvarDecl::Public;
17726   case tok::objc_protected: return ObjCIvarDecl::Protected;
17727   case tok::objc_package: return ObjCIvarDecl::Package;
17728   }
17729 }
17730 
17731 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17732 /// in order to create an IvarDecl object for it.
17733 Decl *Sema::ActOnIvar(Scope *S,
17734                                 SourceLocation DeclStart,
17735                                 Declarator &D, Expr *BitfieldWidth,
17736                                 tok::ObjCKeywordKind Visibility) {
17737 
17738   IdentifierInfo *II = D.getIdentifier();
17739   Expr *BitWidth = (Expr*)BitfieldWidth;
17740   SourceLocation Loc = DeclStart;
17741   if (II) Loc = D.getIdentifierLoc();
17742 
17743   // FIXME: Unnamed fields can be handled in various different ways, for
17744   // example, unnamed unions inject all members into the struct namespace!
17745 
17746   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17747   QualType T = TInfo->getType();
17748 
17749   if (BitWidth) {
17750     // 6.7.2.1p3, 6.7.2.1p4
17751     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17752     if (!BitWidth)
17753       D.setInvalidType();
17754   } else {
17755     // Not a bitfield.
17756 
17757     // validate II.
17758 
17759   }
17760   if (T->isReferenceType()) {
17761     Diag(Loc, diag::err_ivar_reference_type);
17762     D.setInvalidType();
17763   }
17764   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17765   // than a variably modified type.
17766   else if (T->isVariablyModifiedType()) {
17767     if (!tryToFixVariablyModifiedVarType(
17768             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17769       D.setInvalidType();
17770   }
17771 
17772   // Get the visibility (access control) for this ivar.
17773   ObjCIvarDecl::AccessControl ac =
17774     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17775                                         : ObjCIvarDecl::None;
17776   // Must set ivar's DeclContext to its enclosing interface.
17777   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17778   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17779     return nullptr;
17780   ObjCContainerDecl *EnclosingContext;
17781   if (ObjCImplementationDecl *IMPDecl =
17782       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17783     if (LangOpts.ObjCRuntime.isFragile()) {
17784     // Case of ivar declared in an implementation. Context is that of its class.
17785       EnclosingContext = IMPDecl->getClassInterface();
17786       assert(EnclosingContext && "Implementation has no class interface!");
17787     }
17788     else
17789       EnclosingContext = EnclosingDecl;
17790   } else {
17791     if (ObjCCategoryDecl *CDecl =
17792         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17793       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17794         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17795         return nullptr;
17796       }
17797     }
17798     EnclosingContext = EnclosingDecl;
17799   }
17800 
17801   // Construct the decl.
17802   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17803                                              DeclStart, Loc, II, T,
17804                                              TInfo, ac, (Expr *)BitfieldWidth);
17805 
17806   if (II) {
17807     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17808                                            ForVisibleRedeclaration);
17809     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17810         && !isa<TagDecl>(PrevDecl)) {
17811       Diag(Loc, diag::err_duplicate_member) << II;
17812       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17813       NewID->setInvalidDecl();
17814     }
17815   }
17816 
17817   // Process attributes attached to the ivar.
17818   ProcessDeclAttributes(S, NewID, D);
17819 
17820   if (D.isInvalidType())
17821     NewID->setInvalidDecl();
17822 
17823   // In ARC, infer 'retaining' for ivars of retainable type.
17824   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17825     NewID->setInvalidDecl();
17826 
17827   if (D.getDeclSpec().isModulePrivateSpecified())
17828     NewID->setModulePrivate();
17829 
17830   if (II) {
17831     // FIXME: When interfaces are DeclContexts, we'll need to add
17832     // these to the interface.
17833     S->AddDecl(NewID);
17834     IdResolver.AddDecl(NewID);
17835   }
17836 
17837   if (LangOpts.ObjCRuntime.isNonFragile() &&
17838       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17839     Diag(Loc, diag::warn_ivars_in_interface);
17840 
17841   return NewID;
17842 }
17843 
17844 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17845 /// class and class extensions. For every class \@interface and class
17846 /// extension \@interface, if the last ivar is a bitfield of any type,
17847 /// then add an implicit `char :0` ivar to the end of that interface.
17848 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17849                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17850   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17851     return;
17852 
17853   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17854   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17855 
17856   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17857     return;
17858   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17859   if (!ID) {
17860     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17861       if (!CD->IsClassExtension())
17862         return;
17863     }
17864     // No need to add this to end of @implementation.
17865     else
17866       return;
17867   }
17868   // All conditions are met. Add a new bitfield to the tail end of ivars.
17869   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17870   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17871 
17872   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17873                               DeclLoc, DeclLoc, nullptr,
17874                               Context.CharTy,
17875                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17876                                                                DeclLoc),
17877                               ObjCIvarDecl::Private, BW,
17878                               true);
17879   AllIvarDecls.push_back(Ivar);
17880 }
17881 
17882 namespace {
17883 /// [class.dtor]p4:
17884 ///   At the end of the definition of a class, overload resolution is
17885 ///   performed among the prospective destructors declared in that class with
17886 ///   an empty argument list to select the destructor for the class, also
17887 ///   known as the selected destructor.
17888 ///
17889 /// We do the overload resolution here, then mark the selected constructor in the AST.
17890 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17891 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17892   if (!Record->hasUserDeclaredDestructor()) {
17893     return;
17894   }
17895 
17896   SourceLocation Loc = Record->getLocation();
17897   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17898 
17899   for (auto *Decl : Record->decls()) {
17900     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17901       if (DD->isInvalidDecl())
17902         continue;
17903       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17904                              OCS);
17905       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17906     }
17907   }
17908 
17909   if (OCS.empty()) {
17910     return;
17911   }
17912   OverloadCandidateSet::iterator Best;
17913   unsigned Msg = 0;
17914   OverloadCandidateDisplayKind DisplayKind;
17915 
17916   switch (OCS.BestViableFunction(S, Loc, Best)) {
17917   case OR_Success:
17918   case OR_Deleted:
17919     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17920     break;
17921 
17922   case OR_Ambiguous:
17923     Msg = diag::err_ambiguous_destructor;
17924     DisplayKind = OCD_AmbiguousCandidates;
17925     break;
17926 
17927   case OR_No_Viable_Function:
17928     Msg = diag::err_no_viable_destructor;
17929     DisplayKind = OCD_AllCandidates;
17930     break;
17931   }
17932 
17933   if (Msg) {
17934     // OpenCL have got their own thing going with destructors. It's slightly broken,
17935     // but we allow it.
17936     if (!S.LangOpts.OpenCL) {
17937       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17938       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17939       Record->setInvalidDecl();
17940     }
17941     // It's a bit hacky: At this point we've raised an error but we want the
17942     // rest of the compiler to continue somehow working. However almost
17943     // everything we'll try to do with the class will depend on there being a
17944     // destructor. So let's pretend the first one is selected and hope for the
17945     // best.
17946     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17947   }
17948 }
17949 } // namespace
17950 
17951 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17952                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17953                        SourceLocation RBrac,
17954                        const ParsedAttributesView &Attrs) {
17955   assert(EnclosingDecl && "missing record or interface decl");
17956 
17957   // If this is an Objective-C @implementation or category and we have
17958   // new fields here we should reset the layout of the interface since
17959   // it will now change.
17960   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17961     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17962     switch (DC->getKind()) {
17963     default: break;
17964     case Decl::ObjCCategory:
17965       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17966       break;
17967     case Decl::ObjCImplementation:
17968       Context.
17969         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17970       break;
17971     }
17972   }
17973 
17974   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17975   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17976 
17977   if (CXXRecord && !CXXRecord->isDependentType())
17978     ComputeSelectedDestructor(*this, CXXRecord);
17979 
17980   // Start counting up the number of named members; make sure to include
17981   // members of anonymous structs and unions in the total.
17982   unsigned NumNamedMembers = 0;
17983   if (Record) {
17984     for (const auto *I : Record->decls()) {
17985       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17986         if (IFD->getDeclName())
17987           ++NumNamedMembers;
17988     }
17989   }
17990 
17991   // Verify that all the fields are okay.
17992   SmallVector<FieldDecl*, 32> RecFields;
17993 
17994   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17995        i != end; ++i) {
17996     FieldDecl *FD = cast<FieldDecl>(*i);
17997 
17998     // Get the type for the field.
17999     const Type *FDTy = FD->getType().getTypePtr();
18000 
18001     if (!FD->isAnonymousStructOrUnion()) {
18002       // Remember all fields written by the user.
18003       RecFields.push_back(FD);
18004     }
18005 
18006     // If the field is already invalid for some reason, don't emit more
18007     // diagnostics about it.
18008     if (FD->isInvalidDecl()) {
18009       EnclosingDecl->setInvalidDecl();
18010       continue;
18011     }
18012 
18013     // C99 6.7.2.1p2:
18014     //   A structure or union shall not contain a member with
18015     //   incomplete or function type (hence, a structure shall not
18016     //   contain an instance of itself, but may contain a pointer to
18017     //   an instance of itself), except that the last member of a
18018     //   structure with more than one named member may have incomplete
18019     //   array type; such a structure (and any union containing,
18020     //   possibly recursively, a member that is such a structure)
18021     //   shall not be a member of a structure or an element of an
18022     //   array.
18023     bool IsLastField = (i + 1 == Fields.end());
18024     if (FDTy->isFunctionType()) {
18025       // Field declared as a function.
18026       Diag(FD->getLocation(), diag::err_field_declared_as_function)
18027         << FD->getDeclName();
18028       FD->setInvalidDecl();
18029       EnclosingDecl->setInvalidDecl();
18030       continue;
18031     } else if (FDTy->isIncompleteArrayType() &&
18032                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18033       if (Record) {
18034         // Flexible array member.
18035         // Microsoft and g++ is more permissive regarding flexible array.
18036         // It will accept flexible array in union and also
18037         // as the sole element of a struct/class.
18038         unsigned DiagID = 0;
18039         if (!Record->isUnion() && !IsLastField) {
18040           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18041             << FD->getDeclName() << FD->getType() << Record->getTagKind();
18042           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18043           FD->setInvalidDecl();
18044           EnclosingDecl->setInvalidDecl();
18045           continue;
18046         } else if (Record->isUnion())
18047           DiagID = getLangOpts().MicrosoftExt
18048                        ? diag::ext_flexible_array_union_ms
18049                        : getLangOpts().CPlusPlus
18050                              ? diag::ext_flexible_array_union_gnu
18051                              : diag::err_flexible_array_union;
18052         else if (NumNamedMembers < 1)
18053           DiagID = getLangOpts().MicrosoftExt
18054                        ? diag::ext_flexible_array_empty_aggregate_ms
18055                        : getLangOpts().CPlusPlus
18056                              ? diag::ext_flexible_array_empty_aggregate_gnu
18057                              : diag::err_flexible_array_empty_aggregate;
18058 
18059         if (DiagID)
18060           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18061                                           << Record->getTagKind();
18062         // While the layout of types that contain virtual bases is not specified
18063         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18064         // virtual bases after the derived members.  This would make a flexible
18065         // array member declared at the end of an object not adjacent to the end
18066         // of the type.
18067         if (CXXRecord && CXXRecord->getNumVBases() != 0)
18068           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18069               << FD->getDeclName() << Record->getTagKind();
18070         if (!getLangOpts().C99)
18071           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18072             << FD->getDeclName() << Record->getTagKind();
18073 
18074         // If the element type has a non-trivial destructor, we would not
18075         // implicitly destroy the elements, so disallow it for now.
18076         //
18077         // FIXME: GCC allows this. We should probably either implicitly delete
18078         // the destructor of the containing class, or just allow this.
18079         QualType BaseElem = Context.getBaseElementType(FD->getType());
18080         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18081           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18082             << FD->getDeclName() << FD->getType();
18083           FD->setInvalidDecl();
18084           EnclosingDecl->setInvalidDecl();
18085           continue;
18086         }
18087         // Okay, we have a legal flexible array member at the end of the struct.
18088         Record->setHasFlexibleArrayMember(true);
18089       } else {
18090         // In ObjCContainerDecl ivars with incomplete array type are accepted,
18091         // unless they are followed by another ivar. That check is done
18092         // elsewhere, after synthesized ivars are known.
18093       }
18094     } else if (!FDTy->isDependentType() &&
18095                RequireCompleteSizedType(
18096                    FD->getLocation(), FD->getType(),
18097                    diag::err_field_incomplete_or_sizeless)) {
18098       // Incomplete type
18099       FD->setInvalidDecl();
18100       EnclosingDecl->setInvalidDecl();
18101       continue;
18102     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18103       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18104         // A type which contains a flexible array member is considered to be a
18105         // flexible array member.
18106         Record->setHasFlexibleArrayMember(true);
18107         if (!Record->isUnion()) {
18108           // If this is a struct/class and this is not the last element, reject
18109           // it.  Note that GCC supports variable sized arrays in the middle of
18110           // structures.
18111           if (!IsLastField)
18112             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18113               << FD->getDeclName() << FD->getType();
18114           else {
18115             // We support flexible arrays at the end of structs in
18116             // other structs as an extension.
18117             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18118               << FD->getDeclName();
18119           }
18120         }
18121       }
18122       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18123           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18124                                  diag::err_abstract_type_in_decl,
18125                                  AbstractIvarType)) {
18126         // Ivars can not have abstract class types
18127         FD->setInvalidDecl();
18128       }
18129       if (Record && FDTTy->getDecl()->hasObjectMember())
18130         Record->setHasObjectMember(true);
18131       if (Record && FDTTy->getDecl()->hasVolatileMember())
18132         Record->setHasVolatileMember(true);
18133     } else if (FDTy->isObjCObjectType()) {
18134       /// A field cannot be an Objective-c object
18135       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18136         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18137       QualType T = Context.getObjCObjectPointerType(FD->getType());
18138       FD->setType(T);
18139     } else if (Record && Record->isUnion() &&
18140                FD->getType().hasNonTrivialObjCLifetime() &&
18141                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18142                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18143                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18144                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18145       // For backward compatibility, fields of C unions declared in system
18146       // headers that have non-trivial ObjC ownership qualifications are marked
18147       // as unavailable unless the qualifier is explicit and __strong. This can
18148       // break ABI compatibility between programs compiled with ARC and MRR, but
18149       // is a better option than rejecting programs using those unions under
18150       // ARC.
18151       FD->addAttr(UnavailableAttr::CreateImplicit(
18152           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18153           FD->getLocation()));
18154     } else if (getLangOpts().ObjC &&
18155                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18156                !Record->hasObjectMember()) {
18157       if (FD->getType()->isObjCObjectPointerType() ||
18158           FD->getType().isObjCGCStrong())
18159         Record->setHasObjectMember(true);
18160       else if (Context.getAsArrayType(FD->getType())) {
18161         QualType BaseType = Context.getBaseElementType(FD->getType());
18162         if (BaseType->isRecordType() &&
18163             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18164           Record->setHasObjectMember(true);
18165         else if (BaseType->isObjCObjectPointerType() ||
18166                  BaseType.isObjCGCStrong())
18167                Record->setHasObjectMember(true);
18168       }
18169     }
18170 
18171     if (Record && !getLangOpts().CPlusPlus &&
18172         !shouldIgnoreForRecordTriviality(FD)) {
18173       QualType FT = FD->getType();
18174       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18175         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18176         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18177             Record->isUnion())
18178           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18179       }
18180       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18181       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18182         Record->setNonTrivialToPrimitiveCopy(true);
18183         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18184           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18185       }
18186       if (FT.isDestructedType()) {
18187         Record->setNonTrivialToPrimitiveDestroy(true);
18188         Record->setParamDestroyedInCallee(true);
18189         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18190           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18191       }
18192 
18193       if (const auto *RT = FT->getAs<RecordType>()) {
18194         if (RT->getDecl()->getArgPassingRestrictions() ==
18195             RecordDecl::APK_CanNeverPassInRegs)
18196           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18197       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18198         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18199     }
18200 
18201     if (Record && FD->getType().isVolatileQualified())
18202       Record->setHasVolatileMember(true);
18203     // Keep track of the number of named members.
18204     if (FD->getIdentifier())
18205       ++NumNamedMembers;
18206   }
18207 
18208   // Okay, we successfully defined 'Record'.
18209   if (Record) {
18210     bool Completed = false;
18211     if (CXXRecord) {
18212       if (!CXXRecord->isInvalidDecl()) {
18213         // Set access bits correctly on the directly-declared conversions.
18214         for (CXXRecordDecl::conversion_iterator
18215                I = CXXRecord->conversion_begin(),
18216                E = CXXRecord->conversion_end(); I != E; ++I)
18217           I.setAccess((*I)->getAccess());
18218       }
18219 
18220       // Add any implicitly-declared members to this class.
18221       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18222 
18223       if (!CXXRecord->isDependentType()) {
18224         if (!CXXRecord->isInvalidDecl()) {
18225           // If we have virtual base classes, we may end up finding multiple
18226           // final overriders for a given virtual function. Check for this
18227           // problem now.
18228           if (CXXRecord->getNumVBases()) {
18229             CXXFinalOverriderMap FinalOverriders;
18230             CXXRecord->getFinalOverriders(FinalOverriders);
18231 
18232             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18233                                              MEnd = FinalOverriders.end();
18234                  M != MEnd; ++M) {
18235               for (OverridingMethods::iterator SO = M->second.begin(),
18236                                             SOEnd = M->second.end();
18237                    SO != SOEnd; ++SO) {
18238                 assert(SO->second.size() > 0 &&
18239                        "Virtual function without overriding functions?");
18240                 if (SO->second.size() == 1)
18241                   continue;
18242 
18243                 // C++ [class.virtual]p2:
18244                 //   In a derived class, if a virtual member function of a base
18245                 //   class subobject has more than one final overrider the
18246                 //   program is ill-formed.
18247                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18248                   << (const NamedDecl *)M->first << Record;
18249                 Diag(M->first->getLocation(),
18250                      diag::note_overridden_virtual_function);
18251                 for (OverridingMethods::overriding_iterator
18252                           OM = SO->second.begin(),
18253                        OMEnd = SO->second.end();
18254                      OM != OMEnd; ++OM)
18255                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18256                     << (const NamedDecl *)M->first << OM->Method->getParent();
18257 
18258                 Record->setInvalidDecl();
18259               }
18260             }
18261             CXXRecord->completeDefinition(&FinalOverriders);
18262             Completed = true;
18263           }
18264         }
18265       }
18266     }
18267 
18268     if (!Completed)
18269       Record->completeDefinition();
18270 
18271     // Handle attributes before checking the layout.
18272     ProcessDeclAttributeList(S, Record, Attrs);
18273 
18274     // Check to see if a FieldDecl is a pointer to a function.
18275     auto IsFunctionPointer = [&](const Decl *D) {
18276       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18277       if (!FD)
18278         return false;
18279       QualType FieldType = FD->getType().getDesugaredType(Context);
18280       if (isa<PointerType>(FieldType)) {
18281         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18282         return PointeeType.getDesugaredType(Context)->isFunctionType();
18283       }
18284       return false;
18285     };
18286 
18287     // Maybe randomize the record's decls. We automatically randomize a record
18288     // of function pointers, unless it has the "no_randomize_layout" attribute.
18289     if (!getLangOpts().CPlusPlus &&
18290         (Record->hasAttr<RandomizeLayoutAttr>() ||
18291          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18292           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18293         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18294         !Record->isRandomized()) {
18295       SmallVector<Decl *, 32> NewDeclOrdering;
18296       if (randstruct::randomizeStructureLayout(Context, Record,
18297                                                NewDeclOrdering))
18298         Record->reorderDecls(NewDeclOrdering);
18299     }
18300 
18301     // We may have deferred checking for a deleted destructor. Check now.
18302     if (CXXRecord) {
18303       auto *Dtor = CXXRecord->getDestructor();
18304       if (Dtor && Dtor->isImplicit() &&
18305           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18306         CXXRecord->setImplicitDestructorIsDeleted();
18307         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18308       }
18309     }
18310 
18311     if (Record->hasAttrs()) {
18312       CheckAlignasUnderalignment(Record);
18313 
18314       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18315         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18316                                            IA->getRange(), IA->getBestCase(),
18317                                            IA->getInheritanceModel());
18318     }
18319 
18320     // Check if the structure/union declaration is a type that can have zero
18321     // size in C. For C this is a language extension, for C++ it may cause
18322     // compatibility problems.
18323     bool CheckForZeroSize;
18324     if (!getLangOpts().CPlusPlus) {
18325       CheckForZeroSize = true;
18326     } else {
18327       // For C++ filter out types that cannot be referenced in C code.
18328       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18329       CheckForZeroSize =
18330           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18331           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18332           CXXRecord->isCLike();
18333     }
18334     if (CheckForZeroSize) {
18335       bool ZeroSize = true;
18336       bool IsEmpty = true;
18337       unsigned NonBitFields = 0;
18338       for (RecordDecl::field_iterator I = Record->field_begin(),
18339                                       E = Record->field_end();
18340            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18341         IsEmpty = false;
18342         if (I->isUnnamedBitfield()) {
18343           if (!I->isZeroLengthBitField(Context))
18344             ZeroSize = false;
18345         } else {
18346           ++NonBitFields;
18347           QualType FieldType = I->getType();
18348           if (FieldType->isIncompleteType() ||
18349               !Context.getTypeSizeInChars(FieldType).isZero())
18350             ZeroSize = false;
18351         }
18352       }
18353 
18354       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18355       // allowed in C++, but warn if its declaration is inside
18356       // extern "C" block.
18357       if (ZeroSize) {
18358         Diag(RecLoc, getLangOpts().CPlusPlus ?
18359                          diag::warn_zero_size_struct_union_in_extern_c :
18360                          diag::warn_zero_size_struct_union_compat)
18361           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18362       }
18363 
18364       // Structs without named members are extension in C (C99 6.7.2.1p7),
18365       // but are accepted by GCC.
18366       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18367         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18368                                diag::ext_no_named_members_in_struct_union)
18369           << Record->isUnion();
18370       }
18371     }
18372   } else {
18373     ObjCIvarDecl **ClsFields =
18374       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18375     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18376       ID->setEndOfDefinitionLoc(RBrac);
18377       // Add ivar's to class's DeclContext.
18378       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18379         ClsFields[i]->setLexicalDeclContext(ID);
18380         ID->addDecl(ClsFields[i]);
18381       }
18382       // Must enforce the rule that ivars in the base classes may not be
18383       // duplicates.
18384       if (ID->getSuperClass())
18385         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18386     } else if (ObjCImplementationDecl *IMPDecl =
18387                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18388       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18389       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18390         // Ivar declared in @implementation never belongs to the implementation.
18391         // Only it is in implementation's lexical context.
18392         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18393       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18394       IMPDecl->setIvarLBraceLoc(LBrac);
18395       IMPDecl->setIvarRBraceLoc(RBrac);
18396     } else if (ObjCCategoryDecl *CDecl =
18397                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18398       // case of ivars in class extension; all other cases have been
18399       // reported as errors elsewhere.
18400       // FIXME. Class extension does not have a LocEnd field.
18401       // CDecl->setLocEnd(RBrac);
18402       // Add ivar's to class extension's DeclContext.
18403       // Diagnose redeclaration of private ivars.
18404       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18405       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18406         if (IDecl) {
18407           if (const ObjCIvarDecl *ClsIvar =
18408               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18409             Diag(ClsFields[i]->getLocation(),
18410                  diag::err_duplicate_ivar_declaration);
18411             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18412             continue;
18413           }
18414           for (const auto *Ext : IDecl->known_extensions()) {
18415             if (const ObjCIvarDecl *ClsExtIvar
18416                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18417               Diag(ClsFields[i]->getLocation(),
18418                    diag::err_duplicate_ivar_declaration);
18419               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18420               continue;
18421             }
18422           }
18423         }
18424         ClsFields[i]->setLexicalDeclContext(CDecl);
18425         CDecl->addDecl(ClsFields[i]);
18426       }
18427       CDecl->setIvarLBraceLoc(LBrac);
18428       CDecl->setIvarRBraceLoc(RBrac);
18429     }
18430   }
18431 }
18432 
18433 /// Determine whether the given integral value is representable within
18434 /// the given type T.
18435 static bool isRepresentableIntegerValue(ASTContext &Context,
18436                                         llvm::APSInt &Value,
18437                                         QualType T) {
18438   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18439          "Integral type required!");
18440   unsigned BitWidth = Context.getIntWidth(T);
18441 
18442   if (Value.isUnsigned() || Value.isNonNegative()) {
18443     if (T->isSignedIntegerOrEnumerationType())
18444       --BitWidth;
18445     return Value.getActiveBits() <= BitWidth;
18446   }
18447   return Value.getMinSignedBits() <= BitWidth;
18448 }
18449 
18450 // Given an integral type, return the next larger integral type
18451 // (or a NULL type of no such type exists).
18452 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18453   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18454   // enum checking below.
18455   assert((T->isIntegralType(Context) ||
18456          T->isEnumeralType()) && "Integral type required!");
18457   const unsigned NumTypes = 4;
18458   QualType SignedIntegralTypes[NumTypes] = {
18459     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18460   };
18461   QualType UnsignedIntegralTypes[NumTypes] = {
18462     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18463     Context.UnsignedLongLongTy
18464   };
18465 
18466   unsigned BitWidth = Context.getTypeSize(T);
18467   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18468                                                         : UnsignedIntegralTypes;
18469   for (unsigned I = 0; I != NumTypes; ++I)
18470     if (Context.getTypeSize(Types[I]) > BitWidth)
18471       return Types[I];
18472 
18473   return QualType();
18474 }
18475 
18476 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18477                                           EnumConstantDecl *LastEnumConst,
18478                                           SourceLocation IdLoc,
18479                                           IdentifierInfo *Id,
18480                                           Expr *Val) {
18481   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18482   llvm::APSInt EnumVal(IntWidth);
18483   QualType EltTy;
18484 
18485   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18486     Val = nullptr;
18487 
18488   if (Val)
18489     Val = DefaultLvalueConversion(Val).get();
18490 
18491   if (Val) {
18492     if (Enum->isDependentType() || Val->isTypeDependent() ||
18493         Val->containsErrors())
18494       EltTy = Context.DependentTy;
18495     else {
18496       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18497       // underlying type, but do allow it in all other contexts.
18498       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18499         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18500         // constant-expression in the enumerator-definition shall be a converted
18501         // constant expression of the underlying type.
18502         EltTy = Enum->getIntegerType();
18503         ExprResult Converted =
18504           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18505                                            CCEK_Enumerator);
18506         if (Converted.isInvalid())
18507           Val = nullptr;
18508         else
18509           Val = Converted.get();
18510       } else if (!Val->isValueDependent() &&
18511                  !(Val =
18512                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18513                            .get())) {
18514         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18515       } else {
18516         if (Enum->isComplete()) {
18517           EltTy = Enum->getIntegerType();
18518 
18519           // In Obj-C and Microsoft mode, require the enumeration value to be
18520           // representable in the underlying type of the enumeration. In C++11,
18521           // we perform a non-narrowing conversion as part of converted constant
18522           // expression checking.
18523           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18524             if (Context.getTargetInfo()
18525                     .getTriple()
18526                     .isWindowsMSVCEnvironment()) {
18527               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18528             } else {
18529               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18530             }
18531           }
18532 
18533           // Cast to the underlying type.
18534           Val = ImpCastExprToType(Val, EltTy,
18535                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18536                                                          : CK_IntegralCast)
18537                     .get();
18538         } else if (getLangOpts().CPlusPlus) {
18539           // C++11 [dcl.enum]p5:
18540           //   If the underlying type is not fixed, the type of each enumerator
18541           //   is the type of its initializing value:
18542           //     - If an initializer is specified for an enumerator, the
18543           //       initializing value has the same type as the expression.
18544           EltTy = Val->getType();
18545         } else {
18546           // C99 6.7.2.2p2:
18547           //   The expression that defines the value of an enumeration constant
18548           //   shall be an integer constant expression that has a value
18549           //   representable as an int.
18550 
18551           // Complain if the value is not representable in an int.
18552           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18553             Diag(IdLoc, diag::ext_enum_value_not_int)
18554               << toString(EnumVal, 10) << Val->getSourceRange()
18555               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18556           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18557             // Force the type of the expression to 'int'.
18558             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18559           }
18560           EltTy = Val->getType();
18561         }
18562       }
18563     }
18564   }
18565 
18566   if (!Val) {
18567     if (Enum->isDependentType())
18568       EltTy = Context.DependentTy;
18569     else if (!LastEnumConst) {
18570       // C++0x [dcl.enum]p5:
18571       //   If the underlying type is not fixed, the type of each enumerator
18572       //   is the type of its initializing value:
18573       //     - If no initializer is specified for the first enumerator, the
18574       //       initializing value has an unspecified integral type.
18575       //
18576       // GCC uses 'int' for its unspecified integral type, as does
18577       // C99 6.7.2.2p3.
18578       if (Enum->isFixed()) {
18579         EltTy = Enum->getIntegerType();
18580       }
18581       else {
18582         EltTy = Context.IntTy;
18583       }
18584     } else {
18585       // Assign the last value + 1.
18586       EnumVal = LastEnumConst->getInitVal();
18587       ++EnumVal;
18588       EltTy = LastEnumConst->getType();
18589 
18590       // Check for overflow on increment.
18591       if (EnumVal < LastEnumConst->getInitVal()) {
18592         // C++0x [dcl.enum]p5:
18593         //   If the underlying type is not fixed, the type of each enumerator
18594         //   is the type of its initializing value:
18595         //
18596         //     - Otherwise the type of the initializing value is the same as
18597         //       the type of the initializing value of the preceding enumerator
18598         //       unless the incremented value is not representable in that type,
18599         //       in which case the type is an unspecified integral type
18600         //       sufficient to contain the incremented value. If no such type
18601         //       exists, the program is ill-formed.
18602         QualType T = getNextLargerIntegralType(Context, EltTy);
18603         if (T.isNull() || Enum->isFixed()) {
18604           // There is no integral type larger enough to represent this
18605           // value. Complain, then allow the value to wrap around.
18606           EnumVal = LastEnumConst->getInitVal();
18607           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18608           ++EnumVal;
18609           if (Enum->isFixed())
18610             // When the underlying type is fixed, this is ill-formed.
18611             Diag(IdLoc, diag::err_enumerator_wrapped)
18612               << toString(EnumVal, 10)
18613               << EltTy;
18614           else
18615             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18616               << toString(EnumVal, 10);
18617         } else {
18618           EltTy = T;
18619         }
18620 
18621         // Retrieve the last enumerator's value, extent that type to the
18622         // type that is supposed to be large enough to represent the incremented
18623         // value, then increment.
18624         EnumVal = LastEnumConst->getInitVal();
18625         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18626         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18627         ++EnumVal;
18628 
18629         // If we're not in C++, diagnose the overflow of enumerator values,
18630         // which in C99 means that the enumerator value is not representable in
18631         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18632         // permits enumerator values that are representable in some larger
18633         // integral type.
18634         if (!getLangOpts().CPlusPlus && !T.isNull())
18635           Diag(IdLoc, diag::warn_enum_value_overflow);
18636       } else if (!getLangOpts().CPlusPlus &&
18637                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18638         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18639         Diag(IdLoc, diag::ext_enum_value_not_int)
18640           << toString(EnumVal, 10) << 1;
18641       }
18642     }
18643   }
18644 
18645   if (!EltTy->isDependentType()) {
18646     // Make the enumerator value match the signedness and size of the
18647     // enumerator's type.
18648     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18649     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18650   }
18651 
18652   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18653                                   Val, EnumVal);
18654 }
18655 
18656 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18657                                                 SourceLocation IILoc) {
18658   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18659       !getLangOpts().CPlusPlus)
18660     return SkipBodyInfo();
18661 
18662   // We have an anonymous enum definition. Look up the first enumerator to
18663   // determine if we should merge the definition with an existing one and
18664   // skip the body.
18665   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18666                                          forRedeclarationInCurContext());
18667   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18668   if (!PrevECD)
18669     return SkipBodyInfo();
18670 
18671   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18672   NamedDecl *Hidden;
18673   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18674     SkipBodyInfo Skip;
18675     Skip.Previous = Hidden;
18676     return Skip;
18677   }
18678 
18679   return SkipBodyInfo();
18680 }
18681 
18682 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18683                               SourceLocation IdLoc, IdentifierInfo *Id,
18684                               const ParsedAttributesView &Attrs,
18685                               SourceLocation EqualLoc, Expr *Val) {
18686   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18687   EnumConstantDecl *LastEnumConst =
18688     cast_or_null<EnumConstantDecl>(lastEnumConst);
18689 
18690   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18691   // we find one that is.
18692   S = getNonFieldDeclScope(S);
18693 
18694   // Verify that there isn't already something declared with this name in this
18695   // scope.
18696   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18697   LookupName(R, S);
18698   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18699 
18700   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18701     // Maybe we will complain about the shadowed template parameter.
18702     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18703     // Just pretend that we didn't see the previous declaration.
18704     PrevDecl = nullptr;
18705   }
18706 
18707   // C++ [class.mem]p15:
18708   // If T is the name of a class, then each of the following shall have a name
18709   // different from T:
18710   // - every enumerator of every member of class T that is an unscoped
18711   // enumerated type
18712   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18713     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18714                             DeclarationNameInfo(Id, IdLoc));
18715 
18716   EnumConstantDecl *New =
18717     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18718   if (!New)
18719     return nullptr;
18720 
18721   if (PrevDecl) {
18722     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18723       // Check for other kinds of shadowing not already handled.
18724       CheckShadow(New, PrevDecl, R);
18725     }
18726 
18727     // When in C++, we may get a TagDecl with the same name; in this case the
18728     // enum constant will 'hide' the tag.
18729     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18730            "Received TagDecl when not in C++!");
18731     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18732       if (isa<EnumConstantDecl>(PrevDecl))
18733         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18734       else
18735         Diag(IdLoc, diag::err_redefinition) << Id;
18736       notePreviousDefinition(PrevDecl, IdLoc);
18737       return nullptr;
18738     }
18739   }
18740 
18741   // Process attributes.
18742   ProcessDeclAttributeList(S, New, Attrs);
18743   AddPragmaAttributes(S, New);
18744 
18745   // Register this decl in the current scope stack.
18746   New->setAccess(TheEnumDecl->getAccess());
18747   PushOnScopeChains(New, S);
18748 
18749   ActOnDocumentableDecl(New);
18750 
18751   return New;
18752 }
18753 
18754 // Returns true when the enum initial expression does not trigger the
18755 // duplicate enum warning.  A few common cases are exempted as follows:
18756 // Element2 = Element1
18757 // Element2 = Element1 + 1
18758 // Element2 = Element1 - 1
18759 // Where Element2 and Element1 are from the same enum.
18760 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18761   Expr *InitExpr = ECD->getInitExpr();
18762   if (!InitExpr)
18763     return true;
18764   InitExpr = InitExpr->IgnoreImpCasts();
18765 
18766   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18767     if (!BO->isAdditiveOp())
18768       return true;
18769     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18770     if (!IL)
18771       return true;
18772     if (IL->getValue() != 1)
18773       return true;
18774 
18775     InitExpr = BO->getLHS();
18776   }
18777 
18778   // This checks if the elements are from the same enum.
18779   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18780   if (!DRE)
18781     return true;
18782 
18783   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18784   if (!EnumConstant)
18785     return true;
18786 
18787   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18788       Enum)
18789     return true;
18790 
18791   return false;
18792 }
18793 
18794 // Emits a warning when an element is implicitly set a value that
18795 // a previous element has already been set to.
18796 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18797                                         EnumDecl *Enum, QualType EnumType) {
18798   // Avoid anonymous enums
18799   if (!Enum->getIdentifier())
18800     return;
18801 
18802   // Only check for small enums.
18803   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18804     return;
18805 
18806   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18807     return;
18808 
18809   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18810   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18811 
18812   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18813 
18814   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18815   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18816 
18817   // Use int64_t as a key to avoid needing special handling for map keys.
18818   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18819     llvm::APSInt Val = D->getInitVal();
18820     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18821   };
18822 
18823   DuplicatesVector DupVector;
18824   ValueToVectorMap EnumMap;
18825 
18826   // Populate the EnumMap with all values represented by enum constants without
18827   // an initializer.
18828   for (auto *Element : Elements) {
18829     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18830 
18831     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18832     // this constant.  Skip this enum since it may be ill-formed.
18833     if (!ECD) {
18834       return;
18835     }
18836 
18837     // Constants with initalizers are handled in the next loop.
18838     if (ECD->getInitExpr())
18839       continue;
18840 
18841     // Duplicate values are handled in the next loop.
18842     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18843   }
18844 
18845   if (EnumMap.size() == 0)
18846     return;
18847 
18848   // Create vectors for any values that has duplicates.
18849   for (auto *Element : Elements) {
18850     // The last loop returned if any constant was null.
18851     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18852     if (!ValidDuplicateEnum(ECD, Enum))
18853       continue;
18854 
18855     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18856     if (Iter == EnumMap.end())
18857       continue;
18858 
18859     DeclOrVector& Entry = Iter->second;
18860     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18861       // Ensure constants are different.
18862       if (D == ECD)
18863         continue;
18864 
18865       // Create new vector and push values onto it.
18866       auto Vec = std::make_unique<ECDVector>();
18867       Vec->push_back(D);
18868       Vec->push_back(ECD);
18869 
18870       // Update entry to point to the duplicates vector.
18871       Entry = Vec.get();
18872 
18873       // Store the vector somewhere we can consult later for quick emission of
18874       // diagnostics.
18875       DupVector.emplace_back(std::move(Vec));
18876       continue;
18877     }
18878 
18879     ECDVector *Vec = Entry.get<ECDVector*>();
18880     // Make sure constants are not added more than once.
18881     if (*Vec->begin() == ECD)
18882       continue;
18883 
18884     Vec->push_back(ECD);
18885   }
18886 
18887   // Emit diagnostics.
18888   for (const auto &Vec : DupVector) {
18889     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18890 
18891     // Emit warning for one enum constant.
18892     auto *FirstECD = Vec->front();
18893     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18894       << FirstECD << toString(FirstECD->getInitVal(), 10)
18895       << FirstECD->getSourceRange();
18896 
18897     // Emit one note for each of the remaining enum constants with
18898     // the same value.
18899     for (auto *ECD : llvm::drop_begin(*Vec))
18900       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18901         << ECD << toString(ECD->getInitVal(), 10)
18902         << ECD->getSourceRange();
18903   }
18904 }
18905 
18906 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18907                              bool AllowMask) const {
18908   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18909   assert(ED->isCompleteDefinition() && "expected enum definition");
18910 
18911   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18912   llvm::APInt &FlagBits = R.first->second;
18913 
18914   if (R.second) {
18915     for (auto *E : ED->enumerators()) {
18916       const auto &EVal = E->getInitVal();
18917       // Only single-bit enumerators introduce new flag values.
18918       if (EVal.isPowerOf2())
18919         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18920     }
18921   }
18922 
18923   // A value is in a flag enum if either its bits are a subset of the enum's
18924   // flag bits (the first condition) or we are allowing masks and the same is
18925   // true of its complement (the second condition). When masks are allowed, we
18926   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18927   //
18928   // While it's true that any value could be used as a mask, the assumption is
18929   // that a mask will have all of the insignificant bits set. Anything else is
18930   // likely a logic error.
18931   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18932   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18933 }
18934 
18935 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18936                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18937                          const ParsedAttributesView &Attrs) {
18938   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18939   QualType EnumType = Context.getTypeDeclType(Enum);
18940 
18941   ProcessDeclAttributeList(S, Enum, Attrs);
18942 
18943   if (Enum->isDependentType()) {
18944     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18945       EnumConstantDecl *ECD =
18946         cast_or_null<EnumConstantDecl>(Elements[i]);
18947       if (!ECD) continue;
18948 
18949       ECD->setType(EnumType);
18950     }
18951 
18952     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18953     return;
18954   }
18955 
18956   // TODO: If the result value doesn't fit in an int, it must be a long or long
18957   // long value.  ISO C does not support this, but GCC does as an extension,
18958   // emit a warning.
18959   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18960   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18961   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18962 
18963   // Verify that all the values are okay, compute the size of the values, and
18964   // reverse the list.
18965   unsigned NumNegativeBits = 0;
18966   unsigned NumPositiveBits = 0;
18967 
18968   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18969     EnumConstantDecl *ECD =
18970       cast_or_null<EnumConstantDecl>(Elements[i]);
18971     if (!ECD) continue;  // Already issued a diagnostic.
18972 
18973     const llvm::APSInt &InitVal = ECD->getInitVal();
18974 
18975     // Keep track of the size of positive and negative values.
18976     if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
18977       // If the enumerator is zero that should still be counted as a positive
18978       // bit since we need a bit to store the value zero.
18979       unsigned ActiveBits = InitVal.getActiveBits();
18980       NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
18981     } else {
18982       NumNegativeBits = std::max(NumNegativeBits,
18983                                  (unsigned)InitVal.getMinSignedBits());
18984     }
18985   }
18986 
18987   // If we have have an empty set of enumerators we still need one bit.
18988   // From [dcl.enum]p8
18989   // If the enumerator-list is empty, the values of the enumeration are as if
18990   // the enumeration had a single enumerator with value 0
18991   if (!NumPositiveBits && !NumNegativeBits)
18992     NumPositiveBits = 1;
18993 
18994   // Figure out the type that should be used for this enum.
18995   QualType BestType;
18996   unsigned BestWidth;
18997 
18998   // C++0x N3000 [conv.prom]p3:
18999   //   An rvalue of an unscoped enumeration type whose underlying
19000   //   type is not fixed can be converted to an rvalue of the first
19001   //   of the following types that can represent all the values of
19002   //   the enumeration: int, unsigned int, long int, unsigned long
19003   //   int, long long int, or unsigned long long int.
19004   // C99 6.4.4.3p2:
19005   //   An identifier declared as an enumeration constant has type int.
19006   // The C99 rule is modified by a gcc extension
19007   QualType BestPromotionType;
19008 
19009   bool Packed = Enum->hasAttr<PackedAttr>();
19010   // -fshort-enums is the equivalent to specifying the packed attribute on all
19011   // enum definitions.
19012   if (LangOpts.ShortEnums)
19013     Packed = true;
19014 
19015   // If the enum already has a type because it is fixed or dictated by the
19016   // target, promote that type instead of analyzing the enumerators.
19017   if (Enum->isComplete()) {
19018     BestType = Enum->getIntegerType();
19019     if (BestType->isPromotableIntegerType())
19020       BestPromotionType = Context.getPromotedIntegerType(BestType);
19021     else
19022       BestPromotionType = BestType;
19023 
19024     BestWidth = Context.getIntWidth(BestType);
19025   }
19026   else if (NumNegativeBits) {
19027     // If there is a negative value, figure out the smallest integer type (of
19028     // int/long/longlong) that fits.
19029     // If it's packed, check also if it fits a char or a short.
19030     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19031       BestType = Context.SignedCharTy;
19032       BestWidth = CharWidth;
19033     } else if (Packed && NumNegativeBits <= ShortWidth &&
19034                NumPositiveBits < ShortWidth) {
19035       BestType = Context.ShortTy;
19036       BestWidth = ShortWidth;
19037     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19038       BestType = Context.IntTy;
19039       BestWidth = IntWidth;
19040     } else {
19041       BestWidth = Context.getTargetInfo().getLongWidth();
19042 
19043       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19044         BestType = Context.LongTy;
19045       } else {
19046         BestWidth = Context.getTargetInfo().getLongLongWidth();
19047 
19048         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19049           Diag(Enum->getLocation(), diag::ext_enum_too_large);
19050         BestType = Context.LongLongTy;
19051       }
19052     }
19053     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19054   } else {
19055     // If there is no negative value, figure out the smallest type that fits
19056     // all of the enumerator values.
19057     // If it's packed, check also if it fits a char or a short.
19058     if (Packed && NumPositiveBits <= CharWidth) {
19059       BestType = Context.UnsignedCharTy;
19060       BestPromotionType = Context.IntTy;
19061       BestWidth = CharWidth;
19062     } else if (Packed && NumPositiveBits <= ShortWidth) {
19063       BestType = Context.UnsignedShortTy;
19064       BestPromotionType = Context.IntTy;
19065       BestWidth = ShortWidth;
19066     } else if (NumPositiveBits <= IntWidth) {
19067       BestType = Context.UnsignedIntTy;
19068       BestWidth = IntWidth;
19069       BestPromotionType
19070         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19071                            ? Context.UnsignedIntTy : Context.IntTy;
19072     } else if (NumPositiveBits <=
19073                (BestWidth = Context.getTargetInfo().getLongWidth())) {
19074       BestType = Context.UnsignedLongTy;
19075       BestPromotionType
19076         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19077                            ? Context.UnsignedLongTy : Context.LongTy;
19078     } else {
19079       BestWidth = Context.getTargetInfo().getLongLongWidth();
19080       assert(NumPositiveBits <= BestWidth &&
19081              "How could an initializer get larger than ULL?");
19082       BestType = Context.UnsignedLongLongTy;
19083       BestPromotionType
19084         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19085                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
19086     }
19087   }
19088 
19089   // Loop over all of the enumerator constants, changing their types to match
19090   // the type of the enum if needed.
19091   for (auto *D : Elements) {
19092     auto *ECD = cast_or_null<EnumConstantDecl>(D);
19093     if (!ECD) continue;  // Already issued a diagnostic.
19094 
19095     // Standard C says the enumerators have int type, but we allow, as an
19096     // extension, the enumerators to be larger than int size.  If each
19097     // enumerator value fits in an int, type it as an int, otherwise type it the
19098     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
19099     // that X has type 'int', not 'unsigned'.
19100 
19101     // Determine whether the value fits into an int.
19102     llvm::APSInt InitVal = ECD->getInitVal();
19103 
19104     // If it fits into an integer type, force it.  Otherwise force it to match
19105     // the enum decl type.
19106     QualType NewTy;
19107     unsigned NewWidth;
19108     bool NewSign;
19109     if (!getLangOpts().CPlusPlus &&
19110         !Enum->isFixed() &&
19111         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19112       NewTy = Context.IntTy;
19113       NewWidth = IntWidth;
19114       NewSign = true;
19115     } else if (ECD->getType() == BestType) {
19116       // Already the right type!
19117       if (getLangOpts().CPlusPlus)
19118         // C++ [dcl.enum]p4: Following the closing brace of an
19119         // enum-specifier, each enumerator has the type of its
19120         // enumeration.
19121         ECD->setType(EnumType);
19122       continue;
19123     } else {
19124       NewTy = BestType;
19125       NewWidth = BestWidth;
19126       NewSign = BestType->isSignedIntegerOrEnumerationType();
19127     }
19128 
19129     // Adjust the APSInt value.
19130     InitVal = InitVal.extOrTrunc(NewWidth);
19131     InitVal.setIsSigned(NewSign);
19132     ECD->setInitVal(InitVal);
19133 
19134     // Adjust the Expr initializer and type.
19135     if (ECD->getInitExpr() &&
19136         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19137       ECD->setInitExpr(ImplicitCastExpr::Create(
19138           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19139           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19140     if (getLangOpts().CPlusPlus)
19141       // C++ [dcl.enum]p4: Following the closing brace of an
19142       // enum-specifier, each enumerator has the type of its
19143       // enumeration.
19144       ECD->setType(EnumType);
19145     else
19146       ECD->setType(NewTy);
19147   }
19148 
19149   Enum->completeDefinition(BestType, BestPromotionType,
19150                            NumPositiveBits, NumNegativeBits);
19151 
19152   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19153 
19154   if (Enum->isClosedFlag()) {
19155     for (Decl *D : Elements) {
19156       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19157       if (!ECD) continue;  // Already issued a diagnostic.
19158 
19159       llvm::APSInt InitVal = ECD->getInitVal();
19160       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19161           !IsValueInFlagEnum(Enum, InitVal, true))
19162         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19163           << ECD << Enum;
19164     }
19165   }
19166 
19167   // Now that the enum type is defined, ensure it's not been underaligned.
19168   if (Enum->hasAttrs())
19169     CheckAlignasUnderalignment(Enum);
19170 }
19171 
19172 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19173                                   SourceLocation StartLoc,
19174                                   SourceLocation EndLoc) {
19175   StringLiteral *AsmString = cast<StringLiteral>(expr);
19176 
19177   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19178                                                    AsmString, StartLoc,
19179                                                    EndLoc);
19180   CurContext->addDecl(New);
19181   return New;
19182 }
19183 
19184 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19185                                       IdentifierInfo* AliasName,
19186                                       SourceLocation PragmaLoc,
19187                                       SourceLocation NameLoc,
19188                                       SourceLocation AliasNameLoc) {
19189   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19190                                          LookupOrdinaryName);
19191   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19192                            AttributeCommonInfo::AS_Pragma);
19193   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19194       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19195 
19196   // If a declaration that:
19197   // 1) declares a function or a variable
19198   // 2) has external linkage
19199   // already exists, add a label attribute to it.
19200   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19201     if (isDeclExternC(PrevDecl))
19202       PrevDecl->addAttr(Attr);
19203     else
19204       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19205           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19206   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19207   } else
19208     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19209 }
19210 
19211 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19212                              SourceLocation PragmaLoc,
19213                              SourceLocation NameLoc) {
19214   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19215 
19216   if (PrevDecl) {
19217     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19218   } else {
19219     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19220   }
19221 }
19222 
19223 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19224                                 IdentifierInfo* AliasName,
19225                                 SourceLocation PragmaLoc,
19226                                 SourceLocation NameLoc,
19227                                 SourceLocation AliasNameLoc) {
19228   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19229                                     LookupOrdinaryName);
19230   WeakInfo W = WeakInfo(Name, NameLoc);
19231 
19232   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19233     if (!PrevDecl->hasAttr<AliasAttr>())
19234       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19235         DeclApplyPragmaWeak(TUScope, ND, W);
19236   } else {
19237     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19238   }
19239 }
19240 
19241 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19242   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19243 }
19244 
19245 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19246                                                      bool Final) {
19247   assert(FD && "Expected non-null FunctionDecl");
19248 
19249   // SYCL functions can be template, so we check if they have appropriate
19250   // attribute prior to checking if it is a template.
19251   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19252     return FunctionEmissionStatus::Emitted;
19253 
19254   // Templates are emitted when they're instantiated.
19255   if (FD->isDependentContext())
19256     return FunctionEmissionStatus::TemplateDiscarded;
19257 
19258   // Check whether this function is an externally visible definition.
19259   auto IsEmittedForExternalSymbol = [this, FD]() {
19260     // We have to check the GVA linkage of the function's *definition* -- if we
19261     // only have a declaration, we don't know whether or not the function will
19262     // be emitted, because (say) the definition could include "inline".
19263     FunctionDecl *Def = FD->getDefinition();
19264 
19265     return Def && !isDiscardableGVALinkage(
19266                       getASTContext().GetGVALinkageForFunction(Def));
19267   };
19268 
19269   if (LangOpts.OpenMPIsDevice) {
19270     // In OpenMP device mode we will not emit host only functions, or functions
19271     // we don't need due to their linkage.
19272     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19273         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19274     // DevTy may be changed later by
19275     //  #pragma omp declare target to(*) device_type(*).
19276     // Therefore DevTy having no value does not imply host. The emission status
19277     // will be checked again at the end of compilation unit with Final = true.
19278     if (DevTy)
19279       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19280         return FunctionEmissionStatus::OMPDiscarded;
19281     // If we have an explicit value for the device type, or we are in a target
19282     // declare context, we need to emit all extern and used symbols.
19283     if (isInOpenMPDeclareTargetContext() || DevTy)
19284       if (IsEmittedForExternalSymbol())
19285         return FunctionEmissionStatus::Emitted;
19286     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19287     // we'll omit it.
19288     if (Final)
19289       return FunctionEmissionStatus::OMPDiscarded;
19290   } else if (LangOpts.OpenMP > 45) {
19291     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19292     // function. In 5.0, no_host was introduced which might cause a function to
19293     // be ommitted.
19294     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19295         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19296     if (DevTy)
19297       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19298         return FunctionEmissionStatus::OMPDiscarded;
19299   }
19300 
19301   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19302     return FunctionEmissionStatus::Emitted;
19303 
19304   if (LangOpts.CUDA) {
19305     // When compiling for device, host functions are never emitted.  Similarly,
19306     // when compiling for host, device and global functions are never emitted.
19307     // (Technically, we do emit a host-side stub for global functions, but this
19308     // doesn't count for our purposes here.)
19309     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19310     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19311       return FunctionEmissionStatus::CUDADiscarded;
19312     if (!LangOpts.CUDAIsDevice &&
19313         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19314       return FunctionEmissionStatus::CUDADiscarded;
19315 
19316     if (IsEmittedForExternalSymbol())
19317       return FunctionEmissionStatus::Emitted;
19318   }
19319 
19320   // Otherwise, the function is known-emitted if it's in our set of
19321   // known-emitted functions.
19322   return FunctionEmissionStatus::Unknown;
19323 }
19324 
19325 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19326   // Host-side references to a __global__ function refer to the stub, so the
19327   // function itself is never emitted and therefore should not be marked.
19328   // If we have host fn calls kernel fn calls host+device, the HD function
19329   // does not get instantiated on the host. We model this by omitting at the
19330   // call to the kernel from the callgraph. This ensures that, when compiling
19331   // for host, only HD functions actually called from the host get marked as
19332   // known-emitted.
19333   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19334          IdentifyCUDATarget(Callee) == CFT_Global;
19335 }
19336