xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
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 static bool isUsingDecl(NamedDecl *D) {
1715   return isa<UsingShadowDecl>(D) ||
1716          isa<UnresolvedUsingTypenameDecl>(D) ||
1717          isa<UnresolvedUsingValueDecl>(D);
1718 }
1719 
1720 /// Removes using shadow declarations from the lookup results.
1721 static void RemoveUsingDecls(LookupResult &R) {
1722   LookupResult::Filter F = R.makeFilter();
1723   while (F.hasNext())
1724     if (isUsingDecl(F.next()))
1725       F.erase();
1726 
1727   F.done();
1728 }
1729 
1730 /// Check for this common pattern:
1731 /// @code
1732 /// class S {
1733 ///   S(const S&); // DO NOT IMPLEMENT
1734 ///   void operator=(const S&); // DO NOT IMPLEMENT
1735 /// };
1736 /// @endcode
1737 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1738   // FIXME: Should check for private access too but access is set after we get
1739   // the decl here.
1740   if (D->doesThisDeclarationHaveABody())
1741     return false;
1742 
1743   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1744     return CD->isCopyConstructor();
1745   return D->isCopyAssignmentOperator();
1746 }
1747 
1748 // We need this to handle
1749 //
1750 // typedef struct {
1751 //   void *foo() { return 0; }
1752 // } A;
1753 //
1754 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1755 // for example. If 'A', foo will have external linkage. If we have '*A',
1756 // foo will have no linkage. Since we can't know until we get to the end
1757 // of the typedef, this function finds out if D might have non-external linkage.
1758 // Callers should verify at the end of the TU if it D has external linkage or
1759 // not.
1760 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1761   const DeclContext *DC = D->getDeclContext();
1762   while (!DC->isTranslationUnit()) {
1763     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1764       if (!RD->hasNameForLinkage())
1765         return true;
1766     }
1767     DC = DC->getParent();
1768   }
1769 
1770   return !D->isExternallyVisible();
1771 }
1772 
1773 // FIXME: This needs to be refactored; some other isInMainFile users want
1774 // these semantics.
1775 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1776   if (S.TUKind != TU_Complete)
1777     return false;
1778   return S.SourceMgr.isInMainFile(Loc);
1779 }
1780 
1781 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1782   assert(D);
1783 
1784   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1785     return false;
1786 
1787   // Ignore all entities declared within templates, and out-of-line definitions
1788   // of members of class templates.
1789   if (D->getDeclContext()->isDependentContext() ||
1790       D->getLexicalDeclContext()->isDependentContext())
1791     return false;
1792 
1793   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1794     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1795       return false;
1796     // A non-out-of-line declaration of a member specialization was implicitly
1797     // instantiated; it's the out-of-line declaration that we're interested in.
1798     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1799         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1800       return false;
1801 
1802     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1803       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1804         return false;
1805     } else {
1806       // 'static inline' functions are defined in headers; don't warn.
1807       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1808         return false;
1809     }
1810 
1811     if (FD->doesThisDeclarationHaveABody() &&
1812         Context.DeclMustBeEmitted(FD))
1813       return false;
1814   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1815     // Constants and utility variables are defined in headers with internal
1816     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1817     // like "inline".)
1818     if (!isMainFileLoc(*this, VD->getLocation()))
1819       return false;
1820 
1821     if (Context.DeclMustBeEmitted(VD))
1822       return false;
1823 
1824     if (VD->isStaticDataMember() &&
1825         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1826       return false;
1827     if (VD->isStaticDataMember() &&
1828         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1829         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1830       return false;
1831 
1832     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1833       return false;
1834   } else {
1835     return false;
1836   }
1837 
1838   // Only warn for unused decls internal to the translation unit.
1839   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1840   // for inline functions defined in the main source file, for instance.
1841   return mightHaveNonExternalLinkage(D);
1842 }
1843 
1844 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1845   if (!D)
1846     return;
1847 
1848   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1849     const FunctionDecl *First = FD->getFirstDecl();
1850     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1851       return; // First should already be in the vector.
1852   }
1853 
1854   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1855     const VarDecl *First = VD->getFirstDecl();
1856     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1857       return; // First should already be in the vector.
1858   }
1859 
1860   if (ShouldWarnIfUnusedFileScopedDecl(D))
1861     UnusedFileScopedDecls.push_back(D);
1862 }
1863 
1864 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1865   if (D->isInvalidDecl())
1866     return false;
1867 
1868   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1869     // For a decomposition declaration, warn if none of the bindings are
1870     // referenced, instead of if the variable itself is referenced (which
1871     // it is, by the bindings' expressions).
1872     for (auto *BD : DD->bindings())
1873       if (BD->isReferenced())
1874         return false;
1875   } else if (!D->getDeclName()) {
1876     return false;
1877   } else if (D->isReferenced() || D->isUsed()) {
1878     return false;
1879   }
1880 
1881   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1882     return false;
1883 
1884   if (isa<LabelDecl>(D))
1885     return true;
1886 
1887   // Except for labels, we only care about unused decls that are local to
1888   // functions.
1889   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1890   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1891     // For dependent types, the diagnostic is deferred.
1892     WithinFunction =
1893         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1894   if (!WithinFunction)
1895     return false;
1896 
1897   if (isa<TypedefNameDecl>(D))
1898     return true;
1899 
1900   // White-list anything that isn't a local variable.
1901   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1902     return false;
1903 
1904   // Types of valid local variables should be complete, so this should succeed.
1905   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 
1907     const Expr *Init = VD->getInit();
1908     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1909       Init = Cleanups->getSubExpr();
1910 
1911     const auto *Ty = VD->getType().getTypePtr();
1912 
1913     // Only look at the outermost level of typedef.
1914     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1915       // Allow anything marked with __attribute__((unused)).
1916       if (TT->getDecl()->hasAttr<UnusedAttr>())
1917         return false;
1918     }
1919 
1920     // Warn for reference variables whose initializtion performs lifetime
1921     // extension.
1922     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1923       if (MTE->getExtendingDecl()) {
1924         Ty = VD->getType().getNonReferenceType().getTypePtr();
1925         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1926       }
1927     }
1928 
1929     // If we failed to complete the type for some reason, or if the type is
1930     // dependent, don't diagnose the variable.
1931     if (Ty->isIncompleteType() || Ty->isDependentType())
1932       return false;
1933 
1934     // Look at the element type to ensure that the warning behaviour is
1935     // consistent for both scalars and arrays.
1936     Ty = Ty->getBaseElementTypeUnsafe();
1937 
1938     if (const TagType *TT = Ty->getAs<TagType>()) {
1939       const TagDecl *Tag = TT->getDecl();
1940       if (Tag->hasAttr<UnusedAttr>())
1941         return false;
1942 
1943       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1944         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1945           return false;
1946 
1947         if (Init) {
1948           const CXXConstructExpr *Construct =
1949             dyn_cast<CXXConstructExpr>(Init);
1950           if (Construct && !Construct->isElidable()) {
1951             CXXConstructorDecl *CD = Construct->getConstructor();
1952             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1953                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1954               return false;
1955           }
1956 
1957           // Suppress the warning if we don't know how this is constructed, and
1958           // it could possibly be non-trivial constructor.
1959           if (Init->isTypeDependent()) {
1960             for (const CXXConstructorDecl *Ctor : RD->ctors())
1961               if (!Ctor->isTrivial())
1962                 return false;
1963           }
1964 
1965           // Suppress the warning if the constructor is unresolved because
1966           // its arguments are dependent.
1967           if (isa<CXXUnresolvedConstructExpr>(Init))
1968             return false;
1969         }
1970       }
1971     }
1972 
1973     // TODO: __attribute__((unused)) templates?
1974   }
1975 
1976   return true;
1977 }
1978 
1979 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1980                                      FixItHint &Hint) {
1981   if (isa<LabelDecl>(D)) {
1982     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1983         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1984         true);
1985     if (AfterColon.isInvalid())
1986       return;
1987     Hint = FixItHint::CreateRemoval(
1988         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1989   }
1990 }
1991 
1992 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1993   if (D->getTypeForDecl()->isDependentType())
1994     return;
1995 
1996   for (auto *TmpD : D->decls()) {
1997     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1998       DiagnoseUnusedDecl(T);
1999     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2000       DiagnoseUnusedNestedTypedefs(R);
2001   }
2002 }
2003 
2004 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2005 /// unless they are marked attr(unused).
2006 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2007   if (!ShouldDiagnoseUnusedDecl(D))
2008     return;
2009 
2010   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2011     // typedefs can be referenced later on, so the diagnostics are emitted
2012     // at end-of-translation-unit.
2013     UnusedLocalTypedefNameCandidates.insert(TD);
2014     return;
2015   }
2016 
2017   FixItHint Hint;
2018   GenerateFixForUnusedDecl(D, Context, Hint);
2019 
2020   unsigned DiagID;
2021   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2022     DiagID = diag::warn_unused_exception_param;
2023   else if (isa<LabelDecl>(D))
2024     DiagID = diag::warn_unused_label;
2025   else
2026     DiagID = diag::warn_unused_variable;
2027 
2028   Diag(D->getLocation(), DiagID) << D << Hint;
2029 }
2030 
2031 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2032   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2033   // it's not really unused.
2034   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2035       VD->hasAttr<CleanupAttr>())
2036     return;
2037 
2038   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2039 
2040   if (Ty->isReferenceType() || Ty->isDependentType())
2041     return;
2042 
2043   if (const TagType *TT = Ty->getAs<TagType>()) {
2044     const TagDecl *Tag = TT->getDecl();
2045     if (Tag->hasAttr<UnusedAttr>())
2046       return;
2047     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2048     // mimic gcc's behavior.
2049     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2050       if (!RD->hasAttr<WarnUnusedAttr>())
2051         return;
2052     }
2053   }
2054 
2055   // Don't warn about __block Objective-C pointer variables, as they might
2056   // be assigned in the block but not used elsewhere for the purpose of lifetime
2057   // extension.
2058   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2059     return;
2060 
2061   // Don't warn about Objective-C pointer variables with precise lifetime
2062   // semantics; they can be used to ensure ARC releases the object at a known
2063   // time, which may mean assignment but no other references.
2064   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2065     return;
2066 
2067   auto iter = RefsMinusAssignments.find(VD);
2068   if (iter == RefsMinusAssignments.end())
2069     return;
2070 
2071   assert(iter->getSecond() >= 0 &&
2072          "Found a negative number of references to a VarDecl");
2073   if (iter->getSecond() != 0)
2074     return;
2075   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2076                                          : diag::warn_unused_but_set_variable;
2077   Diag(VD->getLocation(), DiagID) << VD;
2078 }
2079 
2080 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2081   // Verify that we have no forward references left.  If so, there was a goto
2082   // or address of a label taken, but no definition of it.  Label fwd
2083   // definitions are indicated with a null substmt which is also not a resolved
2084   // MS inline assembly label name.
2085   bool Diagnose = false;
2086   if (L->isMSAsmLabel())
2087     Diagnose = !L->isResolvedMSAsmLabel();
2088   else
2089     Diagnose = L->getStmt() == nullptr;
2090   if (Diagnose)
2091     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2092 }
2093 
2094 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2095   S->mergeNRVOIntoParent();
2096 
2097   if (S->decl_empty()) return;
2098   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2099          "Scope shouldn't contain decls!");
2100 
2101   for (auto *TmpD : S->decls()) {
2102     assert(TmpD && "This decl didn't get pushed??");
2103 
2104     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2105     NamedDecl *D = cast<NamedDecl>(TmpD);
2106 
2107     // Diagnose unused variables in this scope.
2108     if (!S->hasUnrecoverableErrorOccurred()) {
2109       DiagnoseUnusedDecl(D);
2110       if (const auto *RD = dyn_cast<RecordDecl>(D))
2111         DiagnoseUnusedNestedTypedefs(RD);
2112       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2113         DiagnoseUnusedButSetDecl(VD);
2114         RefsMinusAssignments.erase(VD);
2115       }
2116     }
2117 
2118     if (!D->getDeclName()) continue;
2119 
2120     // If this was a forward reference to a label, verify it was defined.
2121     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2122       CheckPoppedLabel(LD, *this);
2123 
2124     // Remove this name from our lexical scope, and warn on it if we haven't
2125     // already.
2126     IdResolver.RemoveDecl(D);
2127     auto ShadowI = ShadowingDecls.find(D);
2128     if (ShadowI != ShadowingDecls.end()) {
2129       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2130         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2131             << D << FD << FD->getParent();
2132         Diag(FD->getLocation(), diag::note_previous_declaration);
2133       }
2134       ShadowingDecls.erase(ShadowI);
2135     }
2136   }
2137 }
2138 
2139 /// Look for an Objective-C class in the translation unit.
2140 ///
2141 /// \param Id The name of the Objective-C class we're looking for. If
2142 /// typo-correction fixes this name, the Id will be updated
2143 /// to the fixed name.
2144 ///
2145 /// \param IdLoc The location of the name in the translation unit.
2146 ///
2147 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2148 /// if there is no class with the given name.
2149 ///
2150 /// \returns The declaration of the named Objective-C class, or NULL if the
2151 /// class could not be found.
2152 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2153                                               SourceLocation IdLoc,
2154                                               bool DoTypoCorrection) {
2155   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2156   // creation from this context.
2157   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2158 
2159   if (!IDecl && DoTypoCorrection) {
2160     // Perform typo correction at the given location, but only if we
2161     // find an Objective-C class name.
2162     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2163     if (TypoCorrection C =
2164             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2165                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2166       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2167       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2168       Id = IDecl->getIdentifier();
2169     }
2170   }
2171   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2172   // This routine must always return a class definition, if any.
2173   if (Def && Def->getDefinition())
2174       Def = Def->getDefinition();
2175   return Def;
2176 }
2177 
2178 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2179 /// from S, where a non-field would be declared. This routine copes
2180 /// with the difference between C and C++ scoping rules in structs and
2181 /// unions. For example, the following code is well-formed in C but
2182 /// ill-formed in C++:
2183 /// @code
2184 /// struct S6 {
2185 ///   enum { BAR } e;
2186 /// };
2187 ///
2188 /// void test_S6() {
2189 ///   struct S6 a;
2190 ///   a.e = BAR;
2191 /// }
2192 /// @endcode
2193 /// For the declaration of BAR, this routine will return a different
2194 /// scope. The scope S will be the scope of the unnamed enumeration
2195 /// within S6. In C++, this routine will return the scope associated
2196 /// with S6, because the enumeration's scope is a transparent
2197 /// context but structures can contain non-field names. In C, this
2198 /// routine will return the translation unit scope, since the
2199 /// enumeration's scope is a transparent context and structures cannot
2200 /// contain non-field names.
2201 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2202   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2203          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2204          (S->isClassScope() && !getLangOpts().CPlusPlus))
2205     S = S->getParent();
2206   return S;
2207 }
2208 
2209 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2210                                ASTContext::GetBuiltinTypeError Error) {
2211   switch (Error) {
2212   case ASTContext::GE_None:
2213     return "";
2214   case ASTContext::GE_Missing_type:
2215     return BuiltinInfo.getHeaderName(ID);
2216   case ASTContext::GE_Missing_stdio:
2217     return "stdio.h";
2218   case ASTContext::GE_Missing_setjmp:
2219     return "setjmp.h";
2220   case ASTContext::GE_Missing_ucontext:
2221     return "ucontext.h";
2222   }
2223   llvm_unreachable("unhandled error kind");
2224 }
2225 
2226 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2227                                   unsigned ID, SourceLocation Loc) {
2228   DeclContext *Parent = Context.getTranslationUnitDecl();
2229 
2230   if (getLangOpts().CPlusPlus) {
2231     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2232         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2233     CLinkageDecl->setImplicit();
2234     Parent->addDecl(CLinkageDecl);
2235     Parent = CLinkageDecl;
2236   }
2237 
2238   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2239                                            /*TInfo=*/nullptr, SC_Extern,
2240                                            getCurFPFeatures().isFPConstrained(),
2241                                            false, Type->isFunctionProtoType());
2242   New->setImplicit();
2243   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2244 
2245   // Create Decl objects for each parameter, adding them to the
2246   // FunctionDecl.
2247   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2248     SmallVector<ParmVarDecl *, 16> Params;
2249     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2250       ParmVarDecl *parm = ParmVarDecl::Create(
2251           Context, New, SourceLocation(), SourceLocation(), nullptr,
2252           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2253       parm->setScopeInfo(0, i);
2254       Params.push_back(parm);
2255     }
2256     New->setParams(Params);
2257   }
2258 
2259   AddKnownFunctionAttributes(New);
2260   return New;
2261 }
2262 
2263 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2264 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2265 /// if we're creating this built-in in anticipation of redeclaring the
2266 /// built-in.
2267 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2268                                      Scope *S, bool ForRedeclaration,
2269                                      SourceLocation Loc) {
2270   LookupNecessaryTypesForBuiltin(S, ID);
2271 
2272   ASTContext::GetBuiltinTypeError Error;
2273   QualType R = Context.GetBuiltinType(ID, Error);
2274   if (Error) {
2275     if (!ForRedeclaration)
2276       return nullptr;
2277 
2278     // If we have a builtin without an associated type we should not emit a
2279     // warning when we were not able to find a type for it.
2280     if (Error == ASTContext::GE_Missing_type ||
2281         Context.BuiltinInfo.allowTypeMismatch(ID))
2282       return nullptr;
2283 
2284     // If we could not find a type for setjmp it is because the jmp_buf type was
2285     // not defined prior to the setjmp declaration.
2286     if (Error == ASTContext::GE_Missing_setjmp) {
2287       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2288           << Context.BuiltinInfo.getName(ID);
2289       return nullptr;
2290     }
2291 
2292     // Generally, we emit a warning that the declaration requires the
2293     // appropriate header.
2294     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2295         << getHeaderName(Context.BuiltinInfo, ID, Error)
2296         << Context.BuiltinInfo.getName(ID);
2297     return nullptr;
2298   }
2299 
2300   if (!ForRedeclaration &&
2301       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2302        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2303     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2304                            : diag::ext_implicit_lib_function_decl)
2305         << Context.BuiltinInfo.getName(ID) << R;
2306     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2307       Diag(Loc, diag::note_include_header_or_declare)
2308           << Header << Context.BuiltinInfo.getName(ID);
2309   }
2310 
2311   if (R.isNull())
2312     return nullptr;
2313 
2314   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2315   RegisterLocallyScopedExternCDecl(New, S);
2316 
2317   // TUScope is the translation-unit scope to insert this function into.
2318   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2319   // relate Scopes to DeclContexts, and probably eliminate CurContext
2320   // entirely, but we're not there yet.
2321   DeclContext *SavedContext = CurContext;
2322   CurContext = New->getDeclContext();
2323   PushOnScopeChains(New, TUScope);
2324   CurContext = SavedContext;
2325   return New;
2326 }
2327 
2328 /// Typedef declarations don't have linkage, but they still denote the same
2329 /// entity if their types are the same.
2330 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2331 /// isSameEntity.
2332 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2333                                                      TypedefNameDecl *Decl,
2334                                                      LookupResult &Previous) {
2335   // This is only interesting when modules are enabled.
2336   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2337     return;
2338 
2339   // Empty sets are uninteresting.
2340   if (Previous.empty())
2341     return;
2342 
2343   LookupResult::Filter Filter = Previous.makeFilter();
2344   while (Filter.hasNext()) {
2345     NamedDecl *Old = Filter.next();
2346 
2347     // Non-hidden declarations are never ignored.
2348     if (S.isVisible(Old))
2349       continue;
2350 
2351     // Declarations of the same entity are not ignored, even if they have
2352     // different linkages.
2353     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2354       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2355                                 Decl->getUnderlyingType()))
2356         continue;
2357 
2358       // If both declarations give a tag declaration a typedef name for linkage
2359       // purposes, then they declare the same entity.
2360       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2361           Decl->getAnonDeclWithTypedefName())
2362         continue;
2363     }
2364 
2365     Filter.erase();
2366   }
2367 
2368   Filter.done();
2369 }
2370 
2371 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2372   QualType OldType;
2373   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2374     OldType = OldTypedef->getUnderlyingType();
2375   else
2376     OldType = Context.getTypeDeclType(Old);
2377   QualType NewType = New->getUnderlyingType();
2378 
2379   if (NewType->isVariablyModifiedType()) {
2380     // Must not redefine a typedef with a variably-modified type.
2381     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2382     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2383       << Kind << NewType;
2384     if (Old->getLocation().isValid())
2385       notePreviousDefinition(Old, New->getLocation());
2386     New->setInvalidDecl();
2387     return true;
2388   }
2389 
2390   if (OldType != NewType &&
2391       !OldType->isDependentType() &&
2392       !NewType->isDependentType() &&
2393       !Context.hasSameType(OldType, NewType)) {
2394     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2395     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2396       << Kind << NewType << OldType;
2397     if (Old->getLocation().isValid())
2398       notePreviousDefinition(Old, New->getLocation());
2399     New->setInvalidDecl();
2400     return true;
2401   }
2402   return false;
2403 }
2404 
2405 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2406 /// same name and scope as a previous declaration 'Old'.  Figure out
2407 /// how to resolve this situation, merging decls or emitting
2408 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2409 ///
2410 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2411                                 LookupResult &OldDecls) {
2412   // If the new decl is known invalid already, don't bother doing any
2413   // merging checks.
2414   if (New->isInvalidDecl()) return;
2415 
2416   // Allow multiple definitions for ObjC built-in typedefs.
2417   // FIXME: Verify the underlying types are equivalent!
2418   if (getLangOpts().ObjC) {
2419     const IdentifierInfo *TypeID = New->getIdentifier();
2420     switch (TypeID->getLength()) {
2421     default: break;
2422     case 2:
2423       {
2424         if (!TypeID->isStr("id"))
2425           break;
2426         QualType T = New->getUnderlyingType();
2427         if (!T->isPointerType())
2428           break;
2429         if (!T->isVoidPointerType()) {
2430           QualType PT = T->castAs<PointerType>()->getPointeeType();
2431           if (!PT->isStructureType())
2432             break;
2433         }
2434         Context.setObjCIdRedefinitionType(T);
2435         // Install the built-in type for 'id', ignoring the current definition.
2436         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2437         return;
2438       }
2439     case 5:
2440       if (!TypeID->isStr("Class"))
2441         break;
2442       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2443       // Install the built-in type for 'Class', ignoring the current definition.
2444       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2445       return;
2446     case 3:
2447       if (!TypeID->isStr("SEL"))
2448         break;
2449       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2450       // Install the built-in type for 'SEL', ignoring the current definition.
2451       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2452       return;
2453     }
2454     // Fall through - the typedef name was not a builtin type.
2455   }
2456 
2457   // Verify the old decl was also a type.
2458   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2459   if (!Old) {
2460     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2461       << New->getDeclName();
2462 
2463     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2464     if (OldD->getLocation().isValid())
2465       notePreviousDefinition(OldD, New->getLocation());
2466 
2467     return New->setInvalidDecl();
2468   }
2469 
2470   // If the old declaration is invalid, just give up here.
2471   if (Old->isInvalidDecl())
2472     return New->setInvalidDecl();
2473 
2474   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2475     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2476     auto *NewTag = New->getAnonDeclWithTypedefName();
2477     NamedDecl *Hidden = nullptr;
2478     if (OldTag && NewTag &&
2479         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2480         !hasVisibleDefinition(OldTag, &Hidden)) {
2481       // There is a definition of this tag, but it is not visible. Use it
2482       // instead of our tag.
2483       New->setTypeForDecl(OldTD->getTypeForDecl());
2484       if (OldTD->isModed())
2485         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2486                                     OldTD->getUnderlyingType());
2487       else
2488         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2489 
2490       // Make the old tag definition visible.
2491       makeMergedDefinitionVisible(Hidden);
2492 
2493       // If this was an unscoped enumeration, yank all of its enumerators
2494       // out of the scope.
2495       if (isa<EnumDecl>(NewTag)) {
2496         Scope *EnumScope = getNonFieldDeclScope(S);
2497         for (auto *D : NewTag->decls()) {
2498           auto *ED = cast<EnumConstantDecl>(D);
2499           assert(EnumScope->isDeclScope(ED));
2500           EnumScope->RemoveDecl(ED);
2501           IdResolver.RemoveDecl(ED);
2502           ED->getLexicalDeclContext()->removeDecl(ED);
2503         }
2504       }
2505     }
2506   }
2507 
2508   // If the typedef types are not identical, reject them in all languages and
2509   // with any extensions enabled.
2510   if (isIncompatibleTypedef(Old, New))
2511     return;
2512 
2513   // The types match.  Link up the redeclaration chain and merge attributes if
2514   // the old declaration was a typedef.
2515   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2516     New->setPreviousDecl(Typedef);
2517     mergeDeclAttributes(New, Old);
2518   }
2519 
2520   if (getLangOpts().MicrosoftExt)
2521     return;
2522 
2523   if (getLangOpts().CPlusPlus) {
2524     // C++ [dcl.typedef]p2:
2525     //   In a given non-class scope, a typedef specifier can be used to
2526     //   redefine the name of any type declared in that scope to refer
2527     //   to the type to which it already refers.
2528     if (!isa<CXXRecordDecl>(CurContext))
2529       return;
2530 
2531     // C++0x [dcl.typedef]p4:
2532     //   In a given class scope, a typedef specifier can be used to redefine
2533     //   any class-name declared in that scope that is not also a typedef-name
2534     //   to refer to the type to which it already refers.
2535     //
2536     // This wording came in via DR424, which was a correction to the
2537     // wording in DR56, which accidentally banned code like:
2538     //
2539     //   struct S {
2540     //     typedef struct A { } A;
2541     //   };
2542     //
2543     // in the C++03 standard. We implement the C++0x semantics, which
2544     // allow the above but disallow
2545     //
2546     //   struct S {
2547     //     typedef int I;
2548     //     typedef int I;
2549     //   };
2550     //
2551     // since that was the intent of DR56.
2552     if (!isa<TypedefNameDecl>(Old))
2553       return;
2554 
2555     Diag(New->getLocation(), diag::err_redefinition)
2556       << New->getDeclName();
2557     notePreviousDefinition(Old, New->getLocation());
2558     return New->setInvalidDecl();
2559   }
2560 
2561   // Modules always permit redefinition of typedefs, as does C11.
2562   if (getLangOpts().Modules || getLangOpts().C11)
2563     return;
2564 
2565   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2566   // is normally mapped to an error, but can be controlled with
2567   // -Wtypedef-redefinition.  If either the original or the redefinition is
2568   // in a system header, don't emit this for compatibility with GCC.
2569   if (getDiagnostics().getSuppressSystemWarnings() &&
2570       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2571       (Old->isImplicit() ||
2572        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2573        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2574     return;
2575 
2576   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2577     << New->getDeclName();
2578   notePreviousDefinition(Old, New->getLocation());
2579 }
2580 
2581 /// DeclhasAttr - returns true if decl Declaration already has the target
2582 /// attribute.
2583 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2584   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2585   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2586   for (const auto *i : D->attrs())
2587     if (i->getKind() == A->getKind()) {
2588       if (Ann) {
2589         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2590           return true;
2591         continue;
2592       }
2593       // FIXME: Don't hardcode this check
2594       if (OA && isa<OwnershipAttr>(i))
2595         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2596       return true;
2597     }
2598 
2599   return false;
2600 }
2601 
2602 static bool isAttributeTargetADefinition(Decl *D) {
2603   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2604     return VD->isThisDeclarationADefinition();
2605   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2606     return TD->isCompleteDefinition() || TD->isBeingDefined();
2607   return true;
2608 }
2609 
2610 /// Merge alignment attributes from \p Old to \p New, taking into account the
2611 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2612 ///
2613 /// \return \c true if any attributes were added to \p New.
2614 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2615   // Look for alignas attributes on Old, and pick out whichever attribute
2616   // specifies the strictest alignment requirement.
2617   AlignedAttr *OldAlignasAttr = nullptr;
2618   AlignedAttr *OldStrictestAlignAttr = nullptr;
2619   unsigned OldAlign = 0;
2620   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2621     // FIXME: We have no way of representing inherited dependent alignments
2622     // in a case like:
2623     //   template<int A, int B> struct alignas(A) X;
2624     //   template<int A, int B> struct alignas(B) X {};
2625     // For now, we just ignore any alignas attributes which are not on the
2626     // definition in such a case.
2627     if (I->isAlignmentDependent())
2628       return false;
2629 
2630     if (I->isAlignas())
2631       OldAlignasAttr = I;
2632 
2633     unsigned Align = I->getAlignment(S.Context);
2634     if (Align > OldAlign) {
2635       OldAlign = Align;
2636       OldStrictestAlignAttr = I;
2637     }
2638   }
2639 
2640   // Look for alignas attributes on New.
2641   AlignedAttr *NewAlignasAttr = nullptr;
2642   unsigned NewAlign = 0;
2643   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2644     if (I->isAlignmentDependent())
2645       return false;
2646 
2647     if (I->isAlignas())
2648       NewAlignasAttr = I;
2649 
2650     unsigned Align = I->getAlignment(S.Context);
2651     if (Align > NewAlign)
2652       NewAlign = Align;
2653   }
2654 
2655   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2656     // Both declarations have 'alignas' attributes. We require them to match.
2657     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2658     // fall short. (If two declarations both have alignas, they must both match
2659     // every definition, and so must match each other if there is a definition.)
2660 
2661     // If either declaration only contains 'alignas(0)' specifiers, then it
2662     // specifies the natural alignment for the type.
2663     if (OldAlign == 0 || NewAlign == 0) {
2664       QualType Ty;
2665       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2666         Ty = VD->getType();
2667       else
2668         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2669 
2670       if (OldAlign == 0)
2671         OldAlign = S.Context.getTypeAlign(Ty);
2672       if (NewAlign == 0)
2673         NewAlign = S.Context.getTypeAlign(Ty);
2674     }
2675 
2676     if (OldAlign != NewAlign) {
2677       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2678         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2679         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2680       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2681     }
2682   }
2683 
2684   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2685     // C++11 [dcl.align]p6:
2686     //   if any declaration of an entity has an alignment-specifier,
2687     //   every defining declaration of that entity shall specify an
2688     //   equivalent alignment.
2689     // C11 6.7.5/7:
2690     //   If the definition of an object does not have an alignment
2691     //   specifier, any other declaration of that object shall also
2692     //   have no alignment specifier.
2693     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2694       << OldAlignasAttr;
2695     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2696       << OldAlignasAttr;
2697   }
2698 
2699   bool AnyAdded = false;
2700 
2701   // Ensure we have an attribute representing the strictest alignment.
2702   if (OldAlign > NewAlign) {
2703     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2704     Clone->setInherited(true);
2705     New->addAttr(Clone);
2706     AnyAdded = true;
2707   }
2708 
2709   // Ensure we have an alignas attribute if the old declaration had one.
2710   if (OldAlignasAttr && !NewAlignasAttr &&
2711       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2712     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2713     Clone->setInherited(true);
2714     New->addAttr(Clone);
2715     AnyAdded = true;
2716   }
2717 
2718   return AnyAdded;
2719 }
2720 
2721 #define WANT_DECL_MERGE_LOGIC
2722 #include "clang/Sema/AttrParsedAttrImpl.inc"
2723 #undef WANT_DECL_MERGE_LOGIC
2724 
2725 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2726                                const InheritableAttr *Attr,
2727                                Sema::AvailabilityMergeKind AMK) {
2728   // Diagnose any mutual exclusions between the attribute that we want to add
2729   // and attributes that already exist on the declaration.
2730   if (!DiagnoseMutualExclusions(S, D, Attr))
2731     return false;
2732 
2733   // This function copies an attribute Attr from a previous declaration to the
2734   // new declaration D if the new declaration doesn't itself have that attribute
2735   // yet or if that attribute allows duplicates.
2736   // If you're adding a new attribute that requires logic different from
2737   // "use explicit attribute on decl if present, else use attribute from
2738   // previous decl", for example if the attribute needs to be consistent
2739   // between redeclarations, you need to call a custom merge function here.
2740   InheritableAttr *NewAttr = nullptr;
2741   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2742     NewAttr = S.mergeAvailabilityAttr(
2743         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2744         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2745         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2746         AA->getPriority());
2747   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2748     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2749   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2750     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2752     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2753   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2754     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2755   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2756     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2757   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2758     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2759                                 FA->getFirstArg());
2760   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2761     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2762   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2763     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2764   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2765     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2766                                        IA->getInheritanceModel());
2767   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2768     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2769                                       &S.Context.Idents.get(AA->getSpelling()));
2770   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2771            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2772             isa<CUDAGlobalAttr>(Attr))) {
2773     // CUDA target attributes are part of function signature for
2774     // overloading purposes and must not be merged.
2775     return false;
2776   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2777     NewAttr = S.mergeMinSizeAttr(D, *MA);
2778   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2779     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2780   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2781     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2782   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2783     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2784   else if (isa<AlignedAttr>(Attr))
2785     // AlignedAttrs are handled separately, because we need to handle all
2786     // such attributes on a declaration at the same time.
2787     NewAttr = nullptr;
2788   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2789            (AMK == Sema::AMK_Override ||
2790             AMK == Sema::AMK_ProtocolImplementation ||
2791             AMK == Sema::AMK_OptionalProtocolImplementation))
2792     NewAttr = nullptr;
2793   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2794     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2795   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2796     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2797   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2798     NewAttr = S.mergeImportNameAttr(D, *INA);
2799   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2800     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2801   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2803   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2804     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2805   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2806     NewAttr =
2807         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2808   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2809     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2810   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2811     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2812 
2813   if (NewAttr) {
2814     NewAttr->setInherited(true);
2815     D->addAttr(NewAttr);
2816     if (isa<MSInheritanceAttr>(NewAttr))
2817       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2818     return true;
2819   }
2820 
2821   return false;
2822 }
2823 
2824 static const NamedDecl *getDefinition(const Decl *D) {
2825   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2826     return TD->getDefinition();
2827   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2828     const VarDecl *Def = VD->getDefinition();
2829     if (Def)
2830       return Def;
2831     return VD->getActingDefinition();
2832   }
2833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2834     const FunctionDecl *Def = nullptr;
2835     if (FD->isDefined(Def, true))
2836       return Def;
2837   }
2838   return nullptr;
2839 }
2840 
2841 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2842   for (const auto *Attribute : D->attrs())
2843     if (Attribute->getKind() == Kind)
2844       return true;
2845   return false;
2846 }
2847 
2848 /// checkNewAttributesAfterDef - If we already have a definition, check that
2849 /// there are no new attributes in this declaration.
2850 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2851   if (!New->hasAttrs())
2852     return;
2853 
2854   const NamedDecl *Def = getDefinition(Old);
2855   if (!Def || Def == New)
2856     return;
2857 
2858   AttrVec &NewAttributes = New->getAttrs();
2859   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2860     const Attr *NewAttribute = NewAttributes[I];
2861 
2862     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2863       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2864         Sema::SkipBodyInfo SkipBody;
2865         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2866 
2867         // If we're skipping this definition, drop the "alias" attribute.
2868         if (SkipBody.ShouldSkip) {
2869           NewAttributes.erase(NewAttributes.begin() + I);
2870           --E;
2871           continue;
2872         }
2873       } else {
2874         VarDecl *VD = cast<VarDecl>(New);
2875         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2876                                 VarDecl::TentativeDefinition
2877                             ? diag::err_alias_after_tentative
2878                             : diag::err_redefinition;
2879         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2880         if (Diag == diag::err_redefinition)
2881           S.notePreviousDefinition(Def, VD->getLocation());
2882         else
2883           S.Diag(Def->getLocation(), diag::note_previous_definition);
2884         VD->setInvalidDecl();
2885       }
2886       ++I;
2887       continue;
2888     }
2889 
2890     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2891       // Tentative definitions are only interesting for the alias check above.
2892       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2893         ++I;
2894         continue;
2895       }
2896     }
2897 
2898     if (hasAttribute(Def, NewAttribute->getKind())) {
2899       ++I;
2900       continue; // regular attr merging will take care of validating this.
2901     }
2902 
2903     if (isa<C11NoReturnAttr>(NewAttribute)) {
2904       // C's _Noreturn is allowed to be added to a function after it is defined.
2905       ++I;
2906       continue;
2907     } else if (isa<UuidAttr>(NewAttribute)) {
2908       // msvc will allow a subsequent definition to add an uuid to a class
2909       ++I;
2910       continue;
2911     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2912       if (AA->isAlignas()) {
2913         // C++11 [dcl.align]p6:
2914         //   if any declaration of an entity has an alignment-specifier,
2915         //   every defining declaration of that entity shall specify an
2916         //   equivalent alignment.
2917         // C11 6.7.5/7:
2918         //   If the definition of an object does not have an alignment
2919         //   specifier, any other declaration of that object shall also
2920         //   have no alignment specifier.
2921         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2922           << AA;
2923         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2924           << AA;
2925         NewAttributes.erase(NewAttributes.begin() + I);
2926         --E;
2927         continue;
2928       }
2929     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2930       // If there is a C definition followed by a redeclaration with this
2931       // attribute then there are two different definitions. In C++, prefer the
2932       // standard diagnostics.
2933       if (!S.getLangOpts().CPlusPlus) {
2934         S.Diag(NewAttribute->getLocation(),
2935                diag::err_loader_uninitialized_redeclaration);
2936         S.Diag(Def->getLocation(), diag::note_previous_definition);
2937         NewAttributes.erase(NewAttributes.begin() + I);
2938         --E;
2939         continue;
2940       }
2941     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2942                cast<VarDecl>(New)->isInline() &&
2943                !cast<VarDecl>(New)->isInlineSpecified()) {
2944       // Don't warn about applying selectany to implicitly inline variables.
2945       // Older compilers and language modes would require the use of selectany
2946       // to make such variables inline, and it would have no effect if we
2947       // honored it.
2948       ++I;
2949       continue;
2950     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2951       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2952       // declarations after defintions.
2953       ++I;
2954       continue;
2955     }
2956 
2957     S.Diag(NewAttribute->getLocation(),
2958            diag::warn_attribute_precede_definition);
2959     S.Diag(Def->getLocation(), diag::note_previous_definition);
2960     NewAttributes.erase(NewAttributes.begin() + I);
2961     --E;
2962   }
2963 }
2964 
2965 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2966                                      const ConstInitAttr *CIAttr,
2967                                      bool AttrBeforeInit) {
2968   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2969 
2970   // Figure out a good way to write this specifier on the old declaration.
2971   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2972   // enough of the attribute list spelling information to extract that without
2973   // heroics.
2974   std::string SuitableSpelling;
2975   if (S.getLangOpts().CPlusPlus20)
2976     SuitableSpelling = std::string(
2977         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2978   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2979     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2980         InsertLoc, {tok::l_square, tok::l_square,
2981                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2982                     S.PP.getIdentifierInfo("require_constant_initialization"),
2983                     tok::r_square, tok::r_square}));
2984   if (SuitableSpelling.empty())
2985     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2986         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2987                     S.PP.getIdentifierInfo("require_constant_initialization"),
2988                     tok::r_paren, tok::r_paren}));
2989   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2990     SuitableSpelling = "constinit";
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2992     SuitableSpelling = "[[clang::require_constant_initialization]]";
2993   if (SuitableSpelling.empty())
2994     SuitableSpelling = "__attribute__((require_constant_initialization))";
2995   SuitableSpelling += " ";
2996 
2997   if (AttrBeforeInit) {
2998     // extern constinit int a;
2999     // int a = 0; // error (missing 'constinit'), accepted as extension
3000     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3001     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3002         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3003     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3004   } else {
3005     // int a = 0;
3006     // constinit extern int a; // error (missing 'constinit')
3007     S.Diag(CIAttr->getLocation(),
3008            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3009                                  : diag::warn_require_const_init_added_too_late)
3010         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3011     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3012         << CIAttr->isConstinit()
3013         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3014   }
3015 }
3016 
3017 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3018 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3019                                AvailabilityMergeKind AMK) {
3020   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3021     UsedAttr *NewAttr = OldAttr->clone(Context);
3022     NewAttr->setInherited(true);
3023     New->addAttr(NewAttr);
3024   }
3025   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3026     RetainAttr *NewAttr = OldAttr->clone(Context);
3027     NewAttr->setInherited(true);
3028     New->addAttr(NewAttr);
3029   }
3030 
3031   if (!Old->hasAttrs() && !New->hasAttrs())
3032     return;
3033 
3034   // [dcl.constinit]p1:
3035   //   If the [constinit] specifier is applied to any declaration of a
3036   //   variable, it shall be applied to the initializing declaration.
3037   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3038   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3039   if (bool(OldConstInit) != bool(NewConstInit)) {
3040     const auto *OldVD = cast<VarDecl>(Old);
3041     auto *NewVD = cast<VarDecl>(New);
3042 
3043     // Find the initializing declaration. Note that we might not have linked
3044     // the new declaration into the redeclaration chain yet.
3045     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3046     if (!InitDecl &&
3047         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3048       InitDecl = NewVD;
3049 
3050     if (InitDecl == NewVD) {
3051       // This is the initializing declaration. If it would inherit 'constinit',
3052       // that's ill-formed. (Note that we do not apply this to the attribute
3053       // form).
3054       if (OldConstInit && OldConstInit->isConstinit())
3055         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3056                                  /*AttrBeforeInit=*/true);
3057     } else if (NewConstInit) {
3058       // This is the first time we've been told that this declaration should
3059       // have a constant initializer. If we already saw the initializing
3060       // declaration, this is too late.
3061       if (InitDecl && InitDecl != NewVD) {
3062         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3063                                  /*AttrBeforeInit=*/false);
3064         NewVD->dropAttr<ConstInitAttr>();
3065       }
3066     }
3067   }
3068 
3069   // Attributes declared post-definition are currently ignored.
3070   checkNewAttributesAfterDef(*this, New, Old);
3071 
3072   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3073     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3074       if (!OldA->isEquivalent(NewA)) {
3075         // This redeclaration changes __asm__ label.
3076         Diag(New->getLocation(), diag::err_different_asm_label);
3077         Diag(OldA->getLocation(), diag::note_previous_declaration);
3078       }
3079     } else if (Old->isUsed()) {
3080       // This redeclaration adds an __asm__ label to a declaration that has
3081       // already been ODR-used.
3082       Diag(New->getLocation(), diag::err_late_asm_label_name)
3083         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3084     }
3085   }
3086 
3087   // Re-declaration cannot add abi_tag's.
3088   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3089     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3090       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3091         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3092           Diag(NewAbiTagAttr->getLocation(),
3093                diag::err_new_abi_tag_on_redeclaration)
3094               << NewTag;
3095           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3096         }
3097       }
3098     } else {
3099       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3100       Diag(Old->getLocation(), diag::note_previous_declaration);
3101     }
3102   }
3103 
3104   // This redeclaration adds a section attribute.
3105   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3106     if (auto *VD = dyn_cast<VarDecl>(New)) {
3107       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3108         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3109         Diag(Old->getLocation(), diag::note_previous_declaration);
3110       }
3111     }
3112   }
3113 
3114   // Redeclaration adds code-seg attribute.
3115   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3116   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3117       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3118     Diag(New->getLocation(), diag::warn_mismatched_section)
3119          << 0 /*codeseg*/;
3120     Diag(Old->getLocation(), diag::note_previous_declaration);
3121   }
3122 
3123   if (!Old->hasAttrs())
3124     return;
3125 
3126   bool foundAny = New->hasAttrs();
3127 
3128   // Ensure that any moving of objects within the allocated map is done before
3129   // we process them.
3130   if (!foundAny) New->setAttrs(AttrVec());
3131 
3132   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3133     // Ignore deprecated/unavailable/availability attributes if requested.
3134     AvailabilityMergeKind LocalAMK = AMK_None;
3135     if (isa<DeprecatedAttr>(I) ||
3136         isa<UnavailableAttr>(I) ||
3137         isa<AvailabilityAttr>(I)) {
3138       switch (AMK) {
3139       case AMK_None:
3140         continue;
3141 
3142       case AMK_Redeclaration:
3143       case AMK_Override:
3144       case AMK_ProtocolImplementation:
3145       case AMK_OptionalProtocolImplementation:
3146         LocalAMK = AMK;
3147         break;
3148       }
3149     }
3150 
3151     // Already handled.
3152     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3153       continue;
3154 
3155     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3156       foundAny = true;
3157   }
3158 
3159   if (mergeAlignedAttrs(*this, New, Old))
3160     foundAny = true;
3161 
3162   if (!foundAny) New->dropAttrs();
3163 }
3164 
3165 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3166 /// to the new one.
3167 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3168                                      const ParmVarDecl *oldDecl,
3169                                      Sema &S) {
3170   // C++11 [dcl.attr.depend]p2:
3171   //   The first declaration of a function shall specify the
3172   //   carries_dependency attribute for its declarator-id if any declaration
3173   //   of the function specifies the carries_dependency attribute.
3174   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3175   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3176     S.Diag(CDA->getLocation(),
3177            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3178     // Find the first declaration of the parameter.
3179     // FIXME: Should we build redeclaration chains for function parameters?
3180     const FunctionDecl *FirstFD =
3181       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3182     const ParmVarDecl *FirstVD =
3183       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3184     S.Diag(FirstVD->getLocation(),
3185            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3186   }
3187 
3188   if (!oldDecl->hasAttrs())
3189     return;
3190 
3191   bool foundAny = newDecl->hasAttrs();
3192 
3193   // Ensure that any moving of objects within the allocated map is
3194   // done before we process them.
3195   if (!foundAny) newDecl->setAttrs(AttrVec());
3196 
3197   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3198     if (!DeclHasAttr(newDecl, I)) {
3199       InheritableAttr *newAttr =
3200         cast<InheritableParamAttr>(I->clone(S.Context));
3201       newAttr->setInherited(true);
3202       newDecl->addAttr(newAttr);
3203       foundAny = true;
3204     }
3205   }
3206 
3207   if (!foundAny) newDecl->dropAttrs();
3208 }
3209 
3210 static bool EquivalentArrayTypes(QualType Old, QualType New,
3211                                  const ASTContext &Ctx) {
3212 
3213   auto NoSizeInfo = [&Ctx](QualType Ty) {
3214     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3215       return true;
3216     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3217       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3218     return false;
3219   };
3220 
3221   // `type[]` is equivalent to `type *` and `type[*]`.
3222   if (NoSizeInfo(Old) && NoSizeInfo(New))
3223     return true;
3224 
3225   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3226   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3227     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3228     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3229     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3230         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3231       return false;
3232     return true;
3233   }
3234 
3235   // Only compare size, ignore Size modifiers and CVR.
3236   if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3237     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3238            Ctx.getAsConstantArrayType(New)->getSize();
3239   }
3240 
3241   // Don't try to compare dependent sized array
3242   if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3243     return true;
3244   }
3245 
3246   return Old == New;
3247 }
3248 
3249 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3250                                 const ParmVarDecl *OldParam,
3251                                 Sema &S) {
3252   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3253     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3254       if (*Oldnullability != *Newnullability) {
3255         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3256           << DiagNullabilityKind(
3257                *Newnullability,
3258                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3259                 != 0))
3260           << DiagNullabilityKind(
3261                *Oldnullability,
3262                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3263                 != 0));
3264         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3265       }
3266     } else {
3267       QualType NewT = NewParam->getType();
3268       NewT = S.Context.getAttributedType(
3269                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3270                          NewT, NewT);
3271       NewParam->setType(NewT);
3272     }
3273   }
3274   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3275   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3276   if (OldParamDT && NewParamDT &&
3277       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3278     QualType OldParamOT = OldParamDT->getOriginalType();
3279     QualType NewParamOT = NewParamDT->getOriginalType();
3280     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3281       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3282           << NewParam << NewParamOT;
3283       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3284           << OldParamOT;
3285     }
3286   }
3287 }
3288 
3289 namespace {
3290 
3291 /// Used in MergeFunctionDecl to keep track of function parameters in
3292 /// C.
3293 struct GNUCompatibleParamWarning {
3294   ParmVarDecl *OldParm;
3295   ParmVarDecl *NewParm;
3296   QualType PromotedType;
3297 };
3298 
3299 } // end anonymous namespace
3300 
3301 // Determine whether the previous declaration was a definition, implicit
3302 // declaration, or a declaration.
3303 template <typename T>
3304 static std::pair<diag::kind, SourceLocation>
3305 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3306   diag::kind PrevDiag;
3307   SourceLocation OldLocation = Old->getLocation();
3308   if (Old->isThisDeclarationADefinition())
3309     PrevDiag = diag::note_previous_definition;
3310   else if (Old->isImplicit()) {
3311     PrevDiag = diag::note_previous_implicit_declaration;
3312     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3313       if (FD->getBuiltinID())
3314         PrevDiag = diag::note_previous_builtin_declaration;
3315     }
3316     if (OldLocation.isInvalid())
3317       OldLocation = New->getLocation();
3318   } else
3319     PrevDiag = diag::note_previous_declaration;
3320   return std::make_pair(PrevDiag, OldLocation);
3321 }
3322 
3323 /// canRedefineFunction - checks if a function can be redefined. Currently,
3324 /// only extern inline functions can be redefined, and even then only in
3325 /// GNU89 mode.
3326 static bool canRedefineFunction(const FunctionDecl *FD,
3327                                 const LangOptions& LangOpts) {
3328   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3329           !LangOpts.CPlusPlus &&
3330           FD->isInlineSpecified() &&
3331           FD->getStorageClass() == SC_Extern);
3332 }
3333 
3334 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3335   const AttributedType *AT = T->getAs<AttributedType>();
3336   while (AT && !AT->isCallingConv())
3337     AT = AT->getModifiedType()->getAs<AttributedType>();
3338   return AT;
3339 }
3340 
3341 template <typename T>
3342 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3343   const DeclContext *DC = Old->getDeclContext();
3344   if (DC->isRecord())
3345     return false;
3346 
3347   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3348   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3349     return true;
3350   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3351     return true;
3352   return false;
3353 }
3354 
3355 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3356 static bool isExternC(VarTemplateDecl *) { return false; }
3357 static bool isExternC(FunctionTemplateDecl *) { return false; }
3358 
3359 /// Check whether a redeclaration of an entity introduced by a
3360 /// using-declaration is valid, given that we know it's not an overload
3361 /// (nor a hidden tag declaration).
3362 template<typename ExpectedDecl>
3363 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3364                                    ExpectedDecl *New) {
3365   // C++11 [basic.scope.declarative]p4:
3366   //   Given a set of declarations in a single declarative region, each of
3367   //   which specifies the same unqualified name,
3368   //   -- they shall all refer to the same entity, or all refer to functions
3369   //      and function templates; or
3370   //   -- exactly one declaration shall declare a class name or enumeration
3371   //      name that is not a typedef name and the other declarations shall all
3372   //      refer to the same variable or enumerator, or all refer to functions
3373   //      and function templates; in this case the class name or enumeration
3374   //      name is hidden (3.3.10).
3375 
3376   // C++11 [namespace.udecl]p14:
3377   //   If a function declaration in namespace scope or block scope has the
3378   //   same name and the same parameter-type-list as a function introduced
3379   //   by a using-declaration, and the declarations do not declare the same
3380   //   function, the program is ill-formed.
3381 
3382   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3383   if (Old &&
3384       !Old->getDeclContext()->getRedeclContext()->Equals(
3385           New->getDeclContext()->getRedeclContext()) &&
3386       !(isExternC(Old) && isExternC(New)))
3387     Old = nullptr;
3388 
3389   if (!Old) {
3390     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3391     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3392     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3393     return true;
3394   }
3395   return false;
3396 }
3397 
3398 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3399                                             const FunctionDecl *B) {
3400   assert(A->getNumParams() == B->getNumParams());
3401 
3402   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3403     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3404     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3405     if (AttrA == AttrB)
3406       return true;
3407     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3408            AttrA->isDynamic() == AttrB->isDynamic();
3409   };
3410 
3411   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3412 }
3413 
3414 /// If necessary, adjust the semantic declaration context for a qualified
3415 /// declaration to name the correct inline namespace within the qualifier.
3416 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3417                                                DeclaratorDecl *OldD) {
3418   // The only case where we need to update the DeclContext is when
3419   // redeclaration lookup for a qualified name finds a declaration
3420   // in an inline namespace within the context named by the qualifier:
3421   //
3422   //   inline namespace N { int f(); }
3423   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3424   //
3425   // For unqualified declarations, the semantic context *can* change
3426   // along the redeclaration chain (for local extern declarations,
3427   // extern "C" declarations, and friend declarations in particular).
3428   if (!NewD->getQualifier())
3429     return;
3430 
3431   // NewD is probably already in the right context.
3432   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3433   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3434   if (NamedDC->Equals(SemaDC))
3435     return;
3436 
3437   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3438           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3439          "unexpected context for redeclaration");
3440 
3441   auto *LexDC = NewD->getLexicalDeclContext();
3442   auto FixSemaDC = [=](NamedDecl *D) {
3443     if (!D)
3444       return;
3445     D->setDeclContext(SemaDC);
3446     D->setLexicalDeclContext(LexDC);
3447   };
3448 
3449   FixSemaDC(NewD);
3450   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3451     FixSemaDC(FD->getDescribedFunctionTemplate());
3452   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3453     FixSemaDC(VD->getDescribedVarTemplate());
3454 }
3455 
3456 /// MergeFunctionDecl - We just parsed a function 'New' from
3457 /// declarator D which has the same name and scope as a previous
3458 /// declaration 'Old'.  Figure out how to resolve this situation,
3459 /// merging decls or emitting diagnostics as appropriate.
3460 ///
3461 /// In C++, New and Old must be declarations that are not
3462 /// overloaded. Use IsOverload to determine whether New and Old are
3463 /// overloaded, and to select the Old declaration that New should be
3464 /// merged with.
3465 ///
3466 /// Returns true if there was an error, false otherwise.
3467 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3468                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3469   // Verify the old decl was also a function.
3470   FunctionDecl *Old = OldD->getAsFunction();
3471   if (!Old) {
3472     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3473       if (New->getFriendObjectKind()) {
3474         Diag(New->getLocation(), diag::err_using_decl_friend);
3475         Diag(Shadow->getTargetDecl()->getLocation(),
3476              diag::note_using_decl_target);
3477         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3478             << 0;
3479         return true;
3480       }
3481 
3482       // Check whether the two declarations might declare the same function or
3483       // function template.
3484       if (FunctionTemplateDecl *NewTemplate =
3485               New->getDescribedFunctionTemplate()) {
3486         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3487                                                          NewTemplate))
3488           return true;
3489         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3490                          ->getAsFunction();
3491       } else {
3492         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3493           return true;
3494         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3495       }
3496     } else {
3497       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3498         << New->getDeclName();
3499       notePreviousDefinition(OldD, New->getLocation());
3500       return true;
3501     }
3502   }
3503 
3504   // If the old declaration was found in an inline namespace and the new
3505   // declaration was qualified, update the DeclContext to match.
3506   adjustDeclContextForDeclaratorDecl(New, Old);
3507 
3508   // If the old declaration is invalid, just give up here.
3509   if (Old->isInvalidDecl())
3510     return true;
3511 
3512   // Disallow redeclaration of some builtins.
3513   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3514     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3515     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3516         << Old << Old->getType();
3517     return true;
3518   }
3519 
3520   diag::kind PrevDiag;
3521   SourceLocation OldLocation;
3522   std::tie(PrevDiag, OldLocation) =
3523       getNoteDiagForInvalidRedeclaration(Old, New);
3524 
3525   // Don't complain about this if we're in GNU89 mode and the old function
3526   // is an extern inline function.
3527   // Don't complain about specializations. They are not supposed to have
3528   // storage classes.
3529   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3530       New->getStorageClass() == SC_Static &&
3531       Old->hasExternalFormalLinkage() &&
3532       !New->getTemplateSpecializationInfo() &&
3533       !canRedefineFunction(Old, getLangOpts())) {
3534     if (getLangOpts().MicrosoftExt) {
3535       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3536       Diag(OldLocation, PrevDiag);
3537     } else {
3538       Diag(New->getLocation(), diag::err_static_non_static) << New;
3539       Diag(OldLocation, PrevDiag);
3540       return true;
3541     }
3542   }
3543 
3544   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3545     if (!Old->hasAttr<InternalLinkageAttr>()) {
3546       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3547           << ILA;
3548       Diag(Old->getLocation(), diag::note_previous_declaration);
3549       New->dropAttr<InternalLinkageAttr>();
3550     }
3551 
3552   if (auto *EA = New->getAttr<ErrorAttr>()) {
3553     if (!Old->hasAttr<ErrorAttr>()) {
3554       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3555       Diag(Old->getLocation(), diag::note_previous_declaration);
3556       New->dropAttr<ErrorAttr>();
3557     }
3558   }
3559 
3560   if (CheckRedeclarationInModule(New, Old))
3561     return true;
3562 
3563   if (!getLangOpts().CPlusPlus) {
3564     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3565     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3566       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3567         << New << OldOvl;
3568 
3569       // Try our best to find a decl that actually has the overloadable
3570       // attribute for the note. In most cases (e.g. programs with only one
3571       // broken declaration/definition), this won't matter.
3572       //
3573       // FIXME: We could do this if we juggled some extra state in
3574       // OverloadableAttr, rather than just removing it.
3575       const Decl *DiagOld = Old;
3576       if (OldOvl) {
3577         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3578           const auto *A = D->getAttr<OverloadableAttr>();
3579           return A && !A->isImplicit();
3580         });
3581         // If we've implicitly added *all* of the overloadable attrs to this
3582         // chain, emitting a "previous redecl" note is pointless.
3583         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3584       }
3585 
3586       if (DiagOld)
3587         Diag(DiagOld->getLocation(),
3588              diag::note_attribute_overloadable_prev_overload)
3589           << OldOvl;
3590 
3591       if (OldOvl)
3592         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3593       else
3594         New->dropAttr<OverloadableAttr>();
3595     }
3596   }
3597 
3598   // If a function is first declared with a calling convention, but is later
3599   // declared or defined without one, all following decls assume the calling
3600   // convention of the first.
3601   //
3602   // It's OK if a function is first declared without a calling convention,
3603   // but is later declared or defined with the default calling convention.
3604   //
3605   // To test if either decl has an explicit calling convention, we look for
3606   // AttributedType sugar nodes on the type as written.  If they are missing or
3607   // were canonicalized away, we assume the calling convention was implicit.
3608   //
3609   // Note also that we DO NOT return at this point, because we still have
3610   // other tests to run.
3611   QualType OldQType = Context.getCanonicalType(Old->getType());
3612   QualType NewQType = Context.getCanonicalType(New->getType());
3613   const FunctionType *OldType = cast<FunctionType>(OldQType);
3614   const FunctionType *NewType = cast<FunctionType>(NewQType);
3615   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3616   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3617   bool RequiresAdjustment = false;
3618 
3619   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3620     FunctionDecl *First = Old->getFirstDecl();
3621     const FunctionType *FT =
3622         First->getType().getCanonicalType()->castAs<FunctionType>();
3623     FunctionType::ExtInfo FI = FT->getExtInfo();
3624     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3625     if (!NewCCExplicit) {
3626       // Inherit the CC from the previous declaration if it was specified
3627       // there but not here.
3628       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3629       RequiresAdjustment = true;
3630     } else if (Old->getBuiltinID()) {
3631       // Builtin attribute isn't propagated to the new one yet at this point,
3632       // so we check if the old one is a builtin.
3633 
3634       // Calling Conventions on a Builtin aren't really useful and setting a
3635       // default calling convention and cdecl'ing some builtin redeclarations is
3636       // common, so warn and ignore the calling convention on the redeclaration.
3637       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3638           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3639           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3640       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3641       RequiresAdjustment = true;
3642     } else {
3643       // Calling conventions aren't compatible, so complain.
3644       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3645       Diag(New->getLocation(), diag::err_cconv_change)
3646         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3647         << !FirstCCExplicit
3648         << (!FirstCCExplicit ? "" :
3649             FunctionType::getNameForCallConv(FI.getCC()));
3650 
3651       // Put the note on the first decl, since it is the one that matters.
3652       Diag(First->getLocation(), diag::note_previous_declaration);
3653       return true;
3654     }
3655   }
3656 
3657   // FIXME: diagnose the other way around?
3658   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3659     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3660     RequiresAdjustment = true;
3661   }
3662 
3663   // Merge regparm attribute.
3664   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3665       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3666     if (NewTypeInfo.getHasRegParm()) {
3667       Diag(New->getLocation(), diag::err_regparm_mismatch)
3668         << NewType->getRegParmType()
3669         << OldType->getRegParmType();
3670       Diag(OldLocation, diag::note_previous_declaration);
3671       return true;
3672     }
3673 
3674     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3675     RequiresAdjustment = true;
3676   }
3677 
3678   // Merge ns_returns_retained attribute.
3679   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3680     if (NewTypeInfo.getProducesResult()) {
3681       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3682           << "'ns_returns_retained'";
3683       Diag(OldLocation, diag::note_previous_declaration);
3684       return true;
3685     }
3686 
3687     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3688     RequiresAdjustment = true;
3689   }
3690 
3691   if (OldTypeInfo.getNoCallerSavedRegs() !=
3692       NewTypeInfo.getNoCallerSavedRegs()) {
3693     if (NewTypeInfo.getNoCallerSavedRegs()) {
3694       AnyX86NoCallerSavedRegistersAttr *Attr =
3695         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3696       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3697       Diag(OldLocation, diag::note_previous_declaration);
3698       return true;
3699     }
3700 
3701     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3702     RequiresAdjustment = true;
3703   }
3704 
3705   if (RequiresAdjustment) {
3706     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3707     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3708     New->setType(QualType(AdjustedType, 0));
3709     NewQType = Context.getCanonicalType(New->getType());
3710   }
3711 
3712   // If this redeclaration makes the function inline, we may need to add it to
3713   // UndefinedButUsed.
3714   if (!Old->isInlined() && New->isInlined() &&
3715       !New->hasAttr<GNUInlineAttr>() &&
3716       !getLangOpts().GNUInline &&
3717       Old->isUsed(false) &&
3718       !Old->isDefined() && !New->isThisDeclarationADefinition())
3719     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3720                                            SourceLocation()));
3721 
3722   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3723   // about it.
3724   if (New->hasAttr<GNUInlineAttr>() &&
3725       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3726     UndefinedButUsed.erase(Old->getCanonicalDecl());
3727   }
3728 
3729   // If pass_object_size params don't match up perfectly, this isn't a valid
3730   // redeclaration.
3731   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3732       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3733     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3734         << New->getDeclName();
3735     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3736     return true;
3737   }
3738 
3739   if (getLangOpts().CPlusPlus) {
3740     // C++1z [over.load]p2
3741     //   Certain function declarations cannot be overloaded:
3742     //     -- Function declarations that differ only in the return type,
3743     //        the exception specification, or both cannot be overloaded.
3744 
3745     // Check the exception specifications match. This may recompute the type of
3746     // both Old and New if it resolved exception specifications, so grab the
3747     // types again after this. Because this updates the type, we do this before
3748     // any of the other checks below, which may update the "de facto" NewQType
3749     // but do not necessarily update the type of New.
3750     if (CheckEquivalentExceptionSpec(Old, New))
3751       return true;
3752     OldQType = Context.getCanonicalType(Old->getType());
3753     NewQType = Context.getCanonicalType(New->getType());
3754 
3755     // Go back to the type source info to compare the declared return types,
3756     // per C++1y [dcl.type.auto]p13:
3757     //   Redeclarations or specializations of a function or function template
3758     //   with a declared return type that uses a placeholder type shall also
3759     //   use that placeholder, not a deduced type.
3760     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3761     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3762     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3763         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3764                                        OldDeclaredReturnType)) {
3765       QualType ResQT;
3766       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3767           OldDeclaredReturnType->isObjCObjectPointerType())
3768         // FIXME: This does the wrong thing for a deduced return type.
3769         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3770       if (ResQT.isNull()) {
3771         if (New->isCXXClassMember() && New->isOutOfLine())
3772           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3773               << New << New->getReturnTypeSourceRange();
3774         else
3775           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3776               << New->getReturnTypeSourceRange();
3777         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3778                                     << Old->getReturnTypeSourceRange();
3779         return true;
3780       }
3781       else
3782         NewQType = ResQT;
3783     }
3784 
3785     QualType OldReturnType = OldType->getReturnType();
3786     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3787     if (OldReturnType != NewReturnType) {
3788       // If this function has a deduced return type and has already been
3789       // defined, copy the deduced value from the old declaration.
3790       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3791       if (OldAT && OldAT->isDeduced()) {
3792         QualType DT = OldAT->getDeducedType();
3793         if (DT.isNull()) {
3794           New->setType(SubstAutoTypeDependent(New->getType()));
3795           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3796         } else {
3797           New->setType(SubstAutoType(New->getType(), DT));
3798           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3799         }
3800       }
3801     }
3802 
3803     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3804     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3805     if (OldMethod && NewMethod) {
3806       // Preserve triviality.
3807       NewMethod->setTrivial(OldMethod->isTrivial());
3808 
3809       // MSVC allows explicit template specialization at class scope:
3810       // 2 CXXMethodDecls referring to the same function will be injected.
3811       // We don't want a redeclaration error.
3812       bool IsClassScopeExplicitSpecialization =
3813                               OldMethod->isFunctionTemplateSpecialization() &&
3814                               NewMethod->isFunctionTemplateSpecialization();
3815       bool isFriend = NewMethod->getFriendObjectKind();
3816 
3817       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3818           !IsClassScopeExplicitSpecialization) {
3819         //    -- Member function declarations with the same name and the
3820         //       same parameter types cannot be overloaded if any of them
3821         //       is a static member function declaration.
3822         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3823           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3824           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3825           return true;
3826         }
3827 
3828         // C++ [class.mem]p1:
3829         //   [...] A member shall not be declared twice in the
3830         //   member-specification, except that a nested class or member
3831         //   class template can be declared and then later defined.
3832         if (!inTemplateInstantiation()) {
3833           unsigned NewDiag;
3834           if (isa<CXXConstructorDecl>(OldMethod))
3835             NewDiag = diag::err_constructor_redeclared;
3836           else if (isa<CXXDestructorDecl>(NewMethod))
3837             NewDiag = diag::err_destructor_redeclared;
3838           else if (isa<CXXConversionDecl>(NewMethod))
3839             NewDiag = diag::err_conv_function_redeclared;
3840           else
3841             NewDiag = diag::err_member_redeclared;
3842 
3843           Diag(New->getLocation(), NewDiag);
3844         } else {
3845           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3846             << New << New->getType();
3847         }
3848         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3849         return true;
3850 
3851       // Complain if this is an explicit declaration of a special
3852       // member that was initially declared implicitly.
3853       //
3854       // As an exception, it's okay to befriend such methods in order
3855       // to permit the implicit constructor/destructor/operator calls.
3856       } else if (OldMethod->isImplicit()) {
3857         if (isFriend) {
3858           NewMethod->setImplicit();
3859         } else {
3860           Diag(NewMethod->getLocation(),
3861                diag::err_definition_of_implicitly_declared_member)
3862             << New << getSpecialMember(OldMethod);
3863           return true;
3864         }
3865       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3866         Diag(NewMethod->getLocation(),
3867              diag::err_definition_of_explicitly_defaulted_member)
3868           << getSpecialMember(OldMethod);
3869         return true;
3870       }
3871     }
3872 
3873     // C++11 [dcl.attr.noreturn]p1:
3874     //   The first declaration of a function shall specify the noreturn
3875     //   attribute if any declaration of that function specifies the noreturn
3876     //   attribute.
3877     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3878       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3879         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3880             << NRA;
3881         Diag(Old->getLocation(), diag::note_previous_declaration);
3882       }
3883 
3884     // C++11 [dcl.attr.depend]p2:
3885     //   The first declaration of a function shall specify the
3886     //   carries_dependency attribute for its declarator-id if any declaration
3887     //   of the function specifies the carries_dependency attribute.
3888     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3889     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3890       Diag(CDA->getLocation(),
3891            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3892       Diag(Old->getFirstDecl()->getLocation(),
3893            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3894     }
3895 
3896     // (C++98 8.3.5p3):
3897     //   All declarations for a function shall agree exactly in both the
3898     //   return type and the parameter-type-list.
3899     // We also want to respect all the extended bits except noreturn.
3900 
3901     // noreturn should now match unless the old type info didn't have it.
3902     QualType OldQTypeForComparison = OldQType;
3903     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3904       auto *OldType = OldQType->castAs<FunctionProtoType>();
3905       const FunctionType *OldTypeForComparison
3906         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3907       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3908       assert(OldQTypeForComparison.isCanonical());
3909     }
3910 
3911     if (haveIncompatibleLanguageLinkages(Old, New)) {
3912       // As a special case, retain the language linkage from previous
3913       // declarations of a friend function as an extension.
3914       //
3915       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3916       // and is useful because there's otherwise no way to specify language
3917       // linkage within class scope.
3918       //
3919       // Check cautiously as the friend object kind isn't yet complete.
3920       if (New->getFriendObjectKind() != Decl::FOK_None) {
3921         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3922         Diag(OldLocation, PrevDiag);
3923       } else {
3924         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3925         Diag(OldLocation, PrevDiag);
3926         return true;
3927       }
3928     }
3929 
3930     // If the function types are compatible, merge the declarations. Ignore the
3931     // exception specifier because it was already checked above in
3932     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3933     // about incompatible types under -fms-compatibility.
3934     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3935                                                          NewQType))
3936       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3937 
3938     // If the types are imprecise (due to dependent constructs in friends or
3939     // local extern declarations), it's OK if they differ. We'll check again
3940     // during instantiation.
3941     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3942       return false;
3943 
3944     // Fall through for conflicting redeclarations and redefinitions.
3945   }
3946 
3947   // C: Function types need to be compatible, not identical. This handles
3948   // duplicate function decls like "void f(int); void f(enum X);" properly.
3949   if (!getLangOpts().CPlusPlus) {
3950     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3951     // type is specified by a function definition that contains a (possibly
3952     // empty) identifier list, both shall agree in the number of parameters
3953     // and the type of each parameter shall be compatible with the type that
3954     // results from the application of default argument promotions to the
3955     // type of the corresponding identifier. ...
3956     // This cannot be handled by ASTContext::typesAreCompatible() because that
3957     // doesn't know whether the function type is for a definition or not when
3958     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3959     // we need to cover here is that the number of arguments agree as the
3960     // default argument promotion rules were already checked by
3961     // ASTContext::typesAreCompatible().
3962     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3963         Old->getNumParams() != New->getNumParams()) {
3964       if (Old->hasInheritedPrototype())
3965         Old = Old->getCanonicalDecl();
3966       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3967       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3968       return true;
3969     }
3970 
3971     // If we are merging two functions where only one of them has a prototype,
3972     // we may have enough information to decide to issue a diagnostic that the
3973     // function without a protoype will change behavior in C2x. This handles
3974     // cases like:
3975     //   void i(); void i(int j);
3976     //   void i(int j); void i();
3977     //   void i(); void i(int j) {}
3978     // See ActOnFinishFunctionBody() for other cases of the behavior change
3979     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3980     // type without a prototype.
3981     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3982         !New->isImplicit() && !Old->isImplicit()) {
3983       const FunctionDecl *WithProto, *WithoutProto;
3984       if (New->hasWrittenPrototype()) {
3985         WithProto = New;
3986         WithoutProto = Old;
3987       } else {
3988         WithProto = Old;
3989         WithoutProto = New;
3990       }
3991 
3992       if (WithProto->getNumParams() != 0) {
3993         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3994           // The one without the prototype will be changing behavior in C2x, so
3995           // warn about that one so long as it's a user-visible declaration.
3996           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3997           if (WithoutProto == New)
3998             IsWithoutProtoADef = NewDeclIsDefn;
3999           else
4000             IsWithProtoADef = NewDeclIsDefn;
4001           Diag(WithoutProto->getLocation(),
4002                diag::warn_non_prototype_changes_behavior)
4003               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4004               << (WithoutProto == Old) << IsWithProtoADef;
4005 
4006           // The reason the one without the prototype will be changing behavior
4007           // is because of the one with the prototype, so note that so long as
4008           // it's a user-visible declaration. There is one exception to this:
4009           // when the new declaration is a definition without a prototype, the
4010           // old declaration with a prototype is not the cause of the issue,
4011           // and that does not need to be noted because the one with a
4012           // prototype will not change behavior in C2x.
4013           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4014               !IsWithoutProtoADef)
4015             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4016         }
4017       }
4018     }
4019 
4020     if (Context.typesAreCompatible(OldQType, NewQType)) {
4021       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4022       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4023       const FunctionProtoType *OldProto = nullptr;
4024       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4025           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4026         // The old declaration provided a function prototype, but the
4027         // new declaration does not. Merge in the prototype.
4028         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4029         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4030         NewQType =
4031             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4032                                     OldProto->getExtProtoInfo());
4033         New->setType(NewQType);
4034         New->setHasInheritedPrototype();
4035 
4036         // Synthesize parameters with the same types.
4037         SmallVector<ParmVarDecl *, 16> Params;
4038         for (const auto &ParamType : OldProto->param_types()) {
4039           ParmVarDecl *Param = ParmVarDecl::Create(
4040               Context, New, SourceLocation(), SourceLocation(), nullptr,
4041               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4042           Param->setScopeInfo(0, Params.size());
4043           Param->setImplicit();
4044           Params.push_back(Param);
4045         }
4046 
4047         New->setParams(Params);
4048       }
4049 
4050       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4051     }
4052   }
4053 
4054   // Check if the function types are compatible when pointer size address
4055   // spaces are ignored.
4056   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4057     return false;
4058 
4059   // GNU C permits a K&R definition to follow a prototype declaration
4060   // if the declared types of the parameters in the K&R definition
4061   // match the types in the prototype declaration, even when the
4062   // promoted types of the parameters from the K&R definition differ
4063   // from the types in the prototype. GCC then keeps the types from
4064   // the prototype.
4065   //
4066   // If a variadic prototype is followed by a non-variadic K&R definition,
4067   // the K&R definition becomes variadic.  This is sort of an edge case, but
4068   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4069   // C99 6.9.1p8.
4070   if (!getLangOpts().CPlusPlus &&
4071       Old->hasPrototype() && !New->hasPrototype() &&
4072       New->getType()->getAs<FunctionProtoType>() &&
4073       Old->getNumParams() == New->getNumParams()) {
4074     SmallVector<QualType, 16> ArgTypes;
4075     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4076     const FunctionProtoType *OldProto
4077       = Old->getType()->getAs<FunctionProtoType>();
4078     const FunctionProtoType *NewProto
4079       = New->getType()->getAs<FunctionProtoType>();
4080 
4081     // Determine whether this is the GNU C extension.
4082     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4083                                                NewProto->getReturnType());
4084     bool LooseCompatible = !MergedReturn.isNull();
4085     for (unsigned Idx = 0, End = Old->getNumParams();
4086          LooseCompatible && Idx != End; ++Idx) {
4087       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4088       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4089       if (Context.typesAreCompatible(OldParm->getType(),
4090                                      NewProto->getParamType(Idx))) {
4091         ArgTypes.push_back(NewParm->getType());
4092       } else if (Context.typesAreCompatible(OldParm->getType(),
4093                                             NewParm->getType(),
4094                                             /*CompareUnqualified=*/true)) {
4095         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4096                                            NewProto->getParamType(Idx) };
4097         Warnings.push_back(Warn);
4098         ArgTypes.push_back(NewParm->getType());
4099       } else
4100         LooseCompatible = false;
4101     }
4102 
4103     if (LooseCompatible) {
4104       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4105         Diag(Warnings[Warn].NewParm->getLocation(),
4106              diag::ext_param_promoted_not_compatible_with_prototype)
4107           << Warnings[Warn].PromotedType
4108           << Warnings[Warn].OldParm->getType();
4109         if (Warnings[Warn].OldParm->getLocation().isValid())
4110           Diag(Warnings[Warn].OldParm->getLocation(),
4111                diag::note_previous_declaration);
4112       }
4113 
4114       if (MergeTypeWithOld)
4115         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4116                                              OldProto->getExtProtoInfo()));
4117       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4118     }
4119 
4120     // Fall through to diagnose conflicting types.
4121   }
4122 
4123   // A function that has already been declared has been redeclared or
4124   // defined with a different type; show an appropriate diagnostic.
4125 
4126   // If the previous declaration was an implicitly-generated builtin
4127   // declaration, then at the very least we should use a specialized note.
4128   unsigned BuiltinID;
4129   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4130     // If it's actually a library-defined builtin function like 'malloc'
4131     // or 'printf', just warn about the incompatible redeclaration.
4132     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4133       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4134       Diag(OldLocation, diag::note_previous_builtin_declaration)
4135         << Old << Old->getType();
4136       return false;
4137     }
4138 
4139     PrevDiag = diag::note_previous_builtin_declaration;
4140   }
4141 
4142   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4143   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4144   return true;
4145 }
4146 
4147 /// Completes the merge of two function declarations that are
4148 /// known to be compatible.
4149 ///
4150 /// This routine handles the merging of attributes and other
4151 /// properties of function declarations from the old declaration to
4152 /// the new declaration, once we know that New is in fact a
4153 /// redeclaration of Old.
4154 ///
4155 /// \returns false
4156 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4157                                         Scope *S, bool MergeTypeWithOld) {
4158   // Merge the attributes
4159   mergeDeclAttributes(New, Old);
4160 
4161   // Merge "pure" flag.
4162   if (Old->isPure())
4163     New->setPure();
4164 
4165   // Merge "used" flag.
4166   if (Old->getMostRecentDecl()->isUsed(false))
4167     New->setIsUsed();
4168 
4169   // Merge attributes from the parameters.  These can mismatch with K&R
4170   // declarations.
4171   if (New->getNumParams() == Old->getNumParams())
4172       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4173         ParmVarDecl *NewParam = New->getParamDecl(i);
4174         ParmVarDecl *OldParam = Old->getParamDecl(i);
4175         mergeParamDeclAttributes(NewParam, OldParam, *this);
4176         mergeParamDeclTypes(NewParam, OldParam, *this);
4177       }
4178 
4179   if (getLangOpts().CPlusPlus)
4180     return MergeCXXFunctionDecl(New, Old, S);
4181 
4182   // Merge the function types so the we get the composite types for the return
4183   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4184   // was visible.
4185   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4186   if (!Merged.isNull() && MergeTypeWithOld)
4187     New->setType(Merged);
4188 
4189   return false;
4190 }
4191 
4192 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4193                                 ObjCMethodDecl *oldMethod) {
4194   // Merge the attributes, including deprecated/unavailable
4195   AvailabilityMergeKind MergeKind =
4196       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4197           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4198                                      : AMK_ProtocolImplementation)
4199           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4200                                                            : AMK_Override;
4201 
4202   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4203 
4204   // Merge attributes from the parameters.
4205   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4206                                        oe = oldMethod->param_end();
4207   for (ObjCMethodDecl::param_iterator
4208          ni = newMethod->param_begin(), ne = newMethod->param_end();
4209        ni != ne && oi != oe; ++ni, ++oi)
4210     mergeParamDeclAttributes(*ni, *oi, *this);
4211 
4212   CheckObjCMethodOverride(newMethod, oldMethod);
4213 }
4214 
4215 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4216   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4217 
4218   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4219          ? diag::err_redefinition_different_type
4220          : diag::err_redeclaration_different_type)
4221     << New->getDeclName() << New->getType() << Old->getType();
4222 
4223   diag::kind PrevDiag;
4224   SourceLocation OldLocation;
4225   std::tie(PrevDiag, OldLocation)
4226     = getNoteDiagForInvalidRedeclaration(Old, New);
4227   S.Diag(OldLocation, PrevDiag);
4228   New->setInvalidDecl();
4229 }
4230 
4231 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4232 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4233 /// emitting diagnostics as appropriate.
4234 ///
4235 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4236 /// to here in AddInitializerToDecl. We can't check them before the initializer
4237 /// is attached.
4238 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4239                              bool MergeTypeWithOld) {
4240   if (New->isInvalidDecl() || Old->isInvalidDecl())
4241     return;
4242 
4243   QualType MergedT;
4244   if (getLangOpts().CPlusPlus) {
4245     if (New->getType()->isUndeducedType()) {
4246       // We don't know what the new type is until the initializer is attached.
4247       return;
4248     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4249       // These could still be something that needs exception specs checked.
4250       return MergeVarDeclExceptionSpecs(New, Old);
4251     }
4252     // C++ [basic.link]p10:
4253     //   [...] the types specified by all declarations referring to a given
4254     //   object or function shall be identical, except that declarations for an
4255     //   array object can specify array types that differ by the presence or
4256     //   absence of a major array bound (8.3.4).
4257     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4258       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4259       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4260 
4261       // We are merging a variable declaration New into Old. If it has an array
4262       // bound, and that bound differs from Old's bound, we should diagnose the
4263       // mismatch.
4264       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4265         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4266              PrevVD = PrevVD->getPreviousDecl()) {
4267           QualType PrevVDTy = PrevVD->getType();
4268           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4269             continue;
4270 
4271           if (!Context.hasSameType(New->getType(), PrevVDTy))
4272             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4273         }
4274       }
4275 
4276       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4277         if (Context.hasSameType(OldArray->getElementType(),
4278                                 NewArray->getElementType()))
4279           MergedT = New->getType();
4280       }
4281       // FIXME: Check visibility. New is hidden but has a complete type. If New
4282       // has no array bound, it should not inherit one from Old, if Old is not
4283       // visible.
4284       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4285         if (Context.hasSameType(OldArray->getElementType(),
4286                                 NewArray->getElementType()))
4287           MergedT = Old->getType();
4288       }
4289     }
4290     else if (New->getType()->isObjCObjectPointerType() &&
4291                Old->getType()->isObjCObjectPointerType()) {
4292       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4293                                               Old->getType());
4294     }
4295   } else {
4296     // C 6.2.7p2:
4297     //   All declarations that refer to the same object or function shall have
4298     //   compatible type.
4299     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4300   }
4301   if (MergedT.isNull()) {
4302     // It's OK if we couldn't merge types if either type is dependent, for a
4303     // block-scope variable. In other cases (static data members of class
4304     // templates, variable templates, ...), we require the types to be
4305     // equivalent.
4306     // FIXME: The C++ standard doesn't say anything about this.
4307     if ((New->getType()->isDependentType() ||
4308          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4309       // If the old type was dependent, we can't merge with it, so the new type
4310       // becomes dependent for now. We'll reproduce the original type when we
4311       // instantiate the TypeSourceInfo for the variable.
4312       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4313         New->setType(Context.DependentTy);
4314       return;
4315     }
4316     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4317   }
4318 
4319   // Don't actually update the type on the new declaration if the old
4320   // declaration was an extern declaration in a different scope.
4321   if (MergeTypeWithOld)
4322     New->setType(MergedT);
4323 }
4324 
4325 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4326                                   LookupResult &Previous) {
4327   // C11 6.2.7p4:
4328   //   For an identifier with internal or external linkage declared
4329   //   in a scope in which a prior declaration of that identifier is
4330   //   visible, if the prior declaration specifies internal or
4331   //   external linkage, the type of the identifier at the later
4332   //   declaration becomes the composite type.
4333   //
4334   // If the variable isn't visible, we do not merge with its type.
4335   if (Previous.isShadowed())
4336     return false;
4337 
4338   if (S.getLangOpts().CPlusPlus) {
4339     // C++11 [dcl.array]p3:
4340     //   If there is a preceding declaration of the entity in the same
4341     //   scope in which the bound was specified, an omitted array bound
4342     //   is taken to be the same as in that earlier declaration.
4343     return NewVD->isPreviousDeclInSameBlockScope() ||
4344            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4345             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4346   } else {
4347     // If the old declaration was function-local, don't merge with its
4348     // type unless we're in the same function.
4349     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4350            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4351   }
4352 }
4353 
4354 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4355 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4356 /// situation, merging decls or emitting diagnostics as appropriate.
4357 ///
4358 /// Tentative definition rules (C99 6.9.2p2) are checked by
4359 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4360 /// definitions here, since the initializer hasn't been attached.
4361 ///
4362 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4363   // If the new decl is already invalid, don't do any other checking.
4364   if (New->isInvalidDecl())
4365     return;
4366 
4367   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4368     return;
4369 
4370   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4371 
4372   // Verify the old decl was also a variable or variable template.
4373   VarDecl *Old = nullptr;
4374   VarTemplateDecl *OldTemplate = nullptr;
4375   if (Previous.isSingleResult()) {
4376     if (NewTemplate) {
4377       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4378       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4379 
4380       if (auto *Shadow =
4381               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4382         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4383           return New->setInvalidDecl();
4384     } else {
4385       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4386 
4387       if (auto *Shadow =
4388               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4389         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4390           return New->setInvalidDecl();
4391     }
4392   }
4393   if (!Old) {
4394     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4395         << New->getDeclName();
4396     notePreviousDefinition(Previous.getRepresentativeDecl(),
4397                            New->getLocation());
4398     return New->setInvalidDecl();
4399   }
4400 
4401   // If the old declaration was found in an inline namespace and the new
4402   // declaration was qualified, update the DeclContext to match.
4403   adjustDeclContextForDeclaratorDecl(New, Old);
4404 
4405   // Ensure the template parameters are compatible.
4406   if (NewTemplate &&
4407       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4408                                       OldTemplate->getTemplateParameters(),
4409                                       /*Complain=*/true, TPL_TemplateMatch))
4410     return New->setInvalidDecl();
4411 
4412   // C++ [class.mem]p1:
4413   //   A member shall not be declared twice in the member-specification [...]
4414   //
4415   // Here, we need only consider static data members.
4416   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4417     Diag(New->getLocation(), diag::err_duplicate_member)
4418       << New->getIdentifier();
4419     Diag(Old->getLocation(), diag::note_previous_declaration);
4420     New->setInvalidDecl();
4421   }
4422 
4423   mergeDeclAttributes(New, Old);
4424   // Warn if an already-declared variable is made a weak_import in a subsequent
4425   // declaration
4426   if (New->hasAttr<WeakImportAttr>() &&
4427       Old->getStorageClass() == SC_None &&
4428       !Old->hasAttr<WeakImportAttr>()) {
4429     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4430     Diag(Old->getLocation(), diag::note_previous_declaration);
4431     // Remove weak_import attribute on new declaration.
4432     New->dropAttr<WeakImportAttr>();
4433   }
4434 
4435   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4436     if (!Old->hasAttr<InternalLinkageAttr>()) {
4437       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4438           << ILA;
4439       Diag(Old->getLocation(), diag::note_previous_declaration);
4440       New->dropAttr<InternalLinkageAttr>();
4441     }
4442 
4443   // Merge the types.
4444   VarDecl *MostRecent = Old->getMostRecentDecl();
4445   if (MostRecent != Old) {
4446     MergeVarDeclTypes(New, MostRecent,
4447                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4448     if (New->isInvalidDecl())
4449       return;
4450   }
4451 
4452   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4453   if (New->isInvalidDecl())
4454     return;
4455 
4456   diag::kind PrevDiag;
4457   SourceLocation OldLocation;
4458   std::tie(PrevDiag, OldLocation) =
4459       getNoteDiagForInvalidRedeclaration(Old, New);
4460 
4461   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4462   if (New->getStorageClass() == SC_Static &&
4463       !New->isStaticDataMember() &&
4464       Old->hasExternalFormalLinkage()) {
4465     if (getLangOpts().MicrosoftExt) {
4466       Diag(New->getLocation(), diag::ext_static_non_static)
4467           << New->getDeclName();
4468       Diag(OldLocation, PrevDiag);
4469     } else {
4470       Diag(New->getLocation(), diag::err_static_non_static)
4471           << New->getDeclName();
4472       Diag(OldLocation, PrevDiag);
4473       return New->setInvalidDecl();
4474     }
4475   }
4476   // C99 6.2.2p4:
4477   //   For an identifier declared with the storage-class specifier
4478   //   extern in a scope in which a prior declaration of that
4479   //   identifier is visible,23) if the prior declaration specifies
4480   //   internal or external linkage, the linkage of the identifier at
4481   //   the later declaration is the same as the linkage specified at
4482   //   the prior declaration. If no prior declaration is visible, or
4483   //   if the prior declaration specifies no linkage, then the
4484   //   identifier has external linkage.
4485   if (New->hasExternalStorage() && Old->hasLinkage())
4486     /* Okay */;
4487   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4488            !New->isStaticDataMember() &&
4489            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4490     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4491     Diag(OldLocation, PrevDiag);
4492     return New->setInvalidDecl();
4493   }
4494 
4495   // Check if extern is followed by non-extern and vice-versa.
4496   if (New->hasExternalStorage() &&
4497       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4498     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4499     Diag(OldLocation, PrevDiag);
4500     return New->setInvalidDecl();
4501   }
4502   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4503       !New->hasExternalStorage()) {
4504     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4505     Diag(OldLocation, PrevDiag);
4506     return New->setInvalidDecl();
4507   }
4508 
4509   if (CheckRedeclarationInModule(New, Old))
4510     return;
4511 
4512   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4513 
4514   // FIXME: The test for external storage here seems wrong? We still
4515   // need to check for mismatches.
4516   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4517       // Don't complain about out-of-line definitions of static members.
4518       !(Old->getLexicalDeclContext()->isRecord() &&
4519         !New->getLexicalDeclContext()->isRecord())) {
4520     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4521     Diag(OldLocation, PrevDiag);
4522     return New->setInvalidDecl();
4523   }
4524 
4525   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4526     if (VarDecl *Def = Old->getDefinition()) {
4527       // C++1z [dcl.fcn.spec]p4:
4528       //   If the definition of a variable appears in a translation unit before
4529       //   its first declaration as inline, the program is ill-formed.
4530       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4531       Diag(Def->getLocation(), diag::note_previous_definition);
4532     }
4533   }
4534 
4535   // If this redeclaration makes the variable inline, we may need to add it to
4536   // UndefinedButUsed.
4537   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4538       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4539     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4540                                            SourceLocation()));
4541 
4542   if (New->getTLSKind() != Old->getTLSKind()) {
4543     if (!Old->getTLSKind()) {
4544       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4545       Diag(OldLocation, PrevDiag);
4546     } else if (!New->getTLSKind()) {
4547       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4548       Diag(OldLocation, PrevDiag);
4549     } else {
4550       // Do not allow redeclaration to change the variable between requiring
4551       // static and dynamic initialization.
4552       // FIXME: GCC allows this, but uses the TLS keyword on the first
4553       // declaration to determine the kind. Do we need to be compatible here?
4554       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4555         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4556       Diag(OldLocation, PrevDiag);
4557     }
4558   }
4559 
4560   // C++ doesn't have tentative definitions, so go right ahead and check here.
4561   if (getLangOpts().CPlusPlus) {
4562     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4563         Old->getCanonicalDecl()->isConstexpr()) {
4564       // This definition won't be a definition any more once it's been merged.
4565       Diag(New->getLocation(),
4566            diag::warn_deprecated_redundant_constexpr_static_def);
4567     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4568       VarDecl *Def = Old->getDefinition();
4569       if (Def && checkVarDeclRedefinition(Def, New))
4570         return;
4571     }
4572   }
4573 
4574   if (haveIncompatibleLanguageLinkages(Old, New)) {
4575     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4576     Diag(OldLocation, PrevDiag);
4577     New->setInvalidDecl();
4578     return;
4579   }
4580 
4581   // Merge "used" flag.
4582   if (Old->getMostRecentDecl()->isUsed(false))
4583     New->setIsUsed();
4584 
4585   // Keep a chain of previous declarations.
4586   New->setPreviousDecl(Old);
4587   if (NewTemplate)
4588     NewTemplate->setPreviousDecl(OldTemplate);
4589 
4590   // Inherit access appropriately.
4591   New->setAccess(Old->getAccess());
4592   if (NewTemplate)
4593     NewTemplate->setAccess(New->getAccess());
4594 
4595   if (Old->isInline())
4596     New->setImplicitlyInline();
4597 }
4598 
4599 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4600   SourceManager &SrcMgr = getSourceManager();
4601   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4602   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4603   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4604   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4605   auto &HSI = PP.getHeaderSearchInfo();
4606   StringRef HdrFilename =
4607       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4608 
4609   auto noteFromModuleOrInclude = [&](Module *Mod,
4610                                      SourceLocation IncLoc) -> bool {
4611     // Redefinition errors with modules are common with non modular mapped
4612     // headers, example: a non-modular header H in module A that also gets
4613     // included directly in a TU. Pointing twice to the same header/definition
4614     // is confusing, try to get better diagnostics when modules is on.
4615     if (IncLoc.isValid()) {
4616       if (Mod) {
4617         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4618             << HdrFilename.str() << Mod->getFullModuleName();
4619         if (!Mod->DefinitionLoc.isInvalid())
4620           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4621               << Mod->getFullModuleName();
4622       } else {
4623         Diag(IncLoc, diag::note_redefinition_include_same_file)
4624             << HdrFilename.str();
4625       }
4626       return true;
4627     }
4628 
4629     return false;
4630   };
4631 
4632   // Is it the same file and same offset? Provide more information on why
4633   // this leads to a redefinition error.
4634   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4635     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4636     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4637     bool EmittedDiag =
4638         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4639     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4640 
4641     // If the header has no guards, emit a note suggesting one.
4642     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4643       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4644 
4645     if (EmittedDiag)
4646       return;
4647   }
4648 
4649   // Redefinition coming from different files or couldn't do better above.
4650   if (Old->getLocation().isValid())
4651     Diag(Old->getLocation(), diag::note_previous_definition);
4652 }
4653 
4654 /// We've just determined that \p Old and \p New both appear to be definitions
4655 /// of the same variable. Either diagnose or fix the problem.
4656 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4657   if (!hasVisibleDefinition(Old) &&
4658       (New->getFormalLinkage() == InternalLinkage ||
4659        New->isInline() ||
4660        New->getDescribedVarTemplate() ||
4661        New->getNumTemplateParameterLists() ||
4662        New->getDeclContext()->isDependentContext())) {
4663     // The previous definition is hidden, and multiple definitions are
4664     // permitted (in separate TUs). Demote this to a declaration.
4665     New->demoteThisDefinitionToDeclaration();
4666 
4667     // Make the canonical definition visible.
4668     if (auto *OldTD = Old->getDescribedVarTemplate())
4669       makeMergedDefinitionVisible(OldTD);
4670     makeMergedDefinitionVisible(Old);
4671     return false;
4672   } else {
4673     Diag(New->getLocation(), diag::err_redefinition) << New;
4674     notePreviousDefinition(Old, New->getLocation());
4675     New->setInvalidDecl();
4676     return true;
4677   }
4678 }
4679 
4680 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4681 /// no declarator (e.g. "struct foo;") is parsed.
4682 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4683                                        DeclSpec &DS,
4684                                        const ParsedAttributesView &DeclAttrs,
4685                                        RecordDecl *&AnonRecord) {
4686   return ParsedFreeStandingDeclSpec(
4687       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4688 }
4689 
4690 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4691 // disambiguate entities defined in different scopes.
4692 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4693 // compatibility.
4694 // We will pick our mangling number depending on which version of MSVC is being
4695 // targeted.
4696 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4697   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4698              ? S->getMSCurManglingNumber()
4699              : S->getMSLastManglingNumber();
4700 }
4701 
4702 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4703   if (!Context.getLangOpts().CPlusPlus)
4704     return;
4705 
4706   if (isa<CXXRecordDecl>(Tag->getParent())) {
4707     // If this tag is the direct child of a class, number it if
4708     // it is anonymous.
4709     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4710       return;
4711     MangleNumberingContext &MCtx =
4712         Context.getManglingNumberContext(Tag->getParent());
4713     Context.setManglingNumber(
4714         Tag, MCtx.getManglingNumber(
4715                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4716     return;
4717   }
4718 
4719   // If this tag isn't a direct child of a class, number it if it is local.
4720   MangleNumberingContext *MCtx;
4721   Decl *ManglingContextDecl;
4722   std::tie(MCtx, ManglingContextDecl) =
4723       getCurrentMangleNumberContext(Tag->getDeclContext());
4724   if (MCtx) {
4725     Context.setManglingNumber(
4726         Tag, MCtx->getManglingNumber(
4727                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4728   }
4729 }
4730 
4731 namespace {
4732 struct NonCLikeKind {
4733   enum {
4734     None,
4735     BaseClass,
4736     DefaultMemberInit,
4737     Lambda,
4738     Friend,
4739     OtherMember,
4740     Invalid,
4741   } Kind = None;
4742   SourceRange Range;
4743 
4744   explicit operator bool() { return Kind != None; }
4745 };
4746 }
4747 
4748 /// Determine whether a class is C-like, according to the rules of C++
4749 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4750 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4751   if (RD->isInvalidDecl())
4752     return {NonCLikeKind::Invalid, {}};
4753 
4754   // C++ [dcl.typedef]p9: [P1766R1]
4755   //   An unnamed class with a typedef name for linkage purposes shall not
4756   //
4757   //    -- have any base classes
4758   if (RD->getNumBases())
4759     return {NonCLikeKind::BaseClass,
4760             SourceRange(RD->bases_begin()->getBeginLoc(),
4761                         RD->bases_end()[-1].getEndLoc())};
4762   bool Invalid = false;
4763   for (Decl *D : RD->decls()) {
4764     // Don't complain about things we already diagnosed.
4765     if (D->isInvalidDecl()) {
4766       Invalid = true;
4767       continue;
4768     }
4769 
4770     //  -- have any [...] default member initializers
4771     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4772       if (FD->hasInClassInitializer()) {
4773         auto *Init = FD->getInClassInitializer();
4774         return {NonCLikeKind::DefaultMemberInit,
4775                 Init ? Init->getSourceRange() : D->getSourceRange()};
4776       }
4777       continue;
4778     }
4779 
4780     // FIXME: We don't allow friend declarations. This violates the wording of
4781     // P1766, but not the intent.
4782     if (isa<FriendDecl>(D))
4783       return {NonCLikeKind::Friend, D->getSourceRange()};
4784 
4785     //  -- declare any members other than non-static data members, member
4786     //     enumerations, or member classes,
4787     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4788         isa<EnumDecl>(D))
4789       continue;
4790     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4791     if (!MemberRD) {
4792       if (D->isImplicit())
4793         continue;
4794       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4795     }
4796 
4797     //  -- contain a lambda-expression,
4798     if (MemberRD->isLambda())
4799       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4800 
4801     //  and all member classes shall also satisfy these requirements
4802     //  (recursively).
4803     if (MemberRD->isThisDeclarationADefinition()) {
4804       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4805         return Kind;
4806     }
4807   }
4808 
4809   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4810 }
4811 
4812 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4813                                         TypedefNameDecl *NewTD) {
4814   if (TagFromDeclSpec->isInvalidDecl())
4815     return;
4816 
4817   // Do nothing if the tag already has a name for linkage purposes.
4818   if (TagFromDeclSpec->hasNameForLinkage())
4819     return;
4820 
4821   // A well-formed anonymous tag must always be a TUK_Definition.
4822   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4823 
4824   // The type must match the tag exactly;  no qualifiers allowed.
4825   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4826                            Context.getTagDeclType(TagFromDeclSpec))) {
4827     if (getLangOpts().CPlusPlus)
4828       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4829     return;
4830   }
4831 
4832   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4833   //   An unnamed class with a typedef name for linkage purposes shall [be
4834   //   C-like].
4835   //
4836   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4837   // shouldn't happen, but there are constructs that the language rule doesn't
4838   // disallow for which we can't reasonably avoid computing linkage early.
4839   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4840   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4841                              : NonCLikeKind();
4842   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4843   if (NonCLike || ChangesLinkage) {
4844     if (NonCLike.Kind == NonCLikeKind::Invalid)
4845       return;
4846 
4847     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4848     if (ChangesLinkage) {
4849       // If the linkage changes, we can't accept this as an extension.
4850       if (NonCLike.Kind == NonCLikeKind::None)
4851         DiagID = diag::err_typedef_changes_linkage;
4852       else
4853         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4854     }
4855 
4856     SourceLocation FixitLoc =
4857         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4858     llvm::SmallString<40> TextToInsert;
4859     TextToInsert += ' ';
4860     TextToInsert += NewTD->getIdentifier()->getName();
4861 
4862     Diag(FixitLoc, DiagID)
4863       << isa<TypeAliasDecl>(NewTD)
4864       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4865     if (NonCLike.Kind != NonCLikeKind::None) {
4866       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4867         << NonCLike.Kind - 1 << NonCLike.Range;
4868     }
4869     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4870       << NewTD << isa<TypeAliasDecl>(NewTD);
4871 
4872     if (ChangesLinkage)
4873       return;
4874   }
4875 
4876   // Otherwise, set this as the anon-decl typedef for the tag.
4877   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4878 }
4879 
4880 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4881   switch (T) {
4882   case DeclSpec::TST_class:
4883     return 0;
4884   case DeclSpec::TST_struct:
4885     return 1;
4886   case DeclSpec::TST_interface:
4887     return 2;
4888   case DeclSpec::TST_union:
4889     return 3;
4890   case DeclSpec::TST_enum:
4891     return 4;
4892   default:
4893     llvm_unreachable("unexpected type specifier");
4894   }
4895 }
4896 
4897 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4898 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4899 /// parameters to cope with template friend declarations.
4900 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4901                                        DeclSpec &DS,
4902                                        const ParsedAttributesView &DeclAttrs,
4903                                        MultiTemplateParamsArg TemplateParams,
4904                                        bool IsExplicitInstantiation,
4905                                        RecordDecl *&AnonRecord) {
4906   Decl *TagD = nullptr;
4907   TagDecl *Tag = nullptr;
4908   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4909       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4910       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4911       DS.getTypeSpecType() == DeclSpec::TST_union ||
4912       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4913     TagD = DS.getRepAsDecl();
4914 
4915     if (!TagD) // We probably had an error
4916       return nullptr;
4917 
4918     // Note that the above type specs guarantee that the
4919     // type rep is a Decl, whereas in many of the others
4920     // it's a Type.
4921     if (isa<TagDecl>(TagD))
4922       Tag = cast<TagDecl>(TagD);
4923     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4924       Tag = CTD->getTemplatedDecl();
4925   }
4926 
4927   if (Tag) {
4928     handleTagNumbering(Tag, S);
4929     Tag->setFreeStanding();
4930     if (Tag->isInvalidDecl())
4931       return Tag;
4932   }
4933 
4934   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4935     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4936     // or incomplete types shall not be restrict-qualified."
4937     if (TypeQuals & DeclSpec::TQ_restrict)
4938       Diag(DS.getRestrictSpecLoc(),
4939            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4940            << DS.getSourceRange();
4941   }
4942 
4943   if (DS.isInlineSpecified())
4944     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4945         << getLangOpts().CPlusPlus17;
4946 
4947   if (DS.hasConstexprSpecifier()) {
4948     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4949     // and definitions of functions and variables.
4950     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4951     // the declaration of a function or function template
4952     if (Tag)
4953       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4954           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4955           << static_cast<int>(DS.getConstexprSpecifier());
4956     else
4957       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4958           << static_cast<int>(DS.getConstexprSpecifier());
4959     // Don't emit warnings after this error.
4960     return TagD;
4961   }
4962 
4963   DiagnoseFunctionSpecifiers(DS);
4964 
4965   if (DS.isFriendSpecified()) {
4966     // If we're dealing with a decl but not a TagDecl, assume that
4967     // whatever routines created it handled the friendship aspect.
4968     if (TagD && !Tag)
4969       return nullptr;
4970     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4971   }
4972 
4973   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4974   bool IsExplicitSpecialization =
4975     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4976   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4977       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4978       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4979     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4980     // nested-name-specifier unless it is an explicit instantiation
4981     // or an explicit specialization.
4982     //
4983     // FIXME: We allow class template partial specializations here too, per the
4984     // obvious intent of DR1819.
4985     //
4986     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4987     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4988         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4989     return nullptr;
4990   }
4991 
4992   // Track whether this decl-specifier declares anything.
4993   bool DeclaresAnything = true;
4994 
4995   // Handle anonymous struct definitions.
4996   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4997     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4998         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4999       if (getLangOpts().CPlusPlus ||
5000           Record->getDeclContext()->isRecord()) {
5001         // If CurContext is a DeclContext that can contain statements,
5002         // RecursiveASTVisitor won't visit the decls that
5003         // BuildAnonymousStructOrUnion() will put into CurContext.
5004         // Also store them here so that they can be part of the
5005         // DeclStmt that gets created in this case.
5006         // FIXME: Also return the IndirectFieldDecls created by
5007         // BuildAnonymousStructOr union, for the same reason?
5008         if (CurContext->isFunctionOrMethod())
5009           AnonRecord = Record;
5010         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5011                                            Context.getPrintingPolicy());
5012       }
5013 
5014       DeclaresAnything = false;
5015     }
5016   }
5017 
5018   // C11 6.7.2.1p2:
5019   //   A struct-declaration that does not declare an anonymous structure or
5020   //   anonymous union shall contain a struct-declarator-list.
5021   //
5022   // This rule also existed in C89 and C99; the grammar for struct-declaration
5023   // did not permit a struct-declaration without a struct-declarator-list.
5024   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5025       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5026     // Check for Microsoft C extension: anonymous struct/union member.
5027     // Handle 2 kinds of anonymous struct/union:
5028     //   struct STRUCT;
5029     //   union UNION;
5030     // and
5031     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5032     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5033     if ((Tag && Tag->getDeclName()) ||
5034         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5035       RecordDecl *Record = nullptr;
5036       if (Tag)
5037         Record = dyn_cast<RecordDecl>(Tag);
5038       else if (const RecordType *RT =
5039                    DS.getRepAsType().get()->getAsStructureType())
5040         Record = RT->getDecl();
5041       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5042         Record = UT->getDecl();
5043 
5044       if (Record && getLangOpts().MicrosoftExt) {
5045         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5046             << Record->isUnion() << DS.getSourceRange();
5047         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5048       }
5049 
5050       DeclaresAnything = false;
5051     }
5052   }
5053 
5054   // Skip all the checks below if we have a type error.
5055   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5056       (TagD && TagD->isInvalidDecl()))
5057     return TagD;
5058 
5059   if (getLangOpts().CPlusPlus &&
5060       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5061     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5062       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5063           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5064         DeclaresAnything = false;
5065 
5066   if (!DS.isMissingDeclaratorOk()) {
5067     // Customize diagnostic for a typedef missing a name.
5068     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5069       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5070           << DS.getSourceRange();
5071     else
5072       DeclaresAnything = false;
5073   }
5074 
5075   if (DS.isModulePrivateSpecified() &&
5076       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5077     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5078       << Tag->getTagKind()
5079       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5080 
5081   ActOnDocumentableDecl(TagD);
5082 
5083   // C 6.7/2:
5084   //   A declaration [...] shall declare at least a declarator [...], a tag,
5085   //   or the members of an enumeration.
5086   // C++ [dcl.dcl]p3:
5087   //   [If there are no declarators], and except for the declaration of an
5088   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5089   //   names into the program, or shall redeclare a name introduced by a
5090   //   previous declaration.
5091   if (!DeclaresAnything) {
5092     // In C, we allow this as a (popular) extension / bug. Don't bother
5093     // producing further diagnostics for redundant qualifiers after this.
5094     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5095                                ? diag::err_no_declarators
5096                                : diag::ext_no_declarators)
5097         << DS.getSourceRange();
5098     return TagD;
5099   }
5100 
5101   // C++ [dcl.stc]p1:
5102   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5103   //   init-declarator-list of the declaration shall not be empty.
5104   // C++ [dcl.fct.spec]p1:
5105   //   If a cv-qualifier appears in a decl-specifier-seq, the
5106   //   init-declarator-list of the declaration shall not be empty.
5107   //
5108   // Spurious qualifiers here appear to be valid in C.
5109   unsigned DiagID = diag::warn_standalone_specifier;
5110   if (getLangOpts().CPlusPlus)
5111     DiagID = diag::ext_standalone_specifier;
5112 
5113   // Note that a linkage-specification sets a storage class, but
5114   // 'extern "C" struct foo;' is actually valid and not theoretically
5115   // useless.
5116   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5117     if (SCS == DeclSpec::SCS_mutable)
5118       // Since mutable is not a viable storage class specifier in C, there is
5119       // no reason to treat it as an extension. Instead, diagnose as an error.
5120       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5121     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5122       Diag(DS.getStorageClassSpecLoc(), DiagID)
5123         << DeclSpec::getSpecifierName(SCS);
5124   }
5125 
5126   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5127     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5128       << DeclSpec::getSpecifierName(TSCS);
5129   if (DS.getTypeQualifiers()) {
5130     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5131       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5132     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5133       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5134     // Restrict is covered above.
5135     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5136       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5137     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5138       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5139   }
5140 
5141   // Warn about ignored type attributes, for example:
5142   // __attribute__((aligned)) struct A;
5143   // Attributes should be placed after tag to apply to type declaration.
5144   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5145     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5146     if (TypeSpecType == DeclSpec::TST_class ||
5147         TypeSpecType == DeclSpec::TST_struct ||
5148         TypeSpecType == DeclSpec::TST_interface ||
5149         TypeSpecType == DeclSpec::TST_union ||
5150         TypeSpecType == DeclSpec::TST_enum) {
5151       for (const ParsedAttr &AL : DS.getAttributes())
5152         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5153             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5154       for (const ParsedAttr &AL : DeclAttrs)
5155         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5156             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5157     }
5158   }
5159 
5160   return TagD;
5161 }
5162 
5163 /// We are trying to inject an anonymous member into the given scope;
5164 /// check if there's an existing declaration that can't be overloaded.
5165 ///
5166 /// \return true if this is a forbidden redeclaration
5167 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5168                                          Scope *S,
5169                                          DeclContext *Owner,
5170                                          DeclarationName Name,
5171                                          SourceLocation NameLoc,
5172                                          bool IsUnion) {
5173   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5174                  Sema::ForVisibleRedeclaration);
5175   if (!SemaRef.LookupName(R, S)) return false;
5176 
5177   // Pick a representative declaration.
5178   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5179   assert(PrevDecl && "Expected a non-null Decl");
5180 
5181   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5182     return false;
5183 
5184   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5185     << IsUnion << Name;
5186   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5187 
5188   return true;
5189 }
5190 
5191 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5192 /// anonymous struct or union AnonRecord into the owning context Owner
5193 /// and scope S. This routine will be invoked just after we realize
5194 /// that an unnamed union or struct is actually an anonymous union or
5195 /// struct, e.g.,
5196 ///
5197 /// @code
5198 /// union {
5199 ///   int i;
5200 ///   float f;
5201 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5202 ///    // f into the surrounding scope.x
5203 /// @endcode
5204 ///
5205 /// This routine is recursive, injecting the names of nested anonymous
5206 /// structs/unions into the owning context and scope as well.
5207 static bool
5208 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5209                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5210                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5211   bool Invalid = false;
5212 
5213   // Look every FieldDecl and IndirectFieldDecl with a name.
5214   for (auto *D : AnonRecord->decls()) {
5215     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5216         cast<NamedDecl>(D)->getDeclName()) {
5217       ValueDecl *VD = cast<ValueDecl>(D);
5218       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5219                                        VD->getLocation(),
5220                                        AnonRecord->isUnion())) {
5221         // C++ [class.union]p2:
5222         //   The names of the members of an anonymous union shall be
5223         //   distinct from the names of any other entity in the
5224         //   scope in which the anonymous union is declared.
5225         Invalid = true;
5226       } else {
5227         // C++ [class.union]p2:
5228         //   For the purpose of name lookup, after the anonymous union
5229         //   definition, the members of the anonymous union are
5230         //   considered to have been defined in the scope in which the
5231         //   anonymous union is declared.
5232         unsigned OldChainingSize = Chaining.size();
5233         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5234           Chaining.append(IF->chain_begin(), IF->chain_end());
5235         else
5236           Chaining.push_back(VD);
5237 
5238         assert(Chaining.size() >= 2);
5239         NamedDecl **NamedChain =
5240           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5241         for (unsigned i = 0; i < Chaining.size(); i++)
5242           NamedChain[i] = Chaining[i];
5243 
5244         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5245             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5246             VD->getType(), {NamedChain, Chaining.size()});
5247 
5248         for (const auto *Attr : VD->attrs())
5249           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5250 
5251         IndirectField->setAccess(AS);
5252         IndirectField->setImplicit();
5253         SemaRef.PushOnScopeChains(IndirectField, S);
5254 
5255         // That includes picking up the appropriate access specifier.
5256         if (AS != AS_none) IndirectField->setAccess(AS);
5257 
5258         Chaining.resize(OldChainingSize);
5259       }
5260     }
5261   }
5262 
5263   return Invalid;
5264 }
5265 
5266 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5267 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5268 /// illegal input values are mapped to SC_None.
5269 static StorageClass
5270 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5271   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5272   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5273          "Parser allowed 'typedef' as storage class VarDecl.");
5274   switch (StorageClassSpec) {
5275   case DeclSpec::SCS_unspecified:    return SC_None;
5276   case DeclSpec::SCS_extern:
5277     if (DS.isExternInLinkageSpec())
5278       return SC_None;
5279     return SC_Extern;
5280   case DeclSpec::SCS_static:         return SC_Static;
5281   case DeclSpec::SCS_auto:           return SC_Auto;
5282   case DeclSpec::SCS_register:       return SC_Register;
5283   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5284     // Illegal SCSs map to None: error reporting is up to the caller.
5285   case DeclSpec::SCS_mutable:        // Fall through.
5286   case DeclSpec::SCS_typedef:        return SC_None;
5287   }
5288   llvm_unreachable("unknown storage class specifier");
5289 }
5290 
5291 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5292   assert(Record->hasInClassInitializer());
5293 
5294   for (const auto *I : Record->decls()) {
5295     const auto *FD = dyn_cast<FieldDecl>(I);
5296     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5297       FD = IFD->getAnonField();
5298     if (FD && FD->hasInClassInitializer())
5299       return FD->getLocation();
5300   }
5301 
5302   llvm_unreachable("couldn't find in-class initializer");
5303 }
5304 
5305 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5306                                       SourceLocation DefaultInitLoc) {
5307   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5308     return;
5309 
5310   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5311   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5312 }
5313 
5314 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5315                                       CXXRecordDecl *AnonUnion) {
5316   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5317     return;
5318 
5319   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5320 }
5321 
5322 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5323 /// anonymous structure or union. Anonymous unions are a C++ feature
5324 /// (C++ [class.union]) and a C11 feature; anonymous structures
5325 /// are a C11 feature and GNU C++ extension.
5326 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5327                                         AccessSpecifier AS,
5328                                         RecordDecl *Record,
5329                                         const PrintingPolicy &Policy) {
5330   DeclContext *Owner = Record->getDeclContext();
5331 
5332   // Diagnose whether this anonymous struct/union is an extension.
5333   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5334     Diag(Record->getLocation(), diag::ext_anonymous_union);
5335   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5336     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5337   else if (!Record->isUnion() && !getLangOpts().C11)
5338     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5339 
5340   // C and C++ require different kinds of checks for anonymous
5341   // structs/unions.
5342   bool Invalid = false;
5343   if (getLangOpts().CPlusPlus) {
5344     const char *PrevSpec = nullptr;
5345     if (Record->isUnion()) {
5346       // C++ [class.union]p6:
5347       // C++17 [class.union.anon]p2:
5348       //   Anonymous unions declared in a named namespace or in the
5349       //   global namespace shall be declared static.
5350       unsigned DiagID;
5351       DeclContext *OwnerScope = Owner->getRedeclContext();
5352       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5353           (OwnerScope->isTranslationUnit() ||
5354            (OwnerScope->isNamespace() &&
5355             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5356         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5357           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5358 
5359         // Recover by adding 'static'.
5360         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5361                                PrevSpec, DiagID, Policy);
5362       }
5363       // C++ [class.union]p6:
5364       //   A storage class is not allowed in a declaration of an
5365       //   anonymous union in a class scope.
5366       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5367                isa<RecordDecl>(Owner)) {
5368         Diag(DS.getStorageClassSpecLoc(),
5369              diag::err_anonymous_union_with_storage_spec)
5370           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5371 
5372         // Recover by removing the storage specifier.
5373         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5374                                SourceLocation(),
5375                                PrevSpec, DiagID, Context.getPrintingPolicy());
5376       }
5377     }
5378 
5379     // Ignore const/volatile/restrict qualifiers.
5380     if (DS.getTypeQualifiers()) {
5381       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5382         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5383           << Record->isUnion() << "const"
5384           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5385       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5386         Diag(DS.getVolatileSpecLoc(),
5387              diag::ext_anonymous_struct_union_qualified)
5388           << Record->isUnion() << "volatile"
5389           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5390       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5391         Diag(DS.getRestrictSpecLoc(),
5392              diag::ext_anonymous_struct_union_qualified)
5393           << Record->isUnion() << "restrict"
5394           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5395       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5396         Diag(DS.getAtomicSpecLoc(),
5397              diag::ext_anonymous_struct_union_qualified)
5398           << Record->isUnion() << "_Atomic"
5399           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5400       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5401         Diag(DS.getUnalignedSpecLoc(),
5402              diag::ext_anonymous_struct_union_qualified)
5403           << Record->isUnion() << "__unaligned"
5404           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5405 
5406       DS.ClearTypeQualifiers();
5407     }
5408 
5409     // C++ [class.union]p2:
5410     //   The member-specification of an anonymous union shall only
5411     //   define non-static data members. [Note: nested types and
5412     //   functions cannot be declared within an anonymous union. ]
5413     for (auto *Mem : Record->decls()) {
5414       // Ignore invalid declarations; we already diagnosed them.
5415       if (Mem->isInvalidDecl())
5416         continue;
5417 
5418       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5419         // C++ [class.union]p3:
5420         //   An anonymous union shall not have private or protected
5421         //   members (clause 11).
5422         assert(FD->getAccess() != AS_none);
5423         if (FD->getAccess() != AS_public) {
5424           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5425             << Record->isUnion() << (FD->getAccess() == AS_protected);
5426           Invalid = true;
5427         }
5428 
5429         // C++ [class.union]p1
5430         //   An object of a class with a non-trivial constructor, a non-trivial
5431         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5432         //   assignment operator cannot be a member of a union, nor can an
5433         //   array of such objects.
5434         if (CheckNontrivialField(FD))
5435           Invalid = true;
5436       } else if (Mem->isImplicit()) {
5437         // Any implicit members are fine.
5438       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5439         // This is a type that showed up in an
5440         // elaborated-type-specifier inside the anonymous struct or
5441         // union, but which actually declares a type outside of the
5442         // anonymous struct or union. It's okay.
5443       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5444         if (!MemRecord->isAnonymousStructOrUnion() &&
5445             MemRecord->getDeclName()) {
5446           // Visual C++ allows type definition in anonymous struct or union.
5447           if (getLangOpts().MicrosoftExt)
5448             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5449               << Record->isUnion();
5450           else {
5451             // This is a nested type declaration.
5452             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5453               << Record->isUnion();
5454             Invalid = true;
5455           }
5456         } else {
5457           // This is an anonymous type definition within another anonymous type.
5458           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5459           // not part of standard C++.
5460           Diag(MemRecord->getLocation(),
5461                diag::ext_anonymous_record_with_anonymous_type)
5462             << Record->isUnion();
5463         }
5464       } else if (isa<AccessSpecDecl>(Mem)) {
5465         // Any access specifier is fine.
5466       } else if (isa<StaticAssertDecl>(Mem)) {
5467         // In C++1z, static_assert declarations are also fine.
5468       } else {
5469         // We have something that isn't a non-static data
5470         // member. Complain about it.
5471         unsigned DK = diag::err_anonymous_record_bad_member;
5472         if (isa<TypeDecl>(Mem))
5473           DK = diag::err_anonymous_record_with_type;
5474         else if (isa<FunctionDecl>(Mem))
5475           DK = diag::err_anonymous_record_with_function;
5476         else if (isa<VarDecl>(Mem))
5477           DK = diag::err_anonymous_record_with_static;
5478 
5479         // Visual C++ allows type definition in anonymous struct or union.
5480         if (getLangOpts().MicrosoftExt &&
5481             DK == diag::err_anonymous_record_with_type)
5482           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5483             << Record->isUnion();
5484         else {
5485           Diag(Mem->getLocation(), DK) << Record->isUnion();
5486           Invalid = true;
5487         }
5488       }
5489     }
5490 
5491     // C++11 [class.union]p8 (DR1460):
5492     //   At most one variant member of a union may have a
5493     //   brace-or-equal-initializer.
5494     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5495         Owner->isRecord())
5496       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5497                                 cast<CXXRecordDecl>(Record));
5498   }
5499 
5500   if (!Record->isUnion() && !Owner->isRecord()) {
5501     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5502       << getLangOpts().CPlusPlus;
5503     Invalid = true;
5504   }
5505 
5506   // C++ [dcl.dcl]p3:
5507   //   [If there are no declarators], and except for the declaration of an
5508   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5509   //   names into the program
5510   // C++ [class.mem]p2:
5511   //   each such member-declaration shall either declare at least one member
5512   //   name of the class or declare at least one unnamed bit-field
5513   //
5514   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5515   if (getLangOpts().CPlusPlus && Record->field_empty())
5516     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5517 
5518   // Mock up a declarator.
5519   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5520   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5521   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5522 
5523   // Create a declaration for this anonymous struct/union.
5524   NamedDecl *Anon = nullptr;
5525   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5526     Anon = FieldDecl::Create(
5527         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5528         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5529         /*BitWidth=*/nullptr, /*Mutable=*/false,
5530         /*InitStyle=*/ICIS_NoInit);
5531     Anon->setAccess(AS);
5532     ProcessDeclAttributes(S, Anon, Dc);
5533 
5534     if (getLangOpts().CPlusPlus)
5535       FieldCollector->Add(cast<FieldDecl>(Anon));
5536   } else {
5537     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5538     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5539     if (SCSpec == DeclSpec::SCS_mutable) {
5540       // mutable can only appear on non-static class members, so it's always
5541       // an error here
5542       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5543       Invalid = true;
5544       SC = SC_None;
5545     }
5546 
5547     assert(DS.getAttributes().empty() && "No attribute expected");
5548     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5549                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5550                            Context.getTypeDeclType(Record), TInfo, SC);
5551 
5552     // Default-initialize the implicit variable. This initialization will be
5553     // trivial in almost all cases, except if a union member has an in-class
5554     // initializer:
5555     //   union { int n = 0; };
5556     ActOnUninitializedDecl(Anon);
5557   }
5558   Anon->setImplicit();
5559 
5560   // Mark this as an anonymous struct/union type.
5561   Record->setAnonymousStructOrUnion(true);
5562 
5563   // Add the anonymous struct/union object to the current
5564   // context. We'll be referencing this object when we refer to one of
5565   // its members.
5566   Owner->addDecl(Anon);
5567 
5568   // Inject the members of the anonymous struct/union into the owning
5569   // context and into the identifier resolver chain for name lookup
5570   // purposes.
5571   SmallVector<NamedDecl*, 2> Chain;
5572   Chain.push_back(Anon);
5573 
5574   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5575     Invalid = true;
5576 
5577   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5578     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5579       MangleNumberingContext *MCtx;
5580       Decl *ManglingContextDecl;
5581       std::tie(MCtx, ManglingContextDecl) =
5582           getCurrentMangleNumberContext(NewVD->getDeclContext());
5583       if (MCtx) {
5584         Context.setManglingNumber(
5585             NewVD, MCtx->getManglingNumber(
5586                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5587         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5588       }
5589     }
5590   }
5591 
5592   if (Invalid)
5593     Anon->setInvalidDecl();
5594 
5595   return Anon;
5596 }
5597 
5598 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5599 /// Microsoft C anonymous structure.
5600 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5601 /// Example:
5602 ///
5603 /// struct A { int a; };
5604 /// struct B { struct A; int b; };
5605 ///
5606 /// void foo() {
5607 ///   B var;
5608 ///   var.a = 3;
5609 /// }
5610 ///
5611 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5612                                            RecordDecl *Record) {
5613   assert(Record && "expected a record!");
5614 
5615   // Mock up a declarator.
5616   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5617   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5618   assert(TInfo && "couldn't build declarator info for anonymous struct");
5619 
5620   auto *ParentDecl = cast<RecordDecl>(CurContext);
5621   QualType RecTy = Context.getTypeDeclType(Record);
5622 
5623   // Create a declaration for this anonymous struct.
5624   NamedDecl *Anon =
5625       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5626                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5627                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5628                         /*InitStyle=*/ICIS_NoInit);
5629   Anon->setImplicit();
5630 
5631   // Add the anonymous struct object to the current context.
5632   CurContext->addDecl(Anon);
5633 
5634   // Inject the members of the anonymous struct into the current
5635   // context and into the identifier resolver chain for name lookup
5636   // purposes.
5637   SmallVector<NamedDecl*, 2> Chain;
5638   Chain.push_back(Anon);
5639 
5640   RecordDecl *RecordDef = Record->getDefinition();
5641   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5642                                diag::err_field_incomplete_or_sizeless) ||
5643       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5644                                           AS_none, Chain)) {
5645     Anon->setInvalidDecl();
5646     ParentDecl->setInvalidDecl();
5647   }
5648 
5649   return Anon;
5650 }
5651 
5652 /// GetNameForDeclarator - Determine the full declaration name for the
5653 /// given Declarator.
5654 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5655   return GetNameFromUnqualifiedId(D.getName());
5656 }
5657 
5658 /// Retrieves the declaration name from a parsed unqualified-id.
5659 DeclarationNameInfo
5660 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5661   DeclarationNameInfo NameInfo;
5662   NameInfo.setLoc(Name.StartLocation);
5663 
5664   switch (Name.getKind()) {
5665 
5666   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5667   case UnqualifiedIdKind::IK_Identifier:
5668     NameInfo.setName(Name.Identifier);
5669     return NameInfo;
5670 
5671   case UnqualifiedIdKind::IK_DeductionGuideName: {
5672     // C++ [temp.deduct.guide]p3:
5673     //   The simple-template-id shall name a class template specialization.
5674     //   The template-name shall be the same identifier as the template-name
5675     //   of the simple-template-id.
5676     // These together intend to imply that the template-name shall name a
5677     // class template.
5678     // FIXME: template<typename T> struct X {};
5679     //        template<typename T> using Y = X<T>;
5680     //        Y(int) -> Y<int>;
5681     //   satisfies these rules but does not name a class template.
5682     TemplateName TN = Name.TemplateName.get().get();
5683     auto *Template = TN.getAsTemplateDecl();
5684     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5685       Diag(Name.StartLocation,
5686            diag::err_deduction_guide_name_not_class_template)
5687         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5688       if (Template)
5689         Diag(Template->getLocation(), diag::note_template_decl_here);
5690       return DeclarationNameInfo();
5691     }
5692 
5693     NameInfo.setName(
5694         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5695     return NameInfo;
5696   }
5697 
5698   case UnqualifiedIdKind::IK_OperatorFunctionId:
5699     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5700                                            Name.OperatorFunctionId.Operator));
5701     NameInfo.setCXXOperatorNameRange(SourceRange(
5702         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5703     return NameInfo;
5704 
5705   case UnqualifiedIdKind::IK_LiteralOperatorId:
5706     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5707                                                            Name.Identifier));
5708     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5709     return NameInfo;
5710 
5711   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5712     TypeSourceInfo *TInfo;
5713     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5714     if (Ty.isNull())
5715       return DeclarationNameInfo();
5716     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5717                                                Context.getCanonicalType(Ty)));
5718     NameInfo.setNamedTypeInfo(TInfo);
5719     return NameInfo;
5720   }
5721 
5722   case UnqualifiedIdKind::IK_ConstructorName: {
5723     TypeSourceInfo *TInfo;
5724     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5725     if (Ty.isNull())
5726       return DeclarationNameInfo();
5727     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5728                                               Context.getCanonicalType(Ty)));
5729     NameInfo.setNamedTypeInfo(TInfo);
5730     return NameInfo;
5731   }
5732 
5733   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5734     // In well-formed code, we can only have a constructor
5735     // template-id that refers to the current context, so go there
5736     // to find the actual type being constructed.
5737     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5738     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5739       return DeclarationNameInfo();
5740 
5741     // Determine the type of the class being constructed.
5742     QualType CurClassType = Context.getTypeDeclType(CurClass);
5743 
5744     // FIXME: Check two things: that the template-id names the same type as
5745     // CurClassType, and that the template-id does not occur when the name
5746     // was qualified.
5747 
5748     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5749                                     Context.getCanonicalType(CurClassType)));
5750     // FIXME: should we retrieve TypeSourceInfo?
5751     NameInfo.setNamedTypeInfo(nullptr);
5752     return NameInfo;
5753   }
5754 
5755   case UnqualifiedIdKind::IK_DestructorName: {
5756     TypeSourceInfo *TInfo;
5757     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5758     if (Ty.isNull())
5759       return DeclarationNameInfo();
5760     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5761                                               Context.getCanonicalType(Ty)));
5762     NameInfo.setNamedTypeInfo(TInfo);
5763     return NameInfo;
5764   }
5765 
5766   case UnqualifiedIdKind::IK_TemplateId: {
5767     TemplateName TName = Name.TemplateId->Template.get();
5768     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5769     return Context.getNameForTemplate(TName, TNameLoc);
5770   }
5771 
5772   } // switch (Name.getKind())
5773 
5774   llvm_unreachable("Unknown name kind");
5775 }
5776 
5777 static QualType getCoreType(QualType Ty) {
5778   do {
5779     if (Ty->isPointerType() || Ty->isReferenceType())
5780       Ty = Ty->getPointeeType();
5781     else if (Ty->isArrayType())
5782       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5783     else
5784       return Ty.withoutLocalFastQualifiers();
5785   } while (true);
5786 }
5787 
5788 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5789 /// and Definition have "nearly" matching parameters. This heuristic is
5790 /// used to improve diagnostics in the case where an out-of-line function
5791 /// definition doesn't match any declaration within the class or namespace.
5792 /// Also sets Params to the list of indices to the parameters that differ
5793 /// between the declaration and the definition. If hasSimilarParameters
5794 /// returns true and Params is empty, then all of the parameters match.
5795 static bool hasSimilarParameters(ASTContext &Context,
5796                                      FunctionDecl *Declaration,
5797                                      FunctionDecl *Definition,
5798                                      SmallVectorImpl<unsigned> &Params) {
5799   Params.clear();
5800   if (Declaration->param_size() != Definition->param_size())
5801     return false;
5802   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5803     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5804     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5805 
5806     // The parameter types are identical
5807     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5808       continue;
5809 
5810     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5811     QualType DefParamBaseTy = getCoreType(DefParamTy);
5812     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5813     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5814 
5815     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5816         (DeclTyName && DeclTyName == DefTyName))
5817       Params.push_back(Idx);
5818     else  // The two parameters aren't even close
5819       return false;
5820   }
5821 
5822   return true;
5823 }
5824 
5825 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5826 /// declarator needs to be rebuilt in the current instantiation.
5827 /// Any bits of declarator which appear before the name are valid for
5828 /// consideration here.  That's specifically the type in the decl spec
5829 /// and the base type in any member-pointer chunks.
5830 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5831                                                     DeclarationName Name) {
5832   // The types we specifically need to rebuild are:
5833   //   - typenames, typeofs, and decltypes
5834   //   - types which will become injected class names
5835   // Of course, we also need to rebuild any type referencing such a
5836   // type.  It's safest to just say "dependent", but we call out a
5837   // few cases here.
5838 
5839   DeclSpec &DS = D.getMutableDeclSpec();
5840   switch (DS.getTypeSpecType()) {
5841   case DeclSpec::TST_typename:
5842   case DeclSpec::TST_typeofType:
5843   case DeclSpec::TST_underlyingType:
5844   case DeclSpec::TST_atomic: {
5845     // Grab the type from the parser.
5846     TypeSourceInfo *TSI = nullptr;
5847     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5848     if (T.isNull() || !T->isInstantiationDependentType()) break;
5849 
5850     // Make sure there's a type source info.  This isn't really much
5851     // of a waste; most dependent types should have type source info
5852     // attached already.
5853     if (!TSI)
5854       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5855 
5856     // Rebuild the type in the current instantiation.
5857     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5858     if (!TSI) return true;
5859 
5860     // Store the new type back in the decl spec.
5861     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5862     DS.UpdateTypeRep(LocType);
5863     break;
5864   }
5865 
5866   case DeclSpec::TST_decltype:
5867   case DeclSpec::TST_typeofExpr: {
5868     Expr *E = DS.getRepAsExpr();
5869     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5870     if (Result.isInvalid()) return true;
5871     DS.UpdateExprRep(Result.get());
5872     break;
5873   }
5874 
5875   default:
5876     // Nothing to do for these decl specs.
5877     break;
5878   }
5879 
5880   // It doesn't matter what order we do this in.
5881   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5882     DeclaratorChunk &Chunk = D.getTypeObject(I);
5883 
5884     // The only type information in the declarator which can come
5885     // before the declaration name is the base type of a member
5886     // pointer.
5887     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5888       continue;
5889 
5890     // Rebuild the scope specifier in-place.
5891     CXXScopeSpec &SS = Chunk.Mem.Scope();
5892     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5893       return true;
5894   }
5895 
5896   return false;
5897 }
5898 
5899 /// Returns true if the declaration is declared in a system header or from a
5900 /// system macro.
5901 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5902   return SM.isInSystemHeader(D->getLocation()) ||
5903          SM.isInSystemMacro(D->getLocation());
5904 }
5905 
5906 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5907   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5908   // of system decl.
5909   if (D->getPreviousDecl() || D->isImplicit())
5910     return;
5911   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5912   if (Status != ReservedIdentifierStatus::NotReserved &&
5913       !isFromSystemHeader(Context.getSourceManager(), D)) {
5914     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5915         << D << static_cast<int>(Status);
5916   }
5917 }
5918 
5919 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5920   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5921 
5922   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5923   // declaration only if the `bind_to_declaration` extension is set.
5924   SmallVector<FunctionDecl *, 4> Bases;
5925   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5926     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5927               implementation_extension_bind_to_declaration))
5928     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5929         S, D, MultiTemplateParamsArg(), Bases);
5930 
5931   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5932 
5933   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5934       Dcl && Dcl->getDeclContext()->isFileContext())
5935     Dcl->setTopLevelDeclInObjCContainer();
5936 
5937   if (!Bases.empty())
5938     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5939 
5940   return Dcl;
5941 }
5942 
5943 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5944 ///   If T is the name of a class, then each of the following shall have a
5945 ///   name different from T:
5946 ///     - every static data member of class T;
5947 ///     - every member function of class T
5948 ///     - every member of class T that is itself a type;
5949 /// \returns true if the declaration name violates these rules.
5950 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5951                                    DeclarationNameInfo NameInfo) {
5952   DeclarationName Name = NameInfo.getName();
5953 
5954   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5955   while (Record && Record->isAnonymousStructOrUnion())
5956     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5957   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5958     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5959     return true;
5960   }
5961 
5962   return false;
5963 }
5964 
5965 /// Diagnose a declaration whose declarator-id has the given
5966 /// nested-name-specifier.
5967 ///
5968 /// \param SS The nested-name-specifier of the declarator-id.
5969 ///
5970 /// \param DC The declaration context to which the nested-name-specifier
5971 /// resolves.
5972 ///
5973 /// \param Name The name of the entity being declared.
5974 ///
5975 /// \param Loc The location of the name of the entity being declared.
5976 ///
5977 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5978 /// we're declaring an explicit / partial specialization / instantiation.
5979 ///
5980 /// \returns true if we cannot safely recover from this error, false otherwise.
5981 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5982                                         DeclarationName Name,
5983                                         SourceLocation Loc, bool IsTemplateId) {
5984   DeclContext *Cur = CurContext;
5985   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5986     Cur = Cur->getParent();
5987 
5988   // If the user provided a superfluous scope specifier that refers back to the
5989   // class in which the entity is already declared, diagnose and ignore it.
5990   //
5991   // class X {
5992   //   void X::f();
5993   // };
5994   //
5995   // Note, it was once ill-formed to give redundant qualification in all
5996   // contexts, but that rule was removed by DR482.
5997   if (Cur->Equals(DC)) {
5998     if (Cur->isRecord()) {
5999       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6000                                       : diag::err_member_extra_qualification)
6001         << Name << FixItHint::CreateRemoval(SS.getRange());
6002       SS.clear();
6003     } else {
6004       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6005     }
6006     return false;
6007   }
6008 
6009   // Check whether the qualifying scope encloses the scope of the original
6010   // declaration. For a template-id, we perform the checks in
6011   // CheckTemplateSpecializationScope.
6012   if (!Cur->Encloses(DC) && !IsTemplateId) {
6013     if (Cur->isRecord())
6014       Diag(Loc, diag::err_member_qualification)
6015         << Name << SS.getRange();
6016     else if (isa<TranslationUnitDecl>(DC))
6017       Diag(Loc, diag::err_invalid_declarator_global_scope)
6018         << Name << SS.getRange();
6019     else if (isa<FunctionDecl>(Cur))
6020       Diag(Loc, diag::err_invalid_declarator_in_function)
6021         << Name << SS.getRange();
6022     else if (isa<BlockDecl>(Cur))
6023       Diag(Loc, diag::err_invalid_declarator_in_block)
6024         << Name << SS.getRange();
6025     else if (isa<ExportDecl>(Cur)) {
6026       if (!isa<NamespaceDecl>(DC))
6027         Diag(Loc, diag::err_export_non_namespace_scope_name)
6028             << Name << SS.getRange();
6029       else
6030         // The cases that DC is not NamespaceDecl should be handled in
6031         // CheckRedeclarationExported.
6032         return false;
6033     } else
6034       Diag(Loc, diag::err_invalid_declarator_scope)
6035       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6036 
6037     return true;
6038   }
6039 
6040   if (Cur->isRecord()) {
6041     // Cannot qualify members within a class.
6042     Diag(Loc, diag::err_member_qualification)
6043       << Name << SS.getRange();
6044     SS.clear();
6045 
6046     // C++ constructors and destructors with incorrect scopes can break
6047     // our AST invariants by having the wrong underlying types. If
6048     // that's the case, then drop this declaration entirely.
6049     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6050          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6051         !Context.hasSameType(Name.getCXXNameType(),
6052                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6053       return true;
6054 
6055     return false;
6056   }
6057 
6058   // C++11 [dcl.meaning]p1:
6059   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6060   //   not begin with a decltype-specifer"
6061   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6062   while (SpecLoc.getPrefix())
6063     SpecLoc = SpecLoc.getPrefix();
6064   if (isa_and_nonnull<DecltypeType>(
6065           SpecLoc.getNestedNameSpecifier()->getAsType()))
6066     Diag(Loc, diag::err_decltype_in_declarator)
6067       << SpecLoc.getTypeLoc().getSourceRange();
6068 
6069   return false;
6070 }
6071 
6072 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6073                                   MultiTemplateParamsArg TemplateParamLists) {
6074   // TODO: consider using NameInfo for diagnostic.
6075   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6076   DeclarationName Name = NameInfo.getName();
6077 
6078   // All of these full declarators require an identifier.  If it doesn't have
6079   // one, the ParsedFreeStandingDeclSpec action should be used.
6080   if (D.isDecompositionDeclarator()) {
6081     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6082   } else if (!Name) {
6083     if (!D.isInvalidType())  // Reject this if we think it is valid.
6084       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6085           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6086     return nullptr;
6087   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6088     return nullptr;
6089 
6090   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6091   // we find one that is.
6092   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6093          (S->getFlags() & Scope::TemplateParamScope) != 0)
6094     S = S->getParent();
6095 
6096   DeclContext *DC = CurContext;
6097   if (D.getCXXScopeSpec().isInvalid())
6098     D.setInvalidType();
6099   else if (D.getCXXScopeSpec().isSet()) {
6100     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6101                                         UPPC_DeclarationQualifier))
6102       return nullptr;
6103 
6104     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6105     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6106     if (!DC || isa<EnumDecl>(DC)) {
6107       // If we could not compute the declaration context, it's because the
6108       // declaration context is dependent but does not refer to a class,
6109       // class template, or class template partial specialization. Complain
6110       // and return early, to avoid the coming semantic disaster.
6111       Diag(D.getIdentifierLoc(),
6112            diag::err_template_qualified_declarator_no_match)
6113         << D.getCXXScopeSpec().getScopeRep()
6114         << D.getCXXScopeSpec().getRange();
6115       return nullptr;
6116     }
6117     bool IsDependentContext = DC->isDependentContext();
6118 
6119     if (!IsDependentContext &&
6120         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6121       return nullptr;
6122 
6123     // If a class is incomplete, do not parse entities inside it.
6124     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6125       Diag(D.getIdentifierLoc(),
6126            diag::err_member_def_undefined_record)
6127         << Name << DC << D.getCXXScopeSpec().getRange();
6128       return nullptr;
6129     }
6130     if (!D.getDeclSpec().isFriendSpecified()) {
6131       if (diagnoseQualifiedDeclaration(
6132               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6133               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6134         if (DC->isRecord())
6135           return nullptr;
6136 
6137         D.setInvalidType();
6138       }
6139     }
6140 
6141     // Check whether we need to rebuild the type of the given
6142     // declaration in the current instantiation.
6143     if (EnteringContext && IsDependentContext &&
6144         TemplateParamLists.size() != 0) {
6145       ContextRAII SavedContext(*this, DC);
6146       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6147         D.setInvalidType();
6148     }
6149   }
6150 
6151   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6152   QualType R = TInfo->getType();
6153 
6154   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6155                                       UPPC_DeclarationType))
6156     D.setInvalidType();
6157 
6158   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6159                         forRedeclarationInCurContext());
6160 
6161   // See if this is a redefinition of a variable in the same scope.
6162   if (!D.getCXXScopeSpec().isSet()) {
6163     bool IsLinkageLookup = false;
6164     bool CreateBuiltins = false;
6165 
6166     // If the declaration we're planning to build will be a function
6167     // or object with linkage, then look for another declaration with
6168     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6169     //
6170     // If the declaration we're planning to build will be declared with
6171     // external linkage in the translation unit, create any builtin with
6172     // the same name.
6173     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6174       /* Do nothing*/;
6175     else if (CurContext->isFunctionOrMethod() &&
6176              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6177               R->isFunctionType())) {
6178       IsLinkageLookup = true;
6179       CreateBuiltins =
6180           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6181     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6182                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6183       CreateBuiltins = true;
6184 
6185     if (IsLinkageLookup) {
6186       Previous.clear(LookupRedeclarationWithLinkage);
6187       Previous.setRedeclarationKind(ForExternalRedeclaration);
6188     }
6189 
6190     LookupName(Previous, S, CreateBuiltins);
6191   } else { // Something like "int foo::x;"
6192     LookupQualifiedName(Previous, DC);
6193 
6194     // C++ [dcl.meaning]p1:
6195     //   When the declarator-id is qualified, the declaration shall refer to a
6196     //  previously declared member of the class or namespace to which the
6197     //  qualifier refers (or, in the case of a namespace, of an element of the
6198     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6199     //  thereof; [...]
6200     //
6201     // Note that we already checked the context above, and that we do not have
6202     // enough information to make sure that Previous contains the declaration
6203     // we want to match. For example, given:
6204     //
6205     //   class X {
6206     //     void f();
6207     //     void f(float);
6208     //   };
6209     //
6210     //   void X::f(int) { } // ill-formed
6211     //
6212     // In this case, Previous will point to the overload set
6213     // containing the two f's declared in X, but neither of them
6214     // matches.
6215 
6216     // C++ [dcl.meaning]p1:
6217     //   [...] the member shall not merely have been introduced by a
6218     //   using-declaration in the scope of the class or namespace nominated by
6219     //   the nested-name-specifier of the declarator-id.
6220     RemoveUsingDecls(Previous);
6221   }
6222 
6223   if (Previous.isSingleResult() &&
6224       Previous.getFoundDecl()->isTemplateParameter()) {
6225     // Maybe we will complain about the shadowed template parameter.
6226     if (!D.isInvalidType())
6227       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6228                                       Previous.getFoundDecl());
6229 
6230     // Just pretend that we didn't see the previous declaration.
6231     Previous.clear();
6232   }
6233 
6234   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6235     // Forget that the previous declaration is the injected-class-name.
6236     Previous.clear();
6237 
6238   // In C++, the previous declaration we find might be a tag type
6239   // (class or enum). In this case, the new declaration will hide the
6240   // tag type. Note that this applies to functions, function templates, and
6241   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6242   if (Previous.isSingleTagDecl() &&
6243       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6244       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6245     Previous.clear();
6246 
6247   // Check that there are no default arguments other than in the parameters
6248   // of a function declaration (C++ only).
6249   if (getLangOpts().CPlusPlus)
6250     CheckExtraCXXDefaultArguments(D);
6251 
6252   NamedDecl *New;
6253 
6254   bool AddToScope = true;
6255   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6256     if (TemplateParamLists.size()) {
6257       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6258       return nullptr;
6259     }
6260 
6261     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6262   } else if (R->isFunctionType()) {
6263     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6264                                   TemplateParamLists,
6265                                   AddToScope);
6266   } else {
6267     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6268                                   AddToScope);
6269   }
6270 
6271   if (!New)
6272     return nullptr;
6273 
6274   // If this has an identifier and is not a function template specialization,
6275   // add it to the scope stack.
6276   if (New->getDeclName() && AddToScope)
6277     PushOnScopeChains(New, S);
6278 
6279   if (isInOpenMPDeclareTargetContext())
6280     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6281 
6282   return New;
6283 }
6284 
6285 /// Helper method to turn variable array types into constant array
6286 /// types in certain situations which would otherwise be errors (for
6287 /// GCC compatibility).
6288 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6289                                                     ASTContext &Context,
6290                                                     bool &SizeIsNegative,
6291                                                     llvm::APSInt &Oversized) {
6292   // This method tries to turn a variable array into a constant
6293   // array even when the size isn't an ICE.  This is necessary
6294   // for compatibility with code that depends on gcc's buggy
6295   // constant expression folding, like struct {char x[(int)(char*)2];}
6296   SizeIsNegative = false;
6297   Oversized = 0;
6298 
6299   if (T->isDependentType())
6300     return QualType();
6301 
6302   QualifierCollector Qs;
6303   const Type *Ty = Qs.strip(T);
6304 
6305   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6306     QualType Pointee = PTy->getPointeeType();
6307     QualType FixedType =
6308         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6309                                             Oversized);
6310     if (FixedType.isNull()) return FixedType;
6311     FixedType = Context.getPointerType(FixedType);
6312     return Qs.apply(Context, FixedType);
6313   }
6314   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6315     QualType Inner = PTy->getInnerType();
6316     QualType FixedType =
6317         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6318                                             Oversized);
6319     if (FixedType.isNull()) return FixedType;
6320     FixedType = Context.getParenType(FixedType);
6321     return Qs.apply(Context, FixedType);
6322   }
6323 
6324   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6325   if (!VLATy)
6326     return QualType();
6327 
6328   QualType ElemTy = VLATy->getElementType();
6329   if (ElemTy->isVariablyModifiedType()) {
6330     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6331                                                  SizeIsNegative, Oversized);
6332     if (ElemTy.isNull())
6333       return QualType();
6334   }
6335 
6336   Expr::EvalResult Result;
6337   if (!VLATy->getSizeExpr() ||
6338       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6339     return QualType();
6340 
6341   llvm::APSInt Res = Result.Val.getInt();
6342 
6343   // Check whether the array size is negative.
6344   if (Res.isSigned() && Res.isNegative()) {
6345     SizeIsNegative = true;
6346     return QualType();
6347   }
6348 
6349   // Check whether the array is too large to be addressed.
6350   unsigned ActiveSizeBits =
6351       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6352        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6353           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6354           : Res.getActiveBits();
6355   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6356     Oversized = Res;
6357     return QualType();
6358   }
6359 
6360   QualType FoldedArrayType = Context.getConstantArrayType(
6361       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6362   return Qs.apply(Context, FoldedArrayType);
6363 }
6364 
6365 static void
6366 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6367   SrcTL = SrcTL.getUnqualifiedLoc();
6368   DstTL = DstTL.getUnqualifiedLoc();
6369   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6370     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6371     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6372                                       DstPTL.getPointeeLoc());
6373     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6374     return;
6375   }
6376   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6377     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6378     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6379                                       DstPTL.getInnerLoc());
6380     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6381     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6382     return;
6383   }
6384   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6385   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6386   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6387   TypeLoc DstElemTL = DstATL.getElementLoc();
6388   if (VariableArrayTypeLoc SrcElemATL =
6389           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6390     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6391     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6392   } else {
6393     DstElemTL.initializeFullCopy(SrcElemTL);
6394   }
6395   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6396   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6397   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6398 }
6399 
6400 /// Helper method to turn variable array types into constant array
6401 /// types in certain situations which would otherwise be errors (for
6402 /// GCC compatibility).
6403 static TypeSourceInfo*
6404 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6405                                               ASTContext &Context,
6406                                               bool &SizeIsNegative,
6407                                               llvm::APSInt &Oversized) {
6408   QualType FixedTy
6409     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6410                                           SizeIsNegative, Oversized);
6411   if (FixedTy.isNull())
6412     return nullptr;
6413   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6414   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6415                                     FixedTInfo->getTypeLoc());
6416   return FixedTInfo;
6417 }
6418 
6419 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6420 /// true if we were successful.
6421 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6422                                            QualType &T, SourceLocation Loc,
6423                                            unsigned FailedFoldDiagID) {
6424   bool SizeIsNegative;
6425   llvm::APSInt Oversized;
6426   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6427       TInfo, Context, SizeIsNegative, Oversized);
6428   if (FixedTInfo) {
6429     Diag(Loc, diag::ext_vla_folded_to_constant);
6430     TInfo = FixedTInfo;
6431     T = FixedTInfo->getType();
6432     return true;
6433   }
6434 
6435   if (SizeIsNegative)
6436     Diag(Loc, diag::err_typecheck_negative_array_size);
6437   else if (Oversized.getBoolValue())
6438     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6439   else if (FailedFoldDiagID)
6440     Diag(Loc, FailedFoldDiagID);
6441   return false;
6442 }
6443 
6444 /// Register the given locally-scoped extern "C" declaration so
6445 /// that it can be found later for redeclarations. We include any extern "C"
6446 /// declaration that is not visible in the translation unit here, not just
6447 /// function-scope declarations.
6448 void
6449 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6450   if (!getLangOpts().CPlusPlus &&
6451       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6452     // Don't need to track declarations in the TU in C.
6453     return;
6454 
6455   // Note that we have a locally-scoped external with this name.
6456   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6457 }
6458 
6459 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6460   // FIXME: We can have multiple results via __attribute__((overloadable)).
6461   auto Result = Context.getExternCContextDecl()->lookup(Name);
6462   return Result.empty() ? nullptr : *Result.begin();
6463 }
6464 
6465 /// Diagnose function specifiers on a declaration of an identifier that
6466 /// does not identify a function.
6467 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6468   // FIXME: We should probably indicate the identifier in question to avoid
6469   // confusion for constructs like "virtual int a(), b;"
6470   if (DS.isVirtualSpecified())
6471     Diag(DS.getVirtualSpecLoc(),
6472          diag::err_virtual_non_function);
6473 
6474   if (DS.hasExplicitSpecifier())
6475     Diag(DS.getExplicitSpecLoc(),
6476          diag::err_explicit_non_function);
6477 
6478   if (DS.isNoreturnSpecified())
6479     Diag(DS.getNoreturnSpecLoc(),
6480          diag::err_noreturn_non_function);
6481 }
6482 
6483 NamedDecl*
6484 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6485                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6486   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6487   if (D.getCXXScopeSpec().isSet()) {
6488     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6489       << D.getCXXScopeSpec().getRange();
6490     D.setInvalidType();
6491     // Pretend we didn't see the scope specifier.
6492     DC = CurContext;
6493     Previous.clear();
6494   }
6495 
6496   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6497 
6498   if (D.getDeclSpec().isInlineSpecified())
6499     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6500         << getLangOpts().CPlusPlus17;
6501   if (D.getDeclSpec().hasConstexprSpecifier())
6502     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6503         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6504 
6505   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6506     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6507       Diag(D.getName().StartLocation,
6508            diag::err_deduction_guide_invalid_specifier)
6509           << "typedef";
6510     else
6511       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6512           << D.getName().getSourceRange();
6513     return nullptr;
6514   }
6515 
6516   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6517   if (!NewTD) return nullptr;
6518 
6519   // Handle attributes prior to checking for duplicates in MergeVarDecl
6520   ProcessDeclAttributes(S, NewTD, D);
6521 
6522   CheckTypedefForVariablyModifiedType(S, NewTD);
6523 
6524   bool Redeclaration = D.isRedeclaration();
6525   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6526   D.setRedeclaration(Redeclaration);
6527   return ND;
6528 }
6529 
6530 void
6531 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6532   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6533   // then it shall have block scope.
6534   // Note that variably modified types must be fixed before merging the decl so
6535   // that redeclarations will match.
6536   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6537   QualType T = TInfo->getType();
6538   if (T->isVariablyModifiedType()) {
6539     setFunctionHasBranchProtectedScope();
6540 
6541     if (S->getFnParent() == nullptr) {
6542       bool SizeIsNegative;
6543       llvm::APSInt Oversized;
6544       TypeSourceInfo *FixedTInfo =
6545         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6546                                                       SizeIsNegative,
6547                                                       Oversized);
6548       if (FixedTInfo) {
6549         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6550         NewTD->setTypeSourceInfo(FixedTInfo);
6551       } else {
6552         if (SizeIsNegative)
6553           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6554         else if (T->isVariableArrayType())
6555           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6556         else if (Oversized.getBoolValue())
6557           Diag(NewTD->getLocation(), diag::err_array_too_large)
6558             << toString(Oversized, 10);
6559         else
6560           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6561         NewTD->setInvalidDecl();
6562       }
6563     }
6564   }
6565 }
6566 
6567 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6568 /// declares a typedef-name, either using the 'typedef' type specifier or via
6569 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6570 NamedDecl*
6571 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6572                            LookupResult &Previous, bool &Redeclaration) {
6573 
6574   // Find the shadowed declaration before filtering for scope.
6575   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6576 
6577   // Merge the decl with the existing one if appropriate. If the decl is
6578   // in an outer scope, it isn't the same thing.
6579   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6580                        /*AllowInlineNamespace*/false);
6581   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6582   if (!Previous.empty()) {
6583     Redeclaration = true;
6584     MergeTypedefNameDecl(S, NewTD, Previous);
6585   } else {
6586     inferGslPointerAttribute(NewTD);
6587   }
6588 
6589   if (ShadowedDecl && !Redeclaration)
6590     CheckShadow(NewTD, ShadowedDecl, Previous);
6591 
6592   // If this is the C FILE type, notify the AST context.
6593   if (IdentifierInfo *II = NewTD->getIdentifier())
6594     if (!NewTD->isInvalidDecl() &&
6595         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6596       if (II->isStr("FILE"))
6597         Context.setFILEDecl(NewTD);
6598       else if (II->isStr("jmp_buf"))
6599         Context.setjmp_bufDecl(NewTD);
6600       else if (II->isStr("sigjmp_buf"))
6601         Context.setsigjmp_bufDecl(NewTD);
6602       else if (II->isStr("ucontext_t"))
6603         Context.setucontext_tDecl(NewTD);
6604     }
6605 
6606   return NewTD;
6607 }
6608 
6609 /// Determines whether the given declaration is an out-of-scope
6610 /// previous declaration.
6611 ///
6612 /// This routine should be invoked when name lookup has found a
6613 /// previous declaration (PrevDecl) that is not in the scope where a
6614 /// new declaration by the same name is being introduced. If the new
6615 /// declaration occurs in a local scope, previous declarations with
6616 /// linkage may still be considered previous declarations (C99
6617 /// 6.2.2p4-5, C++ [basic.link]p6).
6618 ///
6619 /// \param PrevDecl the previous declaration found by name
6620 /// lookup
6621 ///
6622 /// \param DC the context in which the new declaration is being
6623 /// declared.
6624 ///
6625 /// \returns true if PrevDecl is an out-of-scope previous declaration
6626 /// for a new delcaration with the same name.
6627 static bool
6628 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6629                                 ASTContext &Context) {
6630   if (!PrevDecl)
6631     return false;
6632 
6633   if (!PrevDecl->hasLinkage())
6634     return false;
6635 
6636   if (Context.getLangOpts().CPlusPlus) {
6637     // C++ [basic.link]p6:
6638     //   If there is a visible declaration of an entity with linkage
6639     //   having the same name and type, ignoring entities declared
6640     //   outside the innermost enclosing namespace scope, the block
6641     //   scope declaration declares that same entity and receives the
6642     //   linkage of the previous declaration.
6643     DeclContext *OuterContext = DC->getRedeclContext();
6644     if (!OuterContext->isFunctionOrMethod())
6645       // This rule only applies to block-scope declarations.
6646       return false;
6647 
6648     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6649     if (PrevOuterContext->isRecord())
6650       // We found a member function: ignore it.
6651       return false;
6652 
6653     // Find the innermost enclosing namespace for the new and
6654     // previous declarations.
6655     OuterContext = OuterContext->getEnclosingNamespaceContext();
6656     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6657 
6658     // The previous declaration is in a different namespace, so it
6659     // isn't the same function.
6660     if (!OuterContext->Equals(PrevOuterContext))
6661       return false;
6662   }
6663 
6664   return true;
6665 }
6666 
6667 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6668   CXXScopeSpec &SS = D.getCXXScopeSpec();
6669   if (!SS.isSet()) return;
6670   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6671 }
6672 
6673 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6674   QualType type = decl->getType();
6675   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6676   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6677     // Various kinds of declaration aren't allowed to be __autoreleasing.
6678     unsigned kind = -1U;
6679     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6680       if (var->hasAttr<BlocksAttr>())
6681         kind = 0; // __block
6682       else if (!var->hasLocalStorage())
6683         kind = 1; // global
6684     } else if (isa<ObjCIvarDecl>(decl)) {
6685       kind = 3; // ivar
6686     } else if (isa<FieldDecl>(decl)) {
6687       kind = 2; // field
6688     }
6689 
6690     if (kind != -1U) {
6691       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6692         << kind;
6693     }
6694   } else if (lifetime == Qualifiers::OCL_None) {
6695     // Try to infer lifetime.
6696     if (!type->isObjCLifetimeType())
6697       return false;
6698 
6699     lifetime = type->getObjCARCImplicitLifetime();
6700     type = Context.getLifetimeQualifiedType(type, lifetime);
6701     decl->setType(type);
6702   }
6703 
6704   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6705     // Thread-local variables cannot have lifetime.
6706     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6707         var->getTLSKind()) {
6708       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6709         << var->getType();
6710       return true;
6711     }
6712   }
6713 
6714   return false;
6715 }
6716 
6717 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6718   if (Decl->getType().hasAddressSpace())
6719     return;
6720   if (Decl->getType()->isDependentType())
6721     return;
6722   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6723     QualType Type = Var->getType();
6724     if (Type->isSamplerT() || Type->isVoidType())
6725       return;
6726     LangAS ImplAS = LangAS::opencl_private;
6727     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6728     // __opencl_c_program_scope_global_variables feature, the address space
6729     // for a variable at program scope or a static or extern variable inside
6730     // a function are inferred to be __global.
6731     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6732         Var->hasGlobalStorage())
6733       ImplAS = LangAS::opencl_global;
6734     // If the original type from a decayed type is an array type and that array
6735     // type has no address space yet, deduce it now.
6736     if (auto DT = dyn_cast<DecayedType>(Type)) {
6737       auto OrigTy = DT->getOriginalType();
6738       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6739         // Add the address space to the original array type and then propagate
6740         // that to the element type through `getAsArrayType`.
6741         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6742         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6743         // Re-generate the decayed type.
6744         Type = Context.getDecayedType(OrigTy);
6745       }
6746     }
6747     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6748     // Apply any qualifiers (including address space) from the array type to
6749     // the element type. This implements C99 6.7.3p8: "If the specification of
6750     // an array type includes any type qualifiers, the element type is so
6751     // qualified, not the array type."
6752     if (Type->isArrayType())
6753       Type = QualType(Context.getAsArrayType(Type), 0);
6754     Decl->setType(Type);
6755   }
6756 }
6757 
6758 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6759   // Ensure that an auto decl is deduced otherwise the checks below might cache
6760   // the wrong linkage.
6761   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6762 
6763   // 'weak' only applies to declarations with external linkage.
6764   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6765     if (!ND.isExternallyVisible()) {
6766       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6767       ND.dropAttr<WeakAttr>();
6768     }
6769   }
6770   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6771     if (ND.isExternallyVisible()) {
6772       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6773       ND.dropAttr<WeakRefAttr>();
6774       ND.dropAttr<AliasAttr>();
6775     }
6776   }
6777 
6778   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6779     if (VD->hasInit()) {
6780       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6781         assert(VD->isThisDeclarationADefinition() &&
6782                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6783         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6784         VD->dropAttr<AliasAttr>();
6785       }
6786     }
6787   }
6788 
6789   // 'selectany' only applies to externally visible variable declarations.
6790   // It does not apply to functions.
6791   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6792     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6793       S.Diag(Attr->getLocation(),
6794              diag::err_attribute_selectany_non_extern_data);
6795       ND.dropAttr<SelectAnyAttr>();
6796     }
6797   }
6798 
6799   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6800     auto *VD = dyn_cast<VarDecl>(&ND);
6801     bool IsAnonymousNS = false;
6802     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6803     if (VD) {
6804       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6805       while (NS && !IsAnonymousNS) {
6806         IsAnonymousNS = NS->isAnonymousNamespace();
6807         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6808       }
6809     }
6810     // dll attributes require external linkage. Static locals may have external
6811     // linkage but still cannot be explicitly imported or exported.
6812     // In Microsoft mode, a variable defined in anonymous namespace must have
6813     // external linkage in order to be exported.
6814     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6815     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6816         (!AnonNSInMicrosoftMode &&
6817          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6818       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6819         << &ND << Attr;
6820       ND.setInvalidDecl();
6821     }
6822   }
6823 
6824   // Check the attributes on the function type, if any.
6825   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6826     // Don't declare this variable in the second operand of the for-statement;
6827     // GCC miscompiles that by ending its lifetime before evaluating the
6828     // third operand. See gcc.gnu.org/PR86769.
6829     AttributedTypeLoc ATL;
6830     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6831          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6832          TL = ATL.getModifiedLoc()) {
6833       // The [[lifetimebound]] attribute can be applied to the implicit object
6834       // parameter of a non-static member function (other than a ctor or dtor)
6835       // by applying it to the function type.
6836       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6837         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6838         if (!MD || MD->isStatic()) {
6839           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6840               << !MD << A->getRange();
6841         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6842           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6843               << isa<CXXDestructorDecl>(MD) << A->getRange();
6844         }
6845       }
6846     }
6847   }
6848 }
6849 
6850 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6851                                            NamedDecl *NewDecl,
6852                                            bool IsSpecialization,
6853                                            bool IsDefinition) {
6854   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6855     return;
6856 
6857   bool IsTemplate = false;
6858   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6859     OldDecl = OldTD->getTemplatedDecl();
6860     IsTemplate = true;
6861     if (!IsSpecialization)
6862       IsDefinition = false;
6863   }
6864   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6865     NewDecl = NewTD->getTemplatedDecl();
6866     IsTemplate = true;
6867   }
6868 
6869   if (!OldDecl || !NewDecl)
6870     return;
6871 
6872   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6873   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6874   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6875   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6876 
6877   // dllimport and dllexport are inheritable attributes so we have to exclude
6878   // inherited attribute instances.
6879   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6880                     (NewExportAttr && !NewExportAttr->isInherited());
6881 
6882   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6883   // the only exception being explicit specializations.
6884   // Implicitly generated declarations are also excluded for now because there
6885   // is no other way to switch these to use dllimport or dllexport.
6886   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6887 
6888   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6889     // Allow with a warning for free functions and global variables.
6890     bool JustWarn = false;
6891     if (!OldDecl->isCXXClassMember()) {
6892       auto *VD = dyn_cast<VarDecl>(OldDecl);
6893       if (VD && !VD->getDescribedVarTemplate())
6894         JustWarn = true;
6895       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6896       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6897         JustWarn = true;
6898     }
6899 
6900     // We cannot change a declaration that's been used because IR has already
6901     // been emitted. Dllimported functions will still work though (modulo
6902     // address equality) as they can use the thunk.
6903     if (OldDecl->isUsed())
6904       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6905         JustWarn = false;
6906 
6907     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6908                                : diag::err_attribute_dll_redeclaration;
6909     S.Diag(NewDecl->getLocation(), DiagID)
6910         << NewDecl
6911         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6912     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6913     if (!JustWarn) {
6914       NewDecl->setInvalidDecl();
6915       return;
6916     }
6917   }
6918 
6919   // A redeclaration is not allowed to drop a dllimport attribute, the only
6920   // exceptions being inline function definitions (except for function
6921   // templates), local extern declarations, qualified friend declarations or
6922   // special MSVC extension: in the last case, the declaration is treated as if
6923   // it were marked dllexport.
6924   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6925   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6926   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6927     // Ignore static data because out-of-line definitions are diagnosed
6928     // separately.
6929     IsStaticDataMember = VD->isStaticDataMember();
6930     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6931                    VarDecl::DeclarationOnly;
6932   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6933     IsInline = FD->isInlined();
6934     IsQualifiedFriend = FD->getQualifier() &&
6935                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6936   }
6937 
6938   if (OldImportAttr && !HasNewAttr &&
6939       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6940       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6941     if (IsMicrosoftABI && IsDefinition) {
6942       S.Diag(NewDecl->getLocation(),
6943              diag::warn_redeclaration_without_import_attribute)
6944           << NewDecl;
6945       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6946       NewDecl->dropAttr<DLLImportAttr>();
6947       NewDecl->addAttr(
6948           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6949     } else {
6950       S.Diag(NewDecl->getLocation(),
6951              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6952           << NewDecl << OldImportAttr;
6953       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6954       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6955       OldDecl->dropAttr<DLLImportAttr>();
6956       NewDecl->dropAttr<DLLImportAttr>();
6957     }
6958   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6959     // In MinGW, seeing a function declared inline drops the dllimport
6960     // attribute.
6961     OldDecl->dropAttr<DLLImportAttr>();
6962     NewDecl->dropAttr<DLLImportAttr>();
6963     S.Diag(NewDecl->getLocation(),
6964            diag::warn_dllimport_dropped_from_inline_function)
6965         << NewDecl << OldImportAttr;
6966   }
6967 
6968   // A specialization of a class template member function is processed here
6969   // since it's a redeclaration. If the parent class is dllexport, the
6970   // specialization inherits that attribute. This doesn't happen automatically
6971   // since the parent class isn't instantiated until later.
6972   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6973     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6974         !NewImportAttr && !NewExportAttr) {
6975       if (const DLLExportAttr *ParentExportAttr =
6976               MD->getParent()->getAttr<DLLExportAttr>()) {
6977         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6978         NewAttr->setInherited(true);
6979         NewDecl->addAttr(NewAttr);
6980       }
6981     }
6982   }
6983 }
6984 
6985 /// Given that we are within the definition of the given function,
6986 /// will that definition behave like C99's 'inline', where the
6987 /// definition is discarded except for optimization purposes?
6988 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6989   // Try to avoid calling GetGVALinkageForFunction.
6990 
6991   // All cases of this require the 'inline' keyword.
6992   if (!FD->isInlined()) return false;
6993 
6994   // This is only possible in C++ with the gnu_inline attribute.
6995   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6996     return false;
6997 
6998   // Okay, go ahead and call the relatively-more-expensive function.
6999   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7000 }
7001 
7002 /// Determine whether a variable is extern "C" prior to attaching
7003 /// an initializer. We can't just call isExternC() here, because that
7004 /// will also compute and cache whether the declaration is externally
7005 /// visible, which might change when we attach the initializer.
7006 ///
7007 /// This can only be used if the declaration is known to not be a
7008 /// redeclaration of an internal linkage declaration.
7009 ///
7010 /// For instance:
7011 ///
7012 ///   auto x = []{};
7013 ///
7014 /// Attaching the initializer here makes this declaration not externally
7015 /// visible, because its type has internal linkage.
7016 ///
7017 /// FIXME: This is a hack.
7018 template<typename T>
7019 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7020   if (S.getLangOpts().CPlusPlus) {
7021     // In C++, the overloadable attribute negates the effects of extern "C".
7022     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7023       return false;
7024 
7025     // So do CUDA's host/device attributes.
7026     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7027                                  D->template hasAttr<CUDAHostAttr>()))
7028       return false;
7029   }
7030   return D->isExternC();
7031 }
7032 
7033 static bool shouldConsiderLinkage(const VarDecl *VD) {
7034   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7035   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7036       isa<OMPDeclareMapperDecl>(DC))
7037     return VD->hasExternalStorage();
7038   if (DC->isFileContext())
7039     return true;
7040   if (DC->isRecord())
7041     return false;
7042   if (isa<RequiresExprBodyDecl>(DC))
7043     return false;
7044   llvm_unreachable("Unexpected context");
7045 }
7046 
7047 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7048   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7049   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7050       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7051     return true;
7052   if (DC->isRecord())
7053     return false;
7054   llvm_unreachable("Unexpected context");
7055 }
7056 
7057 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7058                           ParsedAttr::Kind Kind) {
7059   // Check decl attributes on the DeclSpec.
7060   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7061     return true;
7062 
7063   // Walk the declarator structure, checking decl attributes that were in a type
7064   // position to the decl itself.
7065   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7066     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7067       return true;
7068   }
7069 
7070   // Finally, check attributes on the decl itself.
7071   return PD.getAttributes().hasAttribute(Kind) ||
7072          PD.getDeclarationAttributes().hasAttribute(Kind);
7073 }
7074 
7075 /// Adjust the \c DeclContext for a function or variable that might be a
7076 /// function-local external declaration.
7077 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7078   if (!DC->isFunctionOrMethod())
7079     return false;
7080 
7081   // If this is a local extern function or variable declared within a function
7082   // template, don't add it into the enclosing namespace scope until it is
7083   // instantiated; it might have a dependent type right now.
7084   if (DC->isDependentContext())
7085     return true;
7086 
7087   // C++11 [basic.link]p7:
7088   //   When a block scope declaration of an entity with linkage is not found to
7089   //   refer to some other declaration, then that entity is a member of the
7090   //   innermost enclosing namespace.
7091   //
7092   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7093   // semantically-enclosing namespace, not a lexically-enclosing one.
7094   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7095     DC = DC->getParent();
7096   return true;
7097 }
7098 
7099 /// Returns true if given declaration has external C language linkage.
7100 static bool isDeclExternC(const Decl *D) {
7101   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7102     return FD->isExternC();
7103   if (const auto *VD = dyn_cast<VarDecl>(D))
7104     return VD->isExternC();
7105 
7106   llvm_unreachable("Unknown type of decl!");
7107 }
7108 
7109 /// Returns true if there hasn't been any invalid type diagnosed.
7110 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7111   DeclContext *DC = NewVD->getDeclContext();
7112   QualType R = NewVD->getType();
7113 
7114   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7115   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7116   // argument.
7117   if (R->isImageType() || R->isPipeType()) {
7118     Se.Diag(NewVD->getLocation(),
7119             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7120         << R;
7121     NewVD->setInvalidDecl();
7122     return false;
7123   }
7124 
7125   // OpenCL v1.2 s6.9.r:
7126   // The event type cannot be used to declare a program scope variable.
7127   // OpenCL v2.0 s6.9.q:
7128   // The clk_event_t and reserve_id_t types cannot be declared in program
7129   // scope.
7130   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7131     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7132       Se.Diag(NewVD->getLocation(),
7133               diag::err_invalid_type_for_program_scope_var)
7134           << R;
7135       NewVD->setInvalidDecl();
7136       return false;
7137     }
7138   }
7139 
7140   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7141   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7142                                                Se.getLangOpts())) {
7143     QualType NR = R.getCanonicalType();
7144     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7145            NR->isReferenceType()) {
7146       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7147           NR->isFunctionReferenceType()) {
7148         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7149             << NR->isReferenceType();
7150         NewVD->setInvalidDecl();
7151         return false;
7152       }
7153       NR = NR->getPointeeType();
7154     }
7155   }
7156 
7157   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7158                                                Se.getLangOpts())) {
7159     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7160     // half array type (unless the cl_khr_fp16 extension is enabled).
7161     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7162       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7163       NewVD->setInvalidDecl();
7164       return false;
7165     }
7166   }
7167 
7168   // OpenCL v1.2 s6.9.r:
7169   // The event type cannot be used with the __local, __constant and __global
7170   // address space qualifiers.
7171   if (R->isEventT()) {
7172     if (R.getAddressSpace() != LangAS::opencl_private) {
7173       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7174       NewVD->setInvalidDecl();
7175       return false;
7176     }
7177   }
7178 
7179   if (R->isSamplerT()) {
7180     // OpenCL v1.2 s6.9.b p4:
7181     // The sampler type cannot be used with the __local and __global address
7182     // space qualifiers.
7183     if (R.getAddressSpace() == LangAS::opencl_local ||
7184         R.getAddressSpace() == LangAS::opencl_global) {
7185       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7186       NewVD->setInvalidDecl();
7187     }
7188 
7189     // OpenCL v1.2 s6.12.14.1:
7190     // A global sampler must be declared with either the constant address
7191     // space qualifier or with the const qualifier.
7192     if (DC->isTranslationUnit() &&
7193         !(R.getAddressSpace() == LangAS::opencl_constant ||
7194           R.isConstQualified())) {
7195       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7196       NewVD->setInvalidDecl();
7197     }
7198     if (NewVD->isInvalidDecl())
7199       return false;
7200   }
7201 
7202   return true;
7203 }
7204 
7205 template <typename AttrTy>
7206 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7207   const TypedefNameDecl *TND = TT->getDecl();
7208   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7209     AttrTy *Clone = Attribute->clone(S.Context);
7210     Clone->setInherited(true);
7211     D->addAttr(Clone);
7212   }
7213 }
7214 
7215 NamedDecl *Sema::ActOnVariableDeclarator(
7216     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7217     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7218     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7219   QualType R = TInfo->getType();
7220   DeclarationName Name = GetNameForDeclarator(D).getName();
7221 
7222   IdentifierInfo *II = Name.getAsIdentifierInfo();
7223 
7224   if (D.isDecompositionDeclarator()) {
7225     // Take the name of the first declarator as our name for diagnostic
7226     // purposes.
7227     auto &Decomp = D.getDecompositionDeclarator();
7228     if (!Decomp.bindings().empty()) {
7229       II = Decomp.bindings()[0].Name;
7230       Name = II;
7231     }
7232   } else if (!II) {
7233     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7234     return nullptr;
7235   }
7236 
7237 
7238   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7239   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7240 
7241   // dllimport globals without explicit storage class are treated as extern. We
7242   // have to change the storage class this early to get the right DeclContext.
7243   if (SC == SC_None && !DC->isRecord() &&
7244       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7245       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7246     SC = SC_Extern;
7247 
7248   DeclContext *OriginalDC = DC;
7249   bool IsLocalExternDecl = SC == SC_Extern &&
7250                            adjustContextForLocalExternDecl(DC);
7251 
7252   if (SCSpec == DeclSpec::SCS_mutable) {
7253     // mutable can only appear on non-static class members, so it's always
7254     // an error here
7255     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7256     D.setInvalidType();
7257     SC = SC_None;
7258   }
7259 
7260   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7261       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7262                               D.getDeclSpec().getStorageClassSpecLoc())) {
7263     // In C++11, the 'register' storage class specifier is deprecated.
7264     // Suppress the warning in system macros, it's used in macros in some
7265     // popular C system headers, such as in glibc's htonl() macro.
7266     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7267          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7268                                    : diag::warn_deprecated_register)
7269       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7270   }
7271 
7272   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7273 
7274   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7275     // C99 6.9p2: The storage-class specifiers auto and register shall not
7276     // appear in the declaration specifiers in an external declaration.
7277     // Global Register+Asm is a GNU extension we support.
7278     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7279       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7280       D.setInvalidType();
7281     }
7282   }
7283 
7284   // If this variable has a VLA type and an initializer, try to
7285   // fold to a constant-sized type. This is otherwise invalid.
7286   if (D.hasInitializer() && R->isVariableArrayType())
7287     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7288                                     /*DiagID=*/0);
7289 
7290   bool IsMemberSpecialization = false;
7291   bool IsVariableTemplateSpecialization = false;
7292   bool IsPartialSpecialization = false;
7293   bool IsVariableTemplate = false;
7294   VarDecl *NewVD = nullptr;
7295   VarTemplateDecl *NewTemplate = nullptr;
7296   TemplateParameterList *TemplateParams = nullptr;
7297   if (!getLangOpts().CPlusPlus) {
7298     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7299                             II, R, TInfo, SC);
7300 
7301     if (R->getContainedDeducedType())
7302       ParsingInitForAutoVars.insert(NewVD);
7303 
7304     if (D.isInvalidType())
7305       NewVD->setInvalidDecl();
7306 
7307     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7308         NewVD->hasLocalStorage())
7309       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7310                             NTCUC_AutoVar, NTCUK_Destruct);
7311   } else {
7312     bool Invalid = false;
7313 
7314     if (DC->isRecord() && !CurContext->isRecord()) {
7315       // This is an out-of-line definition of a static data member.
7316       switch (SC) {
7317       case SC_None:
7318         break;
7319       case SC_Static:
7320         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7321              diag::err_static_out_of_line)
7322           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7323         break;
7324       case SC_Auto:
7325       case SC_Register:
7326       case SC_Extern:
7327         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7328         // to names of variables declared in a block or to function parameters.
7329         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7330         // of class members
7331 
7332         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7333              diag::err_storage_class_for_static_member)
7334           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7335         break;
7336       case SC_PrivateExtern:
7337         llvm_unreachable("C storage class in c++!");
7338       }
7339     }
7340 
7341     if (SC == SC_Static && CurContext->isRecord()) {
7342       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7343         // Walk up the enclosing DeclContexts to check for any that are
7344         // incompatible with static data members.
7345         const DeclContext *FunctionOrMethod = nullptr;
7346         const CXXRecordDecl *AnonStruct = nullptr;
7347         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7348           if (Ctxt->isFunctionOrMethod()) {
7349             FunctionOrMethod = Ctxt;
7350             break;
7351           }
7352           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7353           if (ParentDecl && !ParentDecl->getDeclName()) {
7354             AnonStruct = ParentDecl;
7355             break;
7356           }
7357         }
7358         if (FunctionOrMethod) {
7359           // C++ [class.static.data]p5: A local class shall not have static data
7360           // members.
7361           Diag(D.getIdentifierLoc(),
7362                diag::err_static_data_member_not_allowed_in_local_class)
7363             << Name << RD->getDeclName() << RD->getTagKind();
7364         } else if (AnonStruct) {
7365           // C++ [class.static.data]p4: Unnamed classes and classes contained
7366           // directly or indirectly within unnamed classes shall not contain
7367           // static data members.
7368           Diag(D.getIdentifierLoc(),
7369                diag::err_static_data_member_not_allowed_in_anon_struct)
7370             << Name << AnonStruct->getTagKind();
7371           Invalid = true;
7372         } else if (RD->isUnion()) {
7373           // C++98 [class.union]p1: If a union contains a static data member,
7374           // the program is ill-formed. C++11 drops this restriction.
7375           Diag(D.getIdentifierLoc(),
7376                getLangOpts().CPlusPlus11
7377                  ? diag::warn_cxx98_compat_static_data_member_in_union
7378                  : diag::ext_static_data_member_in_union) << Name;
7379         }
7380       }
7381     }
7382 
7383     // Match up the template parameter lists with the scope specifier, then
7384     // determine whether we have a template or a template specialization.
7385     bool InvalidScope = false;
7386     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7387         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7388         D.getCXXScopeSpec(),
7389         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7390             ? D.getName().TemplateId
7391             : nullptr,
7392         TemplateParamLists,
7393         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7394     Invalid |= InvalidScope;
7395 
7396     if (TemplateParams) {
7397       if (!TemplateParams->size() &&
7398           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7399         // There is an extraneous 'template<>' for this variable. Complain
7400         // about it, but allow the declaration of the variable.
7401         Diag(TemplateParams->getTemplateLoc(),
7402              diag::err_template_variable_noparams)
7403           << II
7404           << SourceRange(TemplateParams->getTemplateLoc(),
7405                          TemplateParams->getRAngleLoc());
7406         TemplateParams = nullptr;
7407       } else {
7408         // Check that we can declare a template here.
7409         if (CheckTemplateDeclScope(S, TemplateParams))
7410           return nullptr;
7411 
7412         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7413           // This is an explicit specialization or a partial specialization.
7414           IsVariableTemplateSpecialization = true;
7415           IsPartialSpecialization = TemplateParams->size() > 0;
7416         } else { // if (TemplateParams->size() > 0)
7417           // This is a template declaration.
7418           IsVariableTemplate = true;
7419 
7420           // Only C++1y supports variable templates (N3651).
7421           Diag(D.getIdentifierLoc(),
7422                getLangOpts().CPlusPlus14
7423                    ? diag::warn_cxx11_compat_variable_template
7424                    : diag::ext_variable_template);
7425         }
7426       }
7427     } else {
7428       // Check that we can declare a member specialization here.
7429       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7430           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7431         return nullptr;
7432       assert((Invalid ||
7433               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7434              "should have a 'template<>' for this decl");
7435     }
7436 
7437     if (IsVariableTemplateSpecialization) {
7438       SourceLocation TemplateKWLoc =
7439           TemplateParamLists.size() > 0
7440               ? TemplateParamLists[0]->getTemplateLoc()
7441               : SourceLocation();
7442       DeclResult Res = ActOnVarTemplateSpecialization(
7443           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7444           IsPartialSpecialization);
7445       if (Res.isInvalid())
7446         return nullptr;
7447       NewVD = cast<VarDecl>(Res.get());
7448       AddToScope = false;
7449     } else if (D.isDecompositionDeclarator()) {
7450       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7451                                         D.getIdentifierLoc(), R, TInfo, SC,
7452                                         Bindings);
7453     } else
7454       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7455                               D.getIdentifierLoc(), II, R, TInfo, SC);
7456 
7457     // If this is supposed to be a variable template, create it as such.
7458     if (IsVariableTemplate) {
7459       NewTemplate =
7460           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7461                                   TemplateParams, NewVD);
7462       NewVD->setDescribedVarTemplate(NewTemplate);
7463     }
7464 
7465     // If this decl has an auto type in need of deduction, make a note of the
7466     // Decl so we can diagnose uses of it in its own initializer.
7467     if (R->getContainedDeducedType())
7468       ParsingInitForAutoVars.insert(NewVD);
7469 
7470     if (D.isInvalidType() || Invalid) {
7471       NewVD->setInvalidDecl();
7472       if (NewTemplate)
7473         NewTemplate->setInvalidDecl();
7474     }
7475 
7476     SetNestedNameSpecifier(*this, NewVD, D);
7477 
7478     // If we have any template parameter lists that don't directly belong to
7479     // the variable (matching the scope specifier), store them.
7480     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7481     if (TemplateParamLists.size() > VDTemplateParamLists)
7482       NewVD->setTemplateParameterListsInfo(
7483           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7484   }
7485 
7486   if (D.getDeclSpec().isInlineSpecified()) {
7487     if (!getLangOpts().CPlusPlus) {
7488       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7489           << 0;
7490     } else if (CurContext->isFunctionOrMethod()) {
7491       // 'inline' is not allowed on block scope variable declaration.
7492       Diag(D.getDeclSpec().getInlineSpecLoc(),
7493            diag::err_inline_declaration_block_scope) << Name
7494         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7495     } else {
7496       Diag(D.getDeclSpec().getInlineSpecLoc(),
7497            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7498                                      : diag::ext_inline_variable);
7499       NewVD->setInlineSpecified();
7500     }
7501   }
7502 
7503   // Set the lexical context. If the declarator has a C++ scope specifier, the
7504   // lexical context will be different from the semantic context.
7505   NewVD->setLexicalDeclContext(CurContext);
7506   if (NewTemplate)
7507     NewTemplate->setLexicalDeclContext(CurContext);
7508 
7509   if (IsLocalExternDecl) {
7510     if (D.isDecompositionDeclarator())
7511       for (auto *B : Bindings)
7512         B->setLocalExternDecl();
7513     else
7514       NewVD->setLocalExternDecl();
7515   }
7516 
7517   bool EmitTLSUnsupportedError = false;
7518   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7519     // C++11 [dcl.stc]p4:
7520     //   When thread_local is applied to a variable of block scope the
7521     //   storage-class-specifier static is implied if it does not appear
7522     //   explicitly.
7523     // Core issue: 'static' is not implied if the variable is declared
7524     //   'extern'.
7525     if (NewVD->hasLocalStorage() &&
7526         (SCSpec != DeclSpec::SCS_unspecified ||
7527          TSCS != DeclSpec::TSCS_thread_local ||
7528          !DC->isFunctionOrMethod()))
7529       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7530            diag::err_thread_non_global)
7531         << DeclSpec::getSpecifierName(TSCS);
7532     else if (!Context.getTargetInfo().isTLSSupported()) {
7533       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7534           getLangOpts().SYCLIsDevice) {
7535         // Postpone error emission until we've collected attributes required to
7536         // figure out whether it's a host or device variable and whether the
7537         // error should be ignored.
7538         EmitTLSUnsupportedError = true;
7539         // We still need to mark the variable as TLS so it shows up in AST with
7540         // proper storage class for other tools to use even if we're not going
7541         // to emit any code for it.
7542         NewVD->setTSCSpec(TSCS);
7543       } else
7544         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7545              diag::err_thread_unsupported);
7546     } else
7547       NewVD->setTSCSpec(TSCS);
7548   }
7549 
7550   switch (D.getDeclSpec().getConstexprSpecifier()) {
7551   case ConstexprSpecKind::Unspecified:
7552     break;
7553 
7554   case ConstexprSpecKind::Consteval:
7555     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7556          diag::err_constexpr_wrong_decl_kind)
7557         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7558     LLVM_FALLTHROUGH;
7559 
7560   case ConstexprSpecKind::Constexpr:
7561     NewVD->setConstexpr(true);
7562     // C++1z [dcl.spec.constexpr]p1:
7563     //   A static data member declared with the constexpr specifier is
7564     //   implicitly an inline variable.
7565     if (NewVD->isStaticDataMember() &&
7566         (getLangOpts().CPlusPlus17 ||
7567          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7568       NewVD->setImplicitlyInline();
7569     break;
7570 
7571   case ConstexprSpecKind::Constinit:
7572     if (!NewVD->hasGlobalStorage())
7573       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7574            diag::err_constinit_local_variable);
7575     else
7576       NewVD->addAttr(ConstInitAttr::Create(
7577           Context, D.getDeclSpec().getConstexprSpecLoc(),
7578           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7579     break;
7580   }
7581 
7582   // C99 6.7.4p3
7583   //   An inline definition of a function with external linkage shall
7584   //   not contain a definition of a modifiable object with static or
7585   //   thread storage duration...
7586   // We only apply this when the function is required to be defined
7587   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7588   // that a local variable with thread storage duration still has to
7589   // be marked 'static'.  Also note that it's possible to get these
7590   // semantics in C++ using __attribute__((gnu_inline)).
7591   if (SC == SC_Static && S->getFnParent() != nullptr &&
7592       !NewVD->getType().isConstQualified()) {
7593     FunctionDecl *CurFD = getCurFunctionDecl();
7594     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7595       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7596            diag::warn_static_local_in_extern_inline);
7597       MaybeSuggestAddingStaticToDecl(CurFD);
7598     }
7599   }
7600 
7601   if (D.getDeclSpec().isModulePrivateSpecified()) {
7602     if (IsVariableTemplateSpecialization)
7603       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7604           << (IsPartialSpecialization ? 1 : 0)
7605           << FixItHint::CreateRemoval(
7606                  D.getDeclSpec().getModulePrivateSpecLoc());
7607     else if (IsMemberSpecialization)
7608       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7609         << 2
7610         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7611     else if (NewVD->hasLocalStorage())
7612       Diag(NewVD->getLocation(), diag::err_module_private_local)
7613           << 0 << NewVD
7614           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7615           << FixItHint::CreateRemoval(
7616                  D.getDeclSpec().getModulePrivateSpecLoc());
7617     else {
7618       NewVD->setModulePrivate();
7619       if (NewTemplate)
7620         NewTemplate->setModulePrivate();
7621       for (auto *B : Bindings)
7622         B->setModulePrivate();
7623     }
7624   }
7625 
7626   if (getLangOpts().OpenCL) {
7627     deduceOpenCLAddressSpace(NewVD);
7628 
7629     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7630     if (TSC != TSCS_unspecified) {
7631       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7632            diag::err_opencl_unknown_type_specifier)
7633           << getLangOpts().getOpenCLVersionString()
7634           << DeclSpec::getSpecifierName(TSC) << 1;
7635       NewVD->setInvalidDecl();
7636     }
7637   }
7638 
7639   // Handle attributes prior to checking for duplicates in MergeVarDecl
7640   ProcessDeclAttributes(S, NewVD, D);
7641 
7642   // FIXME: This is probably the wrong location to be doing this and we should
7643   // probably be doing this for more attributes (especially for function
7644   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7645   // the code to copy attributes would be generated by TableGen.
7646   if (R->isFunctionPointerType())
7647     if (const auto *TT = R->getAs<TypedefType>())
7648       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7649 
7650   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7651       getLangOpts().SYCLIsDevice) {
7652     if (EmitTLSUnsupportedError &&
7653         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7654          (getLangOpts().OpenMPIsDevice &&
7655           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7656       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7657            diag::err_thread_unsupported);
7658 
7659     if (EmitTLSUnsupportedError &&
7660         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7661       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7662     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7663     // storage [duration]."
7664     if (SC == SC_None && S->getFnParent() != nullptr &&
7665         (NewVD->hasAttr<CUDASharedAttr>() ||
7666          NewVD->hasAttr<CUDAConstantAttr>())) {
7667       NewVD->setStorageClass(SC_Static);
7668     }
7669   }
7670 
7671   // Ensure that dllimport globals without explicit storage class are treated as
7672   // extern. The storage class is set above using parsed attributes. Now we can
7673   // check the VarDecl itself.
7674   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7675          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7676          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7677 
7678   // In auto-retain/release, infer strong retension for variables of
7679   // retainable type.
7680   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7681     NewVD->setInvalidDecl();
7682 
7683   // Handle GNU asm-label extension (encoded as an attribute).
7684   if (Expr *E = (Expr*)D.getAsmLabel()) {
7685     // The parser guarantees this is a string.
7686     StringLiteral *SE = cast<StringLiteral>(E);
7687     StringRef Label = SE->getString();
7688     if (S->getFnParent() != nullptr) {
7689       switch (SC) {
7690       case SC_None:
7691       case SC_Auto:
7692         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7693         break;
7694       case SC_Register:
7695         // Local Named register
7696         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7697             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7698           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7699         break;
7700       case SC_Static:
7701       case SC_Extern:
7702       case SC_PrivateExtern:
7703         break;
7704       }
7705     } else if (SC == SC_Register) {
7706       // Global Named register
7707       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7708         const auto &TI = Context.getTargetInfo();
7709         bool HasSizeMismatch;
7710 
7711         if (!TI.isValidGCCRegisterName(Label))
7712           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7713         else if (!TI.validateGlobalRegisterVariable(Label,
7714                                                     Context.getTypeSize(R),
7715                                                     HasSizeMismatch))
7716           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7717         else if (HasSizeMismatch)
7718           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7719       }
7720 
7721       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7722         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7723         NewVD->setInvalidDecl(true);
7724       }
7725     }
7726 
7727     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7728                                         /*IsLiteralLabel=*/true,
7729                                         SE->getStrTokenLoc(0)));
7730   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7731     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7732       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7733     if (I != ExtnameUndeclaredIdentifiers.end()) {
7734       if (isDeclExternC(NewVD)) {
7735         NewVD->addAttr(I->second);
7736         ExtnameUndeclaredIdentifiers.erase(I);
7737       } else
7738         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7739             << /*Variable*/1 << NewVD;
7740     }
7741   }
7742 
7743   // Find the shadowed declaration before filtering for scope.
7744   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7745                                 ? getShadowedDeclaration(NewVD, Previous)
7746                                 : nullptr;
7747 
7748   // Don't consider existing declarations that are in a different
7749   // scope and are out-of-semantic-context declarations (if the new
7750   // declaration has linkage).
7751   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7752                        D.getCXXScopeSpec().isNotEmpty() ||
7753                        IsMemberSpecialization ||
7754                        IsVariableTemplateSpecialization);
7755 
7756   // Check whether the previous declaration is in the same block scope. This
7757   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7758   if (getLangOpts().CPlusPlus &&
7759       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7760     NewVD->setPreviousDeclInSameBlockScope(
7761         Previous.isSingleResult() && !Previous.isShadowed() &&
7762         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7763 
7764   if (!getLangOpts().CPlusPlus) {
7765     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7766   } else {
7767     // If this is an explicit specialization of a static data member, check it.
7768     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7769         CheckMemberSpecialization(NewVD, Previous))
7770       NewVD->setInvalidDecl();
7771 
7772     // Merge the decl with the existing one if appropriate.
7773     if (!Previous.empty()) {
7774       if (Previous.isSingleResult() &&
7775           isa<FieldDecl>(Previous.getFoundDecl()) &&
7776           D.getCXXScopeSpec().isSet()) {
7777         // The user tried to define a non-static data member
7778         // out-of-line (C++ [dcl.meaning]p1).
7779         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7780           << D.getCXXScopeSpec().getRange();
7781         Previous.clear();
7782         NewVD->setInvalidDecl();
7783       }
7784     } else if (D.getCXXScopeSpec().isSet()) {
7785       // No previous declaration in the qualifying scope.
7786       Diag(D.getIdentifierLoc(), diag::err_no_member)
7787         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7788         << D.getCXXScopeSpec().getRange();
7789       NewVD->setInvalidDecl();
7790     }
7791 
7792     if (!IsVariableTemplateSpecialization)
7793       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7794 
7795     if (NewTemplate) {
7796       VarTemplateDecl *PrevVarTemplate =
7797           NewVD->getPreviousDecl()
7798               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7799               : nullptr;
7800 
7801       // Check the template parameter list of this declaration, possibly
7802       // merging in the template parameter list from the previous variable
7803       // template declaration.
7804       if (CheckTemplateParameterList(
7805               TemplateParams,
7806               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7807                               : nullptr,
7808               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7809                DC->isDependentContext())
7810                   ? TPC_ClassTemplateMember
7811                   : TPC_VarTemplate))
7812         NewVD->setInvalidDecl();
7813 
7814       // If we are providing an explicit specialization of a static variable
7815       // template, make a note of that.
7816       if (PrevVarTemplate &&
7817           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7818         PrevVarTemplate->setMemberSpecialization();
7819     }
7820   }
7821 
7822   // Diagnose shadowed variables iff this isn't a redeclaration.
7823   if (ShadowedDecl && !D.isRedeclaration())
7824     CheckShadow(NewVD, ShadowedDecl, Previous);
7825 
7826   ProcessPragmaWeak(S, NewVD);
7827 
7828   // If this is the first declaration of an extern C variable, update
7829   // the map of such variables.
7830   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7831       isIncompleteDeclExternC(*this, NewVD))
7832     RegisterLocallyScopedExternCDecl(NewVD, S);
7833 
7834   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7835     MangleNumberingContext *MCtx;
7836     Decl *ManglingContextDecl;
7837     std::tie(MCtx, ManglingContextDecl) =
7838         getCurrentMangleNumberContext(NewVD->getDeclContext());
7839     if (MCtx) {
7840       Context.setManglingNumber(
7841           NewVD, MCtx->getManglingNumber(
7842                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7843       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7844     }
7845   }
7846 
7847   // Special handling of variable named 'main'.
7848   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7849       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7850       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7851 
7852     // C++ [basic.start.main]p3
7853     // A program that declares a variable main at global scope is ill-formed.
7854     if (getLangOpts().CPlusPlus)
7855       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7856 
7857     // In C, and external-linkage variable named main results in undefined
7858     // behavior.
7859     else if (NewVD->hasExternalFormalLinkage())
7860       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7861   }
7862 
7863   if (D.isRedeclaration() && !Previous.empty()) {
7864     NamedDecl *Prev = Previous.getRepresentativeDecl();
7865     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7866                                    D.isFunctionDefinition());
7867   }
7868 
7869   if (NewTemplate) {
7870     if (NewVD->isInvalidDecl())
7871       NewTemplate->setInvalidDecl();
7872     ActOnDocumentableDecl(NewTemplate);
7873     return NewTemplate;
7874   }
7875 
7876   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7877     CompleteMemberSpecialization(NewVD, Previous);
7878 
7879   return NewVD;
7880 }
7881 
7882 /// Enum describing the %select options in diag::warn_decl_shadow.
7883 enum ShadowedDeclKind {
7884   SDK_Local,
7885   SDK_Global,
7886   SDK_StaticMember,
7887   SDK_Field,
7888   SDK_Typedef,
7889   SDK_Using,
7890   SDK_StructuredBinding
7891 };
7892 
7893 /// Determine what kind of declaration we're shadowing.
7894 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7895                                                 const DeclContext *OldDC) {
7896   if (isa<TypeAliasDecl>(ShadowedDecl))
7897     return SDK_Using;
7898   else if (isa<TypedefDecl>(ShadowedDecl))
7899     return SDK_Typedef;
7900   else if (isa<BindingDecl>(ShadowedDecl))
7901     return SDK_StructuredBinding;
7902   else if (isa<RecordDecl>(OldDC))
7903     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7904 
7905   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7906 }
7907 
7908 /// Return the location of the capture if the given lambda captures the given
7909 /// variable \p VD, or an invalid source location otherwise.
7910 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7911                                          const VarDecl *VD) {
7912   for (const Capture &Capture : LSI->Captures) {
7913     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7914       return Capture.getLocation();
7915   }
7916   return SourceLocation();
7917 }
7918 
7919 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7920                                      const LookupResult &R) {
7921   // Only diagnose if we're shadowing an unambiguous field or variable.
7922   if (R.getResultKind() != LookupResult::Found)
7923     return false;
7924 
7925   // Return false if warning is ignored.
7926   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7927 }
7928 
7929 /// Return the declaration shadowed by the given variable \p D, or null
7930 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7931 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7932                                         const LookupResult &R) {
7933   if (!shouldWarnIfShadowedDecl(Diags, R))
7934     return nullptr;
7935 
7936   // Don't diagnose declarations at file scope.
7937   if (D->hasGlobalStorage())
7938     return nullptr;
7939 
7940   NamedDecl *ShadowedDecl = R.getFoundDecl();
7941   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7942                                                             : nullptr;
7943 }
7944 
7945 /// Return the declaration shadowed by the given typedef \p D, or null
7946 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7947 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7948                                         const LookupResult &R) {
7949   // Don't warn if typedef declaration is part of a class
7950   if (D->getDeclContext()->isRecord())
7951     return nullptr;
7952 
7953   if (!shouldWarnIfShadowedDecl(Diags, R))
7954     return nullptr;
7955 
7956   NamedDecl *ShadowedDecl = R.getFoundDecl();
7957   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7958 }
7959 
7960 /// Return the declaration shadowed by the given variable \p D, or null
7961 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7962 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7963                                         const LookupResult &R) {
7964   if (!shouldWarnIfShadowedDecl(Diags, R))
7965     return nullptr;
7966 
7967   NamedDecl *ShadowedDecl = R.getFoundDecl();
7968   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7969                                                             : nullptr;
7970 }
7971 
7972 /// Diagnose variable or built-in function shadowing.  Implements
7973 /// -Wshadow.
7974 ///
7975 /// This method is called whenever a VarDecl is added to a "useful"
7976 /// scope.
7977 ///
7978 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7979 /// \param R the lookup of the name
7980 ///
7981 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7982                        const LookupResult &R) {
7983   DeclContext *NewDC = D->getDeclContext();
7984 
7985   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7986     // Fields are not shadowed by variables in C++ static methods.
7987     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7988       if (MD->isStatic())
7989         return;
7990 
7991     // Fields shadowed by constructor parameters are a special case. Usually
7992     // the constructor initializes the field with the parameter.
7993     if (isa<CXXConstructorDecl>(NewDC))
7994       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7995         // Remember that this was shadowed so we can either warn about its
7996         // modification or its existence depending on warning settings.
7997         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7998         return;
7999       }
8000   }
8001 
8002   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8003     if (shadowedVar->isExternC()) {
8004       // For shadowing external vars, make sure that we point to the global
8005       // declaration, not a locally scoped extern declaration.
8006       for (auto I : shadowedVar->redecls())
8007         if (I->isFileVarDecl()) {
8008           ShadowedDecl = I;
8009           break;
8010         }
8011     }
8012 
8013   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8014 
8015   unsigned WarningDiag = diag::warn_decl_shadow;
8016   SourceLocation CaptureLoc;
8017   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8018       isa<CXXMethodDecl>(NewDC)) {
8019     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8020       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8021         if (RD->getLambdaCaptureDefault() == LCD_None) {
8022           // Try to avoid warnings for lambdas with an explicit capture list.
8023           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8024           // Warn only when the lambda captures the shadowed decl explicitly.
8025           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8026           if (CaptureLoc.isInvalid())
8027             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8028         } else {
8029           // Remember that this was shadowed so we can avoid the warning if the
8030           // shadowed decl isn't captured and the warning settings allow it.
8031           cast<LambdaScopeInfo>(getCurFunction())
8032               ->ShadowingDecls.push_back(
8033                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8034           return;
8035         }
8036       }
8037 
8038       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8039         // A variable can't shadow a local variable in an enclosing scope, if
8040         // they are separated by a non-capturing declaration context.
8041         for (DeclContext *ParentDC = NewDC;
8042              ParentDC && !ParentDC->Equals(OldDC);
8043              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8044           // Only block literals, captured statements, and lambda expressions
8045           // can capture; other scopes don't.
8046           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8047               !isLambdaCallOperator(ParentDC)) {
8048             return;
8049           }
8050         }
8051       }
8052     }
8053   }
8054 
8055   // Only warn about certain kinds of shadowing for class members.
8056   if (NewDC && NewDC->isRecord()) {
8057     // In particular, don't warn about shadowing non-class members.
8058     if (!OldDC->isRecord())
8059       return;
8060 
8061     // TODO: should we warn about static data members shadowing
8062     // static data members from base classes?
8063 
8064     // TODO: don't diagnose for inaccessible shadowed members.
8065     // This is hard to do perfectly because we might friend the
8066     // shadowing context, but that's just a false negative.
8067   }
8068 
8069 
8070   DeclarationName Name = R.getLookupName();
8071 
8072   // Emit warning and note.
8073   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8074   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8075   if (!CaptureLoc.isInvalid())
8076     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8077         << Name << /*explicitly*/ 1;
8078   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8079 }
8080 
8081 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8082 /// when these variables are captured by the lambda.
8083 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8084   for (const auto &Shadow : LSI->ShadowingDecls) {
8085     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8086     // Try to avoid the warning when the shadowed decl isn't captured.
8087     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8088     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8089     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8090                                        ? diag::warn_decl_shadow_uncaptured_local
8091                                        : diag::warn_decl_shadow)
8092         << Shadow.VD->getDeclName()
8093         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8094     if (!CaptureLoc.isInvalid())
8095       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8096           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8097     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8098   }
8099 }
8100 
8101 /// Check -Wshadow without the advantage of a previous lookup.
8102 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8103   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8104     return;
8105 
8106   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8107                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8108   LookupName(R, S);
8109   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8110     CheckShadow(D, ShadowedDecl, R);
8111 }
8112 
8113 /// Check if 'E', which is an expression that is about to be modified, refers
8114 /// to a constructor parameter that shadows a field.
8115 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8116   // Quickly ignore expressions that can't be shadowing ctor parameters.
8117   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8118     return;
8119   E = E->IgnoreParenImpCasts();
8120   auto *DRE = dyn_cast<DeclRefExpr>(E);
8121   if (!DRE)
8122     return;
8123   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8124   auto I = ShadowingDecls.find(D);
8125   if (I == ShadowingDecls.end())
8126     return;
8127   const NamedDecl *ShadowedDecl = I->second;
8128   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8129   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8130   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8131   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8132 
8133   // Avoid issuing multiple warnings about the same decl.
8134   ShadowingDecls.erase(I);
8135 }
8136 
8137 /// Check for conflict between this global or extern "C" declaration and
8138 /// previous global or extern "C" declarations. This is only used in C++.
8139 template<typename T>
8140 static bool checkGlobalOrExternCConflict(
8141     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8142   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8143   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8144 
8145   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8146     // The common case: this global doesn't conflict with any extern "C"
8147     // declaration.
8148     return false;
8149   }
8150 
8151   if (Prev) {
8152     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8153       // Both the old and new declarations have C language linkage. This is a
8154       // redeclaration.
8155       Previous.clear();
8156       Previous.addDecl(Prev);
8157       return true;
8158     }
8159 
8160     // This is a global, non-extern "C" declaration, and there is a previous
8161     // non-global extern "C" declaration. Diagnose if this is a variable
8162     // declaration.
8163     if (!isa<VarDecl>(ND))
8164       return false;
8165   } else {
8166     // The declaration is extern "C". Check for any declaration in the
8167     // translation unit which might conflict.
8168     if (IsGlobal) {
8169       // We have already performed the lookup into the translation unit.
8170       IsGlobal = false;
8171       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8172            I != E; ++I) {
8173         if (isa<VarDecl>(*I)) {
8174           Prev = *I;
8175           break;
8176         }
8177       }
8178     } else {
8179       DeclContext::lookup_result R =
8180           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8181       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8182            I != E; ++I) {
8183         if (isa<VarDecl>(*I)) {
8184           Prev = *I;
8185           break;
8186         }
8187         // FIXME: If we have any other entity with this name in global scope,
8188         // the declaration is ill-formed, but that is a defect: it breaks the
8189         // 'stat' hack, for instance. Only variables can have mangled name
8190         // clashes with extern "C" declarations, so only they deserve a
8191         // diagnostic.
8192       }
8193     }
8194 
8195     if (!Prev)
8196       return false;
8197   }
8198 
8199   // Use the first declaration's location to ensure we point at something which
8200   // is lexically inside an extern "C" linkage-spec.
8201   assert(Prev && "should have found a previous declaration to diagnose");
8202   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8203     Prev = FD->getFirstDecl();
8204   else
8205     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8206 
8207   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8208     << IsGlobal << ND;
8209   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8210     << IsGlobal;
8211   return false;
8212 }
8213 
8214 /// Apply special rules for handling extern "C" declarations. Returns \c true
8215 /// if we have found that this is a redeclaration of some prior entity.
8216 ///
8217 /// Per C++ [dcl.link]p6:
8218 ///   Two declarations [for a function or variable] with C language linkage
8219 ///   with the same name that appear in different scopes refer to the same
8220 ///   [entity]. An entity with C language linkage shall not be declared with
8221 ///   the same name as an entity in global scope.
8222 template<typename T>
8223 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8224                                                   LookupResult &Previous) {
8225   if (!S.getLangOpts().CPlusPlus) {
8226     // In C, when declaring a global variable, look for a corresponding 'extern'
8227     // variable declared in function scope. We don't need this in C++, because
8228     // we find local extern decls in the surrounding file-scope DeclContext.
8229     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8230       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8231         Previous.clear();
8232         Previous.addDecl(Prev);
8233         return true;
8234       }
8235     }
8236     return false;
8237   }
8238 
8239   // A declaration in the translation unit can conflict with an extern "C"
8240   // declaration.
8241   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8242     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8243 
8244   // An extern "C" declaration can conflict with a declaration in the
8245   // translation unit or can be a redeclaration of an extern "C" declaration
8246   // in another scope.
8247   if (isIncompleteDeclExternC(S,ND))
8248     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8249 
8250   // Neither global nor extern "C": nothing to do.
8251   return false;
8252 }
8253 
8254 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8255   // If the decl is already known invalid, don't check it.
8256   if (NewVD->isInvalidDecl())
8257     return;
8258 
8259   QualType T = NewVD->getType();
8260 
8261   // Defer checking an 'auto' type until its initializer is attached.
8262   if (T->isUndeducedType())
8263     return;
8264 
8265   if (NewVD->hasAttrs())
8266     CheckAlignasUnderalignment(NewVD);
8267 
8268   if (T->isObjCObjectType()) {
8269     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8270       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8271     T = Context.getObjCObjectPointerType(T);
8272     NewVD->setType(T);
8273   }
8274 
8275   // Emit an error if an address space was applied to decl with local storage.
8276   // This includes arrays of objects with address space qualifiers, but not
8277   // automatic variables that point to other address spaces.
8278   // ISO/IEC TR 18037 S5.1.2
8279   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8280       T.getAddressSpace() != LangAS::Default) {
8281     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8282     NewVD->setInvalidDecl();
8283     return;
8284   }
8285 
8286   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8287   // scope.
8288   if (getLangOpts().OpenCLVersion == 120 &&
8289       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8290                                             getLangOpts()) &&
8291       NewVD->isStaticLocal()) {
8292     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8293     NewVD->setInvalidDecl();
8294     return;
8295   }
8296 
8297   if (getLangOpts().OpenCL) {
8298     if (!diagnoseOpenCLTypes(*this, NewVD))
8299       return;
8300 
8301     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8302     if (NewVD->hasAttr<BlocksAttr>()) {
8303       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8304       return;
8305     }
8306 
8307     if (T->isBlockPointerType()) {
8308       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8309       // can't use 'extern' storage class.
8310       if (!T.isConstQualified()) {
8311         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8312             << 0 /*const*/;
8313         NewVD->setInvalidDecl();
8314         return;
8315       }
8316       if (NewVD->hasExternalStorage()) {
8317         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8318         NewVD->setInvalidDecl();
8319         return;
8320       }
8321     }
8322 
8323     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8324     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8325         NewVD->hasExternalStorage()) {
8326       if (!T->isSamplerT() && !T->isDependentType() &&
8327           !(T.getAddressSpace() == LangAS::opencl_constant ||
8328             (T.getAddressSpace() == LangAS::opencl_global &&
8329              getOpenCLOptions().areProgramScopeVariablesSupported(
8330                  getLangOpts())))) {
8331         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8332         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8333           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8334               << Scope << "global or constant";
8335         else
8336           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8337               << Scope << "constant";
8338         NewVD->setInvalidDecl();
8339         return;
8340       }
8341     } else {
8342       if (T.getAddressSpace() == LangAS::opencl_global) {
8343         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8344             << 1 /*is any function*/ << "global";
8345         NewVD->setInvalidDecl();
8346         return;
8347       }
8348       if (T.getAddressSpace() == LangAS::opencl_constant ||
8349           T.getAddressSpace() == LangAS::opencl_local) {
8350         FunctionDecl *FD = getCurFunctionDecl();
8351         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8352         // in functions.
8353         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8354           if (T.getAddressSpace() == LangAS::opencl_constant)
8355             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8356                 << 0 /*non-kernel only*/ << "constant";
8357           else
8358             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8359                 << 0 /*non-kernel only*/ << "local";
8360           NewVD->setInvalidDecl();
8361           return;
8362         }
8363         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8364         // in the outermost scope of a kernel function.
8365         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8366           if (!getCurScope()->isFunctionScope()) {
8367             if (T.getAddressSpace() == LangAS::opencl_constant)
8368               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8369                   << "constant";
8370             else
8371               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8372                   << "local";
8373             NewVD->setInvalidDecl();
8374             return;
8375           }
8376         }
8377       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8378                  // If we are parsing a template we didn't deduce an addr
8379                  // space yet.
8380                  T.getAddressSpace() != LangAS::Default) {
8381         // Do not allow other address spaces on automatic variable.
8382         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8383         NewVD->setInvalidDecl();
8384         return;
8385       }
8386     }
8387   }
8388 
8389   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8390       && !NewVD->hasAttr<BlocksAttr>()) {
8391     if (getLangOpts().getGC() != LangOptions::NonGC)
8392       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8393     else {
8394       assert(!getLangOpts().ObjCAutoRefCount);
8395       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8396     }
8397   }
8398 
8399   bool isVM = T->isVariablyModifiedType();
8400   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8401       NewVD->hasAttr<BlocksAttr>())
8402     setFunctionHasBranchProtectedScope();
8403 
8404   if ((isVM && NewVD->hasLinkage()) ||
8405       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8406     bool SizeIsNegative;
8407     llvm::APSInt Oversized;
8408     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8409         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8410     QualType FixedT;
8411     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8412       FixedT = FixedTInfo->getType();
8413     else if (FixedTInfo) {
8414       // Type and type-as-written are canonically different. We need to fix up
8415       // both types separately.
8416       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8417                                                    Oversized);
8418     }
8419     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8420       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8421       // FIXME: This won't give the correct result for
8422       // int a[10][n];
8423       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8424 
8425       if (NewVD->isFileVarDecl())
8426         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8427         << SizeRange;
8428       else if (NewVD->isStaticLocal())
8429         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8430         << SizeRange;
8431       else
8432         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8433         << SizeRange;
8434       NewVD->setInvalidDecl();
8435       return;
8436     }
8437 
8438     if (!FixedTInfo) {
8439       if (NewVD->isFileVarDecl())
8440         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8441       else
8442         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8443       NewVD->setInvalidDecl();
8444       return;
8445     }
8446 
8447     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8448     NewVD->setType(FixedT);
8449     NewVD->setTypeSourceInfo(FixedTInfo);
8450   }
8451 
8452   if (T->isVoidType()) {
8453     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8454     //                    of objects and functions.
8455     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8456       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8457         << T;
8458       NewVD->setInvalidDecl();
8459       return;
8460     }
8461   }
8462 
8463   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8464     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8465     NewVD->setInvalidDecl();
8466     return;
8467   }
8468 
8469   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8470     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8471     NewVD->setInvalidDecl();
8472     return;
8473   }
8474 
8475   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8476     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8477     NewVD->setInvalidDecl();
8478     return;
8479   }
8480 
8481   if (NewVD->isConstexpr() && !T->isDependentType() &&
8482       RequireLiteralType(NewVD->getLocation(), T,
8483                          diag::err_constexpr_var_non_literal)) {
8484     NewVD->setInvalidDecl();
8485     return;
8486   }
8487 
8488   // PPC MMA non-pointer types are not allowed as non-local variable types.
8489   if (Context.getTargetInfo().getTriple().isPPC64() &&
8490       !NewVD->isLocalVarDecl() &&
8491       CheckPPCMMAType(T, NewVD->getLocation())) {
8492     NewVD->setInvalidDecl();
8493     return;
8494   }
8495 }
8496 
8497 /// Perform semantic checking on a newly-created variable
8498 /// declaration.
8499 ///
8500 /// This routine performs all of the type-checking required for a
8501 /// variable declaration once it has been built. It is used both to
8502 /// check variables after they have been parsed and their declarators
8503 /// have been translated into a declaration, and to check variables
8504 /// that have been instantiated from a template.
8505 ///
8506 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8507 ///
8508 /// Returns true if the variable declaration is a redeclaration.
8509 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8510   CheckVariableDeclarationType(NewVD);
8511 
8512   // If the decl is already known invalid, don't check it.
8513   if (NewVD->isInvalidDecl())
8514     return false;
8515 
8516   // If we did not find anything by this name, look for a non-visible
8517   // extern "C" declaration with the same name.
8518   if (Previous.empty() &&
8519       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8520     Previous.setShadowed();
8521 
8522   if (!Previous.empty()) {
8523     MergeVarDecl(NewVD, Previous);
8524     return true;
8525   }
8526   return false;
8527 }
8528 
8529 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8530 /// and if so, check that it's a valid override and remember it.
8531 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8532   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8533 
8534   // Look for methods in base classes that this method might override.
8535   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8536                      /*DetectVirtual=*/false);
8537   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8538     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8539     DeclarationName Name = MD->getDeclName();
8540 
8541     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8542       // We really want to find the base class destructor here.
8543       QualType T = Context.getTypeDeclType(BaseRecord);
8544       CanQualType CT = Context.getCanonicalType(T);
8545       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8546     }
8547 
8548     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8549       CXXMethodDecl *BaseMD =
8550           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8551       if (!BaseMD || !BaseMD->isVirtual() ||
8552           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8553                      /*ConsiderCudaAttrs=*/true,
8554                      // C++2a [class.virtual]p2 does not consider requires
8555                      // clauses when overriding.
8556                      /*ConsiderRequiresClauses=*/false))
8557         continue;
8558 
8559       if (Overridden.insert(BaseMD).second) {
8560         MD->addOverriddenMethod(BaseMD);
8561         CheckOverridingFunctionReturnType(MD, BaseMD);
8562         CheckOverridingFunctionAttributes(MD, BaseMD);
8563         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8564         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8565       }
8566 
8567       // A method can only override one function from each base class. We
8568       // don't track indirectly overridden methods from bases of bases.
8569       return true;
8570     }
8571 
8572     return false;
8573   };
8574 
8575   DC->lookupInBases(VisitBase, Paths);
8576   return !Overridden.empty();
8577 }
8578 
8579 namespace {
8580   // Struct for holding all of the extra arguments needed by
8581   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8582   struct ActOnFDArgs {
8583     Scope *S;
8584     Declarator &D;
8585     MultiTemplateParamsArg TemplateParamLists;
8586     bool AddToScope;
8587   };
8588 } // end anonymous namespace
8589 
8590 namespace {
8591 
8592 // Callback to only accept typo corrections that have a non-zero edit distance.
8593 // Also only accept corrections that have the same parent decl.
8594 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8595  public:
8596   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8597                             CXXRecordDecl *Parent)
8598       : Context(Context), OriginalFD(TypoFD),
8599         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8600 
8601   bool ValidateCandidate(const TypoCorrection &candidate) override {
8602     if (candidate.getEditDistance() == 0)
8603       return false;
8604 
8605     SmallVector<unsigned, 1> MismatchedParams;
8606     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8607                                           CDeclEnd = candidate.end();
8608          CDecl != CDeclEnd; ++CDecl) {
8609       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8610 
8611       if (FD && !FD->hasBody() &&
8612           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8613         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8614           CXXRecordDecl *Parent = MD->getParent();
8615           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8616             return true;
8617         } else if (!ExpectedParent) {
8618           return true;
8619         }
8620       }
8621     }
8622 
8623     return false;
8624   }
8625 
8626   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8627     return std::make_unique<DifferentNameValidatorCCC>(*this);
8628   }
8629 
8630  private:
8631   ASTContext &Context;
8632   FunctionDecl *OriginalFD;
8633   CXXRecordDecl *ExpectedParent;
8634 };
8635 
8636 } // end anonymous namespace
8637 
8638 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8639   TypoCorrectedFunctionDefinitions.insert(F);
8640 }
8641 
8642 /// Generate diagnostics for an invalid function redeclaration.
8643 ///
8644 /// This routine handles generating the diagnostic messages for an invalid
8645 /// function redeclaration, including finding possible similar declarations
8646 /// or performing typo correction if there are no previous declarations with
8647 /// the same name.
8648 ///
8649 /// Returns a NamedDecl iff typo correction was performed and substituting in
8650 /// the new declaration name does not cause new errors.
8651 static NamedDecl *DiagnoseInvalidRedeclaration(
8652     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8653     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8654   DeclarationName Name = NewFD->getDeclName();
8655   DeclContext *NewDC = NewFD->getDeclContext();
8656   SmallVector<unsigned, 1> MismatchedParams;
8657   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8658   TypoCorrection Correction;
8659   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8660   unsigned DiagMsg =
8661     IsLocalFriend ? diag::err_no_matching_local_friend :
8662     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8663     diag::err_member_decl_does_not_match;
8664   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8665                     IsLocalFriend ? Sema::LookupLocalFriendName
8666                                   : Sema::LookupOrdinaryName,
8667                     Sema::ForVisibleRedeclaration);
8668 
8669   NewFD->setInvalidDecl();
8670   if (IsLocalFriend)
8671     SemaRef.LookupName(Prev, S);
8672   else
8673     SemaRef.LookupQualifiedName(Prev, NewDC);
8674   assert(!Prev.isAmbiguous() &&
8675          "Cannot have an ambiguity in previous-declaration lookup");
8676   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8677   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8678                                 MD ? MD->getParent() : nullptr);
8679   if (!Prev.empty()) {
8680     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8681          Func != FuncEnd; ++Func) {
8682       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8683       if (FD &&
8684           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8685         // Add 1 to the index so that 0 can mean the mismatch didn't
8686         // involve a parameter
8687         unsigned ParamNum =
8688             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8689         NearMatches.push_back(std::make_pair(FD, ParamNum));
8690       }
8691     }
8692   // If the qualified name lookup yielded nothing, try typo correction
8693   } else if ((Correction = SemaRef.CorrectTypo(
8694                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8695                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8696                   IsLocalFriend ? nullptr : NewDC))) {
8697     // Set up everything for the call to ActOnFunctionDeclarator
8698     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8699                               ExtraArgs.D.getIdentifierLoc());
8700     Previous.clear();
8701     Previous.setLookupName(Correction.getCorrection());
8702     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8703                                     CDeclEnd = Correction.end();
8704          CDecl != CDeclEnd; ++CDecl) {
8705       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8706       if (FD && !FD->hasBody() &&
8707           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8708         Previous.addDecl(FD);
8709       }
8710     }
8711     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8712 
8713     NamedDecl *Result;
8714     // Retry building the function declaration with the new previous
8715     // declarations, and with errors suppressed.
8716     {
8717       // Trap errors.
8718       Sema::SFINAETrap Trap(SemaRef);
8719 
8720       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8721       // pieces need to verify the typo-corrected C++ declaration and hopefully
8722       // eliminate the need for the parameter pack ExtraArgs.
8723       Result = SemaRef.ActOnFunctionDeclarator(
8724           ExtraArgs.S, ExtraArgs.D,
8725           Correction.getCorrectionDecl()->getDeclContext(),
8726           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8727           ExtraArgs.AddToScope);
8728 
8729       if (Trap.hasErrorOccurred())
8730         Result = nullptr;
8731     }
8732 
8733     if (Result) {
8734       // Determine which correction we picked.
8735       Decl *Canonical = Result->getCanonicalDecl();
8736       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8737            I != E; ++I)
8738         if ((*I)->getCanonicalDecl() == Canonical)
8739           Correction.setCorrectionDecl(*I);
8740 
8741       // Let Sema know about the correction.
8742       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8743       SemaRef.diagnoseTypo(
8744           Correction,
8745           SemaRef.PDiag(IsLocalFriend
8746                           ? diag::err_no_matching_local_friend_suggest
8747                           : diag::err_member_decl_does_not_match_suggest)
8748             << Name << NewDC << IsDefinition);
8749       return Result;
8750     }
8751 
8752     // Pretend the typo correction never occurred
8753     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8754                               ExtraArgs.D.getIdentifierLoc());
8755     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8756     Previous.clear();
8757     Previous.setLookupName(Name);
8758   }
8759 
8760   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8761       << Name << NewDC << IsDefinition << NewFD->getLocation();
8762 
8763   bool NewFDisConst = false;
8764   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8765     NewFDisConst = NewMD->isConst();
8766 
8767   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8768        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8769        NearMatch != NearMatchEnd; ++NearMatch) {
8770     FunctionDecl *FD = NearMatch->first;
8771     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8772     bool FDisConst = MD && MD->isConst();
8773     bool IsMember = MD || !IsLocalFriend;
8774 
8775     // FIXME: These notes are poorly worded for the local friend case.
8776     if (unsigned Idx = NearMatch->second) {
8777       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8778       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8779       if (Loc.isInvalid()) Loc = FD->getLocation();
8780       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8781                                  : diag::note_local_decl_close_param_match)
8782         << Idx << FDParam->getType()
8783         << NewFD->getParamDecl(Idx - 1)->getType();
8784     } else if (FDisConst != NewFDisConst) {
8785       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8786           << NewFDisConst << FD->getSourceRange().getEnd()
8787           << (NewFDisConst
8788                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8789                                                  .getConstQualifierLoc())
8790                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8791                                                    .getRParenLoc()
8792                                                    .getLocWithOffset(1),
8793                                                " const"));
8794     } else
8795       SemaRef.Diag(FD->getLocation(),
8796                    IsMember ? diag::note_member_def_close_match
8797                             : diag::note_local_decl_close_match);
8798   }
8799   return nullptr;
8800 }
8801 
8802 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8803   switch (D.getDeclSpec().getStorageClassSpec()) {
8804   default: llvm_unreachable("Unknown storage class!");
8805   case DeclSpec::SCS_auto:
8806   case DeclSpec::SCS_register:
8807   case DeclSpec::SCS_mutable:
8808     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8809                  diag::err_typecheck_sclass_func);
8810     D.getMutableDeclSpec().ClearStorageClassSpecs();
8811     D.setInvalidType();
8812     break;
8813   case DeclSpec::SCS_unspecified: break;
8814   case DeclSpec::SCS_extern:
8815     if (D.getDeclSpec().isExternInLinkageSpec())
8816       return SC_None;
8817     return SC_Extern;
8818   case DeclSpec::SCS_static: {
8819     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8820       // C99 6.7.1p5:
8821       //   The declaration of an identifier for a function that has
8822       //   block scope shall have no explicit storage-class specifier
8823       //   other than extern
8824       // See also (C++ [dcl.stc]p4).
8825       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8826                    diag::err_static_block_func);
8827       break;
8828     } else
8829       return SC_Static;
8830   }
8831   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8832   }
8833 
8834   // No explicit storage class has already been returned
8835   return SC_None;
8836 }
8837 
8838 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8839                                            DeclContext *DC, QualType &R,
8840                                            TypeSourceInfo *TInfo,
8841                                            StorageClass SC,
8842                                            bool &IsVirtualOkay) {
8843   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8844   DeclarationName Name = NameInfo.getName();
8845 
8846   FunctionDecl *NewFD = nullptr;
8847   bool isInline = D.getDeclSpec().isInlineSpecified();
8848 
8849   if (!SemaRef.getLangOpts().CPlusPlus) {
8850     // Determine whether the function was written with a prototype. This is
8851     // true when:
8852     //   - there is a prototype in the declarator, or
8853     //   - the type R of the function is some kind of typedef or other non-
8854     //     attributed reference to a type name (which eventually refers to a
8855     //     function type). Note, we can't always look at the adjusted type to
8856     //     check this case because attributes may cause a non-function
8857     //     declarator to still have a function type. e.g.,
8858     //       typedef void func(int a);
8859     //       __attribute__((noreturn)) func other_func; // This has a prototype
8860     bool HasPrototype =
8861         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8862         (D.getDeclSpec().isTypeRep() &&
8863          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8864         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8865     assert(
8866         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8867         "Strict prototypes are required");
8868 
8869     NewFD = FunctionDecl::Create(
8870         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8871         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8872         ConstexprSpecKind::Unspecified,
8873         /*TrailingRequiresClause=*/nullptr);
8874     if (D.isInvalidType())
8875       NewFD->setInvalidDecl();
8876 
8877     return NewFD;
8878   }
8879 
8880   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8881 
8882   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8883   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8884     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8885                  diag::err_constexpr_wrong_decl_kind)
8886         << static_cast<int>(ConstexprKind);
8887     ConstexprKind = ConstexprSpecKind::Unspecified;
8888     D.getMutableDeclSpec().ClearConstexprSpec();
8889   }
8890   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8891 
8892   // Check that the return type is not an abstract class type.
8893   // For record types, this is done by the AbstractClassUsageDiagnoser once
8894   // the class has been completely parsed.
8895   if (!DC->isRecord() &&
8896       SemaRef.RequireNonAbstractType(
8897           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8898           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8899     D.setInvalidType();
8900 
8901   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8902     // This is a C++ constructor declaration.
8903     assert(DC->isRecord() &&
8904            "Constructors can only be declared in a member context");
8905 
8906     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8907     return CXXConstructorDecl::Create(
8908         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8909         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8910         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8911         InheritedConstructor(), TrailingRequiresClause);
8912 
8913   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8914     // This is a C++ destructor declaration.
8915     if (DC->isRecord()) {
8916       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8917       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8918       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8919           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8920           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8921           /*isImplicitlyDeclared=*/false, ConstexprKind,
8922           TrailingRequiresClause);
8923       // User defined destructors start as not selected if the class definition is still
8924       // not done.
8925       if (Record->isBeingDefined())
8926         NewDD->setIneligibleOrNotSelected(true);
8927 
8928       // If the destructor needs an implicit exception specification, set it
8929       // now. FIXME: It'd be nice to be able to create the right type to start
8930       // with, but the type needs to reference the destructor declaration.
8931       if (SemaRef.getLangOpts().CPlusPlus11)
8932         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8933 
8934       IsVirtualOkay = true;
8935       return NewDD;
8936 
8937     } else {
8938       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8939       D.setInvalidType();
8940 
8941       // Create a FunctionDecl to satisfy the function definition parsing
8942       // code path.
8943       return FunctionDecl::Create(
8944           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8945           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8946           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8947     }
8948 
8949   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8950     if (!DC->isRecord()) {
8951       SemaRef.Diag(D.getIdentifierLoc(),
8952            diag::err_conv_function_not_member);
8953       return nullptr;
8954     }
8955 
8956     SemaRef.CheckConversionDeclarator(D, R, SC);
8957     if (D.isInvalidType())
8958       return nullptr;
8959 
8960     IsVirtualOkay = true;
8961     return CXXConversionDecl::Create(
8962         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8963         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8964         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8965         TrailingRequiresClause);
8966 
8967   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8968     if (TrailingRequiresClause)
8969       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8970                    diag::err_trailing_requires_clause_on_deduction_guide)
8971           << TrailingRequiresClause->getSourceRange();
8972     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8973 
8974     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8975                                          ExplicitSpecifier, NameInfo, R, TInfo,
8976                                          D.getEndLoc());
8977   } else if (DC->isRecord()) {
8978     // If the name of the function is the same as the name of the record,
8979     // then this must be an invalid constructor that has a return type.
8980     // (The parser checks for a return type and makes the declarator a
8981     // constructor if it has no return type).
8982     if (Name.getAsIdentifierInfo() &&
8983         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8984       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8985         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8986         << SourceRange(D.getIdentifierLoc());
8987       return nullptr;
8988     }
8989 
8990     // This is a C++ method declaration.
8991     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8992         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8993         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8994         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8995     IsVirtualOkay = !Ret->isStatic();
8996     return Ret;
8997   } else {
8998     bool isFriend =
8999         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9000     if (!isFriend && SemaRef.CurContext->isRecord())
9001       return nullptr;
9002 
9003     // Determine whether the function was written with a
9004     // prototype. This true when:
9005     //   - we're in C++ (where every function has a prototype),
9006     return FunctionDecl::Create(
9007         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9008         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9009         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9010   }
9011 }
9012 
9013 enum OpenCLParamType {
9014   ValidKernelParam,
9015   PtrPtrKernelParam,
9016   PtrKernelParam,
9017   InvalidAddrSpacePtrKernelParam,
9018   InvalidKernelParam,
9019   RecordKernelParam
9020 };
9021 
9022 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9023   // Size dependent types are just typedefs to normal integer types
9024   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9025   // integers other than by their names.
9026   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9027 
9028   // Remove typedefs one by one until we reach a typedef
9029   // for a size dependent type.
9030   QualType DesugaredTy = Ty;
9031   do {
9032     ArrayRef<StringRef> Names(SizeTypeNames);
9033     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9034     if (Names.end() != Match)
9035       return true;
9036 
9037     Ty = DesugaredTy;
9038     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9039   } while (DesugaredTy != Ty);
9040 
9041   return false;
9042 }
9043 
9044 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9045   if (PT->isDependentType())
9046     return InvalidKernelParam;
9047 
9048   if (PT->isPointerType() || PT->isReferenceType()) {
9049     QualType PointeeType = PT->getPointeeType();
9050     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9051         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9052         PointeeType.getAddressSpace() == LangAS::Default)
9053       return InvalidAddrSpacePtrKernelParam;
9054 
9055     if (PointeeType->isPointerType()) {
9056       // This is a pointer to pointer parameter.
9057       // Recursively check inner type.
9058       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9059       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9060           ParamKind == InvalidKernelParam)
9061         return ParamKind;
9062 
9063       return PtrPtrKernelParam;
9064     }
9065 
9066     // C++ for OpenCL v1.0 s2.4:
9067     // Moreover the types used in parameters of the kernel functions must be:
9068     // Standard layout types for pointer parameters. The same applies to
9069     // reference if an implementation supports them in kernel parameters.
9070     if (S.getLangOpts().OpenCLCPlusPlus &&
9071         !S.getOpenCLOptions().isAvailableOption(
9072             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9073         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9074         !PointeeType->isStandardLayoutType())
9075       return InvalidKernelParam;
9076 
9077     return PtrKernelParam;
9078   }
9079 
9080   // OpenCL v1.2 s6.9.k:
9081   // Arguments to kernel functions in a program cannot be declared with the
9082   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9083   // uintptr_t or a struct and/or union that contain fields declared to be one
9084   // of these built-in scalar types.
9085   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9086     return InvalidKernelParam;
9087 
9088   if (PT->isImageType())
9089     return PtrKernelParam;
9090 
9091   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9092     return InvalidKernelParam;
9093 
9094   // OpenCL extension spec v1.2 s9.5:
9095   // This extension adds support for half scalar and vector types as built-in
9096   // types that can be used for arithmetic operations, conversions etc.
9097   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9098       PT->isHalfType())
9099     return InvalidKernelParam;
9100 
9101   // Look into an array argument to check if it has a forbidden type.
9102   if (PT->isArrayType()) {
9103     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9104     // Call ourself to check an underlying type of an array. Since the
9105     // getPointeeOrArrayElementType returns an innermost type which is not an
9106     // array, this recursive call only happens once.
9107     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9108   }
9109 
9110   // C++ for OpenCL v1.0 s2.4:
9111   // Moreover the types used in parameters of the kernel functions must be:
9112   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9113   // types) for parameters passed by value;
9114   if (S.getLangOpts().OpenCLCPlusPlus &&
9115       !S.getOpenCLOptions().isAvailableOption(
9116           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9117       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9118     return InvalidKernelParam;
9119 
9120   if (PT->isRecordType())
9121     return RecordKernelParam;
9122 
9123   return ValidKernelParam;
9124 }
9125 
9126 static void checkIsValidOpenCLKernelParameter(
9127   Sema &S,
9128   Declarator &D,
9129   ParmVarDecl *Param,
9130   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9131   QualType PT = Param->getType();
9132 
9133   // Cache the valid types we encounter to avoid rechecking structs that are
9134   // used again
9135   if (ValidTypes.count(PT.getTypePtr()))
9136     return;
9137 
9138   switch (getOpenCLKernelParameterType(S, PT)) {
9139   case PtrPtrKernelParam:
9140     // OpenCL v3.0 s6.11.a:
9141     // A kernel function argument cannot be declared as a pointer to a pointer
9142     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9143     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9144       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9145       D.setInvalidType();
9146       return;
9147     }
9148 
9149     ValidTypes.insert(PT.getTypePtr());
9150     return;
9151 
9152   case InvalidAddrSpacePtrKernelParam:
9153     // OpenCL v1.0 s6.5:
9154     // __kernel function arguments declared to be a pointer of a type can point
9155     // to one of the following address spaces only : __global, __local or
9156     // __constant.
9157     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9158     D.setInvalidType();
9159     return;
9160 
9161     // OpenCL v1.2 s6.9.k:
9162     // Arguments to kernel functions in a program cannot be declared with the
9163     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9164     // uintptr_t or a struct and/or union that contain fields declared to be
9165     // one of these built-in scalar types.
9166 
9167   case InvalidKernelParam:
9168     // OpenCL v1.2 s6.8 n:
9169     // A kernel function argument cannot be declared
9170     // of event_t type.
9171     // Do not diagnose half type since it is diagnosed as invalid argument
9172     // type for any function elsewhere.
9173     if (!PT->isHalfType()) {
9174       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9175 
9176       // Explain what typedefs are involved.
9177       const TypedefType *Typedef = nullptr;
9178       while ((Typedef = PT->getAs<TypedefType>())) {
9179         SourceLocation Loc = Typedef->getDecl()->getLocation();
9180         // SourceLocation may be invalid for a built-in type.
9181         if (Loc.isValid())
9182           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9183         PT = Typedef->desugar();
9184       }
9185     }
9186 
9187     D.setInvalidType();
9188     return;
9189 
9190   case PtrKernelParam:
9191   case ValidKernelParam:
9192     ValidTypes.insert(PT.getTypePtr());
9193     return;
9194 
9195   case RecordKernelParam:
9196     break;
9197   }
9198 
9199   // Track nested structs we will inspect
9200   SmallVector<const Decl *, 4> VisitStack;
9201 
9202   // Track where we are in the nested structs. Items will migrate from
9203   // VisitStack to HistoryStack as we do the DFS for bad field.
9204   SmallVector<const FieldDecl *, 4> HistoryStack;
9205   HistoryStack.push_back(nullptr);
9206 
9207   // At this point we already handled everything except of a RecordType or
9208   // an ArrayType of a RecordType.
9209   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9210   const RecordType *RecTy =
9211       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9212   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9213 
9214   VisitStack.push_back(RecTy->getDecl());
9215   assert(VisitStack.back() && "First decl null?");
9216 
9217   do {
9218     const Decl *Next = VisitStack.pop_back_val();
9219     if (!Next) {
9220       assert(!HistoryStack.empty());
9221       // Found a marker, we have gone up a level
9222       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9223         ValidTypes.insert(Hist->getType().getTypePtr());
9224 
9225       continue;
9226     }
9227 
9228     // Adds everything except the original parameter declaration (which is not a
9229     // field itself) to the history stack.
9230     const RecordDecl *RD;
9231     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9232       HistoryStack.push_back(Field);
9233 
9234       QualType FieldTy = Field->getType();
9235       // Other field types (known to be valid or invalid) are handled while we
9236       // walk around RecordDecl::fields().
9237       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9238              "Unexpected type.");
9239       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9240 
9241       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9242     } else {
9243       RD = cast<RecordDecl>(Next);
9244     }
9245 
9246     // Add a null marker so we know when we've gone back up a level
9247     VisitStack.push_back(nullptr);
9248 
9249     for (const auto *FD : RD->fields()) {
9250       QualType QT = FD->getType();
9251 
9252       if (ValidTypes.count(QT.getTypePtr()))
9253         continue;
9254 
9255       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9256       if (ParamType == ValidKernelParam)
9257         continue;
9258 
9259       if (ParamType == RecordKernelParam) {
9260         VisitStack.push_back(FD);
9261         continue;
9262       }
9263 
9264       // OpenCL v1.2 s6.9.p:
9265       // Arguments to kernel functions that are declared to be a struct or union
9266       // do not allow OpenCL objects to be passed as elements of the struct or
9267       // union.
9268       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9269           ParamType == InvalidAddrSpacePtrKernelParam) {
9270         S.Diag(Param->getLocation(),
9271                diag::err_record_with_pointers_kernel_param)
9272           << PT->isUnionType()
9273           << PT;
9274       } else {
9275         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9276       }
9277 
9278       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9279           << OrigRecDecl->getDeclName();
9280 
9281       // We have an error, now let's go back up through history and show where
9282       // the offending field came from
9283       for (ArrayRef<const FieldDecl *>::const_iterator
9284                I = HistoryStack.begin() + 1,
9285                E = HistoryStack.end();
9286            I != E; ++I) {
9287         const FieldDecl *OuterField = *I;
9288         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9289           << OuterField->getType();
9290       }
9291 
9292       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9293         << QT->isPointerType()
9294         << QT;
9295       D.setInvalidType();
9296       return;
9297     }
9298   } while (!VisitStack.empty());
9299 }
9300 
9301 /// Find the DeclContext in which a tag is implicitly declared if we see an
9302 /// elaborated type specifier in the specified context, and lookup finds
9303 /// nothing.
9304 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9305   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9306     DC = DC->getParent();
9307   return DC;
9308 }
9309 
9310 /// Find the Scope in which a tag is implicitly declared if we see an
9311 /// elaborated type specifier in the specified context, and lookup finds
9312 /// nothing.
9313 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9314   while (S->isClassScope() ||
9315          (LangOpts.CPlusPlus &&
9316           S->isFunctionPrototypeScope()) ||
9317          ((S->getFlags() & Scope::DeclScope) == 0) ||
9318          (S->getEntity() && S->getEntity()->isTransparentContext()))
9319     S = S->getParent();
9320   return S;
9321 }
9322 
9323 /// Determine whether a declaration matches a known function in namespace std.
9324 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9325                          unsigned BuiltinID) {
9326   switch (BuiltinID) {
9327   case Builtin::BI__GetExceptionInfo:
9328     // No type checking whatsoever.
9329     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9330 
9331   case Builtin::BIaddressof:
9332   case Builtin::BI__addressof:
9333   case Builtin::BIforward:
9334   case Builtin::BImove:
9335   case Builtin::BImove_if_noexcept:
9336   case Builtin::BIas_const: {
9337     // Ensure that we don't treat the algorithm
9338     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9339     // as the builtin std::move.
9340     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9341     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9342   }
9343 
9344   default:
9345     return false;
9346   }
9347 }
9348 
9349 NamedDecl*
9350 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9351                               TypeSourceInfo *TInfo, LookupResult &Previous,
9352                               MultiTemplateParamsArg TemplateParamListsRef,
9353                               bool &AddToScope) {
9354   QualType R = TInfo->getType();
9355 
9356   assert(R->isFunctionType());
9357   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9358     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9359 
9360   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9361   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9362   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9363     if (!TemplateParamLists.empty() &&
9364         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9365       TemplateParamLists.back() = Invented;
9366     else
9367       TemplateParamLists.push_back(Invented);
9368   }
9369 
9370   // TODO: consider using NameInfo for diagnostic.
9371   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9372   DeclarationName Name = NameInfo.getName();
9373   StorageClass SC = getFunctionStorageClass(*this, D);
9374 
9375   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9376     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9377          diag::err_invalid_thread)
9378       << DeclSpec::getSpecifierName(TSCS);
9379 
9380   if (D.isFirstDeclarationOfMember())
9381     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9382                            D.getIdentifierLoc());
9383 
9384   bool isFriend = false;
9385   FunctionTemplateDecl *FunctionTemplate = nullptr;
9386   bool isMemberSpecialization = false;
9387   bool isFunctionTemplateSpecialization = false;
9388 
9389   bool isDependentClassScopeExplicitSpecialization = false;
9390   bool HasExplicitTemplateArgs = false;
9391   TemplateArgumentListInfo TemplateArgs;
9392 
9393   bool isVirtualOkay = false;
9394 
9395   DeclContext *OriginalDC = DC;
9396   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9397 
9398   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9399                                               isVirtualOkay);
9400   if (!NewFD) return nullptr;
9401 
9402   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9403     NewFD->setTopLevelDeclInObjCContainer();
9404 
9405   // Set the lexical context. If this is a function-scope declaration, or has a
9406   // C++ scope specifier, or is the object of a friend declaration, the lexical
9407   // context will be different from the semantic context.
9408   NewFD->setLexicalDeclContext(CurContext);
9409 
9410   if (IsLocalExternDecl)
9411     NewFD->setLocalExternDecl();
9412 
9413   if (getLangOpts().CPlusPlus) {
9414     // The rules for implicit inlines changed in C++20 for methods and friends
9415     // with an in-class definition (when such a definition is not attached to
9416     // the global module).  User-specified 'inline' overrides this (set when
9417     // the function decl is created above).
9418     // FIXME: We need a better way to separate C++ standard and clang modules.
9419     bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9420                                !NewFD->getOwningModule() ||
9421                                NewFD->getOwningModule()->isGlobalModule() ||
9422                                NewFD->getOwningModule()->isModuleMapModule();
9423     bool isInline = D.getDeclSpec().isInlineSpecified();
9424     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9425     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9426     isFriend = D.getDeclSpec().isFriendSpecified();
9427     if (isFriend && !isInline && D.isFunctionDefinition()) {
9428       // Pre-C++20 [class.friend]p5
9429       //   A function can be defined in a friend declaration of a
9430       //   class . . . . Such a function is implicitly inline.
9431       // Post C++20 [class.friend]p7
9432       //   Such a function is implicitly an inline function if it is attached
9433       //   to the global module.
9434       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9435     }
9436 
9437     // If this is a method defined in an __interface, and is not a constructor
9438     // or an overloaded operator, then set the pure flag (isVirtual will already
9439     // return true).
9440     if (const CXXRecordDecl *Parent =
9441           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9442       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9443         NewFD->setPure(true);
9444 
9445       // C++ [class.union]p2
9446       //   A union can have member functions, but not virtual functions.
9447       if (isVirtual && Parent->isUnion()) {
9448         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9449         NewFD->setInvalidDecl();
9450       }
9451       if ((Parent->isClass() || Parent->isStruct()) &&
9452           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9453           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9454           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9455         if (auto *Def = Parent->getDefinition())
9456           Def->setInitMethod(true);
9457       }
9458     }
9459 
9460     SetNestedNameSpecifier(*this, NewFD, D);
9461     isMemberSpecialization = false;
9462     isFunctionTemplateSpecialization = false;
9463     if (D.isInvalidType())
9464       NewFD->setInvalidDecl();
9465 
9466     // Match up the template parameter lists with the scope specifier, then
9467     // determine whether we have a template or a template specialization.
9468     bool Invalid = false;
9469     TemplateParameterList *TemplateParams =
9470         MatchTemplateParametersToScopeSpecifier(
9471             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9472             D.getCXXScopeSpec(),
9473             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9474                 ? D.getName().TemplateId
9475                 : nullptr,
9476             TemplateParamLists, isFriend, isMemberSpecialization,
9477             Invalid);
9478     if (TemplateParams) {
9479       // Check that we can declare a template here.
9480       if (CheckTemplateDeclScope(S, TemplateParams))
9481         NewFD->setInvalidDecl();
9482 
9483       if (TemplateParams->size() > 0) {
9484         // This is a function template
9485 
9486         // A destructor cannot be a template.
9487         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9488           Diag(NewFD->getLocation(), diag::err_destructor_template);
9489           NewFD->setInvalidDecl();
9490         }
9491 
9492         // If we're adding a template to a dependent context, we may need to
9493         // rebuilding some of the types used within the template parameter list,
9494         // now that we know what the current instantiation is.
9495         if (DC->isDependentContext()) {
9496           ContextRAII SavedContext(*this, DC);
9497           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9498             Invalid = true;
9499         }
9500 
9501         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9502                                                         NewFD->getLocation(),
9503                                                         Name, TemplateParams,
9504                                                         NewFD);
9505         FunctionTemplate->setLexicalDeclContext(CurContext);
9506         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9507 
9508         // For source fidelity, store the other template param lists.
9509         if (TemplateParamLists.size() > 1) {
9510           NewFD->setTemplateParameterListsInfo(Context,
9511               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9512                   .drop_back(1));
9513         }
9514       } else {
9515         // This is a function template specialization.
9516         isFunctionTemplateSpecialization = true;
9517         // For source fidelity, store all the template param lists.
9518         if (TemplateParamLists.size() > 0)
9519           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9520 
9521         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9522         if (isFriend) {
9523           // We want to remove the "template<>", found here.
9524           SourceRange RemoveRange = TemplateParams->getSourceRange();
9525 
9526           // If we remove the template<> and the name is not a
9527           // template-id, we're actually silently creating a problem:
9528           // the friend declaration will refer to an untemplated decl,
9529           // and clearly the user wants a template specialization.  So
9530           // we need to insert '<>' after the name.
9531           SourceLocation InsertLoc;
9532           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9533             InsertLoc = D.getName().getSourceRange().getEnd();
9534             InsertLoc = getLocForEndOfToken(InsertLoc);
9535           }
9536 
9537           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9538             << Name << RemoveRange
9539             << FixItHint::CreateRemoval(RemoveRange)
9540             << FixItHint::CreateInsertion(InsertLoc, "<>");
9541           Invalid = true;
9542         }
9543       }
9544     } else {
9545       // Check that we can declare a template here.
9546       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9547           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9548         NewFD->setInvalidDecl();
9549 
9550       // All template param lists were matched against the scope specifier:
9551       // this is NOT (an explicit specialization of) a template.
9552       if (TemplateParamLists.size() > 0)
9553         // For source fidelity, store all the template param lists.
9554         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9555     }
9556 
9557     if (Invalid) {
9558       NewFD->setInvalidDecl();
9559       if (FunctionTemplate)
9560         FunctionTemplate->setInvalidDecl();
9561     }
9562 
9563     // C++ [dcl.fct.spec]p5:
9564     //   The virtual specifier shall only be used in declarations of
9565     //   nonstatic class member functions that appear within a
9566     //   member-specification of a class declaration; see 10.3.
9567     //
9568     if (isVirtual && !NewFD->isInvalidDecl()) {
9569       if (!isVirtualOkay) {
9570         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9571              diag::err_virtual_non_function);
9572       } else if (!CurContext->isRecord()) {
9573         // 'virtual' was specified outside of the class.
9574         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9575              diag::err_virtual_out_of_class)
9576           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9577       } else if (NewFD->getDescribedFunctionTemplate()) {
9578         // C++ [temp.mem]p3:
9579         //  A member function template shall not be virtual.
9580         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9581              diag::err_virtual_member_function_template)
9582           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9583       } else {
9584         // Okay: Add virtual to the method.
9585         NewFD->setVirtualAsWritten(true);
9586       }
9587 
9588       if (getLangOpts().CPlusPlus14 &&
9589           NewFD->getReturnType()->isUndeducedType())
9590         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9591     }
9592 
9593     if (getLangOpts().CPlusPlus14 &&
9594         (NewFD->isDependentContext() ||
9595          (isFriend && CurContext->isDependentContext())) &&
9596         NewFD->getReturnType()->isUndeducedType()) {
9597       // If the function template is referenced directly (for instance, as a
9598       // member of the current instantiation), pretend it has a dependent type.
9599       // This is not really justified by the standard, but is the only sane
9600       // thing to do.
9601       // FIXME: For a friend function, we have not marked the function as being
9602       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9603       const FunctionProtoType *FPT =
9604           NewFD->getType()->castAs<FunctionProtoType>();
9605       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9606       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9607                                              FPT->getExtProtoInfo()));
9608     }
9609 
9610     // C++ [dcl.fct.spec]p3:
9611     //  The inline specifier shall not appear on a block scope function
9612     //  declaration.
9613     if (isInline && !NewFD->isInvalidDecl()) {
9614       if (CurContext->isFunctionOrMethod()) {
9615         // 'inline' is not allowed on block scope function declaration.
9616         Diag(D.getDeclSpec().getInlineSpecLoc(),
9617              diag::err_inline_declaration_block_scope) << Name
9618           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9619       }
9620     }
9621 
9622     // C++ [dcl.fct.spec]p6:
9623     //  The explicit specifier shall be used only in the declaration of a
9624     //  constructor or conversion function within its class definition;
9625     //  see 12.3.1 and 12.3.2.
9626     if (hasExplicit && !NewFD->isInvalidDecl() &&
9627         !isa<CXXDeductionGuideDecl>(NewFD)) {
9628       if (!CurContext->isRecord()) {
9629         // 'explicit' was specified outside of the class.
9630         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9631              diag::err_explicit_out_of_class)
9632             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9633       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9634                  !isa<CXXConversionDecl>(NewFD)) {
9635         // 'explicit' was specified on a function that wasn't a constructor
9636         // or conversion function.
9637         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9638              diag::err_explicit_non_ctor_or_conv_function)
9639             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9640       }
9641     }
9642 
9643     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9644     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9645       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9646       // are implicitly inline.
9647       NewFD->setImplicitlyInline();
9648 
9649       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9650       // be either constructors or to return a literal type. Therefore,
9651       // destructors cannot be declared constexpr.
9652       if (isa<CXXDestructorDecl>(NewFD) &&
9653           (!getLangOpts().CPlusPlus20 ||
9654            ConstexprKind == ConstexprSpecKind::Consteval)) {
9655         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9656             << static_cast<int>(ConstexprKind);
9657         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9658                                     ? ConstexprSpecKind::Unspecified
9659                                     : ConstexprSpecKind::Constexpr);
9660       }
9661       // C++20 [dcl.constexpr]p2: An allocation function, or a
9662       // deallocation function shall not be declared with the consteval
9663       // specifier.
9664       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9665           (NewFD->getOverloadedOperator() == OO_New ||
9666            NewFD->getOverloadedOperator() == OO_Array_New ||
9667            NewFD->getOverloadedOperator() == OO_Delete ||
9668            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9669         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9670              diag::err_invalid_consteval_decl_kind)
9671             << NewFD;
9672         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9673       }
9674     }
9675 
9676     // If __module_private__ was specified, mark the function accordingly.
9677     if (D.getDeclSpec().isModulePrivateSpecified()) {
9678       if (isFunctionTemplateSpecialization) {
9679         SourceLocation ModulePrivateLoc
9680           = D.getDeclSpec().getModulePrivateSpecLoc();
9681         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9682           << 0
9683           << FixItHint::CreateRemoval(ModulePrivateLoc);
9684       } else {
9685         NewFD->setModulePrivate();
9686         if (FunctionTemplate)
9687           FunctionTemplate->setModulePrivate();
9688       }
9689     }
9690 
9691     if (isFriend) {
9692       if (FunctionTemplate) {
9693         FunctionTemplate->setObjectOfFriendDecl();
9694         FunctionTemplate->setAccess(AS_public);
9695       }
9696       NewFD->setObjectOfFriendDecl();
9697       NewFD->setAccess(AS_public);
9698     }
9699 
9700     // If a function is defined as defaulted or deleted, mark it as such now.
9701     // We'll do the relevant checks on defaulted / deleted functions later.
9702     switch (D.getFunctionDefinitionKind()) {
9703     case FunctionDefinitionKind::Declaration:
9704     case FunctionDefinitionKind::Definition:
9705       break;
9706 
9707     case FunctionDefinitionKind::Defaulted:
9708       NewFD->setDefaulted();
9709       break;
9710 
9711     case FunctionDefinitionKind::Deleted:
9712       NewFD->setDeletedAsWritten();
9713       break;
9714     }
9715 
9716     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9717         D.isFunctionDefinition() && !isInline) {
9718       // Pre C++20 [class.mfct]p2:
9719       //   A member function may be defined (8.4) in its class definition, in
9720       //   which case it is an inline member function (7.1.2)
9721       // Post C++20 [class.mfct]p1:
9722       //   If a member function is attached to the global module and is defined
9723       //   in its class definition, it is inline.
9724       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9725     }
9726 
9727     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9728         !CurContext->isRecord()) {
9729       // C++ [class.static]p1:
9730       //   A data or function member of a class may be declared static
9731       //   in a class definition, in which case it is a static member of
9732       //   the class.
9733 
9734       // Complain about the 'static' specifier if it's on an out-of-line
9735       // member function definition.
9736 
9737       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9738       // member function template declaration and class member template
9739       // declaration (MSVC versions before 2015), warn about this.
9740       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9741            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9742              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9743            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9744            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9745         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9746     }
9747 
9748     // C++11 [except.spec]p15:
9749     //   A deallocation function with no exception-specification is treated
9750     //   as if it were specified with noexcept(true).
9751     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9752     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9753          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9754         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9755       NewFD->setType(Context.getFunctionType(
9756           FPT->getReturnType(), FPT->getParamTypes(),
9757           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9758   }
9759 
9760   // Filter out previous declarations that don't match the scope.
9761   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9762                        D.getCXXScopeSpec().isNotEmpty() ||
9763                        isMemberSpecialization ||
9764                        isFunctionTemplateSpecialization);
9765 
9766   // Handle GNU asm-label extension (encoded as an attribute).
9767   if (Expr *E = (Expr*) D.getAsmLabel()) {
9768     // The parser guarantees this is a string.
9769     StringLiteral *SE = cast<StringLiteral>(E);
9770     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9771                                         /*IsLiteralLabel=*/true,
9772                                         SE->getStrTokenLoc(0)));
9773   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9774     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9775       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9776     if (I != ExtnameUndeclaredIdentifiers.end()) {
9777       if (isDeclExternC(NewFD)) {
9778         NewFD->addAttr(I->second);
9779         ExtnameUndeclaredIdentifiers.erase(I);
9780       } else
9781         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9782             << /*Variable*/0 << NewFD;
9783     }
9784   }
9785 
9786   // Copy the parameter declarations from the declarator D to the function
9787   // declaration NewFD, if they are available.  First scavenge them into Params.
9788   SmallVector<ParmVarDecl*, 16> Params;
9789   unsigned FTIIdx;
9790   if (D.isFunctionDeclarator(FTIIdx)) {
9791     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9792 
9793     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9794     // function that takes no arguments, not a function that takes a
9795     // single void argument.
9796     // We let through "const void" here because Sema::GetTypeForDeclarator
9797     // already checks for that case.
9798     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9799       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9800         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9801         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9802         Param->setDeclContext(NewFD);
9803         Params.push_back(Param);
9804 
9805         if (Param->isInvalidDecl())
9806           NewFD->setInvalidDecl();
9807       }
9808     }
9809 
9810     if (!getLangOpts().CPlusPlus) {
9811       // In C, find all the tag declarations from the prototype and move them
9812       // into the function DeclContext. Remove them from the surrounding tag
9813       // injection context of the function, which is typically but not always
9814       // the TU.
9815       DeclContext *PrototypeTagContext =
9816           getTagInjectionContext(NewFD->getLexicalDeclContext());
9817       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9818         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9819 
9820         // We don't want to reparent enumerators. Look at their parent enum
9821         // instead.
9822         if (!TD) {
9823           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9824             TD = cast<EnumDecl>(ECD->getDeclContext());
9825         }
9826         if (!TD)
9827           continue;
9828         DeclContext *TagDC = TD->getLexicalDeclContext();
9829         if (!TagDC->containsDecl(TD))
9830           continue;
9831         TagDC->removeDecl(TD);
9832         TD->setDeclContext(NewFD);
9833         NewFD->addDecl(TD);
9834 
9835         // Preserve the lexical DeclContext if it is not the surrounding tag
9836         // injection context of the FD. In this example, the semantic context of
9837         // E will be f and the lexical context will be S, while both the
9838         // semantic and lexical contexts of S will be f:
9839         //   void f(struct S { enum E { a } f; } s);
9840         if (TagDC != PrototypeTagContext)
9841           TD->setLexicalDeclContext(TagDC);
9842       }
9843     }
9844   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9845     // When we're declaring a function with a typedef, typeof, etc as in the
9846     // following example, we'll need to synthesize (unnamed)
9847     // parameters for use in the declaration.
9848     //
9849     // @code
9850     // typedef void fn(int);
9851     // fn f;
9852     // @endcode
9853 
9854     // Synthesize a parameter for each argument type.
9855     for (const auto &AI : FT->param_types()) {
9856       ParmVarDecl *Param =
9857           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9858       Param->setScopeInfo(0, Params.size());
9859       Params.push_back(Param);
9860     }
9861   } else {
9862     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9863            "Should not need args for typedef of non-prototype fn");
9864   }
9865 
9866   // Finally, we know we have the right number of parameters, install them.
9867   NewFD->setParams(Params);
9868 
9869   if (D.getDeclSpec().isNoreturnSpecified())
9870     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9871                                            D.getDeclSpec().getNoreturnSpecLoc(),
9872                                            AttributeCommonInfo::AS_Keyword));
9873 
9874   // Functions returning a variably modified type violate C99 6.7.5.2p2
9875   // because all functions have linkage.
9876   if (!NewFD->isInvalidDecl() &&
9877       NewFD->getReturnType()->isVariablyModifiedType()) {
9878     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9879     NewFD->setInvalidDecl();
9880   }
9881 
9882   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9883   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9884       !NewFD->hasAttr<SectionAttr>())
9885     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9886         Context, PragmaClangTextSection.SectionName,
9887         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9888 
9889   // Apply an implicit SectionAttr if #pragma code_seg is active.
9890   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9891       !NewFD->hasAttr<SectionAttr>()) {
9892     NewFD->addAttr(SectionAttr::CreateImplicit(
9893         Context, CodeSegStack.CurrentValue->getString(),
9894         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9895         SectionAttr::Declspec_allocate));
9896     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9897                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9898                          ASTContext::PSF_Read,
9899                      NewFD))
9900       NewFD->dropAttr<SectionAttr>();
9901   }
9902 
9903   // Apply an implicit CodeSegAttr from class declspec or
9904   // apply an implicit SectionAttr from #pragma code_seg if active.
9905   if (!NewFD->hasAttr<CodeSegAttr>()) {
9906     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9907                                                                  D.isFunctionDefinition())) {
9908       NewFD->addAttr(SAttr);
9909     }
9910   }
9911 
9912   // Handle attributes.
9913   ProcessDeclAttributes(S, NewFD, D);
9914 
9915   if (getLangOpts().OpenCL) {
9916     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9917     // type declaration will generate a compilation error.
9918     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9919     if (AddressSpace != LangAS::Default) {
9920       Diag(NewFD->getLocation(),
9921            diag::err_opencl_return_value_with_address_space);
9922       NewFD->setInvalidDecl();
9923     }
9924   }
9925 
9926   if (!getLangOpts().CPlusPlus) {
9927     // Perform semantic checking on the function declaration.
9928     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9929       CheckMain(NewFD, D.getDeclSpec());
9930 
9931     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9932       CheckMSVCRTEntryPoint(NewFD);
9933 
9934     if (!NewFD->isInvalidDecl())
9935       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9936                                                   isMemberSpecialization,
9937                                                   D.isFunctionDefinition()));
9938     else if (!Previous.empty())
9939       // Recover gracefully from an invalid redeclaration.
9940       D.setRedeclaration(true);
9941     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9942             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9943            "previous declaration set still overloaded");
9944 
9945     // Diagnose no-prototype function declarations with calling conventions that
9946     // don't support variadic calls. Only do this in C and do it after merging
9947     // possibly prototyped redeclarations.
9948     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9949     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9950       CallingConv CC = FT->getExtInfo().getCC();
9951       if (!supportsVariadicCall(CC)) {
9952         // Windows system headers sometimes accidentally use stdcall without
9953         // (void) parameters, so we relax this to a warning.
9954         int DiagID =
9955             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9956         Diag(NewFD->getLocation(), DiagID)
9957             << FunctionType::getNameForCallConv(CC);
9958       }
9959     }
9960 
9961    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9962        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9963      checkNonTrivialCUnion(NewFD->getReturnType(),
9964                            NewFD->getReturnTypeSourceRange().getBegin(),
9965                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9966   } else {
9967     // C++11 [replacement.functions]p3:
9968     //  The program's definitions shall not be specified as inline.
9969     //
9970     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9971     //
9972     // Suppress the diagnostic if the function is __attribute__((used)), since
9973     // that forces an external definition to be emitted.
9974     if (D.getDeclSpec().isInlineSpecified() &&
9975         NewFD->isReplaceableGlobalAllocationFunction() &&
9976         !NewFD->hasAttr<UsedAttr>())
9977       Diag(D.getDeclSpec().getInlineSpecLoc(),
9978            diag::ext_operator_new_delete_declared_inline)
9979         << NewFD->getDeclName();
9980 
9981     // If the declarator is a template-id, translate the parser's template
9982     // argument list into our AST format.
9983     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9984       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9985       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9986       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9987       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9988                                          TemplateId->NumArgs);
9989       translateTemplateArguments(TemplateArgsPtr,
9990                                  TemplateArgs);
9991 
9992       HasExplicitTemplateArgs = true;
9993 
9994       if (NewFD->isInvalidDecl()) {
9995         HasExplicitTemplateArgs = false;
9996       } else if (FunctionTemplate) {
9997         // Function template with explicit template arguments.
9998         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9999           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10000 
10001         HasExplicitTemplateArgs = false;
10002       } else {
10003         assert((isFunctionTemplateSpecialization ||
10004                 D.getDeclSpec().isFriendSpecified()) &&
10005                "should have a 'template<>' for this decl");
10006         // "friend void foo<>(int);" is an implicit specialization decl.
10007         isFunctionTemplateSpecialization = true;
10008       }
10009     } else if (isFriend && isFunctionTemplateSpecialization) {
10010       // This combination is only possible in a recovery case;  the user
10011       // wrote something like:
10012       //   template <> friend void foo(int);
10013       // which we're recovering from as if the user had written:
10014       //   friend void foo<>(int);
10015       // Go ahead and fake up a template id.
10016       HasExplicitTemplateArgs = true;
10017       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10018       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10019     }
10020 
10021     // We do not add HD attributes to specializations here because
10022     // they may have different constexpr-ness compared to their
10023     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10024     // may end up with different effective targets. Instead, a
10025     // specialization inherits its target attributes from its template
10026     // in the CheckFunctionTemplateSpecialization() call below.
10027     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10028       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10029 
10030     // If it's a friend (and only if it's a friend), it's possible
10031     // that either the specialized function type or the specialized
10032     // template is dependent, and therefore matching will fail.  In
10033     // this case, don't check the specialization yet.
10034     if (isFunctionTemplateSpecialization && isFriend &&
10035         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10036          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10037              TemplateArgs.arguments()))) {
10038       assert(HasExplicitTemplateArgs &&
10039              "friend function specialization without template args");
10040       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10041                                                        Previous))
10042         NewFD->setInvalidDecl();
10043     } else if (isFunctionTemplateSpecialization) {
10044       if (CurContext->isDependentContext() && CurContext->isRecord()
10045           && !isFriend) {
10046         isDependentClassScopeExplicitSpecialization = true;
10047       } else if (!NewFD->isInvalidDecl() &&
10048                  CheckFunctionTemplateSpecialization(
10049                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10050                      Previous))
10051         NewFD->setInvalidDecl();
10052 
10053       // C++ [dcl.stc]p1:
10054       //   A storage-class-specifier shall not be specified in an explicit
10055       //   specialization (14.7.3)
10056       FunctionTemplateSpecializationInfo *Info =
10057           NewFD->getTemplateSpecializationInfo();
10058       if (Info && SC != SC_None) {
10059         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10060           Diag(NewFD->getLocation(),
10061                diag::err_explicit_specialization_inconsistent_storage_class)
10062             << SC
10063             << FixItHint::CreateRemoval(
10064                                       D.getDeclSpec().getStorageClassSpecLoc());
10065 
10066         else
10067           Diag(NewFD->getLocation(),
10068                diag::ext_explicit_specialization_storage_class)
10069             << FixItHint::CreateRemoval(
10070                                       D.getDeclSpec().getStorageClassSpecLoc());
10071       }
10072     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10073       if (CheckMemberSpecialization(NewFD, Previous))
10074           NewFD->setInvalidDecl();
10075     }
10076 
10077     // Perform semantic checking on the function declaration.
10078     if (!isDependentClassScopeExplicitSpecialization) {
10079       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10080         CheckMain(NewFD, D.getDeclSpec());
10081 
10082       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10083         CheckMSVCRTEntryPoint(NewFD);
10084 
10085       if (!NewFD->isInvalidDecl())
10086         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10087                                                     isMemberSpecialization,
10088                                                     D.isFunctionDefinition()));
10089       else if (!Previous.empty())
10090         // Recover gracefully from an invalid redeclaration.
10091         D.setRedeclaration(true);
10092     }
10093 
10094     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10095             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10096            "previous declaration set still overloaded");
10097 
10098     NamedDecl *PrincipalDecl = (FunctionTemplate
10099                                 ? cast<NamedDecl>(FunctionTemplate)
10100                                 : NewFD);
10101 
10102     if (isFriend && NewFD->getPreviousDecl()) {
10103       AccessSpecifier Access = AS_public;
10104       if (!NewFD->isInvalidDecl())
10105         Access = NewFD->getPreviousDecl()->getAccess();
10106 
10107       NewFD->setAccess(Access);
10108       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10109     }
10110 
10111     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10112         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10113       PrincipalDecl->setNonMemberOperator();
10114 
10115     // If we have a function template, check the template parameter
10116     // list. This will check and merge default template arguments.
10117     if (FunctionTemplate) {
10118       FunctionTemplateDecl *PrevTemplate =
10119                                      FunctionTemplate->getPreviousDecl();
10120       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10121                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10122                                     : nullptr,
10123                             D.getDeclSpec().isFriendSpecified()
10124                               ? (D.isFunctionDefinition()
10125                                    ? TPC_FriendFunctionTemplateDefinition
10126                                    : TPC_FriendFunctionTemplate)
10127                               : (D.getCXXScopeSpec().isSet() &&
10128                                  DC && DC->isRecord() &&
10129                                  DC->isDependentContext())
10130                                   ? TPC_ClassTemplateMember
10131                                   : TPC_FunctionTemplate);
10132     }
10133 
10134     if (NewFD->isInvalidDecl()) {
10135       // Ignore all the rest of this.
10136     } else if (!D.isRedeclaration()) {
10137       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10138                                        AddToScope };
10139       // Fake up an access specifier if it's supposed to be a class member.
10140       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10141         NewFD->setAccess(AS_public);
10142 
10143       // Qualified decls generally require a previous declaration.
10144       if (D.getCXXScopeSpec().isSet()) {
10145         // ...with the major exception of templated-scope or
10146         // dependent-scope friend declarations.
10147 
10148         // TODO: we currently also suppress this check in dependent
10149         // contexts because (1) the parameter depth will be off when
10150         // matching friend templates and (2) we might actually be
10151         // selecting a friend based on a dependent factor.  But there
10152         // are situations where these conditions don't apply and we
10153         // can actually do this check immediately.
10154         //
10155         // Unless the scope is dependent, it's always an error if qualified
10156         // redeclaration lookup found nothing at all. Diagnose that now;
10157         // nothing will diagnose that error later.
10158         if (isFriend &&
10159             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10160              (!Previous.empty() && CurContext->isDependentContext()))) {
10161           // ignore these
10162         } else if (NewFD->isCPUDispatchMultiVersion() ||
10163                    NewFD->isCPUSpecificMultiVersion()) {
10164           // ignore this, we allow the redeclaration behavior here to create new
10165           // versions of the function.
10166         } else {
10167           // The user tried to provide an out-of-line definition for a
10168           // function that is a member of a class or namespace, but there
10169           // was no such member function declared (C++ [class.mfct]p2,
10170           // C++ [namespace.memdef]p2). For example:
10171           //
10172           // class X {
10173           //   void f() const;
10174           // };
10175           //
10176           // void X::f() { } // ill-formed
10177           //
10178           // Complain about this problem, and attempt to suggest close
10179           // matches (e.g., those that differ only in cv-qualifiers and
10180           // whether the parameter types are references).
10181 
10182           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10183                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10184             AddToScope = ExtraArgs.AddToScope;
10185             return Result;
10186           }
10187         }
10188 
10189         // Unqualified local friend declarations are required to resolve
10190         // to something.
10191       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10192         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10193                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10194           AddToScope = ExtraArgs.AddToScope;
10195           return Result;
10196         }
10197       }
10198     } else if (!D.isFunctionDefinition() &&
10199                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10200                !isFriend && !isFunctionTemplateSpecialization &&
10201                !isMemberSpecialization) {
10202       // An out-of-line member function declaration must also be a
10203       // definition (C++ [class.mfct]p2).
10204       // Note that this is not the case for explicit specializations of
10205       // function templates or member functions of class templates, per
10206       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10207       // extension for compatibility with old SWIG code which likes to
10208       // generate them.
10209       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10210         << D.getCXXScopeSpec().getRange();
10211     }
10212   }
10213 
10214   // If this is the first declaration of a library builtin function, add
10215   // attributes as appropriate.
10216   if (!D.isRedeclaration()) {
10217     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10218       if (unsigned BuiltinID = II->getBuiltinID()) {
10219         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10220         if (!InStdNamespace &&
10221             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10222           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10223             // Validate the type matches unless this builtin is specified as
10224             // matching regardless of its declared type.
10225             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10226               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10227             } else {
10228               ASTContext::GetBuiltinTypeError Error;
10229               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10230               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10231 
10232               if (!Error && !BuiltinType.isNull() &&
10233                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10234                       NewFD->getType(), BuiltinType))
10235                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10236             }
10237           }
10238         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10239                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10240           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10241         }
10242       }
10243     }
10244   }
10245 
10246   ProcessPragmaWeak(S, NewFD);
10247   checkAttributesAfterMerging(*this, *NewFD);
10248 
10249   AddKnownFunctionAttributes(NewFD);
10250 
10251   if (NewFD->hasAttr<OverloadableAttr>() &&
10252       !NewFD->getType()->getAs<FunctionProtoType>()) {
10253     Diag(NewFD->getLocation(),
10254          diag::err_attribute_overloadable_no_prototype)
10255       << NewFD;
10256 
10257     // Turn this into a variadic function with no parameters.
10258     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10259     FunctionProtoType::ExtProtoInfo EPI(
10260         Context.getDefaultCallingConvention(true, false));
10261     EPI.Variadic = true;
10262     EPI.ExtInfo = FT->getExtInfo();
10263 
10264     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10265     NewFD->setType(R);
10266   }
10267 
10268   // If there's a #pragma GCC visibility in scope, and this isn't a class
10269   // member, set the visibility of this function.
10270   if (!DC->isRecord() && NewFD->isExternallyVisible())
10271     AddPushedVisibilityAttribute(NewFD);
10272 
10273   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10274   // marking the function.
10275   AddCFAuditedAttribute(NewFD);
10276 
10277   // If this is a function definition, check if we have to apply any
10278   // attributes (i.e. optnone and no_builtin) due to a pragma.
10279   if (D.isFunctionDefinition()) {
10280     AddRangeBasedOptnone(NewFD);
10281     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10282     AddSectionMSAllocText(NewFD);
10283     ModifyFnAttributesMSPragmaOptimize(NewFD);
10284   }
10285 
10286   // If this is the first declaration of an extern C variable, update
10287   // the map of such variables.
10288   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10289       isIncompleteDeclExternC(*this, NewFD))
10290     RegisterLocallyScopedExternCDecl(NewFD, S);
10291 
10292   // Set this FunctionDecl's range up to the right paren.
10293   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10294 
10295   if (D.isRedeclaration() && !Previous.empty()) {
10296     NamedDecl *Prev = Previous.getRepresentativeDecl();
10297     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10298                                    isMemberSpecialization ||
10299                                        isFunctionTemplateSpecialization,
10300                                    D.isFunctionDefinition());
10301   }
10302 
10303   if (getLangOpts().CUDA) {
10304     IdentifierInfo *II = NewFD->getIdentifier();
10305     if (II && II->isStr(getCudaConfigureFuncName()) &&
10306         !NewFD->isInvalidDecl() &&
10307         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10308       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10309         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10310             << getCudaConfigureFuncName();
10311       Context.setcudaConfigureCallDecl(NewFD);
10312     }
10313 
10314     // Variadic functions, other than a *declaration* of printf, are not allowed
10315     // in device-side CUDA code, unless someone passed
10316     // -fcuda-allow-variadic-functions.
10317     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10318         (NewFD->hasAttr<CUDADeviceAttr>() ||
10319          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10320         !(II && II->isStr("printf") && NewFD->isExternC() &&
10321           !D.isFunctionDefinition())) {
10322       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10323     }
10324   }
10325 
10326   MarkUnusedFileScopedDecl(NewFD);
10327 
10328 
10329 
10330   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10331     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10332     if (SC == SC_Static) {
10333       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10334       D.setInvalidType();
10335     }
10336 
10337     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10338     if (!NewFD->getReturnType()->isVoidType()) {
10339       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10340       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10341           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10342                                 : FixItHint());
10343       D.setInvalidType();
10344     }
10345 
10346     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10347     for (auto Param : NewFD->parameters())
10348       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10349 
10350     if (getLangOpts().OpenCLCPlusPlus) {
10351       if (DC->isRecord()) {
10352         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10353         D.setInvalidType();
10354       }
10355       if (FunctionTemplate) {
10356         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10357         D.setInvalidType();
10358       }
10359     }
10360   }
10361 
10362   if (getLangOpts().CPlusPlus) {
10363     if (FunctionTemplate) {
10364       if (NewFD->isInvalidDecl())
10365         FunctionTemplate->setInvalidDecl();
10366       return FunctionTemplate;
10367     }
10368 
10369     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10370       CompleteMemberSpecialization(NewFD, Previous);
10371   }
10372 
10373   for (const ParmVarDecl *Param : NewFD->parameters()) {
10374     QualType PT = Param->getType();
10375 
10376     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10377     // types.
10378     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10379       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10380         QualType ElemTy = PipeTy->getElementType();
10381           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10382             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10383             D.setInvalidType();
10384           }
10385       }
10386     }
10387   }
10388 
10389   // Here we have an function template explicit specialization at class scope.
10390   // The actual specialization will be postponed to template instatiation
10391   // time via the ClassScopeFunctionSpecializationDecl node.
10392   if (isDependentClassScopeExplicitSpecialization) {
10393     ClassScopeFunctionSpecializationDecl *NewSpec =
10394                          ClassScopeFunctionSpecializationDecl::Create(
10395                                 Context, CurContext, NewFD->getLocation(),
10396                                 cast<CXXMethodDecl>(NewFD),
10397                                 HasExplicitTemplateArgs, TemplateArgs);
10398     CurContext->addDecl(NewSpec);
10399     AddToScope = false;
10400   }
10401 
10402   // Diagnose availability attributes. Availability cannot be used on functions
10403   // that are run during load/unload.
10404   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10405     if (NewFD->hasAttr<ConstructorAttr>()) {
10406       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10407           << 1;
10408       NewFD->dropAttr<AvailabilityAttr>();
10409     }
10410     if (NewFD->hasAttr<DestructorAttr>()) {
10411       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10412           << 2;
10413       NewFD->dropAttr<AvailabilityAttr>();
10414     }
10415   }
10416 
10417   // Diagnose no_builtin attribute on function declaration that are not a
10418   // definition.
10419   // FIXME: We should really be doing this in
10420   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10421   // the FunctionDecl and at this point of the code
10422   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10423   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10424   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10425     switch (D.getFunctionDefinitionKind()) {
10426     case FunctionDefinitionKind::Defaulted:
10427     case FunctionDefinitionKind::Deleted:
10428       Diag(NBA->getLocation(),
10429            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10430           << NBA->getSpelling();
10431       break;
10432     case FunctionDefinitionKind::Declaration:
10433       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10434           << NBA->getSpelling();
10435       break;
10436     case FunctionDefinitionKind::Definition:
10437       break;
10438     }
10439 
10440   return NewFD;
10441 }
10442 
10443 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10444 /// when __declspec(code_seg) "is applied to a class, all member functions of
10445 /// the class and nested classes -- this includes compiler-generated special
10446 /// member functions -- are put in the specified segment."
10447 /// The actual behavior is a little more complicated. The Microsoft compiler
10448 /// won't check outer classes if there is an active value from #pragma code_seg.
10449 /// The CodeSeg is always applied from the direct parent but only from outer
10450 /// classes when the #pragma code_seg stack is empty. See:
10451 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10452 /// available since MS has removed the page.
10453 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10454   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10455   if (!Method)
10456     return nullptr;
10457   const CXXRecordDecl *Parent = Method->getParent();
10458   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10459     Attr *NewAttr = SAttr->clone(S.getASTContext());
10460     NewAttr->setImplicit(true);
10461     return NewAttr;
10462   }
10463 
10464   // The Microsoft compiler won't check outer classes for the CodeSeg
10465   // when the #pragma code_seg stack is active.
10466   if (S.CodeSegStack.CurrentValue)
10467    return nullptr;
10468 
10469   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10470     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10471       Attr *NewAttr = SAttr->clone(S.getASTContext());
10472       NewAttr->setImplicit(true);
10473       return NewAttr;
10474     }
10475   }
10476   return nullptr;
10477 }
10478 
10479 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10480 /// containing class. Otherwise it will return implicit SectionAttr if the
10481 /// function is a definition and there is an active value on CodeSegStack
10482 /// (from the current #pragma code-seg value).
10483 ///
10484 /// \param FD Function being declared.
10485 /// \param IsDefinition Whether it is a definition or just a declarartion.
10486 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10487 ///          nullptr if no attribute should be added.
10488 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10489                                                        bool IsDefinition) {
10490   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10491     return A;
10492   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10493       CodeSegStack.CurrentValue)
10494     return SectionAttr::CreateImplicit(
10495         getASTContext(), CodeSegStack.CurrentValue->getString(),
10496         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10497         SectionAttr::Declspec_allocate);
10498   return nullptr;
10499 }
10500 
10501 /// Determines if we can perform a correct type check for \p D as a
10502 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10503 /// best-effort check.
10504 ///
10505 /// \param NewD The new declaration.
10506 /// \param OldD The old declaration.
10507 /// \param NewT The portion of the type of the new declaration to check.
10508 /// \param OldT The portion of the type of the old declaration to check.
10509 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10510                                           QualType NewT, QualType OldT) {
10511   if (!NewD->getLexicalDeclContext()->isDependentContext())
10512     return true;
10513 
10514   // For dependently-typed local extern declarations and friends, we can't
10515   // perform a correct type check in general until instantiation:
10516   //
10517   //   int f();
10518   //   template<typename T> void g() { T f(); }
10519   //
10520   // (valid if g() is only instantiated with T = int).
10521   if (NewT->isDependentType() &&
10522       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10523     return false;
10524 
10525   // Similarly, if the previous declaration was a dependent local extern
10526   // declaration, we don't really know its type yet.
10527   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10528     return false;
10529 
10530   return true;
10531 }
10532 
10533 /// Checks if the new declaration declared in dependent context must be
10534 /// put in the same redeclaration chain as the specified declaration.
10535 ///
10536 /// \param D Declaration that is checked.
10537 /// \param PrevDecl Previous declaration found with proper lookup method for the
10538 ///                 same declaration name.
10539 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10540 ///          belongs to.
10541 ///
10542 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10543   if (!D->getLexicalDeclContext()->isDependentContext())
10544     return true;
10545 
10546   // Don't chain dependent friend function definitions until instantiation, to
10547   // permit cases like
10548   //
10549   //   void func();
10550   //   template<typename T> class C1 { friend void func() {} };
10551   //   template<typename T> class C2 { friend void func() {} };
10552   //
10553   // ... which is valid if only one of C1 and C2 is ever instantiated.
10554   //
10555   // FIXME: This need only apply to function definitions. For now, we proxy
10556   // this by checking for a file-scope function. We do not want this to apply
10557   // to friend declarations nominating member functions, because that gets in
10558   // the way of access checks.
10559   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10560     return false;
10561 
10562   auto *VD = dyn_cast<ValueDecl>(D);
10563   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10564   return !VD || !PrevVD ||
10565          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10566                                         PrevVD->getType());
10567 }
10568 
10569 /// Check the target attribute of the function for MultiVersion
10570 /// validity.
10571 ///
10572 /// Returns true if there was an error, false otherwise.
10573 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10574   const auto *TA = FD->getAttr<TargetAttr>();
10575   assert(TA && "MultiVersion Candidate requires a target attribute");
10576   ParsedTargetAttr ParseInfo = TA->parse();
10577   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10578   enum ErrType { Feature = 0, Architecture = 1 };
10579 
10580   if (!ParseInfo.Architecture.empty() &&
10581       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10582     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10583         << Architecture << ParseInfo.Architecture;
10584     return true;
10585   }
10586 
10587   for (const auto &Feat : ParseInfo.Features) {
10588     auto BareFeat = StringRef{Feat}.substr(1);
10589     if (Feat[0] == '-') {
10590       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10591           << Feature << ("no-" + BareFeat).str();
10592       return true;
10593     }
10594 
10595     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10596         !TargetInfo.isValidFeatureName(BareFeat)) {
10597       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10598           << Feature << BareFeat;
10599       return true;
10600     }
10601   }
10602   return false;
10603 }
10604 
10605 // Provide a white-list of attributes that are allowed to be combined with
10606 // multiversion functions.
10607 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10608                                            MultiVersionKind MVKind) {
10609   // Note: this list/diagnosis must match the list in
10610   // checkMultiversionAttributesAllSame.
10611   switch (Kind) {
10612   default:
10613     return false;
10614   case attr::Used:
10615     return MVKind == MultiVersionKind::Target;
10616   case attr::NonNull:
10617   case attr::NoThrow:
10618     return true;
10619   }
10620 }
10621 
10622 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10623                                                  const FunctionDecl *FD,
10624                                                  const FunctionDecl *CausedFD,
10625                                                  MultiVersionKind MVKind) {
10626   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10627     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10628         << static_cast<unsigned>(MVKind) << A;
10629     if (CausedFD)
10630       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10631     return true;
10632   };
10633 
10634   for (const Attr *A : FD->attrs()) {
10635     switch (A->getKind()) {
10636     case attr::CPUDispatch:
10637     case attr::CPUSpecific:
10638       if (MVKind != MultiVersionKind::CPUDispatch &&
10639           MVKind != MultiVersionKind::CPUSpecific)
10640         return Diagnose(S, A);
10641       break;
10642     case attr::Target:
10643       if (MVKind != MultiVersionKind::Target)
10644         return Diagnose(S, A);
10645       break;
10646     case attr::TargetClones:
10647       if (MVKind != MultiVersionKind::TargetClones)
10648         return Diagnose(S, A);
10649       break;
10650     default:
10651       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10652         return Diagnose(S, A);
10653       break;
10654     }
10655   }
10656   return false;
10657 }
10658 
10659 bool Sema::areMultiversionVariantFunctionsCompatible(
10660     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10661     const PartialDiagnostic &NoProtoDiagID,
10662     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10663     const PartialDiagnosticAt &NoSupportDiagIDAt,
10664     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10665     bool ConstexprSupported, bool CLinkageMayDiffer) {
10666   enum DoesntSupport {
10667     FuncTemplates = 0,
10668     VirtFuncs = 1,
10669     DeducedReturn = 2,
10670     Constructors = 3,
10671     Destructors = 4,
10672     DeletedFuncs = 5,
10673     DefaultedFuncs = 6,
10674     ConstexprFuncs = 7,
10675     ConstevalFuncs = 8,
10676     Lambda = 9,
10677   };
10678   enum Different {
10679     CallingConv = 0,
10680     ReturnType = 1,
10681     ConstexprSpec = 2,
10682     InlineSpec = 3,
10683     Linkage = 4,
10684     LanguageLinkage = 5,
10685   };
10686 
10687   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10688       !OldFD->getType()->getAs<FunctionProtoType>()) {
10689     Diag(OldFD->getLocation(), NoProtoDiagID);
10690     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10691     return true;
10692   }
10693 
10694   if (NoProtoDiagID.getDiagID() != 0 &&
10695       !NewFD->getType()->getAs<FunctionProtoType>())
10696     return Diag(NewFD->getLocation(), NoProtoDiagID);
10697 
10698   if (!TemplatesSupported &&
10699       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10700     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10701            << FuncTemplates;
10702 
10703   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10704     if (NewCXXFD->isVirtual())
10705       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10706              << VirtFuncs;
10707 
10708     if (isa<CXXConstructorDecl>(NewCXXFD))
10709       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10710              << Constructors;
10711 
10712     if (isa<CXXDestructorDecl>(NewCXXFD))
10713       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10714              << Destructors;
10715   }
10716 
10717   if (NewFD->isDeleted())
10718     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10719            << DeletedFuncs;
10720 
10721   if (NewFD->isDefaulted())
10722     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10723            << DefaultedFuncs;
10724 
10725   if (!ConstexprSupported && NewFD->isConstexpr())
10726     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10727            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10728 
10729   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10730   const auto *NewType = cast<FunctionType>(NewQType);
10731   QualType NewReturnType = NewType->getReturnType();
10732 
10733   if (NewReturnType->isUndeducedType())
10734     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10735            << DeducedReturn;
10736 
10737   // Ensure the return type is identical.
10738   if (OldFD) {
10739     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10740     const auto *OldType = cast<FunctionType>(OldQType);
10741     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10742     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10743 
10744     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10745       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10746 
10747     QualType OldReturnType = OldType->getReturnType();
10748 
10749     if (OldReturnType != NewReturnType)
10750       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10751 
10752     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10753       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10754 
10755     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10756       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10757 
10758     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10759       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10760 
10761     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10762       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10763 
10764     if (CheckEquivalentExceptionSpec(
10765             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10766             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10767       return true;
10768   }
10769   return false;
10770 }
10771 
10772 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10773                                              const FunctionDecl *NewFD,
10774                                              bool CausesMV,
10775                                              MultiVersionKind MVKind) {
10776   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10777     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10778     if (OldFD)
10779       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10780     return true;
10781   }
10782 
10783   bool IsCPUSpecificCPUDispatchMVKind =
10784       MVKind == MultiVersionKind::CPUDispatch ||
10785       MVKind == MultiVersionKind::CPUSpecific;
10786 
10787   if (CausesMV && OldFD &&
10788       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10789     return true;
10790 
10791   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10792     return true;
10793 
10794   // Only allow transition to MultiVersion if it hasn't been used.
10795   if (OldFD && CausesMV && OldFD->isUsed(false))
10796     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10797 
10798   return S.areMultiversionVariantFunctionsCompatible(
10799       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10800       PartialDiagnosticAt(NewFD->getLocation(),
10801                           S.PDiag(diag::note_multiversioning_caused_here)),
10802       PartialDiagnosticAt(NewFD->getLocation(),
10803                           S.PDiag(diag::err_multiversion_doesnt_support)
10804                               << static_cast<unsigned>(MVKind)),
10805       PartialDiagnosticAt(NewFD->getLocation(),
10806                           S.PDiag(diag::err_multiversion_diff)),
10807       /*TemplatesSupported=*/false,
10808       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10809       /*CLinkageMayDiffer=*/false);
10810 }
10811 
10812 /// Check the validity of a multiversion function declaration that is the
10813 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10814 ///
10815 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10816 ///
10817 /// Returns true if there was an error, false otherwise.
10818 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10819                                            MultiVersionKind MVKind,
10820                                            const TargetAttr *TA) {
10821   assert(MVKind != MultiVersionKind::None &&
10822          "Function lacks multiversion attribute");
10823 
10824   // Target only causes MV if it is default, otherwise this is a normal
10825   // function.
10826   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10827     return false;
10828 
10829   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10830     FD->setInvalidDecl();
10831     return true;
10832   }
10833 
10834   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10835     FD->setInvalidDecl();
10836     return true;
10837   }
10838 
10839   FD->setIsMultiVersion();
10840   return false;
10841 }
10842 
10843 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10844   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10845     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10846       return true;
10847   }
10848 
10849   return false;
10850 }
10851 
10852 static bool CheckTargetCausesMultiVersioning(
10853     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10854     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10855   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10856   ParsedTargetAttr NewParsed = NewTA->parse();
10857   // Sort order doesn't matter, it just needs to be consistent.
10858   llvm::sort(NewParsed.Features);
10859 
10860   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10861   // to change, this is a simple redeclaration.
10862   if (!NewTA->isDefaultVersion() &&
10863       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10864     return false;
10865 
10866   // Otherwise, this decl causes MultiVersioning.
10867   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10868                                        MultiVersionKind::Target)) {
10869     NewFD->setInvalidDecl();
10870     return true;
10871   }
10872 
10873   if (CheckMultiVersionValue(S, NewFD)) {
10874     NewFD->setInvalidDecl();
10875     return true;
10876   }
10877 
10878   // If this is 'default', permit the forward declaration.
10879   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10880     Redeclaration = true;
10881     OldDecl = OldFD;
10882     OldFD->setIsMultiVersion();
10883     NewFD->setIsMultiVersion();
10884     return false;
10885   }
10886 
10887   if (CheckMultiVersionValue(S, OldFD)) {
10888     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10889     NewFD->setInvalidDecl();
10890     return true;
10891   }
10892 
10893   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10894 
10895   if (OldParsed == NewParsed) {
10896     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10897     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10898     NewFD->setInvalidDecl();
10899     return true;
10900   }
10901 
10902   for (const auto *FD : OldFD->redecls()) {
10903     const auto *CurTA = FD->getAttr<TargetAttr>();
10904     // We allow forward declarations before ANY multiversioning attributes, but
10905     // nothing after the fact.
10906     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10907         (!CurTA || CurTA->isInherited())) {
10908       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10909           << 0;
10910       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10911       NewFD->setInvalidDecl();
10912       return true;
10913     }
10914   }
10915 
10916   OldFD->setIsMultiVersion();
10917   NewFD->setIsMultiVersion();
10918   Redeclaration = false;
10919   OldDecl = nullptr;
10920   Previous.clear();
10921   return false;
10922 }
10923 
10924 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10925                                         MultiVersionKind New) {
10926   if (Old == New || Old == MultiVersionKind::None ||
10927       New == MultiVersionKind::None)
10928     return true;
10929 
10930   return (Old == MultiVersionKind::CPUDispatch &&
10931           New == MultiVersionKind::CPUSpecific) ||
10932          (Old == MultiVersionKind::CPUSpecific &&
10933           New == MultiVersionKind::CPUDispatch);
10934 }
10935 
10936 /// Check the validity of a new function declaration being added to an existing
10937 /// multiversioned declaration collection.
10938 static bool CheckMultiVersionAdditionalDecl(
10939     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10940     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10941     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10942     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10943     LookupResult &Previous) {
10944 
10945   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10946   // Disallow mixing of multiversioning types.
10947   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10948     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10949     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10950     NewFD->setInvalidDecl();
10951     return true;
10952   }
10953 
10954   ParsedTargetAttr NewParsed;
10955   if (NewTA) {
10956     NewParsed = NewTA->parse();
10957     llvm::sort(NewParsed.Features);
10958   }
10959 
10960   bool UseMemberUsingDeclRules =
10961       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10962 
10963   bool MayNeedOverloadableChecks =
10964       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10965 
10966   // Next, check ALL non-overloads to see if this is a redeclaration of a
10967   // previous member of the MultiVersion set.
10968   for (NamedDecl *ND : Previous) {
10969     FunctionDecl *CurFD = ND->getAsFunction();
10970     if (!CurFD)
10971       continue;
10972     if (MayNeedOverloadableChecks &&
10973         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10974       continue;
10975 
10976     switch (NewMVKind) {
10977     case MultiVersionKind::None:
10978       assert(OldMVKind == MultiVersionKind::TargetClones &&
10979              "Only target_clones can be omitted in subsequent declarations");
10980       break;
10981     case MultiVersionKind::Target: {
10982       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10983       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10984         NewFD->setIsMultiVersion();
10985         Redeclaration = true;
10986         OldDecl = ND;
10987         return false;
10988       }
10989 
10990       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10991       if (CurParsed == NewParsed) {
10992         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10993         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10994         NewFD->setInvalidDecl();
10995         return true;
10996       }
10997       break;
10998     }
10999     case MultiVersionKind::TargetClones: {
11000       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11001       Redeclaration = true;
11002       OldDecl = CurFD;
11003       NewFD->setIsMultiVersion();
11004 
11005       if (CurClones && NewClones &&
11006           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11007            !std::equal(CurClones->featuresStrs_begin(),
11008                        CurClones->featuresStrs_end(),
11009                        NewClones->featuresStrs_begin()))) {
11010         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11011         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11012         NewFD->setInvalidDecl();
11013         return true;
11014       }
11015 
11016       return false;
11017     }
11018     case MultiVersionKind::CPUSpecific:
11019     case MultiVersionKind::CPUDispatch: {
11020       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11021       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11022       // Handle CPUDispatch/CPUSpecific versions.
11023       // Only 1 CPUDispatch function is allowed, this will make it go through
11024       // the redeclaration errors.
11025       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11026           CurFD->hasAttr<CPUDispatchAttr>()) {
11027         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11028             std::equal(
11029                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11030                 NewCPUDisp->cpus_begin(),
11031                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11032                   return Cur->getName() == New->getName();
11033                 })) {
11034           NewFD->setIsMultiVersion();
11035           Redeclaration = true;
11036           OldDecl = ND;
11037           return false;
11038         }
11039 
11040         // If the declarations don't match, this is an error condition.
11041         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11042         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11043         NewFD->setInvalidDecl();
11044         return true;
11045       }
11046       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11047         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11048             std::equal(
11049                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11050                 NewCPUSpec->cpus_begin(),
11051                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11052                   return Cur->getName() == New->getName();
11053                 })) {
11054           NewFD->setIsMultiVersion();
11055           Redeclaration = true;
11056           OldDecl = ND;
11057           return false;
11058         }
11059 
11060         // Only 1 version of CPUSpecific is allowed for each CPU.
11061         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11062           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11063             if (CurII == NewII) {
11064               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11065                   << NewII;
11066               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11067               NewFD->setInvalidDecl();
11068               return true;
11069             }
11070           }
11071         }
11072       }
11073       break;
11074     }
11075     }
11076   }
11077 
11078   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11079   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11080   // handled in the attribute adding step.
11081   if (NewMVKind == MultiVersionKind::Target &&
11082       CheckMultiVersionValue(S, NewFD)) {
11083     NewFD->setInvalidDecl();
11084     return true;
11085   }
11086 
11087   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11088                                        !OldFD->isMultiVersion(), NewMVKind)) {
11089     NewFD->setInvalidDecl();
11090     return true;
11091   }
11092 
11093   // Permit forward declarations in the case where these two are compatible.
11094   if (!OldFD->isMultiVersion()) {
11095     OldFD->setIsMultiVersion();
11096     NewFD->setIsMultiVersion();
11097     Redeclaration = true;
11098     OldDecl = OldFD;
11099     return false;
11100   }
11101 
11102   NewFD->setIsMultiVersion();
11103   Redeclaration = false;
11104   OldDecl = nullptr;
11105   Previous.clear();
11106   return false;
11107 }
11108 
11109 /// Check the validity of a mulitversion function declaration.
11110 /// Also sets the multiversion'ness' of the function itself.
11111 ///
11112 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11113 ///
11114 /// Returns true if there was an error, false otherwise.
11115 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11116                                       bool &Redeclaration, NamedDecl *&OldDecl,
11117                                       LookupResult &Previous) {
11118   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11119   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11120   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11121   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11122   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11123 
11124   // Main isn't allowed to become a multiversion function, however it IS
11125   // permitted to have 'main' be marked with the 'target' optimization hint.
11126   if (NewFD->isMain()) {
11127     if (MVKind != MultiVersionKind::None &&
11128         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11129       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11130       NewFD->setInvalidDecl();
11131       return true;
11132     }
11133     return false;
11134   }
11135 
11136   if (!OldDecl || !OldDecl->getAsFunction() ||
11137       OldDecl->getDeclContext()->getRedeclContext() !=
11138           NewFD->getDeclContext()->getRedeclContext()) {
11139     // If there's no previous declaration, AND this isn't attempting to cause
11140     // multiversioning, this isn't an error condition.
11141     if (MVKind == MultiVersionKind::None)
11142       return false;
11143     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11144   }
11145 
11146   FunctionDecl *OldFD = OldDecl->getAsFunction();
11147 
11148   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11149     return false;
11150 
11151   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11152   // for target_clones.
11153   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11154       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11155     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11156         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11157     NewFD->setInvalidDecl();
11158     return true;
11159   }
11160 
11161   if (!OldFD->isMultiVersion()) {
11162     switch (MVKind) {
11163     case MultiVersionKind::Target:
11164       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11165                                               Redeclaration, OldDecl, Previous);
11166     case MultiVersionKind::TargetClones:
11167       if (OldFD->isUsed(false)) {
11168         NewFD->setInvalidDecl();
11169         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11170       }
11171       OldFD->setIsMultiVersion();
11172       break;
11173     case MultiVersionKind::CPUDispatch:
11174     case MultiVersionKind::CPUSpecific:
11175     case MultiVersionKind::None:
11176       break;
11177     }
11178   }
11179 
11180   // At this point, we have a multiversion function decl (in OldFD) AND an
11181   // appropriate attribute in the current function decl.  Resolve that these are
11182   // still compatible with previous declarations.
11183   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11184                                          NewCPUDisp, NewCPUSpec, NewClones,
11185                                          Redeclaration, OldDecl, Previous);
11186 }
11187 
11188 /// Perform semantic checking of a new function declaration.
11189 ///
11190 /// Performs semantic analysis of the new function declaration
11191 /// NewFD. This routine performs all semantic checking that does not
11192 /// require the actual declarator involved in the declaration, and is
11193 /// used both for the declaration of functions as they are parsed
11194 /// (called via ActOnDeclarator) and for the declaration of functions
11195 /// that have been instantiated via C++ template instantiation (called
11196 /// via InstantiateDecl).
11197 ///
11198 /// \param IsMemberSpecialization whether this new function declaration is
11199 /// a member specialization (that replaces any definition provided by the
11200 /// previous declaration).
11201 ///
11202 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11203 ///
11204 /// \returns true if the function declaration is a redeclaration.
11205 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11206                                     LookupResult &Previous,
11207                                     bool IsMemberSpecialization,
11208                                     bool DeclIsDefn) {
11209   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11210          "Variably modified return types are not handled here");
11211 
11212   // Determine whether the type of this function should be merged with
11213   // a previous visible declaration. This never happens for functions in C++,
11214   // and always happens in C if the previous declaration was visible.
11215   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11216                                !Previous.isShadowed();
11217 
11218   bool Redeclaration = false;
11219   NamedDecl *OldDecl = nullptr;
11220   bool MayNeedOverloadableChecks = false;
11221 
11222   // Merge or overload the declaration with an existing declaration of
11223   // the same name, if appropriate.
11224   if (!Previous.empty()) {
11225     // Determine whether NewFD is an overload of PrevDecl or
11226     // a declaration that requires merging. If it's an overload,
11227     // there's no more work to do here; we'll just add the new
11228     // function to the scope.
11229     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11230       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11231       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11232         Redeclaration = true;
11233         OldDecl = Candidate;
11234       }
11235     } else {
11236       MayNeedOverloadableChecks = true;
11237       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11238                             /*NewIsUsingDecl*/ false)) {
11239       case Ovl_Match:
11240         Redeclaration = true;
11241         break;
11242 
11243       case Ovl_NonFunction:
11244         Redeclaration = true;
11245         break;
11246 
11247       case Ovl_Overload:
11248         Redeclaration = false;
11249         break;
11250       }
11251     }
11252   }
11253 
11254   // Check for a previous extern "C" declaration with this name.
11255   if (!Redeclaration &&
11256       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11257     if (!Previous.empty()) {
11258       // This is an extern "C" declaration with the same name as a previous
11259       // declaration, and thus redeclares that entity...
11260       Redeclaration = true;
11261       OldDecl = Previous.getFoundDecl();
11262       MergeTypeWithPrevious = false;
11263 
11264       // ... except in the presence of __attribute__((overloadable)).
11265       if (OldDecl->hasAttr<OverloadableAttr>() ||
11266           NewFD->hasAttr<OverloadableAttr>()) {
11267         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11268           MayNeedOverloadableChecks = true;
11269           Redeclaration = false;
11270           OldDecl = nullptr;
11271         }
11272       }
11273     }
11274   }
11275 
11276   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11277     return Redeclaration;
11278 
11279   // PPC MMA non-pointer types are not allowed as function return types.
11280   if (Context.getTargetInfo().getTriple().isPPC64() &&
11281       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11282     NewFD->setInvalidDecl();
11283   }
11284 
11285   // C++11 [dcl.constexpr]p8:
11286   //   A constexpr specifier for a non-static member function that is not
11287   //   a constructor declares that member function to be const.
11288   //
11289   // This needs to be delayed until we know whether this is an out-of-line
11290   // definition of a static member function.
11291   //
11292   // This rule is not present in C++1y, so we produce a backwards
11293   // compatibility warning whenever it happens in C++11.
11294   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11295   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11296       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11297       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11298     CXXMethodDecl *OldMD = nullptr;
11299     if (OldDecl)
11300       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11301     if (!OldMD || !OldMD->isStatic()) {
11302       const FunctionProtoType *FPT =
11303         MD->getType()->castAs<FunctionProtoType>();
11304       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11305       EPI.TypeQuals.addConst();
11306       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11307                                           FPT->getParamTypes(), EPI));
11308 
11309       // Warn that we did this, if we're not performing template instantiation.
11310       // In that case, we'll have warned already when the template was defined.
11311       if (!inTemplateInstantiation()) {
11312         SourceLocation AddConstLoc;
11313         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11314                 .IgnoreParens().getAs<FunctionTypeLoc>())
11315           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11316 
11317         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11318           << FixItHint::CreateInsertion(AddConstLoc, " const");
11319       }
11320     }
11321   }
11322 
11323   if (Redeclaration) {
11324     // NewFD and OldDecl represent declarations that need to be
11325     // merged.
11326     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11327                           DeclIsDefn)) {
11328       NewFD->setInvalidDecl();
11329       return Redeclaration;
11330     }
11331 
11332     Previous.clear();
11333     Previous.addDecl(OldDecl);
11334 
11335     if (FunctionTemplateDecl *OldTemplateDecl =
11336             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11337       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11338       FunctionTemplateDecl *NewTemplateDecl
11339         = NewFD->getDescribedFunctionTemplate();
11340       assert(NewTemplateDecl && "Template/non-template mismatch");
11341 
11342       // The call to MergeFunctionDecl above may have created some state in
11343       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11344       // can add it as a redeclaration.
11345       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11346 
11347       NewFD->setPreviousDeclaration(OldFD);
11348       if (NewFD->isCXXClassMember()) {
11349         NewFD->setAccess(OldTemplateDecl->getAccess());
11350         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11351       }
11352 
11353       // If this is an explicit specialization of a member that is a function
11354       // template, mark it as a member specialization.
11355       if (IsMemberSpecialization &&
11356           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11357         NewTemplateDecl->setMemberSpecialization();
11358         assert(OldTemplateDecl->isMemberSpecialization());
11359         // Explicit specializations of a member template do not inherit deleted
11360         // status from the parent member template that they are specializing.
11361         if (OldFD->isDeleted()) {
11362           // FIXME: This assert will not hold in the presence of modules.
11363           assert(OldFD->getCanonicalDecl() == OldFD);
11364           // FIXME: We need an update record for this AST mutation.
11365           OldFD->setDeletedAsWritten(false);
11366         }
11367       }
11368 
11369     } else {
11370       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11371         auto *OldFD = cast<FunctionDecl>(OldDecl);
11372         // This needs to happen first so that 'inline' propagates.
11373         NewFD->setPreviousDeclaration(OldFD);
11374         if (NewFD->isCXXClassMember())
11375           NewFD->setAccess(OldFD->getAccess());
11376       }
11377     }
11378   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11379              !NewFD->getAttr<OverloadableAttr>()) {
11380     assert((Previous.empty() ||
11381             llvm::any_of(Previous,
11382                          [](const NamedDecl *ND) {
11383                            return ND->hasAttr<OverloadableAttr>();
11384                          })) &&
11385            "Non-redecls shouldn't happen without overloadable present");
11386 
11387     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11388       const auto *FD = dyn_cast<FunctionDecl>(ND);
11389       return FD && !FD->hasAttr<OverloadableAttr>();
11390     });
11391 
11392     if (OtherUnmarkedIter != Previous.end()) {
11393       Diag(NewFD->getLocation(),
11394            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11395       Diag((*OtherUnmarkedIter)->getLocation(),
11396            diag::note_attribute_overloadable_prev_overload)
11397           << false;
11398 
11399       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11400     }
11401   }
11402 
11403   if (LangOpts.OpenMP)
11404     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11405 
11406   // Semantic checking for this function declaration (in isolation).
11407 
11408   if (getLangOpts().CPlusPlus) {
11409     // C++-specific checks.
11410     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11411       CheckConstructor(Constructor);
11412     } else if (CXXDestructorDecl *Destructor =
11413                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11414       CXXRecordDecl *Record = Destructor->getParent();
11415       QualType ClassType = Context.getTypeDeclType(Record);
11416 
11417       // FIXME: Shouldn't we be able to perform this check even when the class
11418       // type is dependent? Both gcc and edg can handle that.
11419       if (!ClassType->isDependentType()) {
11420         DeclarationName Name
11421           = Context.DeclarationNames.getCXXDestructorName(
11422                                         Context.getCanonicalType(ClassType));
11423         if (NewFD->getDeclName() != Name) {
11424           Diag(NewFD->getLocation(), diag::err_destructor_name);
11425           NewFD->setInvalidDecl();
11426           return Redeclaration;
11427         }
11428       }
11429     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11430       if (auto *TD = Guide->getDescribedFunctionTemplate())
11431         CheckDeductionGuideTemplate(TD);
11432 
11433       // A deduction guide is not on the list of entities that can be
11434       // explicitly specialized.
11435       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11436         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11437             << /*explicit specialization*/ 1;
11438     }
11439 
11440     // Find any virtual functions that this function overrides.
11441     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11442       if (!Method->isFunctionTemplateSpecialization() &&
11443           !Method->getDescribedFunctionTemplate() &&
11444           Method->isCanonicalDecl()) {
11445         AddOverriddenMethods(Method->getParent(), Method);
11446       }
11447       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11448         // C++2a [class.virtual]p6
11449         // A virtual method shall not have a requires-clause.
11450         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11451              diag::err_constrained_virtual_method);
11452 
11453       if (Method->isStatic())
11454         checkThisInStaticMemberFunctionType(Method);
11455     }
11456 
11457     // C++20: dcl.decl.general p4:
11458     // The optional requires-clause ([temp.pre]) in an init-declarator or
11459     // member-declarator shall be present only if the declarator declares a
11460     // templated function ([dcl.fct]).
11461     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11462       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11463         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11464     }
11465 
11466     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11467       ActOnConversionDeclarator(Conversion);
11468 
11469     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11470     if (NewFD->isOverloadedOperator() &&
11471         CheckOverloadedOperatorDeclaration(NewFD)) {
11472       NewFD->setInvalidDecl();
11473       return Redeclaration;
11474     }
11475 
11476     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11477     if (NewFD->getLiteralIdentifier() &&
11478         CheckLiteralOperatorDeclaration(NewFD)) {
11479       NewFD->setInvalidDecl();
11480       return Redeclaration;
11481     }
11482 
11483     // In C++, check default arguments now that we have merged decls. Unless
11484     // the lexical context is the class, because in this case this is done
11485     // during delayed parsing anyway.
11486     if (!CurContext->isRecord())
11487       CheckCXXDefaultArguments(NewFD);
11488 
11489     // If this function is declared as being extern "C", then check to see if
11490     // the function returns a UDT (class, struct, or union type) that is not C
11491     // compatible, and if it does, warn the user.
11492     // But, issue any diagnostic on the first declaration only.
11493     if (Previous.empty() && NewFD->isExternC()) {
11494       QualType R = NewFD->getReturnType();
11495       if (R->isIncompleteType() && !R->isVoidType())
11496         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11497             << NewFD << R;
11498       else if (!R.isPODType(Context) && !R->isVoidType() &&
11499                !R->isObjCObjectPointerType())
11500         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11501     }
11502 
11503     // C++1z [dcl.fct]p6:
11504     //   [...] whether the function has a non-throwing exception-specification
11505     //   [is] part of the function type
11506     //
11507     // This results in an ABI break between C++14 and C++17 for functions whose
11508     // declared type includes an exception-specification in a parameter or
11509     // return type. (Exception specifications on the function itself are OK in
11510     // most cases, and exception specifications are not permitted in most other
11511     // contexts where they could make it into a mangling.)
11512     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11513       auto HasNoexcept = [&](QualType T) -> bool {
11514         // Strip off declarator chunks that could be between us and a function
11515         // type. We don't need to look far, exception specifications are very
11516         // restricted prior to C++17.
11517         if (auto *RT = T->getAs<ReferenceType>())
11518           T = RT->getPointeeType();
11519         else if (T->isAnyPointerType())
11520           T = T->getPointeeType();
11521         else if (auto *MPT = T->getAs<MemberPointerType>())
11522           T = MPT->getPointeeType();
11523         if (auto *FPT = T->getAs<FunctionProtoType>())
11524           if (FPT->isNothrow())
11525             return true;
11526         return false;
11527       };
11528 
11529       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11530       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11531       for (QualType T : FPT->param_types())
11532         AnyNoexcept |= HasNoexcept(T);
11533       if (AnyNoexcept)
11534         Diag(NewFD->getLocation(),
11535              diag::warn_cxx17_compat_exception_spec_in_signature)
11536             << NewFD;
11537     }
11538 
11539     if (!Redeclaration && LangOpts.CUDA)
11540       checkCUDATargetOverload(NewFD, Previous);
11541   }
11542   return Redeclaration;
11543 }
11544 
11545 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11546   // C++11 [basic.start.main]p3:
11547   //   A program that [...] declares main to be inline, static or
11548   //   constexpr is ill-formed.
11549   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11550   //   appear in a declaration of main.
11551   // static main is not an error under C99, but we should warn about it.
11552   // We accept _Noreturn main as an extension.
11553   if (FD->getStorageClass() == SC_Static)
11554     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11555          ? diag::err_static_main : diag::warn_static_main)
11556       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11557   if (FD->isInlineSpecified())
11558     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11559       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11560   if (DS.isNoreturnSpecified()) {
11561     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11562     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11563     Diag(NoreturnLoc, diag::ext_noreturn_main);
11564     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11565       << FixItHint::CreateRemoval(NoreturnRange);
11566   }
11567   if (FD->isConstexpr()) {
11568     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11569         << FD->isConsteval()
11570         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11571     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11572   }
11573 
11574   if (getLangOpts().OpenCL) {
11575     Diag(FD->getLocation(), diag::err_opencl_no_main)
11576         << FD->hasAttr<OpenCLKernelAttr>();
11577     FD->setInvalidDecl();
11578     return;
11579   }
11580 
11581   // Functions named main in hlsl are default entries, but don't have specific
11582   // signatures they are required to conform to.
11583   if (getLangOpts().HLSL)
11584     return;
11585 
11586   QualType T = FD->getType();
11587   assert(T->isFunctionType() && "function decl is not of function type");
11588   const FunctionType* FT = T->castAs<FunctionType>();
11589 
11590   // Set default calling convention for main()
11591   if (FT->getCallConv() != CC_C) {
11592     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11593     FD->setType(QualType(FT, 0));
11594     T = Context.getCanonicalType(FD->getType());
11595   }
11596 
11597   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11598     // In C with GNU extensions we allow main() to have non-integer return
11599     // type, but we should warn about the extension, and we disable the
11600     // implicit-return-zero rule.
11601 
11602     // GCC in C mode accepts qualified 'int'.
11603     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11604       FD->setHasImplicitReturnZero(true);
11605     else {
11606       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11607       SourceRange RTRange = FD->getReturnTypeSourceRange();
11608       if (RTRange.isValid())
11609         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11610             << FixItHint::CreateReplacement(RTRange, "int");
11611     }
11612   } else {
11613     // In C and C++, main magically returns 0 if you fall off the end;
11614     // set the flag which tells us that.
11615     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11616 
11617     // All the standards say that main() should return 'int'.
11618     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11619       FD->setHasImplicitReturnZero(true);
11620     else {
11621       // Otherwise, this is just a flat-out error.
11622       SourceRange RTRange = FD->getReturnTypeSourceRange();
11623       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11624           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11625                                 : FixItHint());
11626       FD->setInvalidDecl(true);
11627     }
11628   }
11629 
11630   // Treat protoless main() as nullary.
11631   if (isa<FunctionNoProtoType>(FT)) return;
11632 
11633   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11634   unsigned nparams = FTP->getNumParams();
11635   assert(FD->getNumParams() == nparams);
11636 
11637   bool HasExtraParameters = (nparams > 3);
11638 
11639   if (FTP->isVariadic()) {
11640     Diag(FD->getLocation(), diag::ext_variadic_main);
11641     // FIXME: if we had information about the location of the ellipsis, we
11642     // could add a FixIt hint to remove it as a parameter.
11643   }
11644 
11645   // Darwin passes an undocumented fourth argument of type char**.  If
11646   // other platforms start sprouting these, the logic below will start
11647   // getting shifty.
11648   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11649     HasExtraParameters = false;
11650 
11651   if (HasExtraParameters) {
11652     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11653     FD->setInvalidDecl(true);
11654     nparams = 3;
11655   }
11656 
11657   // FIXME: a lot of the following diagnostics would be improved
11658   // if we had some location information about types.
11659 
11660   QualType CharPP =
11661     Context.getPointerType(Context.getPointerType(Context.CharTy));
11662   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11663 
11664   for (unsigned i = 0; i < nparams; ++i) {
11665     QualType AT = FTP->getParamType(i);
11666 
11667     bool mismatch = true;
11668 
11669     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11670       mismatch = false;
11671     else if (Expected[i] == CharPP) {
11672       // As an extension, the following forms are okay:
11673       //   char const **
11674       //   char const * const *
11675       //   char * const *
11676 
11677       QualifierCollector qs;
11678       const PointerType* PT;
11679       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11680           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11681           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11682                               Context.CharTy)) {
11683         qs.removeConst();
11684         mismatch = !qs.empty();
11685       }
11686     }
11687 
11688     if (mismatch) {
11689       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11690       // TODO: suggest replacing given type with expected type
11691       FD->setInvalidDecl(true);
11692     }
11693   }
11694 
11695   if (nparams == 1 && !FD->isInvalidDecl()) {
11696     Diag(FD->getLocation(), diag::warn_main_one_arg);
11697   }
11698 
11699   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11700     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11701     FD->setInvalidDecl();
11702   }
11703 }
11704 
11705 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11706 
11707   // Default calling convention for main and wmain is __cdecl
11708   if (FD->getName() == "main" || FD->getName() == "wmain")
11709     return false;
11710 
11711   // Default calling convention for MinGW is __cdecl
11712   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11713   if (T.isWindowsGNUEnvironment())
11714     return false;
11715 
11716   // Default calling convention for WinMain, wWinMain and DllMain
11717   // is __stdcall on 32 bit Windows
11718   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11719     return true;
11720 
11721   return false;
11722 }
11723 
11724 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11725   QualType T = FD->getType();
11726   assert(T->isFunctionType() && "function decl is not of function type");
11727   const FunctionType *FT = T->castAs<FunctionType>();
11728 
11729   // Set an implicit return of 'zero' if the function can return some integral,
11730   // enumeration, pointer or nullptr type.
11731   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11732       FT->getReturnType()->isAnyPointerType() ||
11733       FT->getReturnType()->isNullPtrType())
11734     // DllMain is exempt because a return value of zero means it failed.
11735     if (FD->getName() != "DllMain")
11736       FD->setHasImplicitReturnZero(true);
11737 
11738   // Explicity specified calling conventions are applied to MSVC entry points
11739   if (!hasExplicitCallingConv(T)) {
11740     if (isDefaultStdCall(FD, *this)) {
11741       if (FT->getCallConv() != CC_X86StdCall) {
11742         FT = Context.adjustFunctionType(
11743             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11744         FD->setType(QualType(FT, 0));
11745       }
11746     } else if (FT->getCallConv() != CC_C) {
11747       FT = Context.adjustFunctionType(FT,
11748                                       FT->getExtInfo().withCallingConv(CC_C));
11749       FD->setType(QualType(FT, 0));
11750     }
11751   }
11752 
11753   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11754     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11755     FD->setInvalidDecl();
11756   }
11757 }
11758 
11759 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11760   // FIXME: Need strict checking.  In C89, we need to check for
11761   // any assignment, increment, decrement, function-calls, or
11762   // commas outside of a sizeof.  In C99, it's the same list,
11763   // except that the aforementioned are allowed in unevaluated
11764   // expressions.  Everything else falls under the
11765   // "may accept other forms of constant expressions" exception.
11766   //
11767   // Regular C++ code will not end up here (exceptions: language extensions,
11768   // OpenCL C++ etc), so the constant expression rules there don't matter.
11769   if (Init->isValueDependent()) {
11770     assert(Init->containsErrors() &&
11771            "Dependent code should only occur in error-recovery path.");
11772     return true;
11773   }
11774   const Expr *Culprit;
11775   if (Init->isConstantInitializer(Context, false, &Culprit))
11776     return false;
11777   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11778     << Culprit->getSourceRange();
11779   return true;
11780 }
11781 
11782 namespace {
11783   // Visits an initialization expression to see if OrigDecl is evaluated in
11784   // its own initialization and throws a warning if it does.
11785   class SelfReferenceChecker
11786       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11787     Sema &S;
11788     Decl *OrigDecl;
11789     bool isRecordType;
11790     bool isPODType;
11791     bool isReferenceType;
11792 
11793     bool isInitList;
11794     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11795 
11796   public:
11797     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11798 
11799     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11800                                                     S(S), OrigDecl(OrigDecl) {
11801       isPODType = false;
11802       isRecordType = false;
11803       isReferenceType = false;
11804       isInitList = false;
11805       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11806         isPODType = VD->getType().isPODType(S.Context);
11807         isRecordType = VD->getType()->isRecordType();
11808         isReferenceType = VD->getType()->isReferenceType();
11809       }
11810     }
11811 
11812     // For most expressions, just call the visitor.  For initializer lists,
11813     // track the index of the field being initialized since fields are
11814     // initialized in order allowing use of previously initialized fields.
11815     void CheckExpr(Expr *E) {
11816       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11817       if (!InitList) {
11818         Visit(E);
11819         return;
11820       }
11821 
11822       // Track and increment the index here.
11823       isInitList = true;
11824       InitFieldIndex.push_back(0);
11825       for (auto Child : InitList->children()) {
11826         CheckExpr(cast<Expr>(Child));
11827         ++InitFieldIndex.back();
11828       }
11829       InitFieldIndex.pop_back();
11830     }
11831 
11832     // Returns true if MemberExpr is checked and no further checking is needed.
11833     // Returns false if additional checking is required.
11834     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11835       llvm::SmallVector<FieldDecl*, 4> Fields;
11836       Expr *Base = E;
11837       bool ReferenceField = false;
11838 
11839       // Get the field members used.
11840       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11841         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11842         if (!FD)
11843           return false;
11844         Fields.push_back(FD);
11845         if (FD->getType()->isReferenceType())
11846           ReferenceField = true;
11847         Base = ME->getBase()->IgnoreParenImpCasts();
11848       }
11849 
11850       // Keep checking only if the base Decl is the same.
11851       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11852       if (!DRE || DRE->getDecl() != OrigDecl)
11853         return false;
11854 
11855       // A reference field can be bound to an unininitialized field.
11856       if (CheckReference && !ReferenceField)
11857         return true;
11858 
11859       // Convert FieldDecls to their index number.
11860       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11861       for (const FieldDecl *I : llvm::reverse(Fields))
11862         UsedFieldIndex.push_back(I->getFieldIndex());
11863 
11864       // See if a warning is needed by checking the first difference in index
11865       // numbers.  If field being used has index less than the field being
11866       // initialized, then the use is safe.
11867       for (auto UsedIter = UsedFieldIndex.begin(),
11868                 UsedEnd = UsedFieldIndex.end(),
11869                 OrigIter = InitFieldIndex.begin(),
11870                 OrigEnd = InitFieldIndex.end();
11871            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11872         if (*UsedIter < *OrigIter)
11873           return true;
11874         if (*UsedIter > *OrigIter)
11875           break;
11876       }
11877 
11878       // TODO: Add a different warning which will print the field names.
11879       HandleDeclRefExpr(DRE);
11880       return true;
11881     }
11882 
11883     // For most expressions, the cast is directly above the DeclRefExpr.
11884     // For conditional operators, the cast can be outside the conditional
11885     // operator if both expressions are DeclRefExpr's.
11886     void HandleValue(Expr *E) {
11887       E = E->IgnoreParens();
11888       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11889         HandleDeclRefExpr(DRE);
11890         return;
11891       }
11892 
11893       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11894         Visit(CO->getCond());
11895         HandleValue(CO->getTrueExpr());
11896         HandleValue(CO->getFalseExpr());
11897         return;
11898       }
11899 
11900       if (BinaryConditionalOperator *BCO =
11901               dyn_cast<BinaryConditionalOperator>(E)) {
11902         Visit(BCO->getCond());
11903         HandleValue(BCO->getFalseExpr());
11904         return;
11905       }
11906 
11907       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11908         HandleValue(OVE->getSourceExpr());
11909         return;
11910       }
11911 
11912       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11913         if (BO->getOpcode() == BO_Comma) {
11914           Visit(BO->getLHS());
11915           HandleValue(BO->getRHS());
11916           return;
11917         }
11918       }
11919 
11920       if (isa<MemberExpr>(E)) {
11921         if (isInitList) {
11922           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11923                                       false /*CheckReference*/))
11924             return;
11925         }
11926 
11927         Expr *Base = E->IgnoreParenImpCasts();
11928         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11929           // Check for static member variables and don't warn on them.
11930           if (!isa<FieldDecl>(ME->getMemberDecl()))
11931             return;
11932           Base = ME->getBase()->IgnoreParenImpCasts();
11933         }
11934         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11935           HandleDeclRefExpr(DRE);
11936         return;
11937       }
11938 
11939       Visit(E);
11940     }
11941 
11942     // Reference types not handled in HandleValue are handled here since all
11943     // uses of references are bad, not just r-value uses.
11944     void VisitDeclRefExpr(DeclRefExpr *E) {
11945       if (isReferenceType)
11946         HandleDeclRefExpr(E);
11947     }
11948 
11949     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11950       if (E->getCastKind() == CK_LValueToRValue) {
11951         HandleValue(E->getSubExpr());
11952         return;
11953       }
11954 
11955       Inherited::VisitImplicitCastExpr(E);
11956     }
11957 
11958     void VisitMemberExpr(MemberExpr *E) {
11959       if (isInitList) {
11960         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11961           return;
11962       }
11963 
11964       // Don't warn on arrays since they can be treated as pointers.
11965       if (E->getType()->canDecayToPointerType()) return;
11966 
11967       // Warn when a non-static method call is followed by non-static member
11968       // field accesses, which is followed by a DeclRefExpr.
11969       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11970       bool Warn = (MD && !MD->isStatic());
11971       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11972       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11973         if (!isa<FieldDecl>(ME->getMemberDecl()))
11974           Warn = false;
11975         Base = ME->getBase()->IgnoreParenImpCasts();
11976       }
11977 
11978       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11979         if (Warn)
11980           HandleDeclRefExpr(DRE);
11981         return;
11982       }
11983 
11984       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11985       // Visit that expression.
11986       Visit(Base);
11987     }
11988 
11989     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11990       Expr *Callee = E->getCallee();
11991 
11992       if (isa<UnresolvedLookupExpr>(Callee))
11993         return Inherited::VisitCXXOperatorCallExpr(E);
11994 
11995       Visit(Callee);
11996       for (auto Arg: E->arguments())
11997         HandleValue(Arg->IgnoreParenImpCasts());
11998     }
11999 
12000     void VisitUnaryOperator(UnaryOperator *E) {
12001       // For POD record types, addresses of its own members are well-defined.
12002       if (E->getOpcode() == UO_AddrOf && isRecordType &&
12003           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12004         if (!isPODType)
12005           HandleValue(E->getSubExpr());
12006         return;
12007       }
12008 
12009       if (E->isIncrementDecrementOp()) {
12010         HandleValue(E->getSubExpr());
12011         return;
12012       }
12013 
12014       Inherited::VisitUnaryOperator(E);
12015     }
12016 
12017     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12018 
12019     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12020       if (E->getConstructor()->isCopyConstructor()) {
12021         Expr *ArgExpr = E->getArg(0);
12022         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12023           if (ILE->getNumInits() == 1)
12024             ArgExpr = ILE->getInit(0);
12025         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12026           if (ICE->getCastKind() == CK_NoOp)
12027             ArgExpr = ICE->getSubExpr();
12028         HandleValue(ArgExpr);
12029         return;
12030       }
12031       Inherited::VisitCXXConstructExpr(E);
12032     }
12033 
12034     void VisitCallExpr(CallExpr *E) {
12035       // Treat std::move as a use.
12036       if (E->isCallToStdMove()) {
12037         HandleValue(E->getArg(0));
12038         return;
12039       }
12040 
12041       Inherited::VisitCallExpr(E);
12042     }
12043 
12044     void VisitBinaryOperator(BinaryOperator *E) {
12045       if (E->isCompoundAssignmentOp()) {
12046         HandleValue(E->getLHS());
12047         Visit(E->getRHS());
12048         return;
12049       }
12050 
12051       Inherited::VisitBinaryOperator(E);
12052     }
12053 
12054     // A custom visitor for BinaryConditionalOperator is needed because the
12055     // regular visitor would check the condition and true expression separately
12056     // but both point to the same place giving duplicate diagnostics.
12057     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12058       Visit(E->getCond());
12059       Visit(E->getFalseExpr());
12060     }
12061 
12062     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12063       Decl* ReferenceDecl = DRE->getDecl();
12064       if (OrigDecl != ReferenceDecl) return;
12065       unsigned diag;
12066       if (isReferenceType) {
12067         diag = diag::warn_uninit_self_reference_in_reference_init;
12068       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12069         diag = diag::warn_static_self_reference_in_init;
12070       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12071                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12072                  DRE->getDecl()->getType()->isRecordType()) {
12073         diag = diag::warn_uninit_self_reference_in_init;
12074       } else {
12075         // Local variables will be handled by the CFG analysis.
12076         return;
12077       }
12078 
12079       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12080                             S.PDiag(diag)
12081                                 << DRE->getDecl() << OrigDecl->getLocation()
12082                                 << DRE->getSourceRange());
12083     }
12084   };
12085 
12086   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12087   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12088                                  bool DirectInit) {
12089     // Parameters arguments are occassionially constructed with itself,
12090     // for instance, in recursive functions.  Skip them.
12091     if (isa<ParmVarDecl>(OrigDecl))
12092       return;
12093 
12094     E = E->IgnoreParens();
12095 
12096     // Skip checking T a = a where T is not a record or reference type.
12097     // Doing so is a way to silence uninitialized warnings.
12098     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12099       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12100         if (ICE->getCastKind() == CK_LValueToRValue)
12101           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12102             if (DRE->getDecl() == OrigDecl)
12103               return;
12104 
12105     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12106   }
12107 } // end anonymous namespace
12108 
12109 namespace {
12110   // Simple wrapper to add the name of a variable or (if no variable is
12111   // available) a DeclarationName into a diagnostic.
12112   struct VarDeclOrName {
12113     VarDecl *VDecl;
12114     DeclarationName Name;
12115 
12116     friend const Sema::SemaDiagnosticBuilder &
12117     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12118       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12119     }
12120   };
12121 } // end anonymous namespace
12122 
12123 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12124                                             DeclarationName Name, QualType Type,
12125                                             TypeSourceInfo *TSI,
12126                                             SourceRange Range, bool DirectInit,
12127                                             Expr *Init) {
12128   bool IsInitCapture = !VDecl;
12129   assert((!VDecl || !VDecl->isInitCapture()) &&
12130          "init captures are expected to be deduced prior to initialization");
12131 
12132   VarDeclOrName VN{VDecl, Name};
12133 
12134   DeducedType *Deduced = Type->getContainedDeducedType();
12135   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12136 
12137   // C++11 [dcl.spec.auto]p3
12138   if (!Init) {
12139     assert(VDecl && "no init for init capture deduction?");
12140 
12141     // Except for class argument deduction, and then for an initializing
12142     // declaration only, i.e. no static at class scope or extern.
12143     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12144         VDecl->hasExternalStorage() ||
12145         VDecl->isStaticDataMember()) {
12146       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12147         << VDecl->getDeclName() << Type;
12148       return QualType();
12149     }
12150   }
12151 
12152   ArrayRef<Expr*> DeduceInits;
12153   if (Init)
12154     DeduceInits = Init;
12155 
12156   if (DirectInit) {
12157     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12158       DeduceInits = PL->exprs();
12159   }
12160 
12161   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12162     assert(VDecl && "non-auto type for init capture deduction?");
12163     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12164     InitializationKind Kind = InitializationKind::CreateForInit(
12165         VDecl->getLocation(), DirectInit, Init);
12166     // FIXME: Initialization should not be taking a mutable list of inits.
12167     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12168     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12169                                                        InitsCopy);
12170   }
12171 
12172   if (DirectInit) {
12173     if (auto *IL = dyn_cast<InitListExpr>(Init))
12174       DeduceInits = IL->inits();
12175   }
12176 
12177   // Deduction only works if we have exactly one source expression.
12178   if (DeduceInits.empty()) {
12179     // It isn't possible to write this directly, but it is possible to
12180     // end up in this situation with "auto x(some_pack...);"
12181     Diag(Init->getBeginLoc(), IsInitCapture
12182                                   ? diag::err_init_capture_no_expression
12183                                   : diag::err_auto_var_init_no_expression)
12184         << VN << Type << Range;
12185     return QualType();
12186   }
12187 
12188   if (DeduceInits.size() > 1) {
12189     Diag(DeduceInits[1]->getBeginLoc(),
12190          IsInitCapture ? diag::err_init_capture_multiple_expressions
12191                        : diag::err_auto_var_init_multiple_expressions)
12192         << VN << Type << Range;
12193     return QualType();
12194   }
12195 
12196   Expr *DeduceInit = DeduceInits[0];
12197   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12198     Diag(Init->getBeginLoc(), IsInitCapture
12199                                   ? diag::err_init_capture_paren_braces
12200                                   : diag::err_auto_var_init_paren_braces)
12201         << isa<InitListExpr>(Init) << VN << Type << Range;
12202     return QualType();
12203   }
12204 
12205   // Expressions default to 'id' when we're in a debugger.
12206   bool DefaultedAnyToId = false;
12207   if (getLangOpts().DebuggerCastResultToId &&
12208       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12209     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12210     if (Result.isInvalid()) {
12211       return QualType();
12212     }
12213     Init = Result.get();
12214     DefaultedAnyToId = true;
12215   }
12216 
12217   // C++ [dcl.decomp]p1:
12218   //   If the assignment-expression [...] has array type A and no ref-qualifier
12219   //   is present, e has type cv A
12220   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12221       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12222       DeduceInit->getType()->isConstantArrayType())
12223     return Context.getQualifiedType(DeduceInit->getType(),
12224                                     Type.getQualifiers());
12225 
12226   QualType DeducedType;
12227   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12228     if (!IsInitCapture)
12229       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12230     else if (isa<InitListExpr>(Init))
12231       Diag(Range.getBegin(),
12232            diag::err_init_capture_deduction_failure_from_init_list)
12233           << VN
12234           << (DeduceInit->getType().isNull() ? TSI->getType()
12235                                              : DeduceInit->getType())
12236           << DeduceInit->getSourceRange();
12237     else
12238       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12239           << VN << TSI->getType()
12240           << (DeduceInit->getType().isNull() ? TSI->getType()
12241                                              : DeduceInit->getType())
12242           << DeduceInit->getSourceRange();
12243   }
12244 
12245   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12246   // 'id' instead of a specific object type prevents most of our usual
12247   // checks.
12248   // We only want to warn outside of template instantiations, though:
12249   // inside a template, the 'id' could have come from a parameter.
12250   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12251       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12252     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12253     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12254   }
12255 
12256   return DeducedType;
12257 }
12258 
12259 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12260                                          Expr *Init) {
12261   assert(!Init || !Init->containsErrors());
12262   QualType DeducedType = deduceVarTypeFromInitializer(
12263       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12264       VDecl->getSourceRange(), DirectInit, Init);
12265   if (DeducedType.isNull()) {
12266     VDecl->setInvalidDecl();
12267     return true;
12268   }
12269 
12270   VDecl->setType(DeducedType);
12271   assert(VDecl->isLinkageValid());
12272 
12273   // In ARC, infer lifetime.
12274   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12275     VDecl->setInvalidDecl();
12276 
12277   if (getLangOpts().OpenCL)
12278     deduceOpenCLAddressSpace(VDecl);
12279 
12280   // If this is a redeclaration, check that the type we just deduced matches
12281   // the previously declared type.
12282   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12283     // We never need to merge the type, because we cannot form an incomplete
12284     // array of auto, nor deduce such a type.
12285     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12286   }
12287 
12288   // Check the deduced type is valid for a variable declaration.
12289   CheckVariableDeclarationType(VDecl);
12290   return VDecl->isInvalidDecl();
12291 }
12292 
12293 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12294                                               SourceLocation Loc) {
12295   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12296     Init = EWC->getSubExpr();
12297 
12298   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12299     Init = CE->getSubExpr();
12300 
12301   QualType InitType = Init->getType();
12302   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12303           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12304          "shouldn't be called if type doesn't have a non-trivial C struct");
12305   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12306     for (auto I : ILE->inits()) {
12307       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12308           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12309         continue;
12310       SourceLocation SL = I->getExprLoc();
12311       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12312     }
12313     return;
12314   }
12315 
12316   if (isa<ImplicitValueInitExpr>(Init)) {
12317     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12318       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12319                             NTCUK_Init);
12320   } else {
12321     // Assume all other explicit initializers involving copying some existing
12322     // object.
12323     // TODO: ignore any explicit initializers where we can guarantee
12324     // copy-elision.
12325     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12326       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12327   }
12328 }
12329 
12330 namespace {
12331 
12332 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12333   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12334   // in the source code or implicitly by the compiler if it is in a union
12335   // defined in a system header and has non-trivial ObjC ownership
12336   // qualifications. We don't want those fields to participate in determining
12337   // whether the containing union is non-trivial.
12338   return FD->hasAttr<UnavailableAttr>();
12339 }
12340 
12341 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12342     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12343                                     void> {
12344   using Super =
12345       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12346                                     void>;
12347 
12348   DiagNonTrivalCUnionDefaultInitializeVisitor(
12349       QualType OrigTy, SourceLocation OrigLoc,
12350       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12351       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12352 
12353   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12354                      const FieldDecl *FD, bool InNonTrivialUnion) {
12355     if (const auto *AT = S.Context.getAsArrayType(QT))
12356       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12357                                      InNonTrivialUnion);
12358     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12359   }
12360 
12361   void visitARCStrong(QualType QT, const FieldDecl *FD,
12362                       bool InNonTrivialUnion) {
12363     if (InNonTrivialUnion)
12364       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12365           << 1 << 0 << QT << FD->getName();
12366   }
12367 
12368   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12369     if (InNonTrivialUnion)
12370       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12371           << 1 << 0 << QT << FD->getName();
12372   }
12373 
12374   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12375     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12376     if (RD->isUnion()) {
12377       if (OrigLoc.isValid()) {
12378         bool IsUnion = false;
12379         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12380           IsUnion = OrigRD->isUnion();
12381         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12382             << 0 << OrigTy << IsUnion << UseContext;
12383         // Reset OrigLoc so that this diagnostic is emitted only once.
12384         OrigLoc = SourceLocation();
12385       }
12386       InNonTrivialUnion = true;
12387     }
12388 
12389     if (InNonTrivialUnion)
12390       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12391           << 0 << 0 << QT.getUnqualifiedType() << "";
12392 
12393     for (const FieldDecl *FD : RD->fields())
12394       if (!shouldIgnoreForRecordTriviality(FD))
12395         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12396   }
12397 
12398   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12399 
12400   // The non-trivial C union type or the struct/union type that contains a
12401   // non-trivial C union.
12402   QualType OrigTy;
12403   SourceLocation OrigLoc;
12404   Sema::NonTrivialCUnionContext UseContext;
12405   Sema &S;
12406 };
12407 
12408 struct DiagNonTrivalCUnionDestructedTypeVisitor
12409     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12410   using Super =
12411       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12412 
12413   DiagNonTrivalCUnionDestructedTypeVisitor(
12414       QualType OrigTy, SourceLocation OrigLoc,
12415       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12416       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12417 
12418   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12419                      const FieldDecl *FD, bool InNonTrivialUnion) {
12420     if (const auto *AT = S.Context.getAsArrayType(QT))
12421       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12422                                      InNonTrivialUnion);
12423     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12424   }
12425 
12426   void visitARCStrong(QualType QT, const FieldDecl *FD,
12427                       bool InNonTrivialUnion) {
12428     if (InNonTrivialUnion)
12429       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12430           << 1 << 1 << QT << FD->getName();
12431   }
12432 
12433   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12434     if (InNonTrivialUnion)
12435       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12436           << 1 << 1 << QT << FD->getName();
12437   }
12438 
12439   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12440     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12441     if (RD->isUnion()) {
12442       if (OrigLoc.isValid()) {
12443         bool IsUnion = false;
12444         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12445           IsUnion = OrigRD->isUnion();
12446         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12447             << 1 << OrigTy << IsUnion << UseContext;
12448         // Reset OrigLoc so that this diagnostic is emitted only once.
12449         OrigLoc = SourceLocation();
12450       }
12451       InNonTrivialUnion = true;
12452     }
12453 
12454     if (InNonTrivialUnion)
12455       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12456           << 0 << 1 << QT.getUnqualifiedType() << "";
12457 
12458     for (const FieldDecl *FD : RD->fields())
12459       if (!shouldIgnoreForRecordTriviality(FD))
12460         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12461   }
12462 
12463   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12464   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12465                           bool InNonTrivialUnion) {}
12466 
12467   // The non-trivial C union type or the struct/union type that contains a
12468   // non-trivial C union.
12469   QualType OrigTy;
12470   SourceLocation OrigLoc;
12471   Sema::NonTrivialCUnionContext UseContext;
12472   Sema &S;
12473 };
12474 
12475 struct DiagNonTrivalCUnionCopyVisitor
12476     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12477   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12478 
12479   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12480                                  Sema::NonTrivialCUnionContext UseContext,
12481                                  Sema &S)
12482       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12483 
12484   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12485                      const FieldDecl *FD, bool InNonTrivialUnion) {
12486     if (const auto *AT = S.Context.getAsArrayType(QT))
12487       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12488                                      InNonTrivialUnion);
12489     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12490   }
12491 
12492   void visitARCStrong(QualType QT, const FieldDecl *FD,
12493                       bool InNonTrivialUnion) {
12494     if (InNonTrivialUnion)
12495       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12496           << 1 << 2 << QT << FD->getName();
12497   }
12498 
12499   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12500     if (InNonTrivialUnion)
12501       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12502           << 1 << 2 << QT << FD->getName();
12503   }
12504 
12505   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12506     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12507     if (RD->isUnion()) {
12508       if (OrigLoc.isValid()) {
12509         bool IsUnion = false;
12510         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12511           IsUnion = OrigRD->isUnion();
12512         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12513             << 2 << OrigTy << IsUnion << UseContext;
12514         // Reset OrigLoc so that this diagnostic is emitted only once.
12515         OrigLoc = SourceLocation();
12516       }
12517       InNonTrivialUnion = true;
12518     }
12519 
12520     if (InNonTrivialUnion)
12521       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12522           << 0 << 2 << QT.getUnqualifiedType() << "";
12523 
12524     for (const FieldDecl *FD : RD->fields())
12525       if (!shouldIgnoreForRecordTriviality(FD))
12526         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12527   }
12528 
12529   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12530                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12531   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12532   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12533                             bool InNonTrivialUnion) {}
12534 
12535   // The non-trivial C union type or the struct/union type that contains a
12536   // non-trivial C union.
12537   QualType OrigTy;
12538   SourceLocation OrigLoc;
12539   Sema::NonTrivialCUnionContext UseContext;
12540   Sema &S;
12541 };
12542 
12543 } // namespace
12544 
12545 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12546                                  NonTrivialCUnionContext UseContext,
12547                                  unsigned NonTrivialKind) {
12548   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12549           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12550           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12551          "shouldn't be called if type doesn't have a non-trivial C union");
12552 
12553   if ((NonTrivialKind & NTCUK_Init) &&
12554       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12555     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12556         .visit(QT, nullptr, false);
12557   if ((NonTrivialKind & NTCUK_Destruct) &&
12558       QT.hasNonTrivialToPrimitiveDestructCUnion())
12559     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12560         .visit(QT, nullptr, false);
12561   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12562     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12563         .visit(QT, nullptr, false);
12564 }
12565 
12566 /// AddInitializerToDecl - Adds the initializer Init to the
12567 /// declaration dcl. If DirectInit is true, this is C++ direct
12568 /// initialization rather than copy initialization.
12569 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12570   // If there is no declaration, there was an error parsing it.  Just ignore
12571   // the initializer.
12572   if (!RealDecl || RealDecl->isInvalidDecl()) {
12573     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12574     return;
12575   }
12576 
12577   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12578     // Pure-specifiers are handled in ActOnPureSpecifier.
12579     Diag(Method->getLocation(), diag::err_member_function_initialization)
12580       << Method->getDeclName() << Init->getSourceRange();
12581     Method->setInvalidDecl();
12582     return;
12583   }
12584 
12585   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12586   if (!VDecl) {
12587     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12588     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12589     RealDecl->setInvalidDecl();
12590     return;
12591   }
12592 
12593   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12594   if (VDecl->getType()->isUndeducedType()) {
12595     // Attempt typo correction early so that the type of the init expression can
12596     // be deduced based on the chosen correction if the original init contains a
12597     // TypoExpr.
12598     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12599     if (!Res.isUsable()) {
12600       // There are unresolved typos in Init, just drop them.
12601       // FIXME: improve the recovery strategy to preserve the Init.
12602       RealDecl->setInvalidDecl();
12603       return;
12604     }
12605     if (Res.get()->containsErrors()) {
12606       // Invalidate the decl as we don't know the type for recovery-expr yet.
12607       RealDecl->setInvalidDecl();
12608       VDecl->setInit(Res.get());
12609       return;
12610     }
12611     Init = Res.get();
12612 
12613     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12614       return;
12615   }
12616 
12617   // dllimport cannot be used on variable definitions.
12618   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12619     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12620     VDecl->setInvalidDecl();
12621     return;
12622   }
12623 
12624   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12625     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12626     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12627     VDecl->setInvalidDecl();
12628     return;
12629   }
12630 
12631   if (!VDecl->getType()->isDependentType()) {
12632     // A definition must end up with a complete type, which means it must be
12633     // complete with the restriction that an array type might be completed by
12634     // the initializer; note that later code assumes this restriction.
12635     QualType BaseDeclType = VDecl->getType();
12636     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12637       BaseDeclType = Array->getElementType();
12638     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12639                             diag::err_typecheck_decl_incomplete_type)) {
12640       RealDecl->setInvalidDecl();
12641       return;
12642     }
12643 
12644     // The variable can not have an abstract class type.
12645     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12646                                diag::err_abstract_type_in_decl,
12647                                AbstractVariableType))
12648       VDecl->setInvalidDecl();
12649   }
12650 
12651   // If adding the initializer will turn this declaration into a definition,
12652   // and we already have a definition for this variable, diagnose or otherwise
12653   // handle the situation.
12654   if (VarDecl *Def = VDecl->getDefinition())
12655     if (Def != VDecl &&
12656         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12657         !VDecl->isThisDeclarationADemotedDefinition() &&
12658         checkVarDeclRedefinition(Def, VDecl))
12659       return;
12660 
12661   if (getLangOpts().CPlusPlus) {
12662     // C++ [class.static.data]p4
12663     //   If a static data member is of const integral or const
12664     //   enumeration type, its declaration in the class definition can
12665     //   specify a constant-initializer which shall be an integral
12666     //   constant expression (5.19). In that case, the member can appear
12667     //   in integral constant expressions. The member shall still be
12668     //   defined in a namespace scope if it is used in the program and the
12669     //   namespace scope definition shall not contain an initializer.
12670     //
12671     // We already performed a redefinition check above, but for static
12672     // data members we also need to check whether there was an in-class
12673     // declaration with an initializer.
12674     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12675       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12676           << VDecl->getDeclName();
12677       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12678            diag::note_previous_initializer)
12679           << 0;
12680       return;
12681     }
12682 
12683     if (VDecl->hasLocalStorage())
12684       setFunctionHasBranchProtectedScope();
12685 
12686     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12687       VDecl->setInvalidDecl();
12688       return;
12689     }
12690   }
12691 
12692   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12693   // a kernel function cannot be initialized."
12694   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12695     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12696     VDecl->setInvalidDecl();
12697     return;
12698   }
12699 
12700   // The LoaderUninitialized attribute acts as a definition (of undef).
12701   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12702     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12703     VDecl->setInvalidDecl();
12704     return;
12705   }
12706 
12707   // Get the decls type and save a reference for later, since
12708   // CheckInitializerTypes may change it.
12709   QualType DclT = VDecl->getType(), SavT = DclT;
12710 
12711   // Expressions default to 'id' when we're in a debugger
12712   // and we are assigning it to a variable of Objective-C pointer type.
12713   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12714       Init->getType() == Context.UnknownAnyTy) {
12715     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12716     if (Result.isInvalid()) {
12717       VDecl->setInvalidDecl();
12718       return;
12719     }
12720     Init = Result.get();
12721   }
12722 
12723   // Perform the initialization.
12724   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12725   if (!VDecl->isInvalidDecl()) {
12726     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12727     InitializationKind Kind = InitializationKind::CreateForInit(
12728         VDecl->getLocation(), DirectInit, Init);
12729 
12730     MultiExprArg Args = Init;
12731     if (CXXDirectInit)
12732       Args = MultiExprArg(CXXDirectInit->getExprs(),
12733                           CXXDirectInit->getNumExprs());
12734 
12735     // Try to correct any TypoExprs in the initialization arguments.
12736     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12737       ExprResult Res = CorrectDelayedTyposInExpr(
12738           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12739           [this, Entity, Kind](Expr *E) {
12740             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12741             return Init.Failed() ? ExprError() : E;
12742           });
12743       if (Res.isInvalid()) {
12744         VDecl->setInvalidDecl();
12745       } else if (Res.get() != Args[Idx]) {
12746         Args[Idx] = Res.get();
12747       }
12748     }
12749     if (VDecl->isInvalidDecl())
12750       return;
12751 
12752     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12753                                    /*TopLevelOfInitList=*/false,
12754                                    /*TreatUnavailableAsInvalid=*/false);
12755     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12756     if (Result.isInvalid()) {
12757       // If the provided initializer fails to initialize the var decl,
12758       // we attach a recovery expr for better recovery.
12759       auto RecoveryExpr =
12760           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12761       if (RecoveryExpr.get())
12762         VDecl->setInit(RecoveryExpr.get());
12763       return;
12764     }
12765 
12766     Init = Result.getAs<Expr>();
12767   }
12768 
12769   // Check for self-references within variable initializers.
12770   // Variables declared within a function/method body (except for references)
12771   // are handled by a dataflow analysis.
12772   // This is undefined behavior in C++, but valid in C.
12773   if (getLangOpts().CPlusPlus)
12774     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12775         VDecl->getType()->isReferenceType())
12776       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12777 
12778   // If the type changed, it means we had an incomplete type that was
12779   // completed by the initializer. For example:
12780   //   int ary[] = { 1, 3, 5 };
12781   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12782   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12783     VDecl->setType(DclT);
12784 
12785   if (!VDecl->isInvalidDecl()) {
12786     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12787 
12788     if (VDecl->hasAttr<BlocksAttr>())
12789       checkRetainCycles(VDecl, Init);
12790 
12791     // It is safe to assign a weak reference into a strong variable.
12792     // Although this code can still have problems:
12793     //   id x = self.weakProp;
12794     //   id y = self.weakProp;
12795     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12796     // paths through the function. This should be revisited if
12797     // -Wrepeated-use-of-weak is made flow-sensitive.
12798     if (FunctionScopeInfo *FSI = getCurFunction())
12799       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12800            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12801           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12802                            Init->getBeginLoc()))
12803         FSI->markSafeWeakUse(Init);
12804   }
12805 
12806   // The initialization is usually a full-expression.
12807   //
12808   // FIXME: If this is a braced initialization of an aggregate, it is not
12809   // an expression, and each individual field initializer is a separate
12810   // full-expression. For instance, in:
12811   //
12812   //   struct Temp { ~Temp(); };
12813   //   struct S { S(Temp); };
12814   //   struct T { S a, b; } t = { Temp(), Temp() }
12815   //
12816   // we should destroy the first Temp before constructing the second.
12817   ExprResult Result =
12818       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12819                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12820   if (Result.isInvalid()) {
12821     VDecl->setInvalidDecl();
12822     return;
12823   }
12824   Init = Result.get();
12825 
12826   // Attach the initializer to the decl.
12827   VDecl->setInit(Init);
12828 
12829   if (VDecl->isLocalVarDecl()) {
12830     // Don't check the initializer if the declaration is malformed.
12831     if (VDecl->isInvalidDecl()) {
12832       // do nothing
12833 
12834     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12835     // This is true even in C++ for OpenCL.
12836     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12837       CheckForConstantInitializer(Init, DclT);
12838 
12839     // Otherwise, C++ does not restrict the initializer.
12840     } else if (getLangOpts().CPlusPlus) {
12841       // do nothing
12842 
12843     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12844     // static storage duration shall be constant expressions or string literals.
12845     } else if (VDecl->getStorageClass() == SC_Static) {
12846       CheckForConstantInitializer(Init, DclT);
12847 
12848     // C89 is stricter than C99 for aggregate initializers.
12849     // C89 6.5.7p3: All the expressions [...] in an initializer list
12850     // for an object that has aggregate or union type shall be
12851     // constant expressions.
12852     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12853                isa<InitListExpr>(Init)) {
12854       const Expr *Culprit;
12855       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12856         Diag(Culprit->getExprLoc(),
12857              diag::ext_aggregate_init_not_constant)
12858           << Culprit->getSourceRange();
12859       }
12860     }
12861 
12862     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12863       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12864         if (VDecl->hasLocalStorage())
12865           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12866   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12867              VDecl->getLexicalDeclContext()->isRecord()) {
12868     // This is an in-class initialization for a static data member, e.g.,
12869     //
12870     // struct S {
12871     //   static const int value = 17;
12872     // };
12873 
12874     // C++ [class.mem]p4:
12875     //   A member-declarator can contain a constant-initializer only
12876     //   if it declares a static member (9.4) of const integral or
12877     //   const enumeration type, see 9.4.2.
12878     //
12879     // C++11 [class.static.data]p3:
12880     //   If a non-volatile non-inline const static data member is of integral
12881     //   or enumeration type, its declaration in the class definition can
12882     //   specify a brace-or-equal-initializer in which every initializer-clause
12883     //   that is an assignment-expression is a constant expression. A static
12884     //   data member of literal type can be declared in the class definition
12885     //   with the constexpr specifier; if so, its declaration shall specify a
12886     //   brace-or-equal-initializer in which every initializer-clause that is
12887     //   an assignment-expression is a constant expression.
12888 
12889     // Do nothing on dependent types.
12890     if (DclT->isDependentType()) {
12891 
12892     // Allow any 'static constexpr' members, whether or not they are of literal
12893     // type. We separately check that every constexpr variable is of literal
12894     // type.
12895     } else if (VDecl->isConstexpr()) {
12896 
12897     // Require constness.
12898     } else if (!DclT.isConstQualified()) {
12899       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12900         << Init->getSourceRange();
12901       VDecl->setInvalidDecl();
12902 
12903     // We allow integer constant expressions in all cases.
12904     } else if (DclT->isIntegralOrEnumerationType()) {
12905       // Check whether the expression is a constant expression.
12906       SourceLocation Loc;
12907       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12908         // In C++11, a non-constexpr const static data member with an
12909         // in-class initializer cannot be volatile.
12910         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12911       else if (Init->isValueDependent())
12912         ; // Nothing to check.
12913       else if (Init->isIntegerConstantExpr(Context, &Loc))
12914         ; // Ok, it's an ICE!
12915       else if (Init->getType()->isScopedEnumeralType() &&
12916                Init->isCXX11ConstantExpr(Context))
12917         ; // Ok, it is a scoped-enum constant expression.
12918       else if (Init->isEvaluatable(Context)) {
12919         // If we can constant fold the initializer through heroics, accept it,
12920         // but report this as a use of an extension for -pedantic.
12921         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12922           << Init->getSourceRange();
12923       } else {
12924         // Otherwise, this is some crazy unknown case.  Report the issue at the
12925         // location provided by the isIntegerConstantExpr failed check.
12926         Diag(Loc, diag::err_in_class_initializer_non_constant)
12927           << Init->getSourceRange();
12928         VDecl->setInvalidDecl();
12929       }
12930 
12931     // We allow foldable floating-point constants as an extension.
12932     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12933       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12934       // it anyway and provide a fixit to add the 'constexpr'.
12935       if (getLangOpts().CPlusPlus11) {
12936         Diag(VDecl->getLocation(),
12937              diag::ext_in_class_initializer_float_type_cxx11)
12938             << DclT << Init->getSourceRange();
12939         Diag(VDecl->getBeginLoc(),
12940              diag::note_in_class_initializer_float_type_cxx11)
12941             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12942       } else {
12943         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12944           << DclT << Init->getSourceRange();
12945 
12946         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12947           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12948             << Init->getSourceRange();
12949           VDecl->setInvalidDecl();
12950         }
12951       }
12952 
12953     // Suggest adding 'constexpr' in C++11 for literal types.
12954     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12955       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12956           << DclT << Init->getSourceRange()
12957           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12958       VDecl->setConstexpr(true);
12959 
12960     } else {
12961       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12962         << DclT << Init->getSourceRange();
12963       VDecl->setInvalidDecl();
12964     }
12965   } else if (VDecl->isFileVarDecl()) {
12966     // In C, extern is typically used to avoid tentative definitions when
12967     // declaring variables in headers, but adding an intializer makes it a
12968     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12969     // In C++, extern is often used to give implictly static const variables
12970     // external linkage, so don't warn in that case. If selectany is present,
12971     // this might be header code intended for C and C++ inclusion, so apply the
12972     // C++ rules.
12973     if (VDecl->getStorageClass() == SC_Extern &&
12974         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12975          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12976         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12977         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12978       Diag(VDecl->getLocation(), diag::warn_extern_init);
12979 
12980     // In Microsoft C++ mode, a const variable defined in namespace scope has
12981     // external linkage by default if the variable is declared with
12982     // __declspec(dllexport).
12983     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12984         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12985         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12986       VDecl->setStorageClass(SC_Extern);
12987 
12988     // C99 6.7.8p4. All file scoped initializers need to be constant.
12989     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12990       CheckForConstantInitializer(Init, DclT);
12991   }
12992 
12993   QualType InitType = Init->getType();
12994   if (!InitType.isNull() &&
12995       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12996        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12997     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12998 
12999   // We will represent direct-initialization similarly to copy-initialization:
13000   //    int x(1);  -as-> int x = 1;
13001   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13002   //
13003   // Clients that want to distinguish between the two forms, can check for
13004   // direct initializer using VarDecl::getInitStyle().
13005   // A major benefit is that clients that don't particularly care about which
13006   // exactly form was it (like the CodeGen) can handle both cases without
13007   // special case code.
13008 
13009   // C++ 8.5p11:
13010   // The form of initialization (using parentheses or '=') is generally
13011   // insignificant, but does matter when the entity being initialized has a
13012   // class type.
13013   if (CXXDirectInit) {
13014     assert(DirectInit && "Call-style initializer must be direct init.");
13015     VDecl->setInitStyle(VarDecl::CallInit);
13016   } else if (DirectInit) {
13017     // This must be list-initialization. No other way is direct-initialization.
13018     VDecl->setInitStyle(VarDecl::ListInit);
13019   }
13020 
13021   if (LangOpts.OpenMP &&
13022       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13023       VDecl->isFileVarDecl())
13024     DeclsToCheckForDeferredDiags.insert(VDecl);
13025   CheckCompleteVariableDeclaration(VDecl);
13026 }
13027 
13028 /// ActOnInitializerError - Given that there was an error parsing an
13029 /// initializer for the given declaration, try to at least re-establish
13030 /// invariants such as whether a variable's type is either dependent or
13031 /// complete.
13032 void Sema::ActOnInitializerError(Decl *D) {
13033   // Our main concern here is re-establishing invariants like "a
13034   // variable's type is either dependent or complete".
13035   if (!D || D->isInvalidDecl()) return;
13036 
13037   VarDecl *VD = dyn_cast<VarDecl>(D);
13038   if (!VD) return;
13039 
13040   // Bindings are not usable if we can't make sense of the initializer.
13041   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13042     for (auto *BD : DD->bindings())
13043       BD->setInvalidDecl();
13044 
13045   // Auto types are meaningless if we can't make sense of the initializer.
13046   if (VD->getType()->isUndeducedType()) {
13047     D->setInvalidDecl();
13048     return;
13049   }
13050 
13051   QualType Ty = VD->getType();
13052   if (Ty->isDependentType()) return;
13053 
13054   // Require a complete type.
13055   if (RequireCompleteType(VD->getLocation(),
13056                           Context.getBaseElementType(Ty),
13057                           diag::err_typecheck_decl_incomplete_type)) {
13058     VD->setInvalidDecl();
13059     return;
13060   }
13061 
13062   // Require a non-abstract type.
13063   if (RequireNonAbstractType(VD->getLocation(), Ty,
13064                              diag::err_abstract_type_in_decl,
13065                              AbstractVariableType)) {
13066     VD->setInvalidDecl();
13067     return;
13068   }
13069 
13070   // Don't bother complaining about constructors or destructors,
13071   // though.
13072 }
13073 
13074 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13075   // If there is no declaration, there was an error parsing it. Just ignore it.
13076   if (!RealDecl)
13077     return;
13078 
13079   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13080     QualType Type = Var->getType();
13081 
13082     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13083     if (isa<DecompositionDecl>(RealDecl)) {
13084       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13085       Var->setInvalidDecl();
13086       return;
13087     }
13088 
13089     if (Type->isUndeducedType() &&
13090         DeduceVariableDeclarationType(Var, false, nullptr))
13091       return;
13092 
13093     // C++11 [class.static.data]p3: A static data member can be declared with
13094     // the constexpr specifier; if so, its declaration shall specify
13095     // a brace-or-equal-initializer.
13096     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13097     // the definition of a variable [...] or the declaration of a static data
13098     // member.
13099     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13100         !Var->isThisDeclarationADemotedDefinition()) {
13101       if (Var->isStaticDataMember()) {
13102         // C++1z removes the relevant rule; the in-class declaration is always
13103         // a definition there.
13104         if (!getLangOpts().CPlusPlus17 &&
13105             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13106           Diag(Var->getLocation(),
13107                diag::err_constexpr_static_mem_var_requires_init)
13108               << Var;
13109           Var->setInvalidDecl();
13110           return;
13111         }
13112       } else {
13113         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13114         Var->setInvalidDecl();
13115         return;
13116       }
13117     }
13118 
13119     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13120     // be initialized.
13121     if (!Var->isInvalidDecl() &&
13122         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13123         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13124       bool HasConstExprDefaultConstructor = false;
13125       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13126         for (auto *Ctor : RD->ctors()) {
13127           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13128               Ctor->getMethodQualifiers().getAddressSpace() ==
13129                   LangAS::opencl_constant) {
13130             HasConstExprDefaultConstructor = true;
13131           }
13132         }
13133       }
13134       if (!HasConstExprDefaultConstructor) {
13135         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13136         Var->setInvalidDecl();
13137         return;
13138       }
13139     }
13140 
13141     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13142       if (Var->getStorageClass() == SC_Extern) {
13143         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13144             << Var;
13145         Var->setInvalidDecl();
13146         return;
13147       }
13148       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13149                               diag::err_typecheck_decl_incomplete_type)) {
13150         Var->setInvalidDecl();
13151         return;
13152       }
13153       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13154         if (!RD->hasTrivialDefaultConstructor()) {
13155           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13156           Var->setInvalidDecl();
13157           return;
13158         }
13159       }
13160       // The declaration is unitialized, no need for further checks.
13161       return;
13162     }
13163 
13164     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13165     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13166         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13167       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13168                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13169 
13170 
13171     switch (DefKind) {
13172     case VarDecl::Definition:
13173       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13174         break;
13175 
13176       // We have an out-of-line definition of a static data member
13177       // that has an in-class initializer, so we type-check this like
13178       // a declaration.
13179       //
13180       LLVM_FALLTHROUGH;
13181 
13182     case VarDecl::DeclarationOnly:
13183       // It's only a declaration.
13184 
13185       // Block scope. C99 6.7p7: If an identifier for an object is
13186       // declared with no linkage (C99 6.2.2p6), the type for the
13187       // object shall be complete.
13188       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13189           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13190           RequireCompleteType(Var->getLocation(), Type,
13191                               diag::err_typecheck_decl_incomplete_type))
13192         Var->setInvalidDecl();
13193 
13194       // Make sure that the type is not abstract.
13195       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13196           RequireNonAbstractType(Var->getLocation(), Type,
13197                                  diag::err_abstract_type_in_decl,
13198                                  AbstractVariableType))
13199         Var->setInvalidDecl();
13200       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13201           Var->getStorageClass() == SC_PrivateExtern) {
13202         Diag(Var->getLocation(), diag::warn_private_extern);
13203         Diag(Var->getLocation(), diag::note_private_extern);
13204       }
13205 
13206       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13207           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13208         ExternalDeclarations.push_back(Var);
13209 
13210       return;
13211 
13212     case VarDecl::TentativeDefinition:
13213       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13214       // object that has file scope without an initializer, and without a
13215       // storage-class specifier or with the storage-class specifier "static",
13216       // constitutes a tentative definition. Note: A tentative definition with
13217       // external linkage is valid (C99 6.2.2p5).
13218       if (!Var->isInvalidDecl()) {
13219         if (const IncompleteArrayType *ArrayT
13220                                     = Context.getAsIncompleteArrayType(Type)) {
13221           if (RequireCompleteSizedType(
13222                   Var->getLocation(), ArrayT->getElementType(),
13223                   diag::err_array_incomplete_or_sizeless_type))
13224             Var->setInvalidDecl();
13225         } else if (Var->getStorageClass() == SC_Static) {
13226           // C99 6.9.2p3: If the declaration of an identifier for an object is
13227           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13228           // declared type shall not be an incomplete type.
13229           // NOTE: code such as the following
13230           //     static struct s;
13231           //     struct s { int a; };
13232           // is accepted by gcc. Hence here we issue a warning instead of
13233           // an error and we do not invalidate the static declaration.
13234           // NOTE: to avoid multiple warnings, only check the first declaration.
13235           if (Var->isFirstDecl())
13236             RequireCompleteType(Var->getLocation(), Type,
13237                                 diag::ext_typecheck_decl_incomplete_type);
13238         }
13239       }
13240 
13241       // Record the tentative definition; we're done.
13242       if (!Var->isInvalidDecl())
13243         TentativeDefinitions.push_back(Var);
13244       return;
13245     }
13246 
13247     // Provide a specific diagnostic for uninitialized variable
13248     // definitions with incomplete array type.
13249     if (Type->isIncompleteArrayType()) {
13250       Diag(Var->getLocation(),
13251            diag::err_typecheck_incomplete_array_needs_initializer);
13252       Var->setInvalidDecl();
13253       return;
13254     }
13255 
13256     // Provide a specific diagnostic for uninitialized variable
13257     // definitions with reference type.
13258     if (Type->isReferenceType()) {
13259       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13260           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13261       return;
13262     }
13263 
13264     // Do not attempt to type-check the default initializer for a
13265     // variable with dependent type.
13266     if (Type->isDependentType())
13267       return;
13268 
13269     if (Var->isInvalidDecl())
13270       return;
13271 
13272     if (!Var->hasAttr<AliasAttr>()) {
13273       if (RequireCompleteType(Var->getLocation(),
13274                               Context.getBaseElementType(Type),
13275                               diag::err_typecheck_decl_incomplete_type)) {
13276         Var->setInvalidDecl();
13277         return;
13278       }
13279     } else {
13280       return;
13281     }
13282 
13283     // The variable can not have an abstract class type.
13284     if (RequireNonAbstractType(Var->getLocation(), Type,
13285                                diag::err_abstract_type_in_decl,
13286                                AbstractVariableType)) {
13287       Var->setInvalidDecl();
13288       return;
13289     }
13290 
13291     // Check for jumps past the implicit initializer.  C++0x
13292     // clarifies that this applies to a "variable with automatic
13293     // storage duration", not a "local variable".
13294     // C++11 [stmt.dcl]p3
13295     //   A program that jumps from a point where a variable with automatic
13296     //   storage duration is not in scope to a point where it is in scope is
13297     //   ill-formed unless the variable has scalar type, class type with a
13298     //   trivial default constructor and a trivial destructor, a cv-qualified
13299     //   version of one of these types, or an array of one of the preceding
13300     //   types and is declared without an initializer.
13301     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13302       if (const RecordType *Record
13303             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13304         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13305         // Mark the function (if we're in one) for further checking even if the
13306         // looser rules of C++11 do not require such checks, so that we can
13307         // diagnose incompatibilities with C++98.
13308         if (!CXXRecord->isPOD())
13309           setFunctionHasBranchProtectedScope();
13310       }
13311     }
13312     // In OpenCL, we can't initialize objects in the __local address space,
13313     // even implicitly, so don't synthesize an implicit initializer.
13314     if (getLangOpts().OpenCL &&
13315         Var->getType().getAddressSpace() == LangAS::opencl_local)
13316       return;
13317     // C++03 [dcl.init]p9:
13318     //   If no initializer is specified for an object, and the
13319     //   object is of (possibly cv-qualified) non-POD class type (or
13320     //   array thereof), the object shall be default-initialized; if
13321     //   the object is of const-qualified type, the underlying class
13322     //   type shall have a user-declared default
13323     //   constructor. Otherwise, if no initializer is specified for
13324     //   a non- static object, the object and its subobjects, if
13325     //   any, have an indeterminate initial value); if the object
13326     //   or any of its subobjects are of const-qualified type, the
13327     //   program is ill-formed.
13328     // C++0x [dcl.init]p11:
13329     //   If no initializer is specified for an object, the object is
13330     //   default-initialized; [...].
13331     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13332     InitializationKind Kind
13333       = InitializationKind::CreateDefault(Var->getLocation());
13334 
13335     InitializationSequence InitSeq(*this, Entity, Kind, None);
13336     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13337 
13338     if (Init.get()) {
13339       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13340       // This is important for template substitution.
13341       Var->setInitStyle(VarDecl::CallInit);
13342     } else if (Init.isInvalid()) {
13343       // If default-init fails, attach a recovery-expr initializer to track
13344       // that initialization was attempted and failed.
13345       auto RecoveryExpr =
13346           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13347       if (RecoveryExpr.get())
13348         Var->setInit(RecoveryExpr.get());
13349     }
13350 
13351     CheckCompleteVariableDeclaration(Var);
13352   }
13353 }
13354 
13355 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13356   // If there is no declaration, there was an error parsing it. Ignore it.
13357   if (!D)
13358     return;
13359 
13360   VarDecl *VD = dyn_cast<VarDecl>(D);
13361   if (!VD) {
13362     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13363     D->setInvalidDecl();
13364     return;
13365   }
13366 
13367   VD->setCXXForRangeDecl(true);
13368 
13369   // for-range-declaration cannot be given a storage class specifier.
13370   int Error = -1;
13371   switch (VD->getStorageClass()) {
13372   case SC_None:
13373     break;
13374   case SC_Extern:
13375     Error = 0;
13376     break;
13377   case SC_Static:
13378     Error = 1;
13379     break;
13380   case SC_PrivateExtern:
13381     Error = 2;
13382     break;
13383   case SC_Auto:
13384     Error = 3;
13385     break;
13386   case SC_Register:
13387     Error = 4;
13388     break;
13389   }
13390 
13391   // for-range-declaration cannot be given a storage class specifier con't.
13392   switch (VD->getTSCSpec()) {
13393   case TSCS_thread_local:
13394     Error = 6;
13395     break;
13396   case TSCS___thread:
13397   case TSCS__Thread_local:
13398   case TSCS_unspecified:
13399     break;
13400   }
13401 
13402   if (Error != -1) {
13403     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13404         << VD << Error;
13405     D->setInvalidDecl();
13406   }
13407 }
13408 
13409 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13410                                             IdentifierInfo *Ident,
13411                                             ParsedAttributes &Attrs) {
13412   // C++1y [stmt.iter]p1:
13413   //   A range-based for statement of the form
13414   //      for ( for-range-identifier : for-range-initializer ) statement
13415   //   is equivalent to
13416   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13417   DeclSpec DS(Attrs.getPool().getFactory());
13418 
13419   const char *PrevSpec;
13420   unsigned DiagID;
13421   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13422                      getPrintingPolicy());
13423 
13424   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13425   D.SetIdentifier(Ident, IdentLoc);
13426   D.takeAttributes(Attrs);
13427 
13428   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13429                 IdentLoc);
13430   Decl *Var = ActOnDeclarator(S, D);
13431   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13432   FinalizeDeclaration(Var);
13433   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13434                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13435                                                       : IdentLoc);
13436 }
13437 
13438 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13439   if (var->isInvalidDecl()) return;
13440 
13441   MaybeAddCUDAConstantAttr(var);
13442 
13443   if (getLangOpts().OpenCL) {
13444     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13445     // initialiser
13446     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13447         !var->hasInit()) {
13448       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13449           << 1 /*Init*/;
13450       var->setInvalidDecl();
13451       return;
13452     }
13453   }
13454 
13455   // In Objective-C, don't allow jumps past the implicit initialization of a
13456   // local retaining variable.
13457   if (getLangOpts().ObjC &&
13458       var->hasLocalStorage()) {
13459     switch (var->getType().getObjCLifetime()) {
13460     case Qualifiers::OCL_None:
13461     case Qualifiers::OCL_ExplicitNone:
13462     case Qualifiers::OCL_Autoreleasing:
13463       break;
13464 
13465     case Qualifiers::OCL_Weak:
13466     case Qualifiers::OCL_Strong:
13467       setFunctionHasBranchProtectedScope();
13468       break;
13469     }
13470   }
13471 
13472   if (var->hasLocalStorage() &&
13473       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13474     setFunctionHasBranchProtectedScope();
13475 
13476   // Warn about externally-visible variables being defined without a
13477   // prior declaration.  We only want to do this for global
13478   // declarations, but we also specifically need to avoid doing it for
13479   // class members because the linkage of an anonymous class can
13480   // change if it's later given a typedef name.
13481   if (var->isThisDeclarationADefinition() &&
13482       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13483       var->isExternallyVisible() && var->hasLinkage() &&
13484       !var->isInline() && !var->getDescribedVarTemplate() &&
13485       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13486       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13487       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13488                                   var->getLocation())) {
13489     // Find a previous declaration that's not a definition.
13490     VarDecl *prev = var->getPreviousDecl();
13491     while (prev && prev->isThisDeclarationADefinition())
13492       prev = prev->getPreviousDecl();
13493 
13494     if (!prev) {
13495       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13496       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13497           << /* variable */ 0;
13498     }
13499   }
13500 
13501   // Cache the result of checking for constant initialization.
13502   Optional<bool> CacheHasConstInit;
13503   const Expr *CacheCulprit = nullptr;
13504   auto checkConstInit = [&]() mutable {
13505     if (!CacheHasConstInit)
13506       CacheHasConstInit = var->getInit()->isConstantInitializer(
13507             Context, var->getType()->isReferenceType(), &CacheCulprit);
13508     return *CacheHasConstInit;
13509   };
13510 
13511   if (var->getTLSKind() == VarDecl::TLS_Static) {
13512     if (var->getType().isDestructedType()) {
13513       // GNU C++98 edits for __thread, [basic.start.term]p3:
13514       //   The type of an object with thread storage duration shall not
13515       //   have a non-trivial destructor.
13516       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13517       if (getLangOpts().CPlusPlus11)
13518         Diag(var->getLocation(), diag::note_use_thread_local);
13519     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13520       if (!checkConstInit()) {
13521         // GNU C++98 edits for __thread, [basic.start.init]p4:
13522         //   An object of thread storage duration shall not require dynamic
13523         //   initialization.
13524         // FIXME: Need strict checking here.
13525         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13526           << CacheCulprit->getSourceRange();
13527         if (getLangOpts().CPlusPlus11)
13528           Diag(var->getLocation(), diag::note_use_thread_local);
13529       }
13530     }
13531   }
13532 
13533 
13534   if (!var->getType()->isStructureType() && var->hasInit() &&
13535       isa<InitListExpr>(var->getInit())) {
13536     const auto *ILE = cast<InitListExpr>(var->getInit());
13537     unsigned NumInits = ILE->getNumInits();
13538     if (NumInits > 2)
13539       for (unsigned I = 0; I < NumInits; ++I) {
13540         const auto *Init = ILE->getInit(I);
13541         if (!Init)
13542           break;
13543         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13544         if (!SL)
13545           break;
13546 
13547         unsigned NumConcat = SL->getNumConcatenated();
13548         // Diagnose missing comma in string array initialization.
13549         // Do not warn when all the elements in the initializer are concatenated
13550         // together. Do not warn for macros too.
13551         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13552           bool OnlyOneMissingComma = true;
13553           for (unsigned J = I + 1; J < NumInits; ++J) {
13554             const auto *Init = ILE->getInit(J);
13555             if (!Init)
13556               break;
13557             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13558             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13559               OnlyOneMissingComma = false;
13560               break;
13561             }
13562           }
13563 
13564           if (OnlyOneMissingComma) {
13565             SmallVector<FixItHint, 1> Hints;
13566             for (unsigned i = 0; i < NumConcat - 1; ++i)
13567               Hints.push_back(FixItHint::CreateInsertion(
13568                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13569 
13570             Diag(SL->getStrTokenLoc(1),
13571                  diag::warn_concatenated_literal_array_init)
13572                 << Hints;
13573             Diag(SL->getBeginLoc(),
13574                  diag::note_concatenated_string_literal_silence);
13575           }
13576           // In any case, stop now.
13577           break;
13578         }
13579       }
13580   }
13581 
13582 
13583   QualType type = var->getType();
13584 
13585   if (var->hasAttr<BlocksAttr>())
13586     getCurFunction()->addByrefBlockVar(var);
13587 
13588   Expr *Init = var->getInit();
13589   bool GlobalStorage = var->hasGlobalStorage();
13590   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13591   QualType baseType = Context.getBaseElementType(type);
13592   bool HasConstInit = true;
13593 
13594   // Check whether the initializer is sufficiently constant.
13595   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13596       !Init->isValueDependent() &&
13597       (GlobalStorage || var->isConstexpr() ||
13598        var->mightBeUsableInConstantExpressions(Context))) {
13599     // If this variable might have a constant initializer or might be usable in
13600     // constant expressions, check whether or not it actually is now.  We can't
13601     // do this lazily, because the result might depend on things that change
13602     // later, such as which constexpr functions happen to be defined.
13603     SmallVector<PartialDiagnosticAt, 8> Notes;
13604     if (!getLangOpts().CPlusPlus11) {
13605       // Prior to C++11, in contexts where a constant initializer is required,
13606       // the set of valid constant initializers is described by syntactic rules
13607       // in [expr.const]p2-6.
13608       // FIXME: Stricter checking for these rules would be useful for constinit /
13609       // -Wglobal-constructors.
13610       HasConstInit = checkConstInit();
13611 
13612       // Compute and cache the constant value, and remember that we have a
13613       // constant initializer.
13614       if (HasConstInit) {
13615         (void)var->checkForConstantInitialization(Notes);
13616         Notes.clear();
13617       } else if (CacheCulprit) {
13618         Notes.emplace_back(CacheCulprit->getExprLoc(),
13619                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13620         Notes.back().second << CacheCulprit->getSourceRange();
13621       }
13622     } else {
13623       // Evaluate the initializer to see if it's a constant initializer.
13624       HasConstInit = var->checkForConstantInitialization(Notes);
13625     }
13626 
13627     if (HasConstInit) {
13628       // FIXME: Consider replacing the initializer with a ConstantExpr.
13629     } else if (var->isConstexpr()) {
13630       SourceLocation DiagLoc = var->getLocation();
13631       // If the note doesn't add any useful information other than a source
13632       // location, fold it into the primary diagnostic.
13633       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13634                                    diag::note_invalid_subexpr_in_const_expr) {
13635         DiagLoc = Notes[0].first;
13636         Notes.clear();
13637       }
13638       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13639           << var << Init->getSourceRange();
13640       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13641         Diag(Notes[I].first, Notes[I].second);
13642     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13643       auto *Attr = var->getAttr<ConstInitAttr>();
13644       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13645           << Init->getSourceRange();
13646       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13647           << Attr->getRange() << Attr->isConstinit();
13648       for (auto &it : Notes)
13649         Diag(it.first, it.second);
13650     } else if (IsGlobal &&
13651                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13652                                            var->getLocation())) {
13653       // Warn about globals which don't have a constant initializer.  Don't
13654       // warn about globals with a non-trivial destructor because we already
13655       // warned about them.
13656       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13657       if (!(RD && !RD->hasTrivialDestructor())) {
13658         // checkConstInit() here permits trivial default initialization even in
13659         // C++11 onwards, where such an initializer is not a constant initializer
13660         // but nonetheless doesn't require a global constructor.
13661         if (!checkConstInit())
13662           Diag(var->getLocation(), diag::warn_global_constructor)
13663               << Init->getSourceRange();
13664       }
13665     }
13666   }
13667 
13668   // Apply section attributes and pragmas to global variables.
13669   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13670       !inTemplateInstantiation()) {
13671     PragmaStack<StringLiteral *> *Stack = nullptr;
13672     int SectionFlags = ASTContext::PSF_Read;
13673     if (var->getType().isConstQualified()) {
13674       if (HasConstInit)
13675         Stack = &ConstSegStack;
13676       else {
13677         Stack = &BSSSegStack;
13678         SectionFlags |= ASTContext::PSF_Write;
13679       }
13680     } else if (var->hasInit() && HasConstInit) {
13681       Stack = &DataSegStack;
13682       SectionFlags |= ASTContext::PSF_Write;
13683     } else {
13684       Stack = &BSSSegStack;
13685       SectionFlags |= ASTContext::PSF_Write;
13686     }
13687     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13688       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13689         SectionFlags |= ASTContext::PSF_Implicit;
13690       UnifySection(SA->getName(), SectionFlags, var);
13691     } else if (Stack->CurrentValue) {
13692       SectionFlags |= ASTContext::PSF_Implicit;
13693       auto SectionName = Stack->CurrentValue->getString();
13694       var->addAttr(SectionAttr::CreateImplicit(
13695           Context, SectionName, Stack->CurrentPragmaLocation,
13696           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13697       if (UnifySection(SectionName, SectionFlags, var))
13698         var->dropAttr<SectionAttr>();
13699     }
13700 
13701     // Apply the init_seg attribute if this has an initializer.  If the
13702     // initializer turns out to not be dynamic, we'll end up ignoring this
13703     // attribute.
13704     if (CurInitSeg && var->getInit())
13705       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13706                                                CurInitSegLoc,
13707                                                AttributeCommonInfo::AS_Pragma));
13708   }
13709 
13710   // All the following checks are C++ only.
13711   if (!getLangOpts().CPlusPlus) {
13712     // If this variable must be emitted, add it as an initializer for the
13713     // current module.
13714     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13715       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13716     return;
13717   }
13718 
13719   // Require the destructor.
13720   if (!type->isDependentType())
13721     if (const RecordType *recordType = baseType->getAs<RecordType>())
13722       FinalizeVarWithDestructor(var, recordType);
13723 
13724   // If this variable must be emitted, add it as an initializer for the current
13725   // module.
13726   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13727     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13728 
13729   // Build the bindings if this is a structured binding declaration.
13730   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13731     CheckCompleteDecompositionDeclaration(DD);
13732 }
13733 
13734 /// Check if VD needs to be dllexport/dllimport due to being in a
13735 /// dllexport/import function.
13736 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13737   assert(VD->isStaticLocal());
13738 
13739   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13740 
13741   // Find outermost function when VD is in lambda function.
13742   while (FD && !getDLLAttr(FD) &&
13743          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13744          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13745     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13746   }
13747 
13748   if (!FD)
13749     return;
13750 
13751   // Static locals inherit dll attributes from their function.
13752   if (Attr *A = getDLLAttr(FD)) {
13753     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13754     NewAttr->setInherited(true);
13755     VD->addAttr(NewAttr);
13756   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13757     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13758     NewAttr->setInherited(true);
13759     VD->addAttr(NewAttr);
13760 
13761     // Export this function to enforce exporting this static variable even
13762     // if it is not used in this compilation unit.
13763     if (!FD->hasAttr<DLLExportAttr>())
13764       FD->addAttr(NewAttr);
13765 
13766   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13767     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13768     NewAttr->setInherited(true);
13769     VD->addAttr(NewAttr);
13770   }
13771 }
13772 
13773 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13774 /// any semantic actions necessary after any initializer has been attached.
13775 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13776   // Note that we are no longer parsing the initializer for this declaration.
13777   ParsingInitForAutoVars.erase(ThisDecl);
13778 
13779   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13780   if (!VD)
13781     return;
13782 
13783   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13784   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13785       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13786     if (PragmaClangBSSSection.Valid)
13787       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13788           Context, PragmaClangBSSSection.SectionName,
13789           PragmaClangBSSSection.PragmaLocation,
13790           AttributeCommonInfo::AS_Pragma));
13791     if (PragmaClangDataSection.Valid)
13792       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13793           Context, PragmaClangDataSection.SectionName,
13794           PragmaClangDataSection.PragmaLocation,
13795           AttributeCommonInfo::AS_Pragma));
13796     if (PragmaClangRodataSection.Valid)
13797       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13798           Context, PragmaClangRodataSection.SectionName,
13799           PragmaClangRodataSection.PragmaLocation,
13800           AttributeCommonInfo::AS_Pragma));
13801     if (PragmaClangRelroSection.Valid)
13802       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13803           Context, PragmaClangRelroSection.SectionName,
13804           PragmaClangRelroSection.PragmaLocation,
13805           AttributeCommonInfo::AS_Pragma));
13806   }
13807 
13808   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13809     for (auto *BD : DD->bindings()) {
13810       FinalizeDeclaration(BD);
13811     }
13812   }
13813 
13814   checkAttributesAfterMerging(*this, *VD);
13815 
13816   // Perform TLS alignment check here after attributes attached to the variable
13817   // which may affect the alignment have been processed. Only perform the check
13818   // if the target has a maximum TLS alignment (zero means no constraints).
13819   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13820     // Protect the check so that it's not performed on dependent types and
13821     // dependent alignments (we can't determine the alignment in that case).
13822     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13823       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13824       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13825         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13826           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13827           << (unsigned)MaxAlignChars.getQuantity();
13828       }
13829     }
13830   }
13831 
13832   if (VD->isStaticLocal())
13833     CheckStaticLocalForDllExport(VD);
13834 
13835   // Perform check for initializers of device-side global variables.
13836   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13837   // 7.5). We must also apply the same checks to all __shared__
13838   // variables whether they are local or not. CUDA also allows
13839   // constant initializers for __constant__ and __device__ variables.
13840   if (getLangOpts().CUDA)
13841     checkAllowedCUDAInitializer(VD);
13842 
13843   // Grab the dllimport or dllexport attribute off of the VarDecl.
13844   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13845 
13846   // Imported static data members cannot be defined out-of-line.
13847   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13848     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13849         VD->isThisDeclarationADefinition()) {
13850       // We allow definitions of dllimport class template static data members
13851       // with a warning.
13852       CXXRecordDecl *Context =
13853         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13854       bool IsClassTemplateMember =
13855           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13856           Context->getDescribedClassTemplate();
13857 
13858       Diag(VD->getLocation(),
13859            IsClassTemplateMember
13860                ? diag::warn_attribute_dllimport_static_field_definition
13861                : diag::err_attribute_dllimport_static_field_definition);
13862       Diag(IA->getLocation(), diag::note_attribute);
13863       if (!IsClassTemplateMember)
13864         VD->setInvalidDecl();
13865     }
13866   }
13867 
13868   // dllimport/dllexport variables cannot be thread local, their TLS index
13869   // isn't exported with the variable.
13870   if (DLLAttr && VD->getTLSKind()) {
13871     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13872     if (F && getDLLAttr(F)) {
13873       assert(VD->isStaticLocal());
13874       // But if this is a static local in a dlimport/dllexport function, the
13875       // function will never be inlined, which means the var would never be
13876       // imported, so having it marked import/export is safe.
13877     } else {
13878       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13879                                                                     << DLLAttr;
13880       VD->setInvalidDecl();
13881     }
13882   }
13883 
13884   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13885     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13886       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13887           << Attr;
13888       VD->dropAttr<UsedAttr>();
13889     }
13890   }
13891   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13892     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13893       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13894           << Attr;
13895       VD->dropAttr<RetainAttr>();
13896     }
13897   }
13898 
13899   const DeclContext *DC = VD->getDeclContext();
13900   // If there's a #pragma GCC visibility in scope, and this isn't a class
13901   // member, set the visibility of this variable.
13902   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13903     AddPushedVisibilityAttribute(VD);
13904 
13905   // FIXME: Warn on unused var template partial specializations.
13906   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13907     MarkUnusedFileScopedDecl(VD);
13908 
13909   // Now we have parsed the initializer and can update the table of magic
13910   // tag values.
13911   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13912       !VD->getType()->isIntegralOrEnumerationType())
13913     return;
13914 
13915   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13916     const Expr *MagicValueExpr = VD->getInit();
13917     if (!MagicValueExpr) {
13918       continue;
13919     }
13920     Optional<llvm::APSInt> MagicValueInt;
13921     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13922       Diag(I->getRange().getBegin(),
13923            diag::err_type_tag_for_datatype_not_ice)
13924         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13925       continue;
13926     }
13927     if (MagicValueInt->getActiveBits() > 64) {
13928       Diag(I->getRange().getBegin(),
13929            diag::err_type_tag_for_datatype_too_large)
13930         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13931       continue;
13932     }
13933     uint64_t MagicValue = MagicValueInt->getZExtValue();
13934     RegisterTypeTagForDatatype(I->getArgumentKind(),
13935                                MagicValue,
13936                                I->getMatchingCType(),
13937                                I->getLayoutCompatible(),
13938                                I->getMustBeNull());
13939   }
13940 }
13941 
13942 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13943   auto *VD = dyn_cast<VarDecl>(DD);
13944   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13945 }
13946 
13947 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13948                                                    ArrayRef<Decl *> Group) {
13949   SmallVector<Decl*, 8> Decls;
13950 
13951   if (DS.isTypeSpecOwned())
13952     Decls.push_back(DS.getRepAsDecl());
13953 
13954   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13955   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13956   bool DiagnosedMultipleDecomps = false;
13957   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13958   bool DiagnosedNonDeducedAuto = false;
13959 
13960   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13961     if (Decl *D = Group[i]) {
13962       // For declarators, there are some additional syntactic-ish checks we need
13963       // to perform.
13964       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13965         if (!FirstDeclaratorInGroup)
13966           FirstDeclaratorInGroup = DD;
13967         if (!FirstDecompDeclaratorInGroup)
13968           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13969         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13970             !hasDeducedAuto(DD))
13971           FirstNonDeducedAutoInGroup = DD;
13972 
13973         if (FirstDeclaratorInGroup != DD) {
13974           // A decomposition declaration cannot be combined with any other
13975           // declaration in the same group.
13976           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13977             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13978                  diag::err_decomp_decl_not_alone)
13979                 << FirstDeclaratorInGroup->getSourceRange()
13980                 << DD->getSourceRange();
13981             DiagnosedMultipleDecomps = true;
13982           }
13983 
13984           // A declarator that uses 'auto' in any way other than to declare a
13985           // variable with a deduced type cannot be combined with any other
13986           // declarator in the same group.
13987           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13988             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13989                  diag::err_auto_non_deduced_not_alone)
13990                 << FirstNonDeducedAutoInGroup->getType()
13991                        ->hasAutoForTrailingReturnType()
13992                 << FirstDeclaratorInGroup->getSourceRange()
13993                 << DD->getSourceRange();
13994             DiagnosedNonDeducedAuto = true;
13995           }
13996         }
13997       }
13998 
13999       Decls.push_back(D);
14000     }
14001   }
14002 
14003   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14004     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14005       handleTagNumbering(Tag, S);
14006       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14007           getLangOpts().CPlusPlus)
14008         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14009     }
14010   }
14011 
14012   return BuildDeclaratorGroup(Decls);
14013 }
14014 
14015 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14016 /// group, performing any necessary semantic checking.
14017 Sema::DeclGroupPtrTy
14018 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14019   // C++14 [dcl.spec.auto]p7: (DR1347)
14020   //   If the type that replaces the placeholder type is not the same in each
14021   //   deduction, the program is ill-formed.
14022   if (Group.size() > 1) {
14023     QualType Deduced;
14024     VarDecl *DeducedDecl = nullptr;
14025     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14026       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14027       if (!D || D->isInvalidDecl())
14028         break;
14029       DeducedType *DT = D->getType()->getContainedDeducedType();
14030       if (!DT || DT->getDeducedType().isNull())
14031         continue;
14032       if (Deduced.isNull()) {
14033         Deduced = DT->getDeducedType();
14034         DeducedDecl = D;
14035       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14036         auto *AT = dyn_cast<AutoType>(DT);
14037         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14038                         diag::err_auto_different_deductions)
14039                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14040                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14041                    << D->getDeclName();
14042         if (DeducedDecl->hasInit())
14043           Dia << DeducedDecl->getInit()->getSourceRange();
14044         if (D->getInit())
14045           Dia << D->getInit()->getSourceRange();
14046         D->setInvalidDecl();
14047         break;
14048       }
14049     }
14050   }
14051 
14052   ActOnDocumentableDecls(Group);
14053 
14054   return DeclGroupPtrTy::make(
14055       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14056 }
14057 
14058 void Sema::ActOnDocumentableDecl(Decl *D) {
14059   ActOnDocumentableDecls(D);
14060 }
14061 
14062 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14063   // Don't parse the comment if Doxygen diagnostics are ignored.
14064   if (Group.empty() || !Group[0])
14065     return;
14066 
14067   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14068                       Group[0]->getLocation()) &&
14069       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14070                       Group[0]->getLocation()))
14071     return;
14072 
14073   if (Group.size() >= 2) {
14074     // This is a decl group.  Normally it will contain only declarations
14075     // produced from declarator list.  But in case we have any definitions or
14076     // additional declaration references:
14077     //   'typedef struct S {} S;'
14078     //   'typedef struct S *S;'
14079     //   'struct S *pS;'
14080     // FinalizeDeclaratorGroup adds these as separate declarations.
14081     Decl *MaybeTagDecl = Group[0];
14082     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14083       Group = Group.slice(1);
14084     }
14085   }
14086 
14087   // FIMXE: We assume every Decl in the group is in the same file.
14088   // This is false when preprocessor constructs the group from decls in
14089   // different files (e. g. macros or #include).
14090   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14091 }
14092 
14093 /// Common checks for a parameter-declaration that should apply to both function
14094 /// parameters and non-type template parameters.
14095 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14096   // Check that there are no default arguments inside the type of this
14097   // parameter.
14098   if (getLangOpts().CPlusPlus)
14099     CheckExtraCXXDefaultArguments(D);
14100 
14101   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14102   if (D.getCXXScopeSpec().isSet()) {
14103     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14104       << D.getCXXScopeSpec().getRange();
14105   }
14106 
14107   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14108   // simple identifier except [...irrelevant cases...].
14109   switch (D.getName().getKind()) {
14110   case UnqualifiedIdKind::IK_Identifier:
14111     break;
14112 
14113   case UnqualifiedIdKind::IK_OperatorFunctionId:
14114   case UnqualifiedIdKind::IK_ConversionFunctionId:
14115   case UnqualifiedIdKind::IK_LiteralOperatorId:
14116   case UnqualifiedIdKind::IK_ConstructorName:
14117   case UnqualifiedIdKind::IK_DestructorName:
14118   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14119   case UnqualifiedIdKind::IK_DeductionGuideName:
14120     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14121       << GetNameForDeclarator(D).getName();
14122     break;
14123 
14124   case UnqualifiedIdKind::IK_TemplateId:
14125   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14126     // GetNameForDeclarator would not produce a useful name in this case.
14127     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14128     break;
14129   }
14130 }
14131 
14132 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14133 /// to introduce parameters into function prototype scope.
14134 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14135   const DeclSpec &DS = D.getDeclSpec();
14136 
14137   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14138 
14139   // C++03 [dcl.stc]p2 also permits 'auto'.
14140   StorageClass SC = SC_None;
14141   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14142     SC = SC_Register;
14143     // In C++11, the 'register' storage class specifier is deprecated.
14144     // In C++17, it is not allowed, but we tolerate it as an extension.
14145     if (getLangOpts().CPlusPlus11) {
14146       Diag(DS.getStorageClassSpecLoc(),
14147            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14148                                      : diag::warn_deprecated_register)
14149         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14150     }
14151   } else if (getLangOpts().CPlusPlus &&
14152              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14153     SC = SC_Auto;
14154   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14155     Diag(DS.getStorageClassSpecLoc(),
14156          diag::err_invalid_storage_class_in_func_decl);
14157     D.getMutableDeclSpec().ClearStorageClassSpecs();
14158   }
14159 
14160   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14161     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14162       << DeclSpec::getSpecifierName(TSCS);
14163   if (DS.isInlineSpecified())
14164     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14165         << getLangOpts().CPlusPlus17;
14166   if (DS.hasConstexprSpecifier())
14167     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14168         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14169 
14170   DiagnoseFunctionSpecifiers(DS);
14171 
14172   CheckFunctionOrTemplateParamDeclarator(S, D);
14173 
14174   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14175   QualType parmDeclType = TInfo->getType();
14176 
14177   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14178   IdentifierInfo *II = D.getIdentifier();
14179   if (II) {
14180     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14181                    ForVisibleRedeclaration);
14182     LookupName(R, S);
14183     if (R.isSingleResult()) {
14184       NamedDecl *PrevDecl = R.getFoundDecl();
14185       if (PrevDecl->isTemplateParameter()) {
14186         // Maybe we will complain about the shadowed template parameter.
14187         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14188         // Just pretend that we didn't see the previous declaration.
14189         PrevDecl = nullptr;
14190       } else if (S->isDeclScope(PrevDecl)) {
14191         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14192         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14193 
14194         // Recover by removing the name
14195         II = nullptr;
14196         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14197         D.setInvalidType(true);
14198       }
14199     }
14200   }
14201 
14202   // Temporarily put parameter variables in the translation unit, not
14203   // the enclosing context.  This prevents them from accidentally
14204   // looking like class members in C++.
14205   ParmVarDecl *New =
14206       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14207                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14208 
14209   if (D.isInvalidType())
14210     New->setInvalidDecl();
14211 
14212   assert(S->isFunctionPrototypeScope());
14213   assert(S->getFunctionPrototypeDepth() >= 1);
14214   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14215                     S->getNextFunctionPrototypeIndex());
14216 
14217   // Add the parameter declaration into this scope.
14218   S->AddDecl(New);
14219   if (II)
14220     IdResolver.AddDecl(New);
14221 
14222   ProcessDeclAttributes(S, New, D);
14223 
14224   if (D.getDeclSpec().isModulePrivateSpecified())
14225     Diag(New->getLocation(), diag::err_module_private_local)
14226         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14227         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14228 
14229   if (New->hasAttr<BlocksAttr>()) {
14230     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14231   }
14232 
14233   if (getLangOpts().OpenCL)
14234     deduceOpenCLAddressSpace(New);
14235 
14236   return New;
14237 }
14238 
14239 /// Synthesizes a variable for a parameter arising from a
14240 /// typedef.
14241 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14242                                               SourceLocation Loc,
14243                                               QualType T) {
14244   /* FIXME: setting StartLoc == Loc.
14245      Would it be worth to modify callers so as to provide proper source
14246      location for the unnamed parameters, embedding the parameter's type? */
14247   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14248                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14249                                            SC_None, nullptr);
14250   Param->setImplicit();
14251   return Param;
14252 }
14253 
14254 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14255   // Don't diagnose unused-parameter errors in template instantiations; we
14256   // will already have done so in the template itself.
14257   if (inTemplateInstantiation())
14258     return;
14259 
14260   for (const ParmVarDecl *Parameter : Parameters) {
14261     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14262         !Parameter->hasAttr<UnusedAttr>()) {
14263       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14264         << Parameter->getDeclName();
14265     }
14266   }
14267 }
14268 
14269 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14270     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14271   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14272     return;
14273 
14274   // Warn if the return value is pass-by-value and larger than the specified
14275   // threshold.
14276   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14277     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14278     if (Size > LangOpts.NumLargeByValueCopy)
14279       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14280   }
14281 
14282   // Warn if any parameter is pass-by-value and larger than the specified
14283   // threshold.
14284   for (const ParmVarDecl *Parameter : Parameters) {
14285     QualType T = Parameter->getType();
14286     if (T->isDependentType() || !T.isPODType(Context))
14287       continue;
14288     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14289     if (Size > LangOpts.NumLargeByValueCopy)
14290       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14291           << Parameter << Size;
14292   }
14293 }
14294 
14295 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14296                                   SourceLocation NameLoc, IdentifierInfo *Name,
14297                                   QualType T, TypeSourceInfo *TSInfo,
14298                                   StorageClass SC) {
14299   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14300   if (getLangOpts().ObjCAutoRefCount &&
14301       T.getObjCLifetime() == Qualifiers::OCL_None &&
14302       T->isObjCLifetimeType()) {
14303 
14304     Qualifiers::ObjCLifetime lifetime;
14305 
14306     // Special cases for arrays:
14307     //   - if it's const, use __unsafe_unretained
14308     //   - otherwise, it's an error
14309     if (T->isArrayType()) {
14310       if (!T.isConstQualified()) {
14311         if (DelayedDiagnostics.shouldDelayDiagnostics())
14312           DelayedDiagnostics.add(
14313               sema::DelayedDiagnostic::makeForbiddenType(
14314               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14315         else
14316           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14317               << TSInfo->getTypeLoc().getSourceRange();
14318       }
14319       lifetime = Qualifiers::OCL_ExplicitNone;
14320     } else {
14321       lifetime = T->getObjCARCImplicitLifetime();
14322     }
14323     T = Context.getLifetimeQualifiedType(T, lifetime);
14324   }
14325 
14326   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14327                                          Context.getAdjustedParameterType(T),
14328                                          TSInfo, SC, nullptr);
14329 
14330   // Make a note if we created a new pack in the scope of a lambda, so that
14331   // we know that references to that pack must also be expanded within the
14332   // lambda scope.
14333   if (New->isParameterPack())
14334     if (auto *LSI = getEnclosingLambda())
14335       LSI->LocalPacks.push_back(New);
14336 
14337   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14338       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14339     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14340                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14341 
14342   // Parameters can not be abstract class types.
14343   // For record types, this is done by the AbstractClassUsageDiagnoser once
14344   // the class has been completely parsed.
14345   if (!CurContext->isRecord() &&
14346       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14347                              AbstractParamType))
14348     New->setInvalidDecl();
14349 
14350   // Parameter declarators cannot be interface types. All ObjC objects are
14351   // passed by reference.
14352   if (T->isObjCObjectType()) {
14353     SourceLocation TypeEndLoc =
14354         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14355     Diag(NameLoc,
14356          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14357       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14358     T = Context.getObjCObjectPointerType(T);
14359     New->setType(T);
14360   }
14361 
14362   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14363   // duration shall not be qualified by an address-space qualifier."
14364   // Since all parameters have automatic store duration, they can not have
14365   // an address space.
14366   if (T.getAddressSpace() != LangAS::Default &&
14367       // OpenCL allows function arguments declared to be an array of a type
14368       // to be qualified with an address space.
14369       !(getLangOpts().OpenCL &&
14370         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14371     Diag(NameLoc, diag::err_arg_with_address_space);
14372     New->setInvalidDecl();
14373   }
14374 
14375   // PPC MMA non-pointer types are not allowed as function argument types.
14376   if (Context.getTargetInfo().getTriple().isPPC64() &&
14377       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14378     New->setInvalidDecl();
14379   }
14380 
14381   return New;
14382 }
14383 
14384 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14385                                            SourceLocation LocAfterDecls) {
14386   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14387 
14388   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14389   // in the declaration list shall have at least one declarator, those
14390   // declarators shall only declare identifiers from the identifier list, and
14391   // every identifier in the identifier list shall be declared.
14392   //
14393   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14394   // identifiers it names shall be declared in the declaration list."
14395   //
14396   // This is why we only diagnose in C99 and later. Note, the other conditions
14397   // listed are checked elsewhere.
14398   if (!FTI.hasPrototype) {
14399     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14400       --i;
14401       if (FTI.Params[i].Param == nullptr) {
14402         if (getLangOpts().C99) {
14403           SmallString<256> Code;
14404           llvm::raw_svector_ostream(Code)
14405               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14406           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14407               << FTI.Params[i].Ident
14408               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14409         }
14410 
14411         // Implicitly declare the argument as type 'int' for lack of a better
14412         // type.
14413         AttributeFactory attrs;
14414         DeclSpec DS(attrs);
14415         const char* PrevSpec; // unused
14416         unsigned DiagID; // unused
14417         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14418                            DiagID, Context.getPrintingPolicy());
14419         // Use the identifier location for the type source range.
14420         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14421         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14422         Declarator ParamD(DS, ParsedAttributesView::none(),
14423                           DeclaratorContext::KNRTypeList);
14424         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14425         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14426       }
14427     }
14428   }
14429 }
14430 
14431 Decl *
14432 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14433                               MultiTemplateParamsArg TemplateParameterLists,
14434                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14435   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14436   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14437   Scope *ParentScope = FnBodyScope->getParent();
14438 
14439   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14440   // we define a non-templated function definition, we will create a declaration
14441   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14442   // The base function declaration will have the equivalent of an `omp declare
14443   // variant` annotation which specifies the mangled definition as a
14444   // specialization function under the OpenMP context defined as part of the
14445   // `omp begin declare variant`.
14446   SmallVector<FunctionDecl *, 4> Bases;
14447   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14448     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14449         ParentScope, D, TemplateParameterLists, Bases);
14450 
14451   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14452   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14453   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14454 
14455   if (!Bases.empty())
14456     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14457 
14458   return Dcl;
14459 }
14460 
14461 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14462   Consumer.HandleInlineFunctionDefinition(D);
14463 }
14464 
14465 static bool
14466 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14467                                 const FunctionDecl *&PossiblePrototype) {
14468   // Don't warn about invalid declarations.
14469   if (FD->isInvalidDecl())
14470     return false;
14471 
14472   // Or declarations that aren't global.
14473   if (!FD->isGlobal())
14474     return false;
14475 
14476   // Don't warn about C++ member functions.
14477   if (isa<CXXMethodDecl>(FD))
14478     return false;
14479 
14480   // Don't warn about 'main'.
14481   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14482     if (IdentifierInfo *II = FD->getIdentifier())
14483       if (II->isStr("main") || II->isStr("efi_main"))
14484         return false;
14485 
14486   // Don't warn about inline functions.
14487   if (FD->isInlined())
14488     return false;
14489 
14490   // Don't warn about function templates.
14491   if (FD->getDescribedFunctionTemplate())
14492     return false;
14493 
14494   // Don't warn about function template specializations.
14495   if (FD->isFunctionTemplateSpecialization())
14496     return false;
14497 
14498   // Don't warn for OpenCL kernels.
14499   if (FD->hasAttr<OpenCLKernelAttr>())
14500     return false;
14501 
14502   // Don't warn on explicitly deleted functions.
14503   if (FD->isDeleted())
14504     return false;
14505 
14506   // Don't warn on implicitly local functions (such as having local-typed
14507   // parameters).
14508   if (!FD->isExternallyVisible())
14509     return false;
14510 
14511   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14512        Prev; Prev = Prev->getPreviousDecl()) {
14513     // Ignore any declarations that occur in function or method
14514     // scope, because they aren't visible from the header.
14515     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14516       continue;
14517 
14518     PossiblePrototype = Prev;
14519     return Prev->getType()->isFunctionNoProtoType();
14520   }
14521 
14522   return true;
14523 }
14524 
14525 void
14526 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14527                                    const FunctionDecl *EffectiveDefinition,
14528                                    SkipBodyInfo *SkipBody) {
14529   const FunctionDecl *Definition = EffectiveDefinition;
14530   if (!Definition &&
14531       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14532     return;
14533 
14534   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14535     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14536       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14537         // A merged copy of the same function, instantiated as a member of
14538         // the same class, is OK.
14539         if (declaresSameEntity(OrigFD, OrigDef) &&
14540             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14541                                cast<Decl>(FD->getLexicalDeclContext())))
14542           return;
14543       }
14544     }
14545   }
14546 
14547   if (canRedefineFunction(Definition, getLangOpts()))
14548     return;
14549 
14550   // Don't emit an error when this is redefinition of a typo-corrected
14551   // definition.
14552   if (TypoCorrectedFunctionDefinitions.count(Definition))
14553     return;
14554 
14555   // If we don't have a visible definition of the function, and it's inline or
14556   // a template, skip the new definition.
14557   if (SkipBody && !hasVisibleDefinition(Definition) &&
14558       (Definition->getFormalLinkage() == InternalLinkage ||
14559        Definition->isInlined() ||
14560        Definition->getDescribedFunctionTemplate() ||
14561        Definition->getNumTemplateParameterLists())) {
14562     SkipBody->ShouldSkip = true;
14563     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14564     if (auto *TD = Definition->getDescribedFunctionTemplate())
14565       makeMergedDefinitionVisible(TD);
14566     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14567     return;
14568   }
14569 
14570   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14571       Definition->getStorageClass() == SC_Extern)
14572     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14573         << FD << getLangOpts().CPlusPlus;
14574   else
14575     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14576 
14577   Diag(Definition->getLocation(), diag::note_previous_definition);
14578   FD->setInvalidDecl();
14579 }
14580 
14581 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14582                                    Sema &S) {
14583   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14584 
14585   LambdaScopeInfo *LSI = S.PushLambdaScope();
14586   LSI->CallOperator = CallOperator;
14587   LSI->Lambda = LambdaClass;
14588   LSI->ReturnType = CallOperator->getReturnType();
14589   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14590 
14591   if (LCD == LCD_None)
14592     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14593   else if (LCD == LCD_ByCopy)
14594     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14595   else if (LCD == LCD_ByRef)
14596     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14597   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14598 
14599   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14600   LSI->Mutable = !CallOperator->isConst();
14601 
14602   // Add the captures to the LSI so they can be noted as already
14603   // captured within tryCaptureVar.
14604   auto I = LambdaClass->field_begin();
14605   for (const auto &C : LambdaClass->captures()) {
14606     if (C.capturesVariable()) {
14607       VarDecl *VD = C.getCapturedVar();
14608       if (VD->isInitCapture())
14609         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14610       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14611       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14612           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14613           /*EllipsisLoc*/C.isPackExpansion()
14614                          ? C.getEllipsisLoc() : SourceLocation(),
14615           I->getType(), /*Invalid*/false);
14616 
14617     } else if (C.capturesThis()) {
14618       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14619                           C.getCaptureKind() == LCK_StarThis);
14620     } else {
14621       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14622                              I->getType());
14623     }
14624     ++I;
14625   }
14626 }
14627 
14628 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14629                                     SkipBodyInfo *SkipBody,
14630                                     FnBodyKind BodyKind) {
14631   if (!D) {
14632     // Parsing the function declaration failed in some way. Push on a fake scope
14633     // anyway so we can try to parse the function body.
14634     PushFunctionScope();
14635     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14636     return D;
14637   }
14638 
14639   FunctionDecl *FD = nullptr;
14640 
14641   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14642     FD = FunTmpl->getTemplatedDecl();
14643   else
14644     FD = cast<FunctionDecl>(D);
14645 
14646   // Do not push if it is a lambda because one is already pushed when building
14647   // the lambda in ActOnStartOfLambdaDefinition().
14648   if (!isLambdaCallOperator(FD))
14649     PushExpressionEvaluationContext(
14650         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14651                           : ExprEvalContexts.back().Context);
14652 
14653   // Check for defining attributes before the check for redefinition.
14654   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14655     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14656     FD->dropAttr<AliasAttr>();
14657     FD->setInvalidDecl();
14658   }
14659   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14660     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14661     FD->dropAttr<IFuncAttr>();
14662     FD->setInvalidDecl();
14663   }
14664 
14665   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14666     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14667         Ctor->isDefaultConstructor() &&
14668         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14669       // If this is an MS ABI dllexport default constructor, instantiate any
14670       // default arguments.
14671       InstantiateDefaultCtorDefaultArgs(Ctor);
14672     }
14673   }
14674 
14675   // See if this is a redefinition. If 'will have body' (or similar) is already
14676   // set, then these checks were already performed when it was set.
14677   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14678       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14679     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14680 
14681     // If we're skipping the body, we're done. Don't enter the scope.
14682     if (SkipBody && SkipBody->ShouldSkip)
14683       return D;
14684   }
14685 
14686   // Mark this function as "will have a body eventually".  This lets users to
14687   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14688   // this function.
14689   FD->setWillHaveBody();
14690 
14691   // If we are instantiating a generic lambda call operator, push
14692   // a LambdaScopeInfo onto the function stack.  But use the information
14693   // that's already been calculated (ActOnLambdaExpr) to prime the current
14694   // LambdaScopeInfo.
14695   // When the template operator is being specialized, the LambdaScopeInfo,
14696   // has to be properly restored so that tryCaptureVariable doesn't try
14697   // and capture any new variables. In addition when calculating potential
14698   // captures during transformation of nested lambdas, it is necessary to
14699   // have the LSI properly restored.
14700   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14701     assert(inTemplateInstantiation() &&
14702            "There should be an active template instantiation on the stack "
14703            "when instantiating a generic lambda!");
14704     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14705   } else {
14706     // Enter a new function scope
14707     PushFunctionScope();
14708   }
14709 
14710   // Builtin functions cannot be defined.
14711   if (unsigned BuiltinID = FD->getBuiltinID()) {
14712     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14713         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14714       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14715       FD->setInvalidDecl();
14716     }
14717   }
14718 
14719   // The return type of a function definition must be complete (C99 6.9.1p3),
14720   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14721   QualType ResultType = FD->getReturnType();
14722   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14723       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14724       RequireCompleteType(FD->getLocation(), ResultType,
14725                           diag::err_func_def_incomplete_result))
14726     FD->setInvalidDecl();
14727 
14728   if (FnBodyScope)
14729     PushDeclContext(FnBodyScope, FD);
14730 
14731   // Check the validity of our function parameters
14732   if (BodyKind != FnBodyKind::Delete)
14733     CheckParmsForFunctionDef(FD->parameters(),
14734                              /*CheckParameterNames=*/true);
14735 
14736   // Add non-parameter declarations already in the function to the current
14737   // scope.
14738   if (FnBodyScope) {
14739     for (Decl *NPD : FD->decls()) {
14740       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14741       if (!NonParmDecl)
14742         continue;
14743       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14744              "parameters should not be in newly created FD yet");
14745 
14746       // If the decl has a name, make it accessible in the current scope.
14747       if (NonParmDecl->getDeclName())
14748         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14749 
14750       // Similarly, dive into enums and fish their constants out, making them
14751       // accessible in this scope.
14752       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14753         for (auto *EI : ED->enumerators())
14754           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14755       }
14756     }
14757   }
14758 
14759   // Introduce our parameters into the function scope
14760   for (auto Param : FD->parameters()) {
14761     Param->setOwningFunction(FD);
14762 
14763     // If this has an identifier, add it to the scope stack.
14764     if (Param->getIdentifier() && FnBodyScope) {
14765       CheckShadow(FnBodyScope, Param);
14766 
14767       PushOnScopeChains(Param, FnBodyScope);
14768     }
14769   }
14770 
14771   // Ensure that the function's exception specification is instantiated.
14772   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14773     ResolveExceptionSpec(D->getLocation(), FPT);
14774 
14775   // dllimport cannot be applied to non-inline function definitions.
14776   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14777       !FD->isTemplateInstantiation()) {
14778     assert(!FD->hasAttr<DLLExportAttr>());
14779     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14780     FD->setInvalidDecl();
14781     return D;
14782   }
14783   // We want to attach documentation to original Decl (which might be
14784   // a function template).
14785   ActOnDocumentableDecl(D);
14786   if (getCurLexicalContext()->isObjCContainer() &&
14787       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14788       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14789     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14790 
14791   return D;
14792 }
14793 
14794 /// Given the set of return statements within a function body,
14795 /// compute the variables that are subject to the named return value
14796 /// optimization.
14797 ///
14798 /// Each of the variables that is subject to the named return value
14799 /// optimization will be marked as NRVO variables in the AST, and any
14800 /// return statement that has a marked NRVO variable as its NRVO candidate can
14801 /// use the named return value optimization.
14802 ///
14803 /// This function applies a very simplistic algorithm for NRVO: if every return
14804 /// statement in the scope of a variable has the same NRVO candidate, that
14805 /// candidate is an NRVO variable.
14806 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14807   ReturnStmt **Returns = Scope->Returns.data();
14808 
14809   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14810     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14811       if (!NRVOCandidate->isNRVOVariable())
14812         Returns[I]->setNRVOCandidate(nullptr);
14813     }
14814   }
14815 }
14816 
14817 bool Sema::canDelayFunctionBody(const Declarator &D) {
14818   // We can't delay parsing the body of a constexpr function template (yet).
14819   if (D.getDeclSpec().hasConstexprSpecifier())
14820     return false;
14821 
14822   // We can't delay parsing the body of a function template with a deduced
14823   // return type (yet).
14824   if (D.getDeclSpec().hasAutoTypeSpec()) {
14825     // If the placeholder introduces a non-deduced trailing return type,
14826     // we can still delay parsing it.
14827     if (D.getNumTypeObjects()) {
14828       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14829       if (Outer.Kind == DeclaratorChunk::Function &&
14830           Outer.Fun.hasTrailingReturnType()) {
14831         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14832         return Ty.isNull() || !Ty->isUndeducedType();
14833       }
14834     }
14835     return false;
14836   }
14837 
14838   return true;
14839 }
14840 
14841 bool Sema::canSkipFunctionBody(Decl *D) {
14842   // We cannot skip the body of a function (or function template) which is
14843   // constexpr, since we may need to evaluate its body in order to parse the
14844   // rest of the file.
14845   // We cannot skip the body of a function with an undeduced return type,
14846   // because any callers of that function need to know the type.
14847   if (const FunctionDecl *FD = D->getAsFunction()) {
14848     if (FD->isConstexpr())
14849       return false;
14850     // We can't simply call Type::isUndeducedType here, because inside template
14851     // auto can be deduced to a dependent type, which is not considered
14852     // "undeduced".
14853     if (FD->getReturnType()->getContainedDeducedType())
14854       return false;
14855   }
14856   return Consumer.shouldSkipFunctionBody(D);
14857 }
14858 
14859 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14860   if (!Decl)
14861     return nullptr;
14862   if (FunctionDecl *FD = Decl->getAsFunction())
14863     FD->setHasSkippedBody();
14864   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14865     MD->setHasSkippedBody();
14866   return Decl;
14867 }
14868 
14869 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14870   return ActOnFinishFunctionBody(D, BodyArg, false);
14871 }
14872 
14873 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14874 /// body.
14875 class ExitFunctionBodyRAII {
14876 public:
14877   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14878   ~ExitFunctionBodyRAII() {
14879     if (!IsLambda)
14880       S.PopExpressionEvaluationContext();
14881   }
14882 
14883 private:
14884   Sema &S;
14885   bool IsLambda = false;
14886 };
14887 
14888 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14889   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14890 
14891   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14892     if (EscapeInfo.count(BD))
14893       return EscapeInfo[BD];
14894 
14895     bool R = false;
14896     const BlockDecl *CurBD = BD;
14897 
14898     do {
14899       R = !CurBD->doesNotEscape();
14900       if (R)
14901         break;
14902       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14903     } while (CurBD);
14904 
14905     return EscapeInfo[BD] = R;
14906   };
14907 
14908   // If the location where 'self' is implicitly retained is inside a escaping
14909   // block, emit a diagnostic.
14910   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14911        S.ImplicitlyRetainedSelfLocs)
14912     if (IsOrNestedInEscapingBlock(P.second))
14913       S.Diag(P.first, diag::warn_implicitly_retains_self)
14914           << FixItHint::CreateInsertion(P.first, "self->");
14915 }
14916 
14917 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14918                                     bool IsInstantiation) {
14919   FunctionScopeInfo *FSI = getCurFunction();
14920   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14921 
14922   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14923     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14924 
14925   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14926   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14927 
14928   if (getLangOpts().Coroutines && FSI->isCoroutine())
14929     CheckCompletedCoroutineBody(FD, Body);
14930 
14931   {
14932     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14933     // one is already popped when finishing the lambda in BuildLambdaExpr().
14934     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14935     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14936 
14937     if (FD) {
14938       FD->setBody(Body);
14939       FD->setWillHaveBody(false);
14940 
14941       if (getLangOpts().CPlusPlus14) {
14942         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14943             FD->getReturnType()->isUndeducedType()) {
14944           // For a function with a deduced result type to return void,
14945           // the result type as written must be 'auto' or 'decltype(auto)',
14946           // possibly cv-qualified or constrained, but not ref-qualified.
14947           if (!FD->getReturnType()->getAs<AutoType>()) {
14948             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14949                 << FD->getReturnType();
14950             FD->setInvalidDecl();
14951           } else {
14952             // Falling off the end of the function is the same as 'return;'.
14953             Expr *Dummy = nullptr;
14954             if (DeduceFunctionTypeFromReturnExpr(
14955                     FD, dcl->getLocation(), Dummy,
14956                     FD->getReturnType()->getAs<AutoType>()))
14957               FD->setInvalidDecl();
14958           }
14959         }
14960       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14961         // In C++11, we don't use 'auto' deduction rules for lambda call
14962         // operators because we don't support return type deduction.
14963         auto *LSI = getCurLambda();
14964         if (LSI->HasImplicitReturnType) {
14965           deduceClosureReturnType(*LSI);
14966 
14967           // C++11 [expr.prim.lambda]p4:
14968           //   [...] if there are no return statements in the compound-statement
14969           //   [the deduced type is] the type void
14970           QualType RetType =
14971               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14972 
14973           // Update the return type to the deduced type.
14974           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14975           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14976                                               Proto->getExtProtoInfo()));
14977         }
14978       }
14979 
14980       // If the function implicitly returns zero (like 'main') or is naked,
14981       // don't complain about missing return statements.
14982       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14983         WP.disableCheckFallThrough();
14984 
14985       // MSVC permits the use of pure specifier (=0) on function definition,
14986       // defined at class scope, warn about this non-standard construct.
14987       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14988         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14989 
14990       if (!FD->isInvalidDecl()) {
14991         // Don't diagnose unused parameters of defaulted, deleted or naked
14992         // functions.
14993         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14994             !FD->hasAttr<NakedAttr>())
14995           DiagnoseUnusedParameters(FD->parameters());
14996         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14997                                                FD->getReturnType(), FD);
14998 
14999         // If this is a structor, we need a vtable.
15000         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15001           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15002         else if (CXXDestructorDecl *Destructor =
15003                      dyn_cast<CXXDestructorDecl>(FD))
15004           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15005 
15006         // Try to apply the named return value optimization. We have to check
15007         // if we can do this here because lambdas keep return statements around
15008         // to deduce an implicit return type.
15009         if (FD->getReturnType()->isRecordType() &&
15010             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15011           computeNRVO(Body, FSI);
15012       }
15013 
15014       // GNU warning -Wmissing-prototypes:
15015       //   Warn if a global function is defined without a previous
15016       //   prototype declaration. This warning is issued even if the
15017       //   definition itself provides a prototype. The aim is to detect
15018       //   global functions that fail to be declared in header files.
15019       const FunctionDecl *PossiblePrototype = nullptr;
15020       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15021         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15022 
15023         if (PossiblePrototype) {
15024           // We found a declaration that is not a prototype,
15025           // but that could be a zero-parameter prototype
15026           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15027             TypeLoc TL = TI->getTypeLoc();
15028             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15029               Diag(PossiblePrototype->getLocation(),
15030                    diag::note_declaration_not_a_prototype)
15031                   << (FD->getNumParams() != 0)
15032                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15033                                                     FTL.getRParenLoc(), "void")
15034                                               : FixItHint{});
15035           }
15036         } else {
15037           // Returns true if the token beginning at this Loc is `const`.
15038           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15039                                   const LangOptions &LangOpts) {
15040             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15041             if (LocInfo.first.isInvalid())
15042               return false;
15043 
15044             bool Invalid = false;
15045             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15046             if (Invalid)
15047               return false;
15048 
15049             if (LocInfo.second > Buffer.size())
15050               return false;
15051 
15052             const char *LexStart = Buffer.data() + LocInfo.second;
15053             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15054 
15055             return StartTok.consume_front("const") &&
15056                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15057                     StartTok.startswith("/*") || StartTok.startswith("//"));
15058           };
15059 
15060           auto findBeginLoc = [&]() {
15061             // If the return type has `const` qualifier, we want to insert
15062             // `static` before `const` (and not before the typename).
15063             if ((FD->getReturnType()->isAnyPointerType() &&
15064                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15065                 FD->getReturnType().isConstQualified()) {
15066               // But only do this if we can determine where the `const` is.
15067 
15068               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15069                                getLangOpts()))
15070 
15071                 return FD->getBeginLoc();
15072             }
15073             return FD->getTypeSpecStartLoc();
15074           };
15075           Diag(FD->getTypeSpecStartLoc(),
15076                diag::note_static_for_internal_linkage)
15077               << /* function */ 1
15078               << (FD->getStorageClass() == SC_None
15079                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15080                       : FixItHint{});
15081         }
15082       }
15083 
15084       // If the function being defined does not have a prototype, then we may
15085       // need to diagnose it as changing behavior in C2x because we now know
15086       // whether the function accepts arguments or not. This only handles the
15087       // case where the definition has no prototype but does have parameters
15088       // and either there is no previous potential prototype, or the previous
15089       // potential prototype also has no actual prototype. This handles cases
15090       // like:
15091       //   void f(); void f(a) int a; {}
15092       //   void g(a) int a; {}
15093       // See MergeFunctionDecl() for other cases of the behavior change
15094       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15095       // type without a prototype.
15096       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15097           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15098                                   !PossiblePrototype->isImplicit()))) {
15099         // The function definition has parameters, so this will change behavior
15100         // in C2x. If there is a possible prototype, it comes before the
15101         // function definition.
15102         // FIXME: The declaration may have already been diagnosed as being
15103         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15104         // there's no way to test for the "changes behavior" condition in
15105         // SemaType.cpp when forming the declaration's function type. So, we do
15106         // this awkward dance instead.
15107         //
15108         // If we have a possible prototype and it declares a function with a
15109         // prototype, we don't want to diagnose it; if we have a possible
15110         // prototype and it has no prototype, it may have already been
15111         // diagnosed in SemaType.cpp as deprecated depending on whether
15112         // -Wstrict-prototypes is enabled. If we already warned about it being
15113         // deprecated, add a note that it also changes behavior. If we didn't
15114         // warn about it being deprecated (because the diagnostic is not
15115         // enabled), warn now that it is deprecated and changes behavior.
15116 
15117         // This K&R C function definition definitely changes behavior in C2x,
15118         // so diagnose it.
15119         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15120             << /*definition*/ 1 << /* not supported in C2x */ 0;
15121 
15122         // If we have a possible prototype for the function which is a user-
15123         // visible declaration, we already tested that it has no prototype.
15124         // This will change behavior in C2x. This gets a warning rather than a
15125         // note because it's the same behavior-changing problem as with the
15126         // definition.
15127         if (PossiblePrototype)
15128           Diag(PossiblePrototype->getLocation(),
15129                diag::warn_non_prototype_changes_behavior)
15130               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15131               << /*definition*/ 1;
15132       }
15133 
15134       // Warn on CPUDispatch with an actual body.
15135       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15136         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15137           if (!CmpndBody->body_empty())
15138             Diag(CmpndBody->body_front()->getBeginLoc(),
15139                  diag::warn_dispatch_body_ignored);
15140 
15141       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15142         const CXXMethodDecl *KeyFunction;
15143         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15144             MD->isVirtual() &&
15145             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15146             MD == KeyFunction->getCanonicalDecl()) {
15147           // Update the key-function state if necessary for this ABI.
15148           if (FD->isInlined() &&
15149               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15150             Context.setNonKeyFunction(MD);
15151 
15152             // If the newly-chosen key function is already defined, then we
15153             // need to mark the vtable as used retroactively.
15154             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15155             const FunctionDecl *Definition;
15156             if (KeyFunction && KeyFunction->isDefined(Definition))
15157               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15158           } else {
15159             // We just defined they key function; mark the vtable as used.
15160             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15161           }
15162         }
15163       }
15164 
15165       assert(
15166           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15167           "Function parsing confused");
15168     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15169       assert(MD == getCurMethodDecl() && "Method parsing confused");
15170       MD->setBody(Body);
15171       if (!MD->isInvalidDecl()) {
15172         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15173                                                MD->getReturnType(), MD);
15174 
15175         if (Body)
15176           computeNRVO(Body, FSI);
15177       }
15178       if (FSI->ObjCShouldCallSuper) {
15179         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15180             << MD->getSelector().getAsString();
15181         FSI->ObjCShouldCallSuper = false;
15182       }
15183       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15184         const ObjCMethodDecl *InitMethod = nullptr;
15185         bool isDesignated =
15186             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15187         assert(isDesignated && InitMethod);
15188         (void)isDesignated;
15189 
15190         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15191           auto IFace = MD->getClassInterface();
15192           if (!IFace)
15193             return false;
15194           auto SuperD = IFace->getSuperClass();
15195           if (!SuperD)
15196             return false;
15197           return SuperD->getIdentifier() ==
15198                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15199         };
15200         // Don't issue this warning for unavailable inits or direct subclasses
15201         // of NSObject.
15202         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15203           Diag(MD->getLocation(),
15204                diag::warn_objc_designated_init_missing_super_call);
15205           Diag(InitMethod->getLocation(),
15206                diag::note_objc_designated_init_marked_here);
15207         }
15208         FSI->ObjCWarnForNoDesignatedInitChain = false;
15209       }
15210       if (FSI->ObjCWarnForNoInitDelegation) {
15211         // Don't issue this warning for unavaialable inits.
15212         if (!MD->isUnavailable())
15213           Diag(MD->getLocation(),
15214                diag::warn_objc_secondary_init_missing_init_call);
15215         FSI->ObjCWarnForNoInitDelegation = false;
15216       }
15217 
15218       diagnoseImplicitlyRetainedSelf(*this);
15219     } else {
15220       // Parsing the function declaration failed in some way. Pop the fake scope
15221       // we pushed on.
15222       PopFunctionScopeInfo(ActivePolicy, dcl);
15223       return nullptr;
15224     }
15225 
15226     if (Body && FSI->HasPotentialAvailabilityViolations)
15227       DiagnoseUnguardedAvailabilityViolations(dcl);
15228 
15229     assert(!FSI->ObjCShouldCallSuper &&
15230            "This should only be set for ObjC methods, which should have been "
15231            "handled in the block above.");
15232 
15233     // Verify and clean out per-function state.
15234     if (Body && (!FD || !FD->isDefaulted())) {
15235       // C++ constructors that have function-try-blocks can't have return
15236       // statements in the handlers of that block. (C++ [except.handle]p14)
15237       // Verify this.
15238       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15239         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15240 
15241       // Verify that gotos and switch cases don't jump into scopes illegally.
15242       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15243         DiagnoseInvalidJumps(Body);
15244 
15245       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15246         if (!Destructor->getParent()->isDependentType())
15247           CheckDestructor(Destructor);
15248 
15249         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15250                                                Destructor->getParent());
15251       }
15252 
15253       // If any errors have occurred, clear out any temporaries that may have
15254       // been leftover. This ensures that these temporaries won't be picked up
15255       // for deletion in some later function.
15256       if (hasUncompilableErrorOccurred() ||
15257           getDiagnostics().getSuppressAllDiagnostics()) {
15258         DiscardCleanupsInEvaluationContext();
15259       }
15260       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15261         // Since the body is valid, issue any analysis-based warnings that are
15262         // enabled.
15263         ActivePolicy = &WP;
15264       }
15265 
15266       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15267           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15268         FD->setInvalidDecl();
15269 
15270       if (FD && FD->hasAttr<NakedAttr>()) {
15271         for (const Stmt *S : Body->children()) {
15272           // Allow local register variables without initializer as they don't
15273           // require prologue.
15274           bool RegisterVariables = false;
15275           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15276             for (const auto *Decl : DS->decls()) {
15277               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15278                 RegisterVariables =
15279                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15280                 if (!RegisterVariables)
15281                   break;
15282               }
15283             }
15284           }
15285           if (RegisterVariables)
15286             continue;
15287           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15288             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15289             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15290             FD->setInvalidDecl();
15291             break;
15292           }
15293         }
15294       }
15295 
15296       assert(ExprCleanupObjects.size() ==
15297                  ExprEvalContexts.back().NumCleanupObjects &&
15298              "Leftover temporaries in function");
15299       assert(!Cleanup.exprNeedsCleanups() &&
15300              "Unaccounted cleanups in function");
15301       assert(MaybeODRUseExprs.empty() &&
15302              "Leftover expressions for odr-use checking");
15303     }
15304   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15305     // the declaration context below. Otherwise, we're unable to transform
15306     // 'this' expressions when transforming immediate context functions.
15307 
15308   if (!IsInstantiation)
15309     PopDeclContext();
15310 
15311   PopFunctionScopeInfo(ActivePolicy, dcl);
15312   // If any errors have occurred, clear out any temporaries that may have
15313   // been leftover. This ensures that these temporaries won't be picked up for
15314   // deletion in some later function.
15315   if (hasUncompilableErrorOccurred()) {
15316     DiscardCleanupsInEvaluationContext();
15317   }
15318 
15319   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15320                                   !LangOpts.OMPTargetTriples.empty())) ||
15321              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15322     auto ES = getEmissionStatus(FD);
15323     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15324         ES == Sema::FunctionEmissionStatus::Unknown)
15325       DeclsToCheckForDeferredDiags.insert(FD);
15326   }
15327 
15328   if (FD && !FD->isDeleted())
15329     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15330 
15331   return dcl;
15332 }
15333 
15334 /// When we finish delayed parsing of an attribute, we must attach it to the
15335 /// relevant Decl.
15336 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15337                                        ParsedAttributes &Attrs) {
15338   // Always attach attributes to the underlying decl.
15339   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15340     D = TD->getTemplatedDecl();
15341   ProcessDeclAttributeList(S, D, Attrs);
15342 
15343   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15344     if (Method->isStatic())
15345       checkThisInStaticMemberFunctionAttributes(Method);
15346 }
15347 
15348 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15349 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15350 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15351                                           IdentifierInfo &II, Scope *S) {
15352   // It is not valid to implicitly define a function in C2x.
15353   assert(LangOpts.implicitFunctionsAllowed() &&
15354          "Implicit function declarations aren't allowed in this language mode");
15355 
15356   // Find the scope in which the identifier is injected and the corresponding
15357   // DeclContext.
15358   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15359   // In that case, we inject the declaration into the translation unit scope
15360   // instead.
15361   Scope *BlockScope = S;
15362   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15363     BlockScope = BlockScope->getParent();
15364 
15365   Scope *ContextScope = BlockScope;
15366   while (!ContextScope->getEntity())
15367     ContextScope = ContextScope->getParent();
15368   ContextRAII SavedContext(*this, ContextScope->getEntity());
15369 
15370   // Before we produce a declaration for an implicitly defined
15371   // function, see whether there was a locally-scoped declaration of
15372   // this name as a function or variable. If so, use that
15373   // (non-visible) declaration, and complain about it.
15374   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15375   if (ExternCPrev) {
15376     // We still need to inject the function into the enclosing block scope so
15377     // that later (non-call) uses can see it.
15378     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15379 
15380     // C89 footnote 38:
15381     //   If in fact it is not defined as having type "function returning int",
15382     //   the behavior is undefined.
15383     if (!isa<FunctionDecl>(ExternCPrev) ||
15384         !Context.typesAreCompatible(
15385             cast<FunctionDecl>(ExternCPrev)->getType(),
15386             Context.getFunctionNoProtoType(Context.IntTy))) {
15387       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15388           << ExternCPrev << !getLangOpts().C99;
15389       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15390       return ExternCPrev;
15391     }
15392   }
15393 
15394   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15395   unsigned diag_id;
15396   if (II.getName().startswith("__builtin_"))
15397     diag_id = diag::warn_builtin_unknown;
15398   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15399   else if (getLangOpts().C99)
15400     diag_id = diag::ext_implicit_function_decl_c99;
15401   else
15402     diag_id = diag::warn_implicit_function_decl;
15403 
15404   TypoCorrection Corrected;
15405   // Because typo correction is expensive, only do it if the implicit
15406   // function declaration is going to be treated as an error.
15407   //
15408   // Perform the corection before issuing the main diagnostic, as some consumers
15409   // use typo-correction callbacks to enhance the main diagnostic.
15410   if (S && !ExternCPrev &&
15411       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15412     DeclFilterCCC<FunctionDecl> CCC{};
15413     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15414                             S, nullptr, CCC, CTK_NonError);
15415   }
15416 
15417   Diag(Loc, diag_id) << &II;
15418   if (Corrected) {
15419     // If the correction is going to suggest an implicitly defined function,
15420     // skip the correction as not being a particularly good idea.
15421     bool Diagnose = true;
15422     if (const auto *D = Corrected.getCorrectionDecl())
15423       Diagnose = !D->isImplicit();
15424     if (Diagnose)
15425       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15426                    /*ErrorRecovery*/ false);
15427   }
15428 
15429   // If we found a prior declaration of this function, don't bother building
15430   // another one. We've already pushed that one into scope, so there's nothing
15431   // more to do.
15432   if (ExternCPrev)
15433     return ExternCPrev;
15434 
15435   // Set a Declarator for the implicit definition: int foo();
15436   const char *Dummy;
15437   AttributeFactory attrFactory;
15438   DeclSpec DS(attrFactory);
15439   unsigned DiagID;
15440   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15441                                   Context.getPrintingPolicy());
15442   (void)Error; // Silence warning.
15443   assert(!Error && "Error setting up implicit decl!");
15444   SourceLocation NoLoc;
15445   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15446   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15447                                              /*IsAmbiguous=*/false,
15448                                              /*LParenLoc=*/NoLoc,
15449                                              /*Params=*/nullptr,
15450                                              /*NumParams=*/0,
15451                                              /*EllipsisLoc=*/NoLoc,
15452                                              /*RParenLoc=*/NoLoc,
15453                                              /*RefQualifierIsLvalueRef=*/true,
15454                                              /*RefQualifierLoc=*/NoLoc,
15455                                              /*MutableLoc=*/NoLoc, EST_None,
15456                                              /*ESpecRange=*/SourceRange(),
15457                                              /*Exceptions=*/nullptr,
15458                                              /*ExceptionRanges=*/nullptr,
15459                                              /*NumExceptions=*/0,
15460                                              /*NoexceptExpr=*/nullptr,
15461                                              /*ExceptionSpecTokens=*/nullptr,
15462                                              /*DeclsInPrototype=*/None, Loc,
15463                                              Loc, D),
15464                 std::move(DS.getAttributes()), SourceLocation());
15465   D.SetIdentifier(&II, Loc);
15466 
15467   // Insert this function into the enclosing block scope.
15468   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15469   FD->setImplicit();
15470 
15471   AddKnownFunctionAttributes(FD);
15472 
15473   return FD;
15474 }
15475 
15476 /// If this function is a C++ replaceable global allocation function
15477 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15478 /// adds any function attributes that we know a priori based on the standard.
15479 ///
15480 /// We need to check for duplicate attributes both here and where user-written
15481 /// attributes are applied to declarations.
15482 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15483     FunctionDecl *FD) {
15484   if (FD->isInvalidDecl())
15485     return;
15486 
15487   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15488       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15489     return;
15490 
15491   Optional<unsigned> AlignmentParam;
15492   bool IsNothrow = false;
15493   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15494     return;
15495 
15496   // C++2a [basic.stc.dynamic.allocation]p4:
15497   //   An allocation function that has a non-throwing exception specification
15498   //   indicates failure by returning a null pointer value. Any other allocation
15499   //   function never returns a null pointer value and indicates failure only by
15500   //   throwing an exception [...]
15501   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15502     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15503 
15504   // C++2a [basic.stc.dynamic.allocation]p2:
15505   //   An allocation function attempts to allocate the requested amount of
15506   //   storage. [...] If the request succeeds, the value returned by a
15507   //   replaceable allocation function is a [...] pointer value p0 different
15508   //   from any previously returned value p1 [...]
15509   //
15510   // However, this particular information is being added in codegen,
15511   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15512 
15513   // C++2a [basic.stc.dynamic.allocation]p2:
15514   //   An allocation function attempts to allocate the requested amount of
15515   //   storage. If it is successful, it returns the address of the start of a
15516   //   block of storage whose length in bytes is at least as large as the
15517   //   requested size.
15518   if (!FD->hasAttr<AllocSizeAttr>()) {
15519     FD->addAttr(AllocSizeAttr::CreateImplicit(
15520         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15521         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15522   }
15523 
15524   // C++2a [basic.stc.dynamic.allocation]p3:
15525   //   For an allocation function [...], the pointer returned on a successful
15526   //   call shall represent the address of storage that is aligned as follows:
15527   //   (3.1) If the allocation function takes an argument of type
15528   //         std​::​align_­val_­t, the storage will have the alignment
15529   //         specified by the value of this argument.
15530   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15531     FD->addAttr(AllocAlignAttr::CreateImplicit(
15532         Context, ParamIdx(AlignmentParam.value(), FD), FD->getLocation()));
15533   }
15534 
15535   // FIXME:
15536   // C++2a [basic.stc.dynamic.allocation]p3:
15537   //   For an allocation function [...], the pointer returned on a successful
15538   //   call shall represent the address of storage that is aligned as follows:
15539   //   (3.2) Otherwise, if the allocation function is named operator new[],
15540   //         the storage is aligned for any object that does not have
15541   //         new-extended alignment ([basic.align]) and is no larger than the
15542   //         requested size.
15543   //   (3.3) Otherwise, the storage is aligned for any object that does not
15544   //         have new-extended alignment and is of the requested size.
15545 }
15546 
15547 /// Adds any function attributes that we know a priori based on
15548 /// the declaration of this function.
15549 ///
15550 /// These attributes can apply both to implicitly-declared builtins
15551 /// (like __builtin___printf_chk) or to library-declared functions
15552 /// like NSLog or printf.
15553 ///
15554 /// We need to check for duplicate attributes both here and where user-written
15555 /// attributes are applied to declarations.
15556 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15557   if (FD->isInvalidDecl())
15558     return;
15559 
15560   // If this is a built-in function, map its builtin attributes to
15561   // actual attributes.
15562   if (unsigned BuiltinID = FD->getBuiltinID()) {
15563     // Handle printf-formatting attributes.
15564     unsigned FormatIdx;
15565     bool HasVAListArg;
15566     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15567       if (!FD->hasAttr<FormatAttr>()) {
15568         const char *fmt = "printf";
15569         unsigned int NumParams = FD->getNumParams();
15570         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15571             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15572           fmt = "NSString";
15573         FD->addAttr(FormatAttr::CreateImplicit(Context,
15574                                                &Context.Idents.get(fmt),
15575                                                FormatIdx+1,
15576                                                HasVAListArg ? 0 : FormatIdx+2,
15577                                                FD->getLocation()));
15578       }
15579     }
15580     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15581                                              HasVAListArg)) {
15582      if (!FD->hasAttr<FormatAttr>())
15583        FD->addAttr(FormatAttr::CreateImplicit(Context,
15584                                               &Context.Idents.get("scanf"),
15585                                               FormatIdx+1,
15586                                               HasVAListArg ? 0 : FormatIdx+2,
15587                                               FD->getLocation()));
15588     }
15589 
15590     // Handle automatically recognized callbacks.
15591     SmallVector<int, 4> Encoding;
15592     if (!FD->hasAttr<CallbackAttr>() &&
15593         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15594       FD->addAttr(CallbackAttr::CreateImplicit(
15595           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15596 
15597     // Mark const if we don't care about errno and that is the only thing
15598     // preventing the function from being const. This allows IRgen to use LLVM
15599     // intrinsics for such functions.
15600     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15601         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15602       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15603 
15604     // We make "fma" on GNU or Windows const because we know it does not set
15605     // errno in those environments even though it could set errno based on the
15606     // C standard.
15607     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15608     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15609         !FD->hasAttr<ConstAttr>()) {
15610       switch (BuiltinID) {
15611       case Builtin::BI__builtin_fma:
15612       case Builtin::BI__builtin_fmaf:
15613       case Builtin::BI__builtin_fmal:
15614       case Builtin::BIfma:
15615       case Builtin::BIfmaf:
15616       case Builtin::BIfmal:
15617         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15618         break;
15619       default:
15620         break;
15621       }
15622     }
15623 
15624     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15625         !FD->hasAttr<ReturnsTwiceAttr>())
15626       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15627                                          FD->getLocation()));
15628     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15629       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15630     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15631       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15632     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15633       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15634     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15635         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15636       // Add the appropriate attribute, depending on the CUDA compilation mode
15637       // and which target the builtin belongs to. For example, during host
15638       // compilation, aux builtins are __device__, while the rest are __host__.
15639       if (getLangOpts().CUDAIsDevice !=
15640           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15641         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15642       else
15643         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15644     }
15645 
15646     // Add known guaranteed alignment for allocation functions.
15647     switch (BuiltinID) {
15648     case Builtin::BImemalign:
15649     case Builtin::BIaligned_alloc:
15650       if (!FD->hasAttr<AllocAlignAttr>())
15651         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15652                                                    FD->getLocation()));
15653       break;
15654     default:
15655       break;
15656     }
15657 
15658     // Add allocsize attribute for allocation functions.
15659     switch (BuiltinID) {
15660     case Builtin::BIcalloc:
15661       FD->addAttr(AllocSizeAttr::CreateImplicit(
15662           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15663       break;
15664     case Builtin::BImemalign:
15665     case Builtin::BIaligned_alloc:
15666     case Builtin::BIrealloc:
15667       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15668                                                 ParamIdx(), FD->getLocation()));
15669       break;
15670     case Builtin::BImalloc:
15671       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15672                                                 ParamIdx(), FD->getLocation()));
15673       break;
15674     default:
15675       break;
15676     }
15677   }
15678 
15679   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15680 
15681   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15682   // throw, add an implicit nothrow attribute to any extern "C" function we come
15683   // across.
15684   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15685       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15686     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15687     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15688       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15689   }
15690 
15691   IdentifierInfo *Name = FD->getIdentifier();
15692   if (!Name)
15693     return;
15694   if ((!getLangOpts().CPlusPlus &&
15695        FD->getDeclContext()->isTranslationUnit()) ||
15696       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15697        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15698        LinkageSpecDecl::lang_c)) {
15699     // Okay: this could be a libc/libm/Objective-C function we know
15700     // about.
15701   } else
15702     return;
15703 
15704   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15705     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15706     // target-specific builtins, perhaps?
15707     if (!FD->hasAttr<FormatAttr>())
15708       FD->addAttr(FormatAttr::CreateImplicit(Context,
15709                                              &Context.Idents.get("printf"), 2,
15710                                              Name->isStr("vasprintf") ? 0 : 3,
15711                                              FD->getLocation()));
15712   }
15713 
15714   if (Name->isStr("__CFStringMakeConstantString")) {
15715     // We already have a __builtin___CFStringMakeConstantString,
15716     // but builds that use -fno-constant-cfstrings don't go through that.
15717     if (!FD->hasAttr<FormatArgAttr>())
15718       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15719                                                 FD->getLocation()));
15720   }
15721 }
15722 
15723 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15724                                     TypeSourceInfo *TInfo) {
15725   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15726   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15727 
15728   if (!TInfo) {
15729     assert(D.isInvalidType() && "no declarator info for valid type");
15730     TInfo = Context.getTrivialTypeSourceInfo(T);
15731   }
15732 
15733   // Scope manipulation handled by caller.
15734   TypedefDecl *NewTD =
15735       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15736                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15737 
15738   // Bail out immediately if we have an invalid declaration.
15739   if (D.isInvalidType()) {
15740     NewTD->setInvalidDecl();
15741     return NewTD;
15742   }
15743 
15744   if (D.getDeclSpec().isModulePrivateSpecified()) {
15745     if (CurContext->isFunctionOrMethod())
15746       Diag(NewTD->getLocation(), diag::err_module_private_local)
15747           << 2 << NewTD
15748           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15749           << FixItHint::CreateRemoval(
15750                  D.getDeclSpec().getModulePrivateSpecLoc());
15751     else
15752       NewTD->setModulePrivate();
15753   }
15754 
15755   // C++ [dcl.typedef]p8:
15756   //   If the typedef declaration defines an unnamed class (or
15757   //   enum), the first typedef-name declared by the declaration
15758   //   to be that class type (or enum type) is used to denote the
15759   //   class type (or enum type) for linkage purposes only.
15760   // We need to check whether the type was declared in the declaration.
15761   switch (D.getDeclSpec().getTypeSpecType()) {
15762   case TST_enum:
15763   case TST_struct:
15764   case TST_interface:
15765   case TST_union:
15766   case TST_class: {
15767     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15768     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15769     break;
15770   }
15771 
15772   default:
15773     break;
15774   }
15775 
15776   return NewTD;
15777 }
15778 
15779 /// Check that this is a valid underlying type for an enum declaration.
15780 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15781   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15782   QualType T = TI->getType();
15783 
15784   if (T->isDependentType())
15785     return false;
15786 
15787   // This doesn't use 'isIntegralType' despite the error message mentioning
15788   // integral type because isIntegralType would also allow enum types in C.
15789   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15790     if (BT->isInteger())
15791       return false;
15792 
15793   if (T->isBitIntType())
15794     return false;
15795 
15796   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15797 }
15798 
15799 /// Check whether this is a valid redeclaration of a previous enumeration.
15800 /// \return true if the redeclaration was invalid.
15801 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15802                                   QualType EnumUnderlyingTy, bool IsFixed,
15803                                   const EnumDecl *Prev) {
15804   if (IsScoped != Prev->isScoped()) {
15805     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15806       << Prev->isScoped();
15807     Diag(Prev->getLocation(), diag::note_previous_declaration);
15808     return true;
15809   }
15810 
15811   if (IsFixed && Prev->isFixed()) {
15812     if (!EnumUnderlyingTy->isDependentType() &&
15813         !Prev->getIntegerType()->isDependentType() &&
15814         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15815                                         Prev->getIntegerType())) {
15816       // TODO: Highlight the underlying type of the redeclaration.
15817       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15818         << EnumUnderlyingTy << Prev->getIntegerType();
15819       Diag(Prev->getLocation(), diag::note_previous_declaration)
15820           << Prev->getIntegerTypeRange();
15821       return true;
15822     }
15823   } else if (IsFixed != Prev->isFixed()) {
15824     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15825       << Prev->isFixed();
15826     Diag(Prev->getLocation(), diag::note_previous_declaration);
15827     return true;
15828   }
15829 
15830   return false;
15831 }
15832 
15833 /// Get diagnostic %select index for tag kind for
15834 /// redeclaration diagnostic message.
15835 /// WARNING: Indexes apply to particular diagnostics only!
15836 ///
15837 /// \returns diagnostic %select index.
15838 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15839   switch (Tag) {
15840   case TTK_Struct: return 0;
15841   case TTK_Interface: return 1;
15842   case TTK_Class:  return 2;
15843   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15844   }
15845 }
15846 
15847 /// Determine if tag kind is a class-key compatible with
15848 /// class for redeclaration (class, struct, or __interface).
15849 ///
15850 /// \returns true iff the tag kind is compatible.
15851 static bool isClassCompatTagKind(TagTypeKind Tag)
15852 {
15853   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15854 }
15855 
15856 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15857                                              TagTypeKind TTK) {
15858   if (isa<TypedefDecl>(PrevDecl))
15859     return NTK_Typedef;
15860   else if (isa<TypeAliasDecl>(PrevDecl))
15861     return NTK_TypeAlias;
15862   else if (isa<ClassTemplateDecl>(PrevDecl))
15863     return NTK_Template;
15864   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15865     return NTK_TypeAliasTemplate;
15866   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15867     return NTK_TemplateTemplateArgument;
15868   switch (TTK) {
15869   case TTK_Struct:
15870   case TTK_Interface:
15871   case TTK_Class:
15872     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15873   case TTK_Union:
15874     return NTK_NonUnion;
15875   case TTK_Enum:
15876     return NTK_NonEnum;
15877   }
15878   llvm_unreachable("invalid TTK");
15879 }
15880 
15881 /// Determine whether a tag with a given kind is acceptable
15882 /// as a redeclaration of the given tag declaration.
15883 ///
15884 /// \returns true if the new tag kind is acceptable, false otherwise.
15885 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15886                                         TagTypeKind NewTag, bool isDefinition,
15887                                         SourceLocation NewTagLoc,
15888                                         const IdentifierInfo *Name) {
15889   // C++ [dcl.type.elab]p3:
15890   //   The class-key or enum keyword present in the
15891   //   elaborated-type-specifier shall agree in kind with the
15892   //   declaration to which the name in the elaborated-type-specifier
15893   //   refers. This rule also applies to the form of
15894   //   elaborated-type-specifier that declares a class-name or
15895   //   friend class since it can be construed as referring to the
15896   //   definition of the class. Thus, in any
15897   //   elaborated-type-specifier, the enum keyword shall be used to
15898   //   refer to an enumeration (7.2), the union class-key shall be
15899   //   used to refer to a union (clause 9), and either the class or
15900   //   struct class-key shall be used to refer to a class (clause 9)
15901   //   declared using the class or struct class-key.
15902   TagTypeKind OldTag = Previous->getTagKind();
15903   if (OldTag != NewTag &&
15904       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15905     return false;
15906 
15907   // Tags are compatible, but we might still want to warn on mismatched tags.
15908   // Non-class tags can't be mismatched at this point.
15909   if (!isClassCompatTagKind(NewTag))
15910     return true;
15911 
15912   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15913   // by our warning analysis. We don't want to warn about mismatches with (eg)
15914   // declarations in system headers that are designed to be specialized, but if
15915   // a user asks us to warn, we should warn if their code contains mismatched
15916   // declarations.
15917   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15918     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15919                                       Loc);
15920   };
15921   if (IsIgnoredLoc(NewTagLoc))
15922     return true;
15923 
15924   auto IsIgnored = [&](const TagDecl *Tag) {
15925     return IsIgnoredLoc(Tag->getLocation());
15926   };
15927   while (IsIgnored(Previous)) {
15928     Previous = Previous->getPreviousDecl();
15929     if (!Previous)
15930       return true;
15931     OldTag = Previous->getTagKind();
15932   }
15933 
15934   bool isTemplate = false;
15935   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15936     isTemplate = Record->getDescribedClassTemplate();
15937 
15938   if (inTemplateInstantiation()) {
15939     if (OldTag != NewTag) {
15940       // In a template instantiation, do not offer fix-its for tag mismatches
15941       // since they usually mess up the template instead of fixing the problem.
15942       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15943         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15944         << getRedeclDiagFromTagKind(OldTag);
15945       // FIXME: Note previous location?
15946     }
15947     return true;
15948   }
15949 
15950   if (isDefinition) {
15951     // On definitions, check all previous tags and issue a fix-it for each
15952     // one that doesn't match the current tag.
15953     if (Previous->getDefinition()) {
15954       // Don't suggest fix-its for redefinitions.
15955       return true;
15956     }
15957 
15958     bool previousMismatch = false;
15959     for (const TagDecl *I : Previous->redecls()) {
15960       if (I->getTagKind() != NewTag) {
15961         // Ignore previous declarations for which the warning was disabled.
15962         if (IsIgnored(I))
15963           continue;
15964 
15965         if (!previousMismatch) {
15966           previousMismatch = true;
15967           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15968             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15969             << getRedeclDiagFromTagKind(I->getTagKind());
15970         }
15971         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15972           << getRedeclDiagFromTagKind(NewTag)
15973           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15974                TypeWithKeyword::getTagTypeKindName(NewTag));
15975       }
15976     }
15977     return true;
15978   }
15979 
15980   // Identify the prevailing tag kind: this is the kind of the definition (if
15981   // there is a non-ignored definition), or otherwise the kind of the prior
15982   // (non-ignored) declaration.
15983   const TagDecl *PrevDef = Previous->getDefinition();
15984   if (PrevDef && IsIgnored(PrevDef))
15985     PrevDef = nullptr;
15986   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15987   if (Redecl->getTagKind() != NewTag) {
15988     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15989       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15990       << getRedeclDiagFromTagKind(OldTag);
15991     Diag(Redecl->getLocation(), diag::note_previous_use);
15992 
15993     // If there is a previous definition, suggest a fix-it.
15994     if (PrevDef) {
15995       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15996         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15997         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15998              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15999     }
16000   }
16001 
16002   return true;
16003 }
16004 
16005 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16006 /// from an outer enclosing namespace or file scope inside a friend declaration.
16007 /// This should provide the commented out code in the following snippet:
16008 ///   namespace N {
16009 ///     struct X;
16010 ///     namespace M {
16011 ///       struct Y { friend struct /*N::*/ X; };
16012 ///     }
16013 ///   }
16014 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16015                                          SourceLocation NameLoc) {
16016   // While the decl is in a namespace, do repeated lookup of that name and see
16017   // if we get the same namespace back.  If we do not, continue until
16018   // translation unit scope, at which point we have a fully qualified NNS.
16019   SmallVector<IdentifierInfo *, 4> Namespaces;
16020   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16021   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16022     // This tag should be declared in a namespace, which can only be enclosed by
16023     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16024     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16025     if (!Namespace || Namespace->isAnonymousNamespace())
16026       return FixItHint();
16027     IdentifierInfo *II = Namespace->getIdentifier();
16028     Namespaces.push_back(II);
16029     NamedDecl *Lookup = SemaRef.LookupSingleName(
16030         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16031     if (Lookup == Namespace)
16032       break;
16033   }
16034 
16035   // Once we have all the namespaces, reverse them to go outermost first, and
16036   // build an NNS.
16037   SmallString<64> Insertion;
16038   llvm::raw_svector_ostream OS(Insertion);
16039   if (DC->isTranslationUnit())
16040     OS << "::";
16041   std::reverse(Namespaces.begin(), Namespaces.end());
16042   for (auto *II : Namespaces)
16043     OS << II->getName() << "::";
16044   return FixItHint::CreateInsertion(NameLoc, Insertion);
16045 }
16046 
16047 /// Determine whether a tag originally declared in context \p OldDC can
16048 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16049 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16050 /// using-declaration).
16051 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16052                                          DeclContext *NewDC) {
16053   OldDC = OldDC->getRedeclContext();
16054   NewDC = NewDC->getRedeclContext();
16055 
16056   if (OldDC->Equals(NewDC))
16057     return true;
16058 
16059   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16060   // encloses the other).
16061   if (S.getLangOpts().MSVCCompat &&
16062       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16063     return true;
16064 
16065   return false;
16066 }
16067 
16068 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16069 /// former case, Name will be non-null.  In the later case, Name will be null.
16070 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16071 /// reference/declaration/definition of a tag.
16072 ///
16073 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16074 /// trailing-type-specifier) other than one in an alias-declaration.
16075 ///
16076 /// \param SkipBody If non-null, will be set to indicate if the caller should
16077 /// skip the definition of this tag and treat it as if it were a declaration.
16078 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16079                      SourceLocation KWLoc, CXXScopeSpec &SS,
16080                      IdentifierInfo *Name, SourceLocation NameLoc,
16081                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16082                      SourceLocation ModulePrivateLoc,
16083                      MultiTemplateParamsArg TemplateParameterLists,
16084                      bool &OwnedDecl, bool &IsDependent,
16085                      SourceLocation ScopedEnumKWLoc,
16086                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16087                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16088                      SkipBodyInfo *SkipBody) {
16089   // If this is not a definition, it must have a name.
16090   IdentifierInfo *OrigName = Name;
16091   assert((Name != nullptr || TUK == TUK_Definition) &&
16092          "Nameless record must be a definition!");
16093   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16094 
16095   OwnedDecl = false;
16096   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16097   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16098 
16099   // FIXME: Check member specializations more carefully.
16100   bool isMemberSpecialization = false;
16101   bool Invalid = false;
16102 
16103   // We only need to do this matching if we have template parameters
16104   // or a scope specifier, which also conveniently avoids this work
16105   // for non-C++ cases.
16106   if (TemplateParameterLists.size() > 0 ||
16107       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16108     if (TemplateParameterList *TemplateParams =
16109             MatchTemplateParametersToScopeSpecifier(
16110                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16111                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16112       if (Kind == TTK_Enum) {
16113         Diag(KWLoc, diag::err_enum_template);
16114         return nullptr;
16115       }
16116 
16117       if (TemplateParams->size() > 0) {
16118         // This is a declaration or definition of a class template (which may
16119         // be a member of another template).
16120 
16121         if (Invalid)
16122           return nullptr;
16123 
16124         OwnedDecl = false;
16125         DeclResult Result = CheckClassTemplate(
16126             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16127             AS, ModulePrivateLoc,
16128             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16129             TemplateParameterLists.data(), SkipBody);
16130         return Result.get();
16131       } else {
16132         // The "template<>" header is extraneous.
16133         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16134           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16135         isMemberSpecialization = true;
16136       }
16137     }
16138 
16139     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16140         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16141       return nullptr;
16142   }
16143 
16144   // Figure out the underlying type if this a enum declaration. We need to do
16145   // this early, because it's needed to detect if this is an incompatible
16146   // redeclaration.
16147   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16148   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16149 
16150   if (Kind == TTK_Enum) {
16151     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16152       // No underlying type explicitly specified, or we failed to parse the
16153       // type, default to int.
16154       EnumUnderlying = Context.IntTy.getTypePtr();
16155     } else if (UnderlyingType.get()) {
16156       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16157       // integral type; any cv-qualification is ignored.
16158       TypeSourceInfo *TI = nullptr;
16159       GetTypeFromParser(UnderlyingType.get(), &TI);
16160       EnumUnderlying = TI;
16161 
16162       if (CheckEnumUnderlyingType(TI))
16163         // Recover by falling back to int.
16164         EnumUnderlying = Context.IntTy.getTypePtr();
16165 
16166       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16167                                           UPPC_FixedUnderlyingType))
16168         EnumUnderlying = Context.IntTy.getTypePtr();
16169 
16170     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16171       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16172       // of 'int'. However, if this is an unfixed forward declaration, don't set
16173       // the underlying type unless the user enables -fms-compatibility. This
16174       // makes unfixed forward declared enums incomplete and is more conforming.
16175       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16176         EnumUnderlying = Context.IntTy.getTypePtr();
16177     }
16178   }
16179 
16180   DeclContext *SearchDC = CurContext;
16181   DeclContext *DC = CurContext;
16182   bool isStdBadAlloc = false;
16183   bool isStdAlignValT = false;
16184 
16185   RedeclarationKind Redecl = forRedeclarationInCurContext();
16186   if (TUK == TUK_Friend || TUK == TUK_Reference)
16187     Redecl = NotForRedeclaration;
16188 
16189   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16190   /// implemented asks for structural equivalence checking, the returned decl
16191   /// here is passed back to the parser, allowing the tag body to be parsed.
16192   auto createTagFromNewDecl = [&]() -> TagDecl * {
16193     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16194     // If there is an identifier, use the location of the identifier as the
16195     // location of the decl, otherwise use the location of the struct/union
16196     // keyword.
16197     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16198     TagDecl *New = nullptr;
16199 
16200     if (Kind == TTK_Enum) {
16201       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16202                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16203       // If this is an undefined enum, bail.
16204       if (TUK != TUK_Definition && !Invalid)
16205         return nullptr;
16206       if (EnumUnderlying) {
16207         EnumDecl *ED = cast<EnumDecl>(New);
16208         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16209           ED->setIntegerTypeSourceInfo(TI);
16210         else
16211           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16212         QualType EnumTy = ED->getIntegerType();
16213         ED->setPromotionType(EnumTy->isPromotableIntegerType()
16214                                  ? Context.getPromotedIntegerType(EnumTy)
16215                                  : EnumTy);
16216       }
16217     } else { // struct/union
16218       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16219                                nullptr);
16220     }
16221 
16222     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16223       // Add alignment attributes if necessary; these attributes are checked
16224       // when the ASTContext lays out the structure.
16225       //
16226       // It is important for implementing the correct semantics that this
16227       // happen here (in ActOnTag). The #pragma pack stack is
16228       // maintained as a result of parser callbacks which can occur at
16229       // many points during the parsing of a struct declaration (because
16230       // the #pragma tokens are effectively skipped over during the
16231       // parsing of the struct).
16232       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16233         AddAlignmentAttributesForRecord(RD);
16234         AddMsStructLayoutForRecord(RD);
16235       }
16236     }
16237     New->setLexicalDeclContext(CurContext);
16238     return New;
16239   };
16240 
16241   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16242   if (Name && SS.isNotEmpty()) {
16243     // We have a nested-name tag ('struct foo::bar').
16244 
16245     // Check for invalid 'foo::'.
16246     if (SS.isInvalid()) {
16247       Name = nullptr;
16248       goto CreateNewDecl;
16249     }
16250 
16251     // If this is a friend or a reference to a class in a dependent
16252     // context, don't try to make a decl for it.
16253     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16254       DC = computeDeclContext(SS, false);
16255       if (!DC) {
16256         IsDependent = true;
16257         return nullptr;
16258       }
16259     } else {
16260       DC = computeDeclContext(SS, true);
16261       if (!DC) {
16262         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16263           << SS.getRange();
16264         return nullptr;
16265       }
16266     }
16267 
16268     if (RequireCompleteDeclContext(SS, DC))
16269       return nullptr;
16270 
16271     SearchDC = DC;
16272     // Look-up name inside 'foo::'.
16273     LookupQualifiedName(Previous, DC);
16274 
16275     if (Previous.isAmbiguous())
16276       return nullptr;
16277 
16278     if (Previous.empty()) {
16279       // Name lookup did not find anything. However, if the
16280       // nested-name-specifier refers to the current instantiation,
16281       // and that current instantiation has any dependent base
16282       // classes, we might find something at instantiation time: treat
16283       // this as a dependent elaborated-type-specifier.
16284       // But this only makes any sense for reference-like lookups.
16285       if (Previous.wasNotFoundInCurrentInstantiation() &&
16286           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16287         IsDependent = true;
16288         return nullptr;
16289       }
16290 
16291       // A tag 'foo::bar' must already exist.
16292       Diag(NameLoc, diag::err_not_tag_in_scope)
16293         << Kind << Name << DC << SS.getRange();
16294       Name = nullptr;
16295       Invalid = true;
16296       goto CreateNewDecl;
16297     }
16298   } else if (Name) {
16299     // C++14 [class.mem]p14:
16300     //   If T is the name of a class, then each of the following shall have a
16301     //   name different from T:
16302     //    -- every member of class T that is itself a type
16303     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16304         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16305       return nullptr;
16306 
16307     // If this is a named struct, check to see if there was a previous forward
16308     // declaration or definition.
16309     // FIXME: We're looking into outer scopes here, even when we
16310     // shouldn't be. Doing so can result in ambiguities that we
16311     // shouldn't be diagnosing.
16312     LookupName(Previous, S);
16313 
16314     // When declaring or defining a tag, ignore ambiguities introduced
16315     // by types using'ed into this scope.
16316     if (Previous.isAmbiguous() &&
16317         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16318       LookupResult::Filter F = Previous.makeFilter();
16319       while (F.hasNext()) {
16320         NamedDecl *ND = F.next();
16321         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16322                 SearchDC->getRedeclContext()))
16323           F.erase();
16324       }
16325       F.done();
16326     }
16327 
16328     // C++11 [namespace.memdef]p3:
16329     //   If the name in a friend declaration is neither qualified nor
16330     //   a template-id and the declaration is a function or an
16331     //   elaborated-type-specifier, the lookup to determine whether
16332     //   the entity has been previously declared shall not consider
16333     //   any scopes outside the innermost enclosing namespace.
16334     //
16335     // MSVC doesn't implement the above rule for types, so a friend tag
16336     // declaration may be a redeclaration of a type declared in an enclosing
16337     // scope.  They do implement this rule for friend functions.
16338     //
16339     // Does it matter that this should be by scope instead of by
16340     // semantic context?
16341     if (!Previous.empty() && TUK == TUK_Friend) {
16342       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16343       LookupResult::Filter F = Previous.makeFilter();
16344       bool FriendSawTagOutsideEnclosingNamespace = false;
16345       while (F.hasNext()) {
16346         NamedDecl *ND = F.next();
16347         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16348         if (DC->isFileContext() &&
16349             !EnclosingNS->Encloses(ND->getDeclContext())) {
16350           if (getLangOpts().MSVCCompat)
16351             FriendSawTagOutsideEnclosingNamespace = true;
16352           else
16353             F.erase();
16354         }
16355       }
16356       F.done();
16357 
16358       // Diagnose this MSVC extension in the easy case where lookup would have
16359       // unambiguously found something outside the enclosing namespace.
16360       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16361         NamedDecl *ND = Previous.getFoundDecl();
16362         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16363             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16364       }
16365     }
16366 
16367     // Note:  there used to be some attempt at recovery here.
16368     if (Previous.isAmbiguous())
16369       return nullptr;
16370 
16371     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16372       // FIXME: This makes sure that we ignore the contexts associated
16373       // with C structs, unions, and enums when looking for a matching
16374       // tag declaration or definition. See the similar lookup tweak
16375       // in Sema::LookupName; is there a better way to deal with this?
16376       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16377         SearchDC = SearchDC->getParent();
16378     } else if (getLangOpts().CPlusPlus) {
16379       // Inside ObjCContainer want to keep it as a lexical decl context but go
16380       // past it (most often to TranslationUnit) to find the semantic decl
16381       // context.
16382       while (isa<ObjCContainerDecl>(SearchDC))
16383         SearchDC = SearchDC->getParent();
16384     }
16385   } else if (getLangOpts().CPlusPlus) {
16386     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16387     // TagDecl the same way as we skip it for named TagDecl.
16388     while (isa<ObjCContainerDecl>(SearchDC))
16389       SearchDC = SearchDC->getParent();
16390   }
16391 
16392   if (Previous.isSingleResult() &&
16393       Previous.getFoundDecl()->isTemplateParameter()) {
16394     // Maybe we will complain about the shadowed template parameter.
16395     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16396     // Just pretend that we didn't see the previous declaration.
16397     Previous.clear();
16398   }
16399 
16400   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16401       DC->Equals(getStdNamespace())) {
16402     if (Name->isStr("bad_alloc")) {
16403       // This is a declaration of or a reference to "std::bad_alloc".
16404       isStdBadAlloc = true;
16405 
16406       // If std::bad_alloc has been implicitly declared (but made invisible to
16407       // name lookup), fill in this implicit declaration as the previous
16408       // declaration, so that the declarations get chained appropriately.
16409       if (Previous.empty() && StdBadAlloc)
16410         Previous.addDecl(getStdBadAlloc());
16411     } else if (Name->isStr("align_val_t")) {
16412       isStdAlignValT = true;
16413       if (Previous.empty() && StdAlignValT)
16414         Previous.addDecl(getStdAlignValT());
16415     }
16416   }
16417 
16418   // If we didn't find a previous declaration, and this is a reference
16419   // (or friend reference), move to the correct scope.  In C++, we
16420   // also need to do a redeclaration lookup there, just in case
16421   // there's a shadow friend decl.
16422   if (Name && Previous.empty() &&
16423       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16424     if (Invalid) goto CreateNewDecl;
16425     assert(SS.isEmpty());
16426 
16427     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16428       // C++ [basic.scope.pdecl]p5:
16429       //   -- for an elaborated-type-specifier of the form
16430       //
16431       //          class-key identifier
16432       //
16433       //      if the elaborated-type-specifier is used in the
16434       //      decl-specifier-seq or parameter-declaration-clause of a
16435       //      function defined in namespace scope, the identifier is
16436       //      declared as a class-name in the namespace that contains
16437       //      the declaration; otherwise, except as a friend
16438       //      declaration, the identifier is declared in the smallest
16439       //      non-class, non-function-prototype scope that contains the
16440       //      declaration.
16441       //
16442       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16443       // C structs and unions.
16444       //
16445       // It is an error in C++ to declare (rather than define) an enum
16446       // type, including via an elaborated type specifier.  We'll
16447       // diagnose that later; for now, declare the enum in the same
16448       // scope as we would have picked for any other tag type.
16449       //
16450       // GNU C also supports this behavior as part of its incomplete
16451       // enum types extension, while GNU C++ does not.
16452       //
16453       // Find the context where we'll be declaring the tag.
16454       // FIXME: We would like to maintain the current DeclContext as the
16455       // lexical context,
16456       SearchDC = getTagInjectionContext(SearchDC);
16457 
16458       // Find the scope where we'll be declaring the tag.
16459       S = getTagInjectionScope(S, getLangOpts());
16460     } else {
16461       assert(TUK == TUK_Friend);
16462       // C++ [namespace.memdef]p3:
16463       //   If a friend declaration in a non-local class first declares a
16464       //   class or function, the friend class or function is a member of
16465       //   the innermost enclosing namespace.
16466       SearchDC = SearchDC->getEnclosingNamespaceContext();
16467     }
16468 
16469     // In C++, we need to do a redeclaration lookup to properly
16470     // diagnose some problems.
16471     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16472     // hidden declaration so that we don't get ambiguity errors when using a
16473     // type declared by an elaborated-type-specifier.  In C that is not correct
16474     // and we should instead merge compatible types found by lookup.
16475     if (getLangOpts().CPlusPlus) {
16476       // FIXME: This can perform qualified lookups into function contexts,
16477       // which are meaningless.
16478       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16479       LookupQualifiedName(Previous, SearchDC);
16480     } else {
16481       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16482       LookupName(Previous, S);
16483     }
16484   }
16485 
16486   // If we have a known previous declaration to use, then use it.
16487   if (Previous.empty() && SkipBody && SkipBody->Previous)
16488     Previous.addDecl(SkipBody->Previous);
16489 
16490   if (!Previous.empty()) {
16491     NamedDecl *PrevDecl = Previous.getFoundDecl();
16492     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16493 
16494     // It's okay to have a tag decl in the same scope as a typedef
16495     // which hides a tag decl in the same scope.  Finding this
16496     // with a redeclaration lookup can only actually happen in C++.
16497     //
16498     // This is also okay for elaborated-type-specifiers, which is
16499     // technically forbidden by the current standard but which is
16500     // okay according to the likely resolution of an open issue;
16501     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16502     if (getLangOpts().CPlusPlus) {
16503       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16504         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16505           TagDecl *Tag = TT->getDecl();
16506           if (Tag->getDeclName() == Name &&
16507               Tag->getDeclContext()->getRedeclContext()
16508                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16509             PrevDecl = Tag;
16510             Previous.clear();
16511             Previous.addDecl(Tag);
16512             Previous.resolveKind();
16513           }
16514         }
16515       }
16516     }
16517 
16518     // If this is a redeclaration of a using shadow declaration, it must
16519     // declare a tag in the same context. In MSVC mode, we allow a
16520     // redefinition if either context is within the other.
16521     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16522       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16523       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16524           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16525           !(OldTag && isAcceptableTagRedeclContext(
16526                           *this, OldTag->getDeclContext(), SearchDC))) {
16527         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16528         Diag(Shadow->getTargetDecl()->getLocation(),
16529              diag::note_using_decl_target);
16530         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16531             << 0;
16532         // Recover by ignoring the old declaration.
16533         Previous.clear();
16534         goto CreateNewDecl;
16535       }
16536     }
16537 
16538     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16539       // If this is a use of a previous tag, or if the tag is already declared
16540       // in the same scope (so that the definition/declaration completes or
16541       // rementions the tag), reuse the decl.
16542       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16543           isDeclInScope(DirectPrevDecl, SearchDC, S,
16544                         SS.isNotEmpty() || isMemberSpecialization)) {
16545         // Make sure that this wasn't declared as an enum and now used as a
16546         // struct or something similar.
16547         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16548                                           TUK == TUK_Definition, KWLoc,
16549                                           Name)) {
16550           bool SafeToContinue
16551             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16552                Kind != TTK_Enum);
16553           if (SafeToContinue)
16554             Diag(KWLoc, diag::err_use_with_wrong_tag)
16555               << Name
16556               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16557                                               PrevTagDecl->getKindName());
16558           else
16559             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16560           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16561 
16562           if (SafeToContinue)
16563             Kind = PrevTagDecl->getTagKind();
16564           else {
16565             // Recover by making this an anonymous redefinition.
16566             Name = nullptr;
16567             Previous.clear();
16568             Invalid = true;
16569           }
16570         }
16571 
16572         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16573           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16574           if (TUK == TUK_Reference || TUK == TUK_Friend)
16575             return PrevTagDecl;
16576 
16577           QualType EnumUnderlyingTy;
16578           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16579             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16580           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16581             EnumUnderlyingTy = QualType(T, 0);
16582 
16583           // All conflicts with previous declarations are recovered by
16584           // returning the previous declaration, unless this is a definition,
16585           // in which case we want the caller to bail out.
16586           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16587                                      ScopedEnum, EnumUnderlyingTy,
16588                                      IsFixed, PrevEnum))
16589             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16590         }
16591 
16592         // C++11 [class.mem]p1:
16593         //   A member shall not be declared twice in the member-specification,
16594         //   except that a nested class or member class template can be declared
16595         //   and then later defined.
16596         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16597             S->isDeclScope(PrevDecl)) {
16598           Diag(NameLoc, diag::ext_member_redeclared);
16599           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16600         }
16601 
16602         if (!Invalid) {
16603           // If this is a use, just return the declaration we found, unless
16604           // we have attributes.
16605           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16606             if (!Attrs.empty()) {
16607               // FIXME: Diagnose these attributes. For now, we create a new
16608               // declaration to hold them.
16609             } else if (TUK == TUK_Reference &&
16610                        (PrevTagDecl->getFriendObjectKind() ==
16611                             Decl::FOK_Undeclared ||
16612                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16613                        SS.isEmpty()) {
16614               // This declaration is a reference to an existing entity, but
16615               // has different visibility from that entity: it either makes
16616               // a friend visible or it makes a type visible in a new module.
16617               // In either case, create a new declaration. We only do this if
16618               // the declaration would have meant the same thing if no prior
16619               // declaration were found, that is, if it was found in the same
16620               // scope where we would have injected a declaration.
16621               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16622                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16623                 return PrevTagDecl;
16624               // This is in the injected scope, create a new declaration in
16625               // that scope.
16626               S = getTagInjectionScope(S, getLangOpts());
16627             } else {
16628               return PrevTagDecl;
16629             }
16630           }
16631 
16632           // Diagnose attempts to redefine a tag.
16633           if (TUK == TUK_Definition) {
16634             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16635               // If we're defining a specialization and the previous definition
16636               // is from an implicit instantiation, don't emit an error
16637               // here; we'll catch this in the general case below.
16638               bool IsExplicitSpecializationAfterInstantiation = false;
16639               if (isMemberSpecialization) {
16640                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16641                   IsExplicitSpecializationAfterInstantiation =
16642                     RD->getTemplateSpecializationKind() !=
16643                     TSK_ExplicitSpecialization;
16644                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16645                   IsExplicitSpecializationAfterInstantiation =
16646                     ED->getTemplateSpecializationKind() !=
16647                     TSK_ExplicitSpecialization;
16648               }
16649 
16650               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16651               // not keep more that one definition around (merge them). However,
16652               // ensure the decl passes the structural compatibility check in
16653               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16654               NamedDecl *Hidden = nullptr;
16655               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16656                 // There is a definition of this tag, but it is not visible. We
16657                 // explicitly make use of C++'s one definition rule here, and
16658                 // assume that this definition is identical to the hidden one
16659                 // we already have. Make the existing definition visible and
16660                 // use it in place of this one.
16661                 if (!getLangOpts().CPlusPlus) {
16662                   // Postpone making the old definition visible until after we
16663                   // complete parsing the new one and do the structural
16664                   // comparison.
16665                   SkipBody->CheckSameAsPrevious = true;
16666                   SkipBody->New = createTagFromNewDecl();
16667                   SkipBody->Previous = Def;
16668                   return Def;
16669                 } else {
16670                   SkipBody->ShouldSkip = true;
16671                   SkipBody->Previous = Def;
16672                   makeMergedDefinitionVisible(Hidden);
16673                   // Carry on and handle it like a normal definition. We'll
16674                   // skip starting the definitiion later.
16675                 }
16676               } else if (!IsExplicitSpecializationAfterInstantiation) {
16677                 // A redeclaration in function prototype scope in C isn't
16678                 // visible elsewhere, so merely issue a warning.
16679                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16680                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16681                 else
16682                   Diag(NameLoc, diag::err_redefinition) << Name;
16683                 notePreviousDefinition(Def,
16684                                        NameLoc.isValid() ? NameLoc : KWLoc);
16685                 // If this is a redefinition, recover by making this
16686                 // struct be anonymous, which will make any later
16687                 // references get the previous definition.
16688                 Name = nullptr;
16689                 Previous.clear();
16690                 Invalid = true;
16691               }
16692             } else {
16693               // If the type is currently being defined, complain
16694               // about a nested redefinition.
16695               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16696               if (TD->isBeingDefined()) {
16697                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16698                 Diag(PrevTagDecl->getLocation(),
16699                      diag::note_previous_definition);
16700                 Name = nullptr;
16701                 Previous.clear();
16702                 Invalid = true;
16703               }
16704             }
16705 
16706             // Okay, this is definition of a previously declared or referenced
16707             // tag. We're going to create a new Decl for it.
16708           }
16709 
16710           // Okay, we're going to make a redeclaration.  If this is some kind
16711           // of reference, make sure we build the redeclaration in the same DC
16712           // as the original, and ignore the current access specifier.
16713           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16714             SearchDC = PrevTagDecl->getDeclContext();
16715             AS = AS_none;
16716           }
16717         }
16718         // If we get here we have (another) forward declaration or we
16719         // have a definition.  Just create a new decl.
16720 
16721       } else {
16722         // If we get here, this is a definition of a new tag type in a nested
16723         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16724         // new decl/type.  We set PrevDecl to NULL so that the entities
16725         // have distinct types.
16726         Previous.clear();
16727       }
16728       // If we get here, we're going to create a new Decl. If PrevDecl
16729       // is non-NULL, it's a definition of the tag declared by
16730       // PrevDecl. If it's NULL, we have a new definition.
16731 
16732     // Otherwise, PrevDecl is not a tag, but was found with tag
16733     // lookup.  This is only actually possible in C++, where a few
16734     // things like templates still live in the tag namespace.
16735     } else {
16736       // Use a better diagnostic if an elaborated-type-specifier
16737       // found the wrong kind of type on the first
16738       // (non-redeclaration) lookup.
16739       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16740           !Previous.isForRedeclaration()) {
16741         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16742         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16743                                                        << Kind;
16744         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16745         Invalid = true;
16746 
16747       // Otherwise, only diagnose if the declaration is in scope.
16748       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16749                                 SS.isNotEmpty() || isMemberSpecialization)) {
16750         // do nothing
16751 
16752       // Diagnose implicit declarations introduced by elaborated types.
16753       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16754         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16755         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16756         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16757         Invalid = true;
16758 
16759       // Otherwise it's a declaration.  Call out a particularly common
16760       // case here.
16761       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16762         unsigned Kind = 0;
16763         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16764         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16765           << Name << Kind << TND->getUnderlyingType();
16766         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16767         Invalid = true;
16768 
16769       // Otherwise, diagnose.
16770       } else {
16771         // The tag name clashes with something else in the target scope,
16772         // issue an error and recover by making this tag be anonymous.
16773         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16774         notePreviousDefinition(PrevDecl, NameLoc);
16775         Name = nullptr;
16776         Invalid = true;
16777       }
16778 
16779       // The existing declaration isn't relevant to us; we're in a
16780       // new scope, so clear out the previous declaration.
16781       Previous.clear();
16782     }
16783   }
16784 
16785 CreateNewDecl:
16786 
16787   TagDecl *PrevDecl = nullptr;
16788   if (Previous.isSingleResult())
16789     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16790 
16791   // If there is an identifier, use the location of the identifier as the
16792   // location of the decl, otherwise use the location of the struct/union
16793   // keyword.
16794   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16795 
16796   // Otherwise, create a new declaration. If there is a previous
16797   // declaration of the same entity, the two will be linked via
16798   // PrevDecl.
16799   TagDecl *New;
16800 
16801   if (Kind == TTK_Enum) {
16802     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16803     // enum X { A, B, C } D;    D should chain to X.
16804     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16805                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16806                            ScopedEnumUsesClassTag, IsFixed);
16807 
16808     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16809       StdAlignValT = cast<EnumDecl>(New);
16810 
16811     // If this is an undefined enum, warn.
16812     if (TUK != TUK_Definition && !Invalid) {
16813       TagDecl *Def;
16814       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16815         // C++0x: 7.2p2: opaque-enum-declaration.
16816         // Conflicts are diagnosed above. Do nothing.
16817       }
16818       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16819         Diag(Loc, diag::ext_forward_ref_enum_def)
16820           << New;
16821         Diag(Def->getLocation(), diag::note_previous_definition);
16822       } else {
16823         unsigned DiagID = diag::ext_forward_ref_enum;
16824         if (getLangOpts().MSVCCompat)
16825           DiagID = diag::ext_ms_forward_ref_enum;
16826         else if (getLangOpts().CPlusPlus)
16827           DiagID = diag::err_forward_ref_enum;
16828         Diag(Loc, DiagID);
16829       }
16830     }
16831 
16832     if (EnumUnderlying) {
16833       EnumDecl *ED = cast<EnumDecl>(New);
16834       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16835         ED->setIntegerTypeSourceInfo(TI);
16836       else
16837         ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16838       QualType EnumTy = ED->getIntegerType();
16839       ED->setPromotionType(EnumTy->isPromotableIntegerType()
16840                                ? Context.getPromotedIntegerType(EnumTy)
16841                                : EnumTy);
16842       assert(ED->isComplete() && "enum with type should be complete");
16843     }
16844   } else {
16845     // struct/union/class
16846 
16847     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16848     // struct X { int A; } D;    D should chain to X.
16849     if (getLangOpts().CPlusPlus) {
16850       // FIXME: Look for a way to use RecordDecl for simple structs.
16851       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16852                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16853 
16854       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16855         StdBadAlloc = cast<CXXRecordDecl>(New);
16856     } else
16857       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16858                                cast_or_null<RecordDecl>(PrevDecl));
16859   }
16860 
16861   // C++11 [dcl.type]p3:
16862   //   A type-specifier-seq shall not define a class or enumeration [...].
16863   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16864       TUK == TUK_Definition) {
16865     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16866       << Context.getTagDeclType(New);
16867     Invalid = true;
16868   }
16869 
16870   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16871       DC->getDeclKind() == Decl::Enum) {
16872     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16873       << Context.getTagDeclType(New);
16874     Invalid = true;
16875   }
16876 
16877   // Maybe add qualifier info.
16878   if (SS.isNotEmpty()) {
16879     if (SS.isSet()) {
16880       // If this is either a declaration or a definition, check the
16881       // nested-name-specifier against the current context.
16882       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16883           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16884                                        isMemberSpecialization))
16885         Invalid = true;
16886 
16887       New->setQualifierInfo(SS.getWithLocInContext(Context));
16888       if (TemplateParameterLists.size() > 0) {
16889         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16890       }
16891     }
16892     else
16893       Invalid = true;
16894   }
16895 
16896   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16897     // Add alignment attributes if necessary; these attributes are checked when
16898     // the ASTContext lays out the structure.
16899     //
16900     // It is important for implementing the correct semantics that this
16901     // happen here (in ActOnTag). The #pragma pack stack is
16902     // maintained as a result of parser callbacks which can occur at
16903     // many points during the parsing of a struct declaration (because
16904     // the #pragma tokens are effectively skipped over during the
16905     // parsing of the struct).
16906     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16907       AddAlignmentAttributesForRecord(RD);
16908       AddMsStructLayoutForRecord(RD);
16909     }
16910   }
16911 
16912   if (ModulePrivateLoc.isValid()) {
16913     if (isMemberSpecialization)
16914       Diag(New->getLocation(), diag::err_module_private_specialization)
16915         << 2
16916         << FixItHint::CreateRemoval(ModulePrivateLoc);
16917     // __module_private__ does not apply to local classes. However, we only
16918     // diagnose this as an error when the declaration specifiers are
16919     // freestanding. Here, we just ignore the __module_private__.
16920     else if (!SearchDC->isFunctionOrMethod())
16921       New->setModulePrivate();
16922   }
16923 
16924   // If this is a specialization of a member class (of a class template),
16925   // check the specialization.
16926   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16927     Invalid = true;
16928 
16929   // If we're declaring or defining a tag in function prototype scope in C,
16930   // note that this type can only be used within the function and add it to
16931   // the list of decls to inject into the function definition scope.
16932   if ((Name || Kind == TTK_Enum) &&
16933       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16934     if (getLangOpts().CPlusPlus) {
16935       // C++ [dcl.fct]p6:
16936       //   Types shall not be defined in return or parameter types.
16937       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16938         Diag(Loc, diag::err_type_defined_in_param_type)
16939             << Name;
16940         Invalid = true;
16941       }
16942     } else if (!PrevDecl) {
16943       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16944     }
16945   }
16946 
16947   if (Invalid)
16948     New->setInvalidDecl();
16949 
16950   // Set the lexical context. If the tag has a C++ scope specifier, the
16951   // lexical context will be different from the semantic context.
16952   New->setLexicalDeclContext(CurContext);
16953 
16954   // Mark this as a friend decl if applicable.
16955   // In Microsoft mode, a friend declaration also acts as a forward
16956   // declaration so we always pass true to setObjectOfFriendDecl to make
16957   // the tag name visible.
16958   if (TUK == TUK_Friend)
16959     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16960 
16961   // Set the access specifier.
16962   if (!Invalid && SearchDC->isRecord())
16963     SetMemberAccessSpecifier(New, PrevDecl, AS);
16964 
16965   if (PrevDecl)
16966     CheckRedeclarationInModule(New, PrevDecl);
16967 
16968   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16969     New->startDefinition();
16970 
16971   ProcessDeclAttributeList(S, New, Attrs);
16972   AddPragmaAttributes(S, New);
16973 
16974   // If this has an identifier, add it to the scope stack.
16975   if (TUK == TUK_Friend) {
16976     // We might be replacing an existing declaration in the lookup tables;
16977     // if so, borrow its access specifier.
16978     if (PrevDecl)
16979       New->setAccess(PrevDecl->getAccess());
16980 
16981     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16982     DC->makeDeclVisibleInContext(New);
16983     if (Name) // can be null along some error paths
16984       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16985         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16986   } else if (Name) {
16987     S = getNonFieldDeclScope(S);
16988     PushOnScopeChains(New, S, true);
16989   } else {
16990     CurContext->addDecl(New);
16991   }
16992 
16993   // If this is the C FILE type, notify the AST context.
16994   if (IdentifierInfo *II = New->getIdentifier())
16995     if (!New->isInvalidDecl() &&
16996         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16997         II->isStr("FILE"))
16998       Context.setFILEDecl(New);
16999 
17000   if (PrevDecl)
17001     mergeDeclAttributes(New, PrevDecl);
17002 
17003   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17004     inferGslOwnerPointerAttribute(CXXRD);
17005 
17006   // If there's a #pragma GCC visibility in scope, set the visibility of this
17007   // record.
17008   AddPushedVisibilityAttribute(New);
17009 
17010   if (isMemberSpecialization && !New->isInvalidDecl())
17011     CompleteMemberSpecialization(New, Previous);
17012 
17013   OwnedDecl = true;
17014   // In C++, don't return an invalid declaration. We can't recover well from
17015   // the cases where we make the type anonymous.
17016   if (Invalid && getLangOpts().CPlusPlus) {
17017     if (New->isBeingDefined())
17018       if (auto RD = dyn_cast<RecordDecl>(New))
17019         RD->completeDefinition();
17020     return nullptr;
17021   } else if (SkipBody && SkipBody->ShouldSkip) {
17022     return SkipBody->Previous;
17023   } else {
17024     return New;
17025   }
17026 }
17027 
17028 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17029   AdjustDeclIfTemplate(TagD);
17030   TagDecl *Tag = cast<TagDecl>(TagD);
17031 
17032   // Enter the tag context.
17033   PushDeclContext(S, Tag);
17034 
17035   ActOnDocumentableDecl(TagD);
17036 
17037   // If there's a #pragma GCC visibility in scope, set the visibility of this
17038   // record.
17039   AddPushedVisibilityAttribute(Tag);
17040 }
17041 
17042 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17043   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17044     return false;
17045 
17046   // Make the previous decl visible.
17047   makeMergedDefinitionVisible(SkipBody.Previous);
17048   return true;
17049 }
17050 
17051 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17052   assert(IDecl->getLexicalParent() == CurContext &&
17053       "The next DeclContext should be lexically contained in the current one.");
17054   CurContext = IDecl;
17055 }
17056 
17057 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17058                                            SourceLocation FinalLoc,
17059                                            bool IsFinalSpelledSealed,
17060                                            bool IsAbstract,
17061                                            SourceLocation LBraceLoc) {
17062   AdjustDeclIfTemplate(TagD);
17063   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17064 
17065   FieldCollector->StartClass();
17066 
17067   if (!Record->getIdentifier())
17068     return;
17069 
17070   if (IsAbstract)
17071     Record->markAbstract();
17072 
17073   if (FinalLoc.isValid()) {
17074     Record->addAttr(FinalAttr::Create(
17075         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17076         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17077   }
17078   // C++ [class]p2:
17079   //   [...] The class-name is also inserted into the scope of the
17080   //   class itself; this is known as the injected-class-name. For
17081   //   purposes of access checking, the injected-class-name is treated
17082   //   as if it were a public member name.
17083   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17084       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17085       Record->getLocation(), Record->getIdentifier(),
17086       /*PrevDecl=*/nullptr,
17087       /*DelayTypeCreation=*/true);
17088   Context.getTypeDeclType(InjectedClassName, Record);
17089   InjectedClassName->setImplicit();
17090   InjectedClassName->setAccess(AS_public);
17091   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17092       InjectedClassName->setDescribedClassTemplate(Template);
17093   PushOnScopeChains(InjectedClassName, S);
17094   assert(InjectedClassName->isInjectedClassName() &&
17095          "Broken injected-class-name");
17096 }
17097 
17098 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17099                                     SourceRange BraceRange) {
17100   AdjustDeclIfTemplate(TagD);
17101   TagDecl *Tag = cast<TagDecl>(TagD);
17102   Tag->setBraceRange(BraceRange);
17103 
17104   // Make sure we "complete" the definition even it is invalid.
17105   if (Tag->isBeingDefined()) {
17106     assert(Tag->isInvalidDecl() && "We should already have completed it");
17107     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17108       RD->completeDefinition();
17109   }
17110 
17111   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17112     FieldCollector->FinishClass();
17113     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17114       auto *Def = RD->getDefinition();
17115       assert(Def && "The record is expected to have a completed definition");
17116       unsigned NumInitMethods = 0;
17117       for (auto *Method : Def->methods()) {
17118         if (!Method->getIdentifier())
17119             continue;
17120         if (Method->getName() == "__init")
17121           NumInitMethods++;
17122       }
17123       if (NumInitMethods > 1 || !Def->hasInitMethod())
17124         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17125     }
17126   }
17127 
17128   // Exit this scope of this tag's definition.
17129   PopDeclContext();
17130 
17131   if (getCurLexicalContext()->isObjCContainer() &&
17132       Tag->getDeclContext()->isFileContext())
17133     Tag->setTopLevelDeclInObjCContainer();
17134 
17135   // Notify the consumer that we've defined a tag.
17136   if (!Tag->isInvalidDecl())
17137     Consumer.HandleTagDeclDefinition(Tag);
17138 
17139   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17140   // from XLs and instead matches the XL #pragma pack(1) behavior.
17141   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17142       AlignPackStack.hasValue()) {
17143     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17144     // Only diagnose #pragma align(packed).
17145     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17146       return;
17147     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17148     if (!RD)
17149       return;
17150     // Only warn if there is at least 1 bitfield member.
17151     if (llvm::any_of(RD->fields(),
17152                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17153       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17154   }
17155 }
17156 
17157 void Sema::ActOnObjCContainerFinishDefinition() {
17158   // Exit this scope of this interface definition.
17159   PopDeclContext();
17160 }
17161 
17162 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17163   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17164   OriginalLexicalContext = ObjCCtx;
17165   ActOnObjCContainerFinishDefinition();
17166 }
17167 
17168 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17169   ActOnObjCContainerStartDefinition(ObjCCtx);
17170   OriginalLexicalContext = nullptr;
17171 }
17172 
17173 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17174   AdjustDeclIfTemplate(TagD);
17175   TagDecl *Tag = cast<TagDecl>(TagD);
17176   Tag->setInvalidDecl();
17177 
17178   // Make sure we "complete" the definition even it is invalid.
17179   if (Tag->isBeingDefined()) {
17180     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17181       RD->completeDefinition();
17182   }
17183 
17184   // We're undoing ActOnTagStartDefinition here, not
17185   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17186   // the FieldCollector.
17187 
17188   PopDeclContext();
17189 }
17190 
17191 // Note that FieldName may be null for anonymous bitfields.
17192 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17193                                 IdentifierInfo *FieldName, QualType FieldTy,
17194                                 bool IsMsStruct, Expr *BitWidth) {
17195   assert(BitWidth);
17196   if (BitWidth->containsErrors())
17197     return ExprError();
17198 
17199   // C99 6.7.2.1p4 - verify the field type.
17200   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17201   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17202     // Handle incomplete and sizeless types with a specific error.
17203     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17204                                  diag::err_field_incomplete_or_sizeless))
17205       return ExprError();
17206     if (FieldName)
17207       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17208         << FieldName << FieldTy << BitWidth->getSourceRange();
17209     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17210       << FieldTy << BitWidth->getSourceRange();
17211   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17212                                              UPPC_BitFieldWidth))
17213     return ExprError();
17214 
17215   // If the bit-width is type- or value-dependent, don't try to check
17216   // it now.
17217   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17218     return BitWidth;
17219 
17220   llvm::APSInt Value;
17221   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17222   if (ICE.isInvalid())
17223     return ICE;
17224   BitWidth = ICE.get();
17225 
17226   // Zero-width bitfield is ok for anonymous field.
17227   if (Value == 0 && FieldName)
17228     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17229 
17230   if (Value.isSigned() && Value.isNegative()) {
17231     if (FieldName)
17232       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17233                << FieldName << toString(Value, 10);
17234     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17235       << toString(Value, 10);
17236   }
17237 
17238   // The size of the bit-field must not exceed our maximum permitted object
17239   // size.
17240   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17241     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17242            << !FieldName << FieldName << toString(Value, 10);
17243   }
17244 
17245   if (!FieldTy->isDependentType()) {
17246     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17247     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17248     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17249 
17250     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17251     // ABI.
17252     bool CStdConstraintViolation =
17253         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17254     bool MSBitfieldViolation =
17255         Value.ugt(TypeStorageSize) &&
17256         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17257     if (CStdConstraintViolation || MSBitfieldViolation) {
17258       unsigned DiagWidth =
17259           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17260       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17261              << (bool)FieldName << FieldName << toString(Value, 10)
17262              << !CStdConstraintViolation << DiagWidth;
17263     }
17264 
17265     // Warn on types where the user might conceivably expect to get all
17266     // specified bits as value bits: that's all integral types other than
17267     // 'bool'.
17268     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17269       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17270           << FieldName << toString(Value, 10)
17271           << (unsigned)TypeWidth;
17272     }
17273   }
17274 
17275   return BitWidth;
17276 }
17277 
17278 /// ActOnField - Each field of a C struct/union is passed into this in order
17279 /// to create a FieldDecl object for it.
17280 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17281                        Declarator &D, Expr *BitfieldWidth) {
17282   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17283                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17284                                /*InitStyle=*/ICIS_NoInit, AS_public);
17285   return Res;
17286 }
17287 
17288 /// HandleField - Analyze a field of a C struct or a C++ data member.
17289 ///
17290 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17291                              SourceLocation DeclStart,
17292                              Declarator &D, Expr *BitWidth,
17293                              InClassInitStyle InitStyle,
17294                              AccessSpecifier AS) {
17295   if (D.isDecompositionDeclarator()) {
17296     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17297     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17298       << Decomp.getSourceRange();
17299     return nullptr;
17300   }
17301 
17302   IdentifierInfo *II = D.getIdentifier();
17303   SourceLocation Loc = DeclStart;
17304   if (II) Loc = D.getIdentifierLoc();
17305 
17306   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17307   QualType T = TInfo->getType();
17308   if (getLangOpts().CPlusPlus) {
17309     CheckExtraCXXDefaultArguments(D);
17310 
17311     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17312                                         UPPC_DataMemberType)) {
17313       D.setInvalidType();
17314       T = Context.IntTy;
17315       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17316     }
17317   }
17318 
17319   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17320 
17321   if (D.getDeclSpec().isInlineSpecified())
17322     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17323         << getLangOpts().CPlusPlus17;
17324   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17325     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17326          diag::err_invalid_thread)
17327       << DeclSpec::getSpecifierName(TSCS);
17328 
17329   // Check to see if this name was declared as a member previously
17330   NamedDecl *PrevDecl = nullptr;
17331   LookupResult Previous(*this, II, Loc, LookupMemberName,
17332                         ForVisibleRedeclaration);
17333   LookupName(Previous, S);
17334   switch (Previous.getResultKind()) {
17335     case LookupResult::Found:
17336     case LookupResult::FoundUnresolvedValue:
17337       PrevDecl = Previous.getAsSingle<NamedDecl>();
17338       break;
17339 
17340     case LookupResult::FoundOverloaded:
17341       PrevDecl = Previous.getRepresentativeDecl();
17342       break;
17343 
17344     case LookupResult::NotFound:
17345     case LookupResult::NotFoundInCurrentInstantiation:
17346     case LookupResult::Ambiguous:
17347       break;
17348   }
17349   Previous.suppressDiagnostics();
17350 
17351   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17352     // Maybe we will complain about the shadowed template parameter.
17353     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17354     // Just pretend that we didn't see the previous declaration.
17355     PrevDecl = nullptr;
17356   }
17357 
17358   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17359     PrevDecl = nullptr;
17360 
17361   bool Mutable
17362     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17363   SourceLocation TSSL = D.getBeginLoc();
17364   FieldDecl *NewFD
17365     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17366                      TSSL, AS, PrevDecl, &D);
17367 
17368   if (NewFD->isInvalidDecl())
17369     Record->setInvalidDecl();
17370 
17371   if (D.getDeclSpec().isModulePrivateSpecified())
17372     NewFD->setModulePrivate();
17373 
17374   if (NewFD->isInvalidDecl() && PrevDecl) {
17375     // Don't introduce NewFD into scope; there's already something
17376     // with the same name in the same scope.
17377   } else if (II) {
17378     PushOnScopeChains(NewFD, S);
17379   } else
17380     Record->addDecl(NewFD);
17381 
17382   return NewFD;
17383 }
17384 
17385 /// Build a new FieldDecl and check its well-formedness.
17386 ///
17387 /// This routine builds a new FieldDecl given the fields name, type,
17388 /// record, etc. \p PrevDecl should refer to any previous declaration
17389 /// with the same name and in the same scope as the field to be
17390 /// created.
17391 ///
17392 /// \returns a new FieldDecl.
17393 ///
17394 /// \todo The Declarator argument is a hack. It will be removed once
17395 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17396                                 TypeSourceInfo *TInfo,
17397                                 RecordDecl *Record, SourceLocation Loc,
17398                                 bool Mutable, Expr *BitWidth,
17399                                 InClassInitStyle InitStyle,
17400                                 SourceLocation TSSL,
17401                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17402                                 Declarator *D) {
17403   IdentifierInfo *II = Name.getAsIdentifierInfo();
17404   bool InvalidDecl = false;
17405   if (D) InvalidDecl = D->isInvalidType();
17406 
17407   // If we receive a broken type, recover by assuming 'int' and
17408   // marking this declaration as invalid.
17409   if (T.isNull() || T->containsErrors()) {
17410     InvalidDecl = true;
17411     T = Context.IntTy;
17412   }
17413 
17414   QualType EltTy = Context.getBaseElementType(T);
17415   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17416     if (RequireCompleteSizedType(Loc, EltTy,
17417                                  diag::err_field_incomplete_or_sizeless)) {
17418       // Fields of incomplete type force their record to be invalid.
17419       Record->setInvalidDecl();
17420       InvalidDecl = true;
17421     } else {
17422       NamedDecl *Def;
17423       EltTy->isIncompleteType(&Def);
17424       if (Def && Def->isInvalidDecl()) {
17425         Record->setInvalidDecl();
17426         InvalidDecl = true;
17427       }
17428     }
17429   }
17430 
17431   // TR 18037 does not allow fields to be declared with address space
17432   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17433       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17434     Diag(Loc, diag::err_field_with_address_space);
17435     Record->setInvalidDecl();
17436     InvalidDecl = true;
17437   }
17438 
17439   if (LangOpts.OpenCL) {
17440     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17441     // used as structure or union field: image, sampler, event or block types.
17442     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17443         T->isBlockPointerType()) {
17444       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17445       Record->setInvalidDecl();
17446       InvalidDecl = true;
17447     }
17448     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17449     // is enabled.
17450     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17451                         "__cl_clang_bitfields", LangOpts)) {
17452       Diag(Loc, diag::err_opencl_bitfields);
17453       InvalidDecl = true;
17454     }
17455   }
17456 
17457   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17458   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17459       T.hasQualifiers()) {
17460     InvalidDecl = true;
17461     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17462   }
17463 
17464   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17465   // than a variably modified type.
17466   if (!InvalidDecl && T->isVariablyModifiedType()) {
17467     if (!tryToFixVariablyModifiedVarType(
17468             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17469       InvalidDecl = true;
17470   }
17471 
17472   // Fields can not have abstract class types
17473   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17474                                              diag::err_abstract_type_in_decl,
17475                                              AbstractFieldType))
17476     InvalidDecl = true;
17477 
17478   if (InvalidDecl)
17479     BitWidth = nullptr;
17480   // If this is declared as a bit-field, check the bit-field.
17481   if (BitWidth) {
17482     BitWidth =
17483         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17484     if (!BitWidth) {
17485       InvalidDecl = true;
17486       BitWidth = nullptr;
17487     }
17488   }
17489 
17490   // Check that 'mutable' is consistent with the type of the declaration.
17491   if (!InvalidDecl && Mutable) {
17492     unsigned DiagID = 0;
17493     if (T->isReferenceType())
17494       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17495                                         : diag::err_mutable_reference;
17496     else if (T.isConstQualified())
17497       DiagID = diag::err_mutable_const;
17498 
17499     if (DiagID) {
17500       SourceLocation ErrLoc = Loc;
17501       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17502         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17503       Diag(ErrLoc, DiagID);
17504       if (DiagID != diag::ext_mutable_reference) {
17505         Mutable = false;
17506         InvalidDecl = true;
17507       }
17508     }
17509   }
17510 
17511   // C++11 [class.union]p8 (DR1460):
17512   //   At most one variant member of a union may have a
17513   //   brace-or-equal-initializer.
17514   if (InitStyle != ICIS_NoInit)
17515     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17516 
17517   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17518                                        BitWidth, Mutable, InitStyle);
17519   if (InvalidDecl)
17520     NewFD->setInvalidDecl();
17521 
17522   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17523     Diag(Loc, diag::err_duplicate_member) << II;
17524     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17525     NewFD->setInvalidDecl();
17526   }
17527 
17528   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17529     if (Record->isUnion()) {
17530       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17531         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17532         if (RDecl->getDefinition()) {
17533           // C++ [class.union]p1: An object of a class with a non-trivial
17534           // constructor, a non-trivial copy constructor, a non-trivial
17535           // destructor, or a non-trivial copy assignment operator
17536           // cannot be a member of a union, nor can an array of such
17537           // objects.
17538           if (CheckNontrivialField(NewFD))
17539             NewFD->setInvalidDecl();
17540         }
17541       }
17542 
17543       // C++ [class.union]p1: If a union contains a member of reference type,
17544       // the program is ill-formed, except when compiling with MSVC extensions
17545       // enabled.
17546       if (EltTy->isReferenceType()) {
17547         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17548                                     diag::ext_union_member_of_reference_type :
17549                                     diag::err_union_member_of_reference_type)
17550           << NewFD->getDeclName() << EltTy;
17551         if (!getLangOpts().MicrosoftExt)
17552           NewFD->setInvalidDecl();
17553       }
17554     }
17555   }
17556 
17557   // FIXME: We need to pass in the attributes given an AST
17558   // representation, not a parser representation.
17559   if (D) {
17560     // FIXME: The current scope is almost... but not entirely... correct here.
17561     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17562 
17563     if (NewFD->hasAttrs())
17564       CheckAlignasUnderalignment(NewFD);
17565   }
17566 
17567   // In auto-retain/release, infer strong retension for fields of
17568   // retainable type.
17569   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17570     NewFD->setInvalidDecl();
17571 
17572   if (T.isObjCGCWeak())
17573     Diag(Loc, diag::warn_attribute_weak_on_field);
17574 
17575   // PPC MMA non-pointer types are not allowed as field types.
17576   if (Context.getTargetInfo().getTriple().isPPC64() &&
17577       CheckPPCMMAType(T, NewFD->getLocation()))
17578     NewFD->setInvalidDecl();
17579 
17580   NewFD->setAccess(AS);
17581   return NewFD;
17582 }
17583 
17584 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17585   assert(FD);
17586   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17587 
17588   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17589     return false;
17590 
17591   QualType EltTy = Context.getBaseElementType(FD->getType());
17592   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17593     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17594     if (RDecl->getDefinition()) {
17595       // We check for copy constructors before constructors
17596       // because otherwise we'll never get complaints about
17597       // copy constructors.
17598 
17599       CXXSpecialMember member = CXXInvalid;
17600       // We're required to check for any non-trivial constructors. Since the
17601       // implicit default constructor is suppressed if there are any
17602       // user-declared constructors, we just need to check that there is a
17603       // trivial default constructor and a trivial copy constructor. (We don't
17604       // worry about move constructors here, since this is a C++98 check.)
17605       if (RDecl->hasNonTrivialCopyConstructor())
17606         member = CXXCopyConstructor;
17607       else if (!RDecl->hasTrivialDefaultConstructor())
17608         member = CXXDefaultConstructor;
17609       else if (RDecl->hasNonTrivialCopyAssignment())
17610         member = CXXCopyAssignment;
17611       else if (RDecl->hasNonTrivialDestructor())
17612         member = CXXDestructor;
17613 
17614       if (member != CXXInvalid) {
17615         if (!getLangOpts().CPlusPlus11 &&
17616             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17617           // Objective-C++ ARC: it is an error to have a non-trivial field of
17618           // a union. However, system headers in Objective-C programs
17619           // occasionally have Objective-C lifetime objects within unions,
17620           // and rather than cause the program to fail, we make those
17621           // members unavailable.
17622           SourceLocation Loc = FD->getLocation();
17623           if (getSourceManager().isInSystemHeader(Loc)) {
17624             if (!FD->hasAttr<UnavailableAttr>())
17625               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17626                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17627             return false;
17628           }
17629         }
17630 
17631         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17632                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17633                diag::err_illegal_union_or_anon_struct_member)
17634           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17635         DiagnoseNontrivial(RDecl, member);
17636         return !getLangOpts().CPlusPlus11;
17637       }
17638     }
17639   }
17640 
17641   return false;
17642 }
17643 
17644 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17645 ///  AST enum value.
17646 static ObjCIvarDecl::AccessControl
17647 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17648   switch (ivarVisibility) {
17649   default: llvm_unreachable("Unknown visitibility kind");
17650   case tok::objc_private: return ObjCIvarDecl::Private;
17651   case tok::objc_public: return ObjCIvarDecl::Public;
17652   case tok::objc_protected: return ObjCIvarDecl::Protected;
17653   case tok::objc_package: return ObjCIvarDecl::Package;
17654   }
17655 }
17656 
17657 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17658 /// in order to create an IvarDecl object for it.
17659 Decl *Sema::ActOnIvar(Scope *S,
17660                                 SourceLocation DeclStart,
17661                                 Declarator &D, Expr *BitfieldWidth,
17662                                 tok::ObjCKeywordKind Visibility) {
17663 
17664   IdentifierInfo *II = D.getIdentifier();
17665   Expr *BitWidth = (Expr*)BitfieldWidth;
17666   SourceLocation Loc = DeclStart;
17667   if (II) Loc = D.getIdentifierLoc();
17668 
17669   // FIXME: Unnamed fields can be handled in various different ways, for
17670   // example, unnamed unions inject all members into the struct namespace!
17671 
17672   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17673   QualType T = TInfo->getType();
17674 
17675   if (BitWidth) {
17676     // 6.7.2.1p3, 6.7.2.1p4
17677     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17678     if (!BitWidth)
17679       D.setInvalidType();
17680   } else {
17681     // Not a bitfield.
17682 
17683     // validate II.
17684 
17685   }
17686   if (T->isReferenceType()) {
17687     Diag(Loc, diag::err_ivar_reference_type);
17688     D.setInvalidType();
17689   }
17690   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17691   // than a variably modified type.
17692   else if (T->isVariablyModifiedType()) {
17693     if (!tryToFixVariablyModifiedVarType(
17694             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17695       D.setInvalidType();
17696   }
17697 
17698   // Get the visibility (access control) for this ivar.
17699   ObjCIvarDecl::AccessControl ac =
17700     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17701                                         : ObjCIvarDecl::None;
17702   // Must set ivar's DeclContext to its enclosing interface.
17703   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17704   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17705     return nullptr;
17706   ObjCContainerDecl *EnclosingContext;
17707   if (ObjCImplementationDecl *IMPDecl =
17708       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17709     if (LangOpts.ObjCRuntime.isFragile()) {
17710     // Case of ivar declared in an implementation. Context is that of its class.
17711       EnclosingContext = IMPDecl->getClassInterface();
17712       assert(EnclosingContext && "Implementation has no class interface!");
17713     }
17714     else
17715       EnclosingContext = EnclosingDecl;
17716   } else {
17717     if (ObjCCategoryDecl *CDecl =
17718         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17719       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17720         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17721         return nullptr;
17722       }
17723     }
17724     EnclosingContext = EnclosingDecl;
17725   }
17726 
17727   // Construct the decl.
17728   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17729                                              DeclStart, Loc, II, T,
17730                                              TInfo, ac, (Expr *)BitfieldWidth);
17731 
17732   if (II) {
17733     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17734                                            ForVisibleRedeclaration);
17735     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17736         && !isa<TagDecl>(PrevDecl)) {
17737       Diag(Loc, diag::err_duplicate_member) << II;
17738       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17739       NewID->setInvalidDecl();
17740     }
17741   }
17742 
17743   // Process attributes attached to the ivar.
17744   ProcessDeclAttributes(S, NewID, D);
17745 
17746   if (D.isInvalidType())
17747     NewID->setInvalidDecl();
17748 
17749   // In ARC, infer 'retaining' for ivars of retainable type.
17750   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17751     NewID->setInvalidDecl();
17752 
17753   if (D.getDeclSpec().isModulePrivateSpecified())
17754     NewID->setModulePrivate();
17755 
17756   if (II) {
17757     // FIXME: When interfaces are DeclContexts, we'll need to add
17758     // these to the interface.
17759     S->AddDecl(NewID);
17760     IdResolver.AddDecl(NewID);
17761   }
17762 
17763   if (LangOpts.ObjCRuntime.isNonFragile() &&
17764       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17765     Diag(Loc, diag::warn_ivars_in_interface);
17766 
17767   return NewID;
17768 }
17769 
17770 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17771 /// class and class extensions. For every class \@interface and class
17772 /// extension \@interface, if the last ivar is a bitfield of any type,
17773 /// then add an implicit `char :0` ivar to the end of that interface.
17774 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17775                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17776   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17777     return;
17778 
17779   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17780   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17781 
17782   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17783     return;
17784   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17785   if (!ID) {
17786     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17787       if (!CD->IsClassExtension())
17788         return;
17789     }
17790     // No need to add this to end of @implementation.
17791     else
17792       return;
17793   }
17794   // All conditions are met. Add a new bitfield to the tail end of ivars.
17795   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17796   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17797 
17798   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17799                               DeclLoc, DeclLoc, nullptr,
17800                               Context.CharTy,
17801                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17802                                                                DeclLoc),
17803                               ObjCIvarDecl::Private, BW,
17804                               true);
17805   AllIvarDecls.push_back(Ivar);
17806 }
17807 
17808 namespace {
17809 /// [class.dtor]p4:
17810 ///   At the end of the definition of a class, overload resolution is
17811 ///   performed among the prospective destructors declared in that class with
17812 ///   an empty argument list to select the destructor for the class, also
17813 ///   known as the selected destructor.
17814 ///
17815 /// We do the overload resolution here, then mark the selected constructor in the AST.
17816 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17817 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17818   if (!Record->hasUserDeclaredDestructor()) {
17819     return;
17820   }
17821 
17822   SourceLocation Loc = Record->getLocation();
17823   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17824 
17825   for (auto *Decl : Record->decls()) {
17826     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17827       if (DD->isInvalidDecl())
17828         continue;
17829       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17830                              OCS);
17831       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17832     }
17833   }
17834 
17835   if (OCS.empty()) {
17836     return;
17837   }
17838   OverloadCandidateSet::iterator Best;
17839   unsigned Msg = 0;
17840   OverloadCandidateDisplayKind DisplayKind;
17841 
17842   switch (OCS.BestViableFunction(S, Loc, Best)) {
17843   case OR_Success:
17844   case OR_Deleted:
17845     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17846     break;
17847 
17848   case OR_Ambiguous:
17849     Msg = diag::err_ambiguous_destructor;
17850     DisplayKind = OCD_AmbiguousCandidates;
17851     break;
17852 
17853   case OR_No_Viable_Function:
17854     Msg = diag::err_no_viable_destructor;
17855     DisplayKind = OCD_AllCandidates;
17856     break;
17857   }
17858 
17859   if (Msg) {
17860     // OpenCL have got their own thing going with destructors. It's slightly broken,
17861     // but we allow it.
17862     if (!S.LangOpts.OpenCL) {
17863       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17864       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17865       Record->setInvalidDecl();
17866     }
17867     // It's a bit hacky: At this point we've raised an error but we want the
17868     // rest of the compiler to continue somehow working. However almost
17869     // everything we'll try to do with the class will depend on there being a
17870     // destructor. So let's pretend the first one is selected and hope for the
17871     // best.
17872     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17873   }
17874 }
17875 } // namespace
17876 
17877 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17878                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17879                        SourceLocation RBrac,
17880                        const ParsedAttributesView &Attrs) {
17881   assert(EnclosingDecl && "missing record or interface decl");
17882 
17883   // If this is an Objective-C @implementation or category and we have
17884   // new fields here we should reset the layout of the interface since
17885   // it will now change.
17886   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17887     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17888     switch (DC->getKind()) {
17889     default: break;
17890     case Decl::ObjCCategory:
17891       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17892       break;
17893     case Decl::ObjCImplementation:
17894       Context.
17895         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17896       break;
17897     }
17898   }
17899 
17900   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17901   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17902 
17903   if (CXXRecord && !CXXRecord->isDependentType())
17904     ComputeSelectedDestructor(*this, CXXRecord);
17905 
17906   // Start counting up the number of named members; make sure to include
17907   // members of anonymous structs and unions in the total.
17908   unsigned NumNamedMembers = 0;
17909   if (Record) {
17910     for (const auto *I : Record->decls()) {
17911       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17912         if (IFD->getDeclName())
17913           ++NumNamedMembers;
17914     }
17915   }
17916 
17917   // Verify that all the fields are okay.
17918   SmallVector<FieldDecl*, 32> RecFields;
17919 
17920   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17921        i != end; ++i) {
17922     FieldDecl *FD = cast<FieldDecl>(*i);
17923 
17924     // Get the type for the field.
17925     const Type *FDTy = FD->getType().getTypePtr();
17926 
17927     if (!FD->isAnonymousStructOrUnion()) {
17928       // Remember all fields written by the user.
17929       RecFields.push_back(FD);
17930     }
17931 
17932     // If the field is already invalid for some reason, don't emit more
17933     // diagnostics about it.
17934     if (FD->isInvalidDecl()) {
17935       EnclosingDecl->setInvalidDecl();
17936       continue;
17937     }
17938 
17939     // C99 6.7.2.1p2:
17940     //   A structure or union shall not contain a member with
17941     //   incomplete or function type (hence, a structure shall not
17942     //   contain an instance of itself, but may contain a pointer to
17943     //   an instance of itself), except that the last member of a
17944     //   structure with more than one named member may have incomplete
17945     //   array type; such a structure (and any union containing,
17946     //   possibly recursively, a member that is such a structure)
17947     //   shall not be a member of a structure or an element of an
17948     //   array.
17949     bool IsLastField = (i + 1 == Fields.end());
17950     if (FDTy->isFunctionType()) {
17951       // Field declared as a function.
17952       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17953         << FD->getDeclName();
17954       FD->setInvalidDecl();
17955       EnclosingDecl->setInvalidDecl();
17956       continue;
17957     } else if (FDTy->isIncompleteArrayType() &&
17958                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17959       if (Record) {
17960         // Flexible array member.
17961         // Microsoft and g++ is more permissive regarding flexible array.
17962         // It will accept flexible array in union and also
17963         // as the sole element of a struct/class.
17964         unsigned DiagID = 0;
17965         if (!Record->isUnion() && !IsLastField) {
17966           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17967             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17968           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17969           FD->setInvalidDecl();
17970           EnclosingDecl->setInvalidDecl();
17971           continue;
17972         } else if (Record->isUnion())
17973           DiagID = getLangOpts().MicrosoftExt
17974                        ? diag::ext_flexible_array_union_ms
17975                        : getLangOpts().CPlusPlus
17976                              ? diag::ext_flexible_array_union_gnu
17977                              : diag::err_flexible_array_union;
17978         else if (NumNamedMembers < 1)
17979           DiagID = getLangOpts().MicrosoftExt
17980                        ? diag::ext_flexible_array_empty_aggregate_ms
17981                        : getLangOpts().CPlusPlus
17982                              ? diag::ext_flexible_array_empty_aggregate_gnu
17983                              : diag::err_flexible_array_empty_aggregate;
17984 
17985         if (DiagID)
17986           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17987                                           << Record->getTagKind();
17988         // While the layout of types that contain virtual bases is not specified
17989         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17990         // virtual bases after the derived members.  This would make a flexible
17991         // array member declared at the end of an object not adjacent to the end
17992         // of the type.
17993         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17994           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17995               << FD->getDeclName() << Record->getTagKind();
17996         if (!getLangOpts().C99)
17997           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17998             << FD->getDeclName() << Record->getTagKind();
17999 
18000         // If the element type has a non-trivial destructor, we would not
18001         // implicitly destroy the elements, so disallow it for now.
18002         //
18003         // FIXME: GCC allows this. We should probably either implicitly delete
18004         // the destructor of the containing class, or just allow this.
18005         QualType BaseElem = Context.getBaseElementType(FD->getType());
18006         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18007           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18008             << FD->getDeclName() << FD->getType();
18009           FD->setInvalidDecl();
18010           EnclosingDecl->setInvalidDecl();
18011           continue;
18012         }
18013         // Okay, we have a legal flexible array member at the end of the struct.
18014         Record->setHasFlexibleArrayMember(true);
18015       } else {
18016         // In ObjCContainerDecl ivars with incomplete array type are accepted,
18017         // unless they are followed by another ivar. That check is done
18018         // elsewhere, after synthesized ivars are known.
18019       }
18020     } else if (!FDTy->isDependentType() &&
18021                RequireCompleteSizedType(
18022                    FD->getLocation(), FD->getType(),
18023                    diag::err_field_incomplete_or_sizeless)) {
18024       // Incomplete type
18025       FD->setInvalidDecl();
18026       EnclosingDecl->setInvalidDecl();
18027       continue;
18028     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18029       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18030         // A type which contains a flexible array member is considered to be a
18031         // flexible array member.
18032         Record->setHasFlexibleArrayMember(true);
18033         if (!Record->isUnion()) {
18034           // If this is a struct/class and this is not the last element, reject
18035           // it.  Note that GCC supports variable sized arrays in the middle of
18036           // structures.
18037           if (!IsLastField)
18038             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18039               << FD->getDeclName() << FD->getType();
18040           else {
18041             // We support flexible arrays at the end of structs in
18042             // other structs as an extension.
18043             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18044               << FD->getDeclName();
18045           }
18046         }
18047       }
18048       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18049           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18050                                  diag::err_abstract_type_in_decl,
18051                                  AbstractIvarType)) {
18052         // Ivars can not have abstract class types
18053         FD->setInvalidDecl();
18054       }
18055       if (Record && FDTTy->getDecl()->hasObjectMember())
18056         Record->setHasObjectMember(true);
18057       if (Record && FDTTy->getDecl()->hasVolatileMember())
18058         Record->setHasVolatileMember(true);
18059     } else if (FDTy->isObjCObjectType()) {
18060       /// A field cannot be an Objective-c object
18061       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18062         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18063       QualType T = Context.getObjCObjectPointerType(FD->getType());
18064       FD->setType(T);
18065     } else if (Record && Record->isUnion() &&
18066                FD->getType().hasNonTrivialObjCLifetime() &&
18067                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18068                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18069                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18070                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18071       // For backward compatibility, fields of C unions declared in system
18072       // headers that have non-trivial ObjC ownership qualifications are marked
18073       // as unavailable unless the qualifier is explicit and __strong. This can
18074       // break ABI compatibility between programs compiled with ARC and MRR, but
18075       // is a better option than rejecting programs using those unions under
18076       // ARC.
18077       FD->addAttr(UnavailableAttr::CreateImplicit(
18078           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18079           FD->getLocation()));
18080     } else if (getLangOpts().ObjC &&
18081                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18082                !Record->hasObjectMember()) {
18083       if (FD->getType()->isObjCObjectPointerType() ||
18084           FD->getType().isObjCGCStrong())
18085         Record->setHasObjectMember(true);
18086       else if (Context.getAsArrayType(FD->getType())) {
18087         QualType BaseType = Context.getBaseElementType(FD->getType());
18088         if (BaseType->isRecordType() &&
18089             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18090           Record->setHasObjectMember(true);
18091         else if (BaseType->isObjCObjectPointerType() ||
18092                  BaseType.isObjCGCStrong())
18093                Record->setHasObjectMember(true);
18094       }
18095     }
18096 
18097     if (Record && !getLangOpts().CPlusPlus &&
18098         !shouldIgnoreForRecordTriviality(FD)) {
18099       QualType FT = FD->getType();
18100       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18101         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18102         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18103             Record->isUnion())
18104           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18105       }
18106       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18107       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18108         Record->setNonTrivialToPrimitiveCopy(true);
18109         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18110           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18111       }
18112       if (FT.isDestructedType()) {
18113         Record->setNonTrivialToPrimitiveDestroy(true);
18114         Record->setParamDestroyedInCallee(true);
18115         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18116           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18117       }
18118 
18119       if (const auto *RT = FT->getAs<RecordType>()) {
18120         if (RT->getDecl()->getArgPassingRestrictions() ==
18121             RecordDecl::APK_CanNeverPassInRegs)
18122           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18123       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18124         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18125     }
18126 
18127     if (Record && FD->getType().isVolatileQualified())
18128       Record->setHasVolatileMember(true);
18129     // Keep track of the number of named members.
18130     if (FD->getIdentifier())
18131       ++NumNamedMembers;
18132   }
18133 
18134   // Okay, we successfully defined 'Record'.
18135   if (Record) {
18136     bool Completed = false;
18137     if (CXXRecord) {
18138       if (!CXXRecord->isInvalidDecl()) {
18139         // Set access bits correctly on the directly-declared conversions.
18140         for (CXXRecordDecl::conversion_iterator
18141                I = CXXRecord->conversion_begin(),
18142                E = CXXRecord->conversion_end(); I != E; ++I)
18143           I.setAccess((*I)->getAccess());
18144       }
18145 
18146       // Add any implicitly-declared members to this class.
18147       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18148 
18149       if (!CXXRecord->isDependentType()) {
18150         if (!CXXRecord->isInvalidDecl()) {
18151           // If we have virtual base classes, we may end up finding multiple
18152           // final overriders for a given virtual function. Check for this
18153           // problem now.
18154           if (CXXRecord->getNumVBases()) {
18155             CXXFinalOverriderMap FinalOverriders;
18156             CXXRecord->getFinalOverriders(FinalOverriders);
18157 
18158             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18159                                              MEnd = FinalOverriders.end();
18160                  M != MEnd; ++M) {
18161               for (OverridingMethods::iterator SO = M->second.begin(),
18162                                             SOEnd = M->second.end();
18163                    SO != SOEnd; ++SO) {
18164                 assert(SO->second.size() > 0 &&
18165                        "Virtual function without overriding functions?");
18166                 if (SO->second.size() == 1)
18167                   continue;
18168 
18169                 // C++ [class.virtual]p2:
18170                 //   In a derived class, if a virtual member function of a base
18171                 //   class subobject has more than one final overrider the
18172                 //   program is ill-formed.
18173                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18174                   << (const NamedDecl *)M->first << Record;
18175                 Diag(M->first->getLocation(),
18176                      diag::note_overridden_virtual_function);
18177                 for (OverridingMethods::overriding_iterator
18178                           OM = SO->second.begin(),
18179                        OMEnd = SO->second.end();
18180                      OM != OMEnd; ++OM)
18181                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18182                     << (const NamedDecl *)M->first << OM->Method->getParent();
18183 
18184                 Record->setInvalidDecl();
18185               }
18186             }
18187             CXXRecord->completeDefinition(&FinalOverriders);
18188             Completed = true;
18189           }
18190         }
18191       }
18192     }
18193 
18194     if (!Completed)
18195       Record->completeDefinition();
18196 
18197     // Handle attributes before checking the layout.
18198     ProcessDeclAttributeList(S, Record, Attrs);
18199 
18200     // Check to see if a FieldDecl is a pointer to a function.
18201     auto IsFunctionPointer = [&](const Decl *D) {
18202       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18203       if (!FD)
18204         return false;
18205       QualType FieldType = FD->getType().getDesugaredType(Context);
18206       if (isa<PointerType>(FieldType)) {
18207         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18208         return PointeeType.getDesugaredType(Context)->isFunctionType();
18209       }
18210       return false;
18211     };
18212 
18213     // Maybe randomize the record's decls. We automatically randomize a record
18214     // of function pointers, unless it has the "no_randomize_layout" attribute.
18215     if (!getLangOpts().CPlusPlus &&
18216         (Record->hasAttr<RandomizeLayoutAttr>() ||
18217          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18218           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18219         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18220         !Record->isRandomized()) {
18221       SmallVector<Decl *, 32> NewDeclOrdering;
18222       if (randstruct::randomizeStructureLayout(Context, Record,
18223                                                NewDeclOrdering))
18224         Record->reorderDecls(NewDeclOrdering);
18225     }
18226 
18227     // We may have deferred checking for a deleted destructor. Check now.
18228     if (CXXRecord) {
18229       auto *Dtor = CXXRecord->getDestructor();
18230       if (Dtor && Dtor->isImplicit() &&
18231           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18232         CXXRecord->setImplicitDestructorIsDeleted();
18233         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18234       }
18235     }
18236 
18237     if (Record->hasAttrs()) {
18238       CheckAlignasUnderalignment(Record);
18239 
18240       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18241         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18242                                            IA->getRange(), IA->getBestCase(),
18243                                            IA->getInheritanceModel());
18244     }
18245 
18246     // Check if the structure/union declaration is a type that can have zero
18247     // size in C. For C this is a language extension, for C++ it may cause
18248     // compatibility problems.
18249     bool CheckForZeroSize;
18250     if (!getLangOpts().CPlusPlus) {
18251       CheckForZeroSize = true;
18252     } else {
18253       // For C++ filter out types that cannot be referenced in C code.
18254       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18255       CheckForZeroSize =
18256           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18257           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18258           CXXRecord->isCLike();
18259     }
18260     if (CheckForZeroSize) {
18261       bool ZeroSize = true;
18262       bool IsEmpty = true;
18263       unsigned NonBitFields = 0;
18264       for (RecordDecl::field_iterator I = Record->field_begin(),
18265                                       E = Record->field_end();
18266            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18267         IsEmpty = false;
18268         if (I->isUnnamedBitfield()) {
18269           if (!I->isZeroLengthBitField(Context))
18270             ZeroSize = false;
18271         } else {
18272           ++NonBitFields;
18273           QualType FieldType = I->getType();
18274           if (FieldType->isIncompleteType() ||
18275               !Context.getTypeSizeInChars(FieldType).isZero())
18276             ZeroSize = false;
18277         }
18278       }
18279 
18280       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18281       // allowed in C++, but warn if its declaration is inside
18282       // extern "C" block.
18283       if (ZeroSize) {
18284         Diag(RecLoc, getLangOpts().CPlusPlus ?
18285                          diag::warn_zero_size_struct_union_in_extern_c :
18286                          diag::warn_zero_size_struct_union_compat)
18287           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18288       }
18289 
18290       // Structs without named members are extension in C (C99 6.7.2.1p7),
18291       // but are accepted by GCC.
18292       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18293         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18294                                diag::ext_no_named_members_in_struct_union)
18295           << Record->isUnion();
18296       }
18297     }
18298   } else {
18299     ObjCIvarDecl **ClsFields =
18300       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18301     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18302       ID->setEndOfDefinitionLoc(RBrac);
18303       // Add ivar's to class's DeclContext.
18304       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18305         ClsFields[i]->setLexicalDeclContext(ID);
18306         ID->addDecl(ClsFields[i]);
18307       }
18308       // Must enforce the rule that ivars in the base classes may not be
18309       // duplicates.
18310       if (ID->getSuperClass())
18311         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18312     } else if (ObjCImplementationDecl *IMPDecl =
18313                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18314       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18315       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18316         // Ivar declared in @implementation never belongs to the implementation.
18317         // Only it is in implementation's lexical context.
18318         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18319       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18320       IMPDecl->setIvarLBraceLoc(LBrac);
18321       IMPDecl->setIvarRBraceLoc(RBrac);
18322     } else if (ObjCCategoryDecl *CDecl =
18323                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18324       // case of ivars in class extension; all other cases have been
18325       // reported as errors elsewhere.
18326       // FIXME. Class extension does not have a LocEnd field.
18327       // CDecl->setLocEnd(RBrac);
18328       // Add ivar's to class extension's DeclContext.
18329       // Diagnose redeclaration of private ivars.
18330       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18331       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18332         if (IDecl) {
18333           if (const ObjCIvarDecl *ClsIvar =
18334               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18335             Diag(ClsFields[i]->getLocation(),
18336                  diag::err_duplicate_ivar_declaration);
18337             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18338             continue;
18339           }
18340           for (const auto *Ext : IDecl->known_extensions()) {
18341             if (const ObjCIvarDecl *ClsExtIvar
18342                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18343               Diag(ClsFields[i]->getLocation(),
18344                    diag::err_duplicate_ivar_declaration);
18345               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18346               continue;
18347             }
18348           }
18349         }
18350         ClsFields[i]->setLexicalDeclContext(CDecl);
18351         CDecl->addDecl(ClsFields[i]);
18352       }
18353       CDecl->setIvarLBraceLoc(LBrac);
18354       CDecl->setIvarRBraceLoc(RBrac);
18355     }
18356   }
18357 }
18358 
18359 /// Determine whether the given integral value is representable within
18360 /// the given type T.
18361 static bool isRepresentableIntegerValue(ASTContext &Context,
18362                                         llvm::APSInt &Value,
18363                                         QualType T) {
18364   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18365          "Integral type required!");
18366   unsigned BitWidth = Context.getIntWidth(T);
18367 
18368   if (Value.isUnsigned() || Value.isNonNegative()) {
18369     if (T->isSignedIntegerOrEnumerationType())
18370       --BitWidth;
18371     return Value.getActiveBits() <= BitWidth;
18372   }
18373   return Value.getMinSignedBits() <= BitWidth;
18374 }
18375 
18376 // Given an integral type, return the next larger integral type
18377 // (or a NULL type of no such type exists).
18378 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18379   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18380   // enum checking below.
18381   assert((T->isIntegralType(Context) ||
18382          T->isEnumeralType()) && "Integral type required!");
18383   const unsigned NumTypes = 4;
18384   QualType SignedIntegralTypes[NumTypes] = {
18385     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18386   };
18387   QualType UnsignedIntegralTypes[NumTypes] = {
18388     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18389     Context.UnsignedLongLongTy
18390   };
18391 
18392   unsigned BitWidth = Context.getTypeSize(T);
18393   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18394                                                         : UnsignedIntegralTypes;
18395   for (unsigned I = 0; I != NumTypes; ++I)
18396     if (Context.getTypeSize(Types[I]) > BitWidth)
18397       return Types[I];
18398 
18399   return QualType();
18400 }
18401 
18402 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18403                                           EnumConstantDecl *LastEnumConst,
18404                                           SourceLocation IdLoc,
18405                                           IdentifierInfo *Id,
18406                                           Expr *Val) {
18407   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18408   llvm::APSInt EnumVal(IntWidth);
18409   QualType EltTy;
18410 
18411   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18412     Val = nullptr;
18413 
18414   if (Val)
18415     Val = DefaultLvalueConversion(Val).get();
18416 
18417   if (Val) {
18418     if (Enum->isDependentType() || Val->isTypeDependent() ||
18419         Val->containsErrors())
18420       EltTy = Context.DependentTy;
18421     else {
18422       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18423       // underlying type, but do allow it in all other contexts.
18424       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18425         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18426         // constant-expression in the enumerator-definition shall be a converted
18427         // constant expression of the underlying type.
18428         EltTy = Enum->getIntegerType();
18429         ExprResult Converted =
18430           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18431                                            CCEK_Enumerator);
18432         if (Converted.isInvalid())
18433           Val = nullptr;
18434         else
18435           Val = Converted.get();
18436       } else if (!Val->isValueDependent() &&
18437                  !(Val =
18438                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18439                            .get())) {
18440         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18441       } else {
18442         if (Enum->isComplete()) {
18443           EltTy = Enum->getIntegerType();
18444 
18445           // In Obj-C and Microsoft mode, require the enumeration value to be
18446           // representable in the underlying type of the enumeration. In C++11,
18447           // we perform a non-narrowing conversion as part of converted constant
18448           // expression checking.
18449           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18450             if (Context.getTargetInfo()
18451                     .getTriple()
18452                     .isWindowsMSVCEnvironment()) {
18453               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18454             } else {
18455               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18456             }
18457           }
18458 
18459           // Cast to the underlying type.
18460           Val = ImpCastExprToType(Val, EltTy,
18461                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18462                                                          : CK_IntegralCast)
18463                     .get();
18464         } else if (getLangOpts().CPlusPlus) {
18465           // C++11 [dcl.enum]p5:
18466           //   If the underlying type is not fixed, the type of each enumerator
18467           //   is the type of its initializing value:
18468           //     - If an initializer is specified for an enumerator, the
18469           //       initializing value has the same type as the expression.
18470           EltTy = Val->getType();
18471         } else {
18472           // C99 6.7.2.2p2:
18473           //   The expression that defines the value of an enumeration constant
18474           //   shall be an integer constant expression that has a value
18475           //   representable as an int.
18476 
18477           // Complain if the value is not representable in an int.
18478           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18479             Diag(IdLoc, diag::ext_enum_value_not_int)
18480               << toString(EnumVal, 10) << Val->getSourceRange()
18481               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18482           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18483             // Force the type of the expression to 'int'.
18484             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18485           }
18486           EltTy = Val->getType();
18487         }
18488       }
18489     }
18490   }
18491 
18492   if (!Val) {
18493     if (Enum->isDependentType())
18494       EltTy = Context.DependentTy;
18495     else if (!LastEnumConst) {
18496       // C++0x [dcl.enum]p5:
18497       //   If the underlying type is not fixed, the type of each enumerator
18498       //   is the type of its initializing value:
18499       //     - If no initializer is specified for the first enumerator, the
18500       //       initializing value has an unspecified integral type.
18501       //
18502       // GCC uses 'int' for its unspecified integral type, as does
18503       // C99 6.7.2.2p3.
18504       if (Enum->isFixed()) {
18505         EltTy = Enum->getIntegerType();
18506       }
18507       else {
18508         EltTy = Context.IntTy;
18509       }
18510     } else {
18511       // Assign the last value + 1.
18512       EnumVal = LastEnumConst->getInitVal();
18513       ++EnumVal;
18514       EltTy = LastEnumConst->getType();
18515 
18516       // Check for overflow on increment.
18517       if (EnumVal < LastEnumConst->getInitVal()) {
18518         // C++0x [dcl.enum]p5:
18519         //   If the underlying type is not fixed, the type of each enumerator
18520         //   is the type of its initializing value:
18521         //
18522         //     - Otherwise the type of the initializing value is the same as
18523         //       the type of the initializing value of the preceding enumerator
18524         //       unless the incremented value is not representable in that type,
18525         //       in which case the type is an unspecified integral type
18526         //       sufficient to contain the incremented value. If no such type
18527         //       exists, the program is ill-formed.
18528         QualType T = getNextLargerIntegralType(Context, EltTy);
18529         if (T.isNull() || Enum->isFixed()) {
18530           // There is no integral type larger enough to represent this
18531           // value. Complain, then allow the value to wrap around.
18532           EnumVal = LastEnumConst->getInitVal();
18533           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18534           ++EnumVal;
18535           if (Enum->isFixed())
18536             // When the underlying type is fixed, this is ill-formed.
18537             Diag(IdLoc, diag::err_enumerator_wrapped)
18538               << toString(EnumVal, 10)
18539               << EltTy;
18540           else
18541             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18542               << toString(EnumVal, 10);
18543         } else {
18544           EltTy = T;
18545         }
18546 
18547         // Retrieve the last enumerator's value, extent that type to the
18548         // type that is supposed to be large enough to represent the incremented
18549         // value, then increment.
18550         EnumVal = LastEnumConst->getInitVal();
18551         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18552         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18553         ++EnumVal;
18554 
18555         // If we're not in C++, diagnose the overflow of enumerator values,
18556         // which in C99 means that the enumerator value is not representable in
18557         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18558         // permits enumerator values that are representable in some larger
18559         // integral type.
18560         if (!getLangOpts().CPlusPlus && !T.isNull())
18561           Diag(IdLoc, diag::warn_enum_value_overflow);
18562       } else if (!getLangOpts().CPlusPlus &&
18563                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18564         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18565         Diag(IdLoc, diag::ext_enum_value_not_int)
18566           << toString(EnumVal, 10) << 1;
18567       }
18568     }
18569   }
18570 
18571   if (!EltTy->isDependentType()) {
18572     // Make the enumerator value match the signedness and size of the
18573     // enumerator's type.
18574     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18575     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18576   }
18577 
18578   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18579                                   Val, EnumVal);
18580 }
18581 
18582 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18583                                                 SourceLocation IILoc) {
18584   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18585       !getLangOpts().CPlusPlus)
18586     return SkipBodyInfo();
18587 
18588   // We have an anonymous enum definition. Look up the first enumerator to
18589   // determine if we should merge the definition with an existing one and
18590   // skip the body.
18591   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18592                                          forRedeclarationInCurContext());
18593   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18594   if (!PrevECD)
18595     return SkipBodyInfo();
18596 
18597   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18598   NamedDecl *Hidden;
18599   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18600     SkipBodyInfo Skip;
18601     Skip.Previous = Hidden;
18602     return Skip;
18603   }
18604 
18605   return SkipBodyInfo();
18606 }
18607 
18608 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18609                               SourceLocation IdLoc, IdentifierInfo *Id,
18610                               const ParsedAttributesView &Attrs,
18611                               SourceLocation EqualLoc, Expr *Val) {
18612   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18613   EnumConstantDecl *LastEnumConst =
18614     cast_or_null<EnumConstantDecl>(lastEnumConst);
18615 
18616   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18617   // we find one that is.
18618   S = getNonFieldDeclScope(S);
18619 
18620   // Verify that there isn't already something declared with this name in this
18621   // scope.
18622   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18623   LookupName(R, S);
18624   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18625 
18626   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18627     // Maybe we will complain about the shadowed template parameter.
18628     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18629     // Just pretend that we didn't see the previous declaration.
18630     PrevDecl = nullptr;
18631   }
18632 
18633   // C++ [class.mem]p15:
18634   // If T is the name of a class, then each of the following shall have a name
18635   // different from T:
18636   // - every enumerator of every member of class T that is an unscoped
18637   // enumerated type
18638   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18639     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18640                             DeclarationNameInfo(Id, IdLoc));
18641 
18642   EnumConstantDecl *New =
18643     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18644   if (!New)
18645     return nullptr;
18646 
18647   if (PrevDecl) {
18648     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18649       // Check for other kinds of shadowing not already handled.
18650       CheckShadow(New, PrevDecl, R);
18651     }
18652 
18653     // When in C++, we may get a TagDecl with the same name; in this case the
18654     // enum constant will 'hide' the tag.
18655     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18656            "Received TagDecl when not in C++!");
18657     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18658       if (isa<EnumConstantDecl>(PrevDecl))
18659         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18660       else
18661         Diag(IdLoc, diag::err_redefinition) << Id;
18662       notePreviousDefinition(PrevDecl, IdLoc);
18663       return nullptr;
18664     }
18665   }
18666 
18667   // Process attributes.
18668   ProcessDeclAttributeList(S, New, Attrs);
18669   AddPragmaAttributes(S, New);
18670 
18671   // Register this decl in the current scope stack.
18672   New->setAccess(TheEnumDecl->getAccess());
18673   PushOnScopeChains(New, S);
18674 
18675   ActOnDocumentableDecl(New);
18676 
18677   return New;
18678 }
18679 
18680 // Returns true when the enum initial expression does not trigger the
18681 // duplicate enum warning.  A few common cases are exempted as follows:
18682 // Element2 = Element1
18683 // Element2 = Element1 + 1
18684 // Element2 = Element1 - 1
18685 // Where Element2 and Element1 are from the same enum.
18686 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18687   Expr *InitExpr = ECD->getInitExpr();
18688   if (!InitExpr)
18689     return true;
18690   InitExpr = InitExpr->IgnoreImpCasts();
18691 
18692   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18693     if (!BO->isAdditiveOp())
18694       return true;
18695     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18696     if (!IL)
18697       return true;
18698     if (IL->getValue() != 1)
18699       return true;
18700 
18701     InitExpr = BO->getLHS();
18702   }
18703 
18704   // This checks if the elements are from the same enum.
18705   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18706   if (!DRE)
18707     return true;
18708 
18709   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18710   if (!EnumConstant)
18711     return true;
18712 
18713   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18714       Enum)
18715     return true;
18716 
18717   return false;
18718 }
18719 
18720 // Emits a warning when an element is implicitly set a value that
18721 // a previous element has already been set to.
18722 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18723                                         EnumDecl *Enum, QualType EnumType) {
18724   // Avoid anonymous enums
18725   if (!Enum->getIdentifier())
18726     return;
18727 
18728   // Only check for small enums.
18729   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18730     return;
18731 
18732   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18733     return;
18734 
18735   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18736   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18737 
18738   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18739 
18740   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18741   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18742 
18743   // Use int64_t as a key to avoid needing special handling for map keys.
18744   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18745     llvm::APSInt Val = D->getInitVal();
18746     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18747   };
18748 
18749   DuplicatesVector DupVector;
18750   ValueToVectorMap EnumMap;
18751 
18752   // Populate the EnumMap with all values represented by enum constants without
18753   // an initializer.
18754   for (auto *Element : Elements) {
18755     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18756 
18757     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18758     // this constant.  Skip this enum since it may be ill-formed.
18759     if (!ECD) {
18760       return;
18761     }
18762 
18763     // Constants with initalizers are handled in the next loop.
18764     if (ECD->getInitExpr())
18765       continue;
18766 
18767     // Duplicate values are handled in the next loop.
18768     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18769   }
18770 
18771   if (EnumMap.size() == 0)
18772     return;
18773 
18774   // Create vectors for any values that has duplicates.
18775   for (auto *Element : Elements) {
18776     // The last loop returned if any constant was null.
18777     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18778     if (!ValidDuplicateEnum(ECD, Enum))
18779       continue;
18780 
18781     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18782     if (Iter == EnumMap.end())
18783       continue;
18784 
18785     DeclOrVector& Entry = Iter->second;
18786     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18787       // Ensure constants are different.
18788       if (D == ECD)
18789         continue;
18790 
18791       // Create new vector and push values onto it.
18792       auto Vec = std::make_unique<ECDVector>();
18793       Vec->push_back(D);
18794       Vec->push_back(ECD);
18795 
18796       // Update entry to point to the duplicates vector.
18797       Entry = Vec.get();
18798 
18799       // Store the vector somewhere we can consult later for quick emission of
18800       // diagnostics.
18801       DupVector.emplace_back(std::move(Vec));
18802       continue;
18803     }
18804 
18805     ECDVector *Vec = Entry.get<ECDVector*>();
18806     // Make sure constants are not added more than once.
18807     if (*Vec->begin() == ECD)
18808       continue;
18809 
18810     Vec->push_back(ECD);
18811   }
18812 
18813   // Emit diagnostics.
18814   for (const auto &Vec : DupVector) {
18815     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18816 
18817     // Emit warning for one enum constant.
18818     auto *FirstECD = Vec->front();
18819     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18820       << FirstECD << toString(FirstECD->getInitVal(), 10)
18821       << FirstECD->getSourceRange();
18822 
18823     // Emit one note for each of the remaining enum constants with
18824     // the same value.
18825     for (auto *ECD : llvm::drop_begin(*Vec))
18826       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18827         << ECD << toString(ECD->getInitVal(), 10)
18828         << ECD->getSourceRange();
18829   }
18830 }
18831 
18832 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18833                              bool AllowMask) const {
18834   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18835   assert(ED->isCompleteDefinition() && "expected enum definition");
18836 
18837   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18838   llvm::APInt &FlagBits = R.first->second;
18839 
18840   if (R.second) {
18841     for (auto *E : ED->enumerators()) {
18842       const auto &EVal = E->getInitVal();
18843       // Only single-bit enumerators introduce new flag values.
18844       if (EVal.isPowerOf2())
18845         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18846     }
18847   }
18848 
18849   // A value is in a flag enum if either its bits are a subset of the enum's
18850   // flag bits (the first condition) or we are allowing masks and the same is
18851   // true of its complement (the second condition). When masks are allowed, we
18852   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18853   //
18854   // While it's true that any value could be used as a mask, the assumption is
18855   // that a mask will have all of the insignificant bits set. Anything else is
18856   // likely a logic error.
18857   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18858   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18859 }
18860 
18861 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18862                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18863                          const ParsedAttributesView &Attrs) {
18864   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18865   QualType EnumType = Context.getTypeDeclType(Enum);
18866 
18867   ProcessDeclAttributeList(S, Enum, Attrs);
18868 
18869   if (Enum->isDependentType()) {
18870     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18871       EnumConstantDecl *ECD =
18872         cast_or_null<EnumConstantDecl>(Elements[i]);
18873       if (!ECD) continue;
18874 
18875       ECD->setType(EnumType);
18876     }
18877 
18878     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18879     return;
18880   }
18881 
18882   // TODO: If the result value doesn't fit in an int, it must be a long or long
18883   // long value.  ISO C does not support this, but GCC does as an extension,
18884   // emit a warning.
18885   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18886   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18887   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18888 
18889   // Verify that all the values are okay, compute the size of the values, and
18890   // reverse the list.
18891   unsigned NumNegativeBits = 0;
18892   unsigned NumPositiveBits = 0;
18893 
18894   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18895     EnumConstantDecl *ECD =
18896       cast_or_null<EnumConstantDecl>(Elements[i]);
18897     if (!ECD) continue;  // Already issued a diagnostic.
18898 
18899     const llvm::APSInt &InitVal = ECD->getInitVal();
18900 
18901     // Keep track of the size of positive and negative values.
18902     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18903       NumPositiveBits = std::max(NumPositiveBits,
18904                                  (unsigned)InitVal.getActiveBits());
18905     else
18906       NumNegativeBits = std::max(NumNegativeBits,
18907                                  (unsigned)InitVal.getMinSignedBits());
18908   }
18909 
18910   // Figure out the type that should be used for this enum.
18911   QualType BestType;
18912   unsigned BestWidth;
18913 
18914   // C++0x N3000 [conv.prom]p3:
18915   //   An rvalue of an unscoped enumeration type whose underlying
18916   //   type is not fixed can be converted to an rvalue of the first
18917   //   of the following types that can represent all the values of
18918   //   the enumeration: int, unsigned int, long int, unsigned long
18919   //   int, long long int, or unsigned long long int.
18920   // C99 6.4.4.3p2:
18921   //   An identifier declared as an enumeration constant has type int.
18922   // The C99 rule is modified by a gcc extension
18923   QualType BestPromotionType;
18924 
18925   bool Packed = Enum->hasAttr<PackedAttr>();
18926   // -fshort-enums is the equivalent to specifying the packed attribute on all
18927   // enum definitions.
18928   if (LangOpts.ShortEnums)
18929     Packed = true;
18930 
18931   // If the enum already has a type because it is fixed or dictated by the
18932   // target, promote that type instead of analyzing the enumerators.
18933   if (Enum->isComplete()) {
18934     BestType = Enum->getIntegerType();
18935     if (BestType->isPromotableIntegerType())
18936       BestPromotionType = Context.getPromotedIntegerType(BestType);
18937     else
18938       BestPromotionType = BestType;
18939 
18940     BestWidth = Context.getIntWidth(BestType);
18941   }
18942   else if (NumNegativeBits) {
18943     // If there is a negative value, figure out the smallest integer type (of
18944     // int/long/longlong) that fits.
18945     // If it's packed, check also if it fits a char or a short.
18946     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18947       BestType = Context.SignedCharTy;
18948       BestWidth = CharWidth;
18949     } else if (Packed && NumNegativeBits <= ShortWidth &&
18950                NumPositiveBits < ShortWidth) {
18951       BestType = Context.ShortTy;
18952       BestWidth = ShortWidth;
18953     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18954       BestType = Context.IntTy;
18955       BestWidth = IntWidth;
18956     } else {
18957       BestWidth = Context.getTargetInfo().getLongWidth();
18958 
18959       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18960         BestType = Context.LongTy;
18961       } else {
18962         BestWidth = Context.getTargetInfo().getLongLongWidth();
18963 
18964         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18965           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18966         BestType = Context.LongLongTy;
18967       }
18968     }
18969     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18970   } else {
18971     // If there is no negative value, figure out the smallest type that fits
18972     // all of the enumerator values.
18973     // If it's packed, check also if it fits a char or a short.
18974     if (Packed && NumPositiveBits <= CharWidth) {
18975       BestType = Context.UnsignedCharTy;
18976       BestPromotionType = Context.IntTy;
18977       BestWidth = CharWidth;
18978     } else if (Packed && NumPositiveBits <= ShortWidth) {
18979       BestType = Context.UnsignedShortTy;
18980       BestPromotionType = Context.IntTy;
18981       BestWidth = ShortWidth;
18982     } else if (NumPositiveBits <= IntWidth) {
18983       BestType = Context.UnsignedIntTy;
18984       BestWidth = IntWidth;
18985       BestPromotionType
18986         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18987                            ? Context.UnsignedIntTy : Context.IntTy;
18988     } else if (NumPositiveBits <=
18989                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18990       BestType = Context.UnsignedLongTy;
18991       BestPromotionType
18992         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18993                            ? Context.UnsignedLongTy : Context.LongTy;
18994     } else {
18995       BestWidth = Context.getTargetInfo().getLongLongWidth();
18996       assert(NumPositiveBits <= BestWidth &&
18997              "How could an initializer get larger than ULL?");
18998       BestType = Context.UnsignedLongLongTy;
18999       BestPromotionType
19000         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19001                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
19002     }
19003   }
19004 
19005   // Loop over all of the enumerator constants, changing their types to match
19006   // the type of the enum if needed.
19007   for (auto *D : Elements) {
19008     auto *ECD = cast_or_null<EnumConstantDecl>(D);
19009     if (!ECD) continue;  // Already issued a diagnostic.
19010 
19011     // Standard C says the enumerators have int type, but we allow, as an
19012     // extension, the enumerators to be larger than int size.  If each
19013     // enumerator value fits in an int, type it as an int, otherwise type it the
19014     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
19015     // that X has type 'int', not 'unsigned'.
19016 
19017     // Determine whether the value fits into an int.
19018     llvm::APSInt InitVal = ECD->getInitVal();
19019 
19020     // If it fits into an integer type, force it.  Otherwise force it to match
19021     // the enum decl type.
19022     QualType NewTy;
19023     unsigned NewWidth;
19024     bool NewSign;
19025     if (!getLangOpts().CPlusPlus &&
19026         !Enum->isFixed() &&
19027         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19028       NewTy = Context.IntTy;
19029       NewWidth = IntWidth;
19030       NewSign = true;
19031     } else if (ECD->getType() == BestType) {
19032       // Already the right type!
19033       if (getLangOpts().CPlusPlus)
19034         // C++ [dcl.enum]p4: Following the closing brace of an
19035         // enum-specifier, each enumerator has the type of its
19036         // enumeration.
19037         ECD->setType(EnumType);
19038       continue;
19039     } else {
19040       NewTy = BestType;
19041       NewWidth = BestWidth;
19042       NewSign = BestType->isSignedIntegerOrEnumerationType();
19043     }
19044 
19045     // Adjust the APSInt value.
19046     InitVal = InitVal.extOrTrunc(NewWidth);
19047     InitVal.setIsSigned(NewSign);
19048     ECD->setInitVal(InitVal);
19049 
19050     // Adjust the Expr initializer and type.
19051     if (ECD->getInitExpr() &&
19052         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19053       ECD->setInitExpr(ImplicitCastExpr::Create(
19054           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19055           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19056     if (getLangOpts().CPlusPlus)
19057       // C++ [dcl.enum]p4: Following the closing brace of an
19058       // enum-specifier, each enumerator has the type of its
19059       // enumeration.
19060       ECD->setType(EnumType);
19061     else
19062       ECD->setType(NewTy);
19063   }
19064 
19065   Enum->completeDefinition(BestType, BestPromotionType,
19066                            NumPositiveBits, NumNegativeBits);
19067 
19068   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19069 
19070   if (Enum->isClosedFlag()) {
19071     for (Decl *D : Elements) {
19072       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19073       if (!ECD) continue;  // Already issued a diagnostic.
19074 
19075       llvm::APSInt InitVal = ECD->getInitVal();
19076       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19077           !IsValueInFlagEnum(Enum, InitVal, true))
19078         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19079           << ECD << Enum;
19080     }
19081   }
19082 
19083   // Now that the enum type is defined, ensure it's not been underaligned.
19084   if (Enum->hasAttrs())
19085     CheckAlignasUnderalignment(Enum);
19086 }
19087 
19088 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19089                                   SourceLocation StartLoc,
19090                                   SourceLocation EndLoc) {
19091   StringLiteral *AsmString = cast<StringLiteral>(expr);
19092 
19093   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19094                                                    AsmString, StartLoc,
19095                                                    EndLoc);
19096   CurContext->addDecl(New);
19097   return New;
19098 }
19099 
19100 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19101                                       IdentifierInfo* AliasName,
19102                                       SourceLocation PragmaLoc,
19103                                       SourceLocation NameLoc,
19104                                       SourceLocation AliasNameLoc) {
19105   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19106                                          LookupOrdinaryName);
19107   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19108                            AttributeCommonInfo::AS_Pragma);
19109   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19110       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19111 
19112   // If a declaration that:
19113   // 1) declares a function or a variable
19114   // 2) has external linkage
19115   // already exists, add a label attribute to it.
19116   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19117     if (isDeclExternC(PrevDecl))
19118       PrevDecl->addAttr(Attr);
19119     else
19120       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19121           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19122   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19123   } else
19124     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19125 }
19126 
19127 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19128                              SourceLocation PragmaLoc,
19129                              SourceLocation NameLoc) {
19130   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19131 
19132   if (PrevDecl) {
19133     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19134   } else {
19135     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19136   }
19137 }
19138 
19139 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19140                                 IdentifierInfo* AliasName,
19141                                 SourceLocation PragmaLoc,
19142                                 SourceLocation NameLoc,
19143                                 SourceLocation AliasNameLoc) {
19144   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19145                                     LookupOrdinaryName);
19146   WeakInfo W = WeakInfo(Name, NameLoc);
19147 
19148   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19149     if (!PrevDecl->hasAttr<AliasAttr>())
19150       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19151         DeclApplyPragmaWeak(TUScope, ND, W);
19152   } else {
19153     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19154   }
19155 }
19156 
19157 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19158   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19159 }
19160 
19161 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19162                                                      bool Final) {
19163   assert(FD && "Expected non-null FunctionDecl");
19164 
19165   // SYCL functions can be template, so we check if they have appropriate
19166   // attribute prior to checking if it is a template.
19167   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19168     return FunctionEmissionStatus::Emitted;
19169 
19170   // Templates are emitted when they're instantiated.
19171   if (FD->isDependentContext())
19172     return FunctionEmissionStatus::TemplateDiscarded;
19173 
19174   // Check whether this function is an externally visible definition.
19175   auto IsEmittedForExternalSymbol = [this, FD]() {
19176     // We have to check the GVA linkage of the function's *definition* -- if we
19177     // only have a declaration, we don't know whether or not the function will
19178     // be emitted, because (say) the definition could include "inline".
19179     FunctionDecl *Def = FD->getDefinition();
19180 
19181     return Def && !isDiscardableGVALinkage(
19182                       getASTContext().GetGVALinkageForFunction(Def));
19183   };
19184 
19185   if (LangOpts.OpenMPIsDevice) {
19186     // In OpenMP device mode we will not emit host only functions, or functions
19187     // we don't need due to their linkage.
19188     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19189         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19190     // DevTy may be changed later by
19191     //  #pragma omp declare target to(*) device_type(*).
19192     // Therefore DevTy having no value does not imply host. The emission status
19193     // will be checked again at the end of compilation unit with Final = true.
19194     if (DevTy)
19195       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19196         return FunctionEmissionStatus::OMPDiscarded;
19197     // If we have an explicit value for the device type, or we are in a target
19198     // declare context, we need to emit all extern and used symbols.
19199     if (isInOpenMPDeclareTargetContext() || DevTy)
19200       if (IsEmittedForExternalSymbol())
19201         return FunctionEmissionStatus::Emitted;
19202     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19203     // we'll omit it.
19204     if (Final)
19205       return FunctionEmissionStatus::OMPDiscarded;
19206   } else if (LangOpts.OpenMP > 45) {
19207     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19208     // function. In 5.0, no_host was introduced which might cause a function to
19209     // be ommitted.
19210     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19211         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19212     if (DevTy)
19213       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19214         return FunctionEmissionStatus::OMPDiscarded;
19215   }
19216 
19217   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19218     return FunctionEmissionStatus::Emitted;
19219 
19220   if (LangOpts.CUDA) {
19221     // When compiling for device, host functions are never emitted.  Similarly,
19222     // when compiling for host, device and global functions are never emitted.
19223     // (Technically, we do emit a host-side stub for global functions, but this
19224     // doesn't count for our purposes here.)
19225     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19226     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19227       return FunctionEmissionStatus::CUDADiscarded;
19228     if (!LangOpts.CUDAIsDevice &&
19229         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19230       return FunctionEmissionStatus::CUDADiscarded;
19231 
19232     if (IsEmittedForExternalSymbol())
19233       return FunctionEmissionStatus::Emitted;
19234   }
19235 
19236   // Otherwise, the function is known-emitted if it's in our set of
19237   // known-emitted functions.
19238   return FunctionEmissionStatus::Unknown;
19239 }
19240 
19241 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19242   // Host-side references to a __global__ function refer to the stub, so the
19243   // function itself is never emitted and therefore should not be marked.
19244   // If we have host fn calls kernel fn calls host+device, the HD function
19245   // does not get instantiated on the host. We model this by omitting at the
19246   // call to the kernel from the callgraph. This ensures that, when compiling
19247   // for host, only HD functions actually called from the host get marked as
19248   // known-emitted.
19249   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19250          IdentifyCUDATarget(Callee) == CFT_Global;
19251 }
19252