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/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <functional>
54 #include <optional>
55 #include <unordered_map>
56 
57 using namespace clang;
58 using namespace sema;
59 
60 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
61   if (OwnedType) {
62     Decl *Group[2] = { OwnedType, Ptr };
63     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
64   }
65 
66   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
67 }
68 
69 namespace {
70 
71 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72  public:
73    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74                         bool AllowTemplates = false,
75                         bool AllowNonTemplates = true)
76        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78      WantExpressionKeywords = false;
79      WantCXXNamedCasts = false;
80      WantRemainingKeywords = false;
81   }
82 
83   bool ValidateCandidate(const TypoCorrection &candidate) override {
84     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85       if (!AllowInvalidDecl && ND->isInvalidDecl())
86         return false;
87 
88       if (getAsTypeTemplateDecl(ND))
89         return AllowTemplates;
90 
91       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
92       if (!IsType)
93         return false;
94 
95       if (AllowNonTemplates)
96         return true;
97 
98       // An injected-class-name of a class template (specialization) is valid
99       // as a template or as a non-template.
100       if (AllowTemplates) {
101         auto *RD = dyn_cast<CXXRecordDecl>(ND);
102         if (!RD || !RD->isInjectedClassName())
103           return false;
104         RD = cast<CXXRecordDecl>(RD->getDeclContext());
105         return RD->getDescribedClassTemplate() ||
106                isa<ClassTemplateSpecializationDecl>(RD);
107       }
108 
109       return false;
110     }
111 
112     return !WantClassName && candidate.isKeyword();
113   }
114 
115   std::unique_ptr<CorrectionCandidateCallback> clone() override {
116     return std::make_unique<TypeNameValidatorCCC>(*this);
117   }
118 
119  private:
120   bool AllowInvalidDecl;
121   bool WantClassName;
122   bool AllowTemplates;
123   bool AllowNonTemplates;
124 };
125 
126 } // end anonymous namespace
127 
128 /// Determine whether the token kind starts a simple-type-specifier.
129 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
130   switch (Kind) {
131   // FIXME: Take into account the current language when deciding whether a
132   // token kind is a valid type specifier
133   case tok::kw_short:
134   case tok::kw_long:
135   case tok::kw___int64:
136   case tok::kw___int128:
137   case tok::kw_signed:
138   case tok::kw_unsigned:
139   case tok::kw_void:
140   case tok::kw_char:
141   case tok::kw_int:
142   case tok::kw_half:
143   case tok::kw_float:
144   case tok::kw_double:
145   case tok::kw___bf16:
146   case tok::kw__Float16:
147   case tok::kw___float128:
148   case tok::kw___ibm128:
149   case tok::kw_wchar_t:
150   case tok::kw_bool:
151 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152 #include "clang/Basic/TransformTypeTraits.def"
153   case tok::kw___auto_type:
154     return true;
155 
156   case tok::annot_typename:
157   case tok::kw_char16_t:
158   case tok::kw_char32_t:
159   case tok::kw_typeof:
160   case tok::annot_decltype:
161   case tok::kw_decltype:
162     return getLangOpts().CPlusPlus;
163 
164   case tok::kw_char8_t:
165     return getLangOpts().Char8;
166 
167   default:
168     break;
169   }
170 
171   return false;
172 }
173 
174 namespace {
175 enum class UnqualifiedTypeNameLookupResult {
176   NotFound,
177   FoundNonType,
178   FoundType
179 };
180 } // end anonymous namespace
181 
182 /// Tries to perform unqualified lookup of the type decls in bases for
183 /// dependent class.
184 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185 /// type decl, \a FoundType if only type decls are found.
186 static UnqualifiedTypeNameLookupResult
187 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
188                                 SourceLocation NameLoc,
189                                 const CXXRecordDecl *RD) {
190   if (!RD->hasDefinition())
191     return UnqualifiedTypeNameLookupResult::NotFound;
192   // Look for type decls in base classes.
193   UnqualifiedTypeNameLookupResult FoundTypeDecl =
194       UnqualifiedTypeNameLookupResult::NotFound;
195   for (const auto &Base : RD->bases()) {
196     const CXXRecordDecl *BaseRD = nullptr;
197     if (auto *BaseTT = Base.getType()->getAs<TagType>())
198       BaseRD = BaseTT->getAsCXXRecordDecl();
199     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200       // Look for type decls in dependent base classes that have known primary
201       // templates.
202       if (!TST || !TST->isDependentType())
203         continue;
204       auto *TD = TST->getTemplateName().getAsTemplateDecl();
205       if (!TD)
206         continue;
207       if (auto *BasePrimaryTemplate =
208           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210           BaseRD = BasePrimaryTemplate;
211         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212           if (const ClassTemplatePartialSpecializationDecl *PS =
213                   CTD->findPartialSpecialization(Base.getType()))
214             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215               BaseRD = PS;
216         }
217       }
218     }
219     if (BaseRD) {
220       for (NamedDecl *ND : BaseRD->lookup(&II)) {
221         if (!isa<TypeDecl>(ND))
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224       }
225       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227         case UnqualifiedTypeNameLookupResult::FoundNonType:
228           return UnqualifiedTypeNameLookupResult::FoundNonType;
229         case UnqualifiedTypeNameLookupResult::FoundType:
230           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231           break;
232         case UnqualifiedTypeNameLookupResult::NotFound:
233           break;
234         }
235       }
236     }
237   }
238 
239   return FoundTypeDecl;
240 }
241 
242 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
243                                                       const IdentifierInfo &II,
244                                                       SourceLocation NameLoc) {
245   // Lookup in the parent class template context, if any.
246   const CXXRecordDecl *RD = nullptr;
247   UnqualifiedTypeNameLookupResult FoundTypeDecl =
248       UnqualifiedTypeNameLookupResult::NotFound;
249   for (DeclContext *DC = S.CurContext;
250        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
251        DC = DC->getParent()) {
252     // Look for type decls in dependent base classes that have known primary
253     // templates.
254     RD = dyn_cast<CXXRecordDecl>(DC);
255     if (RD && RD->getDescribedClassTemplate())
256       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
257   }
258   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259     return nullptr;
260 
261   // We found some types in dependent base classes.  Recover as if the user
262   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
263   // lookup during template instantiation.
264   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
265 
266   ASTContext &Context = S.Context;
267   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268                                           cast<Type>(Context.getRecordType(RD)));
269   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
270 
271   CXXScopeSpec SS;
272   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
273 
274   TypeLocBuilder Builder;
275   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
276   DepTL.setNameLoc(NameLoc);
277   DepTL.setElaboratedKeywordLoc(SourceLocation());
278   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
279   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
280 }
281 
282 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
283 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
284                                  SourceLocation NameLoc,
285                                  bool WantNontrivialTypeSourceInfo = true) {
286   switch (T->getTypeClass()) {
287   case Type::DeducedTemplateSpecialization:
288   case Type::Enum:
289   case Type::InjectedClassName:
290   case Type::Record:
291   case Type::Typedef:
292   case Type::UnresolvedUsing:
293   case Type::Using:
294     break;
295   // These can never be qualified so an ElaboratedType node
296   // would carry no additional meaning.
297   case Type::ObjCInterface:
298   case Type::ObjCTypeParam:
299   case Type::TemplateTypeParm:
300     return ParsedType::make(T);
301   default:
302     llvm_unreachable("Unexpected Type Class");
303   }
304 
305   if (!SS || SS->isEmpty())
306     return ParsedType::make(
307         S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
308 
309   QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
310   if (!WantNontrivialTypeSourceInfo)
311     return ParsedType::make(ElTy);
312 
313   TypeLocBuilder Builder;
314   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
315   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
316   ElabTL.setElaboratedKeywordLoc(SourceLocation());
317   ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
318   return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
319 }
320 
321 /// If the identifier refers to a type name within this scope,
322 /// return the declaration of that type.
323 ///
324 /// This routine performs ordinary name lookup of the identifier II
325 /// within the given scope, with optional C++ scope specifier SS, to
326 /// determine whether the name refers to a type. If so, returns an
327 /// opaque pointer (actually a QualType) corresponding to that
328 /// type. Otherwise, returns NULL.
329 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
330                              Scope *S, CXXScopeSpec *SS, bool isClassName,
331                              bool HasTrailingDot, ParsedType ObjectTypePtr,
332                              bool IsCtorOrDtorName,
333                              bool WantNontrivialTypeSourceInfo,
334                              bool IsClassTemplateDeductionContext,
335                              ImplicitTypenameContext AllowImplicitTypename,
336                              IdentifierInfo **CorrectedII) {
337   // FIXME: Consider allowing this outside C++1z mode as an extension.
338   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
339                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
340                               !isClassName && !HasTrailingDot;
341 
342   // Determine where we will perform name lookup.
343   DeclContext *LookupCtx = nullptr;
344   if (ObjectTypePtr) {
345     QualType ObjectType = ObjectTypePtr.get();
346     if (ObjectType->isRecordType())
347       LookupCtx = computeDeclContext(ObjectType);
348   } else if (SS && SS->isNotEmpty()) {
349     LookupCtx = computeDeclContext(*SS, false);
350 
351     if (!LookupCtx) {
352       if (isDependentScopeSpecifier(*SS)) {
353         // C++ [temp.res]p3:
354         //   A qualified-id that refers to a type and in which the
355         //   nested-name-specifier depends on a template-parameter (14.6.2)
356         //   shall be prefixed by the keyword typename to indicate that the
357         //   qualified-id denotes a type, forming an
358         //   elaborated-type-specifier (7.1.5.3).
359         //
360         // We therefore do not perform any name lookup if the result would
361         // refer to a member of an unknown specialization.
362         // In C++2a, in several contexts a 'typename' is not required. Also
363         // allow this as an extension.
364         if (AllowImplicitTypename == ImplicitTypenameContext::No &&
365             !isClassName && !IsCtorOrDtorName)
366           return nullptr;
367         bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
368         if (IsImplicitTypename) {
369           SourceLocation QualifiedLoc = SS->getRange().getBegin();
370           if (getLangOpts().CPlusPlus20)
371             Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
372           else
373             Diag(QualifiedLoc, diag::ext_implicit_typename)
374                 << SS->getScopeRep() << II.getName()
375                 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
376         }
377 
378         // We know from the grammar that this name refers to a type,
379         // so build a dependent node to describe the type.
380         if (WantNontrivialTypeSourceInfo)
381           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
382                                    (ImplicitTypenameContext)IsImplicitTypename)
383               .get();
384 
385         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
386         QualType T =
387             CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
388                               SourceLocation(), QualifierLoc, II, NameLoc);
389         return ParsedType::make(T);
390       }
391 
392       return nullptr;
393     }
394 
395     if (!LookupCtx->isDependentContext() &&
396         RequireCompleteDeclContext(*SS, LookupCtx))
397       return nullptr;
398   }
399 
400   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
401   // lookup for class-names.
402   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
403                                       LookupOrdinaryName;
404   LookupResult Result(*this, &II, NameLoc, Kind);
405   if (LookupCtx) {
406     // Perform "qualified" name lookup into the declaration context we
407     // computed, which is either the type of the base of a member access
408     // expression or the declaration context associated with a prior
409     // nested-name-specifier.
410     LookupQualifiedName(Result, LookupCtx);
411 
412     if (ObjectTypePtr && Result.empty()) {
413       // C++ [basic.lookup.classref]p3:
414       //   If the unqualified-id is ~type-name, the type-name is looked up
415       //   in the context of the entire postfix-expression. If the type T of
416       //   the object expression is of a class type C, the type-name is also
417       //   looked up in the scope of class C. At least one of the lookups shall
418       //   find a name that refers to (possibly cv-qualified) T.
419       LookupName(Result, S);
420     }
421   } else {
422     // Perform unqualified name lookup.
423     LookupName(Result, S);
424 
425     // For unqualified lookup in a class template in MSVC mode, look into
426     // dependent base classes where the primary class template is known.
427     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
428       if (ParsedType TypeInBase =
429               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
430         return TypeInBase;
431     }
432   }
433 
434   NamedDecl *IIDecl = nullptr;
435   UsingShadowDecl *FoundUsingShadow = nullptr;
436   switch (Result.getResultKind()) {
437   case LookupResult::NotFound:
438   case LookupResult::NotFoundInCurrentInstantiation:
439     if (CorrectedII) {
440       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
441                                AllowDeducedTemplate);
442       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
443                                               S, SS, CCC, CTK_ErrorRecovery);
444       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
445       TemplateTy Template;
446       bool MemberOfUnknownSpecialization;
447       UnqualifiedId TemplateName;
448       TemplateName.setIdentifier(NewII, NameLoc);
449       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
450       CXXScopeSpec NewSS, *NewSSPtr = SS;
451       if (SS && NNS) {
452         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
453         NewSSPtr = &NewSS;
454       }
455       if (Correction && (NNS || NewII != &II) &&
456           // Ignore a correction to a template type as the to-be-corrected
457           // identifier is not a template (typo correction for template names
458           // is handled elsewhere).
459           !(getLangOpts().CPlusPlus && NewSSPtr &&
460             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
461                            Template, MemberOfUnknownSpecialization))) {
462         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
463                                     isClassName, HasTrailingDot, ObjectTypePtr,
464                                     IsCtorOrDtorName,
465                                     WantNontrivialTypeSourceInfo,
466                                     IsClassTemplateDeductionContext);
467         if (Ty) {
468           diagnoseTypo(Correction,
469                        PDiag(diag::err_unknown_type_or_class_name_suggest)
470                          << Result.getLookupName() << isClassName);
471           if (SS && NNS)
472             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
473           *CorrectedII = NewII;
474           return Ty;
475         }
476       }
477     }
478     // If typo correction failed or was not performed, fall through
479     [[fallthrough]];
480   case LookupResult::FoundOverloaded:
481   case LookupResult::FoundUnresolvedValue:
482     Result.suppressDiagnostics();
483     return nullptr;
484 
485   case LookupResult::Ambiguous:
486     // Recover from type-hiding ambiguities by hiding the type.  We'll
487     // do the lookup again when looking for an object, and we can
488     // diagnose the error then.  If we don't do this, then the error
489     // about hiding the type will be immediately followed by an error
490     // that only makes sense if the identifier was treated like a type.
491     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
492       Result.suppressDiagnostics();
493       return nullptr;
494     }
495 
496     // Look to see if we have a type anywhere in the list of results.
497     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
498          Res != ResEnd; ++Res) {
499       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
500       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
501               RealRes) ||
502           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
503         if (!IIDecl ||
504             // Make the selection of the recovery decl deterministic.
505             RealRes->getLocation() < IIDecl->getLocation()) {
506           IIDecl = RealRes;
507           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
508         }
509       }
510     }
511 
512     if (!IIDecl) {
513       // None of the entities we found is a type, so there is no way
514       // to even assume that the result is a type. In this case, don't
515       // complain about the ambiguity. The parser will either try to
516       // perform this lookup again (e.g., as an object name), which
517       // will produce the ambiguity, or will complain that it expected
518       // a type name.
519       Result.suppressDiagnostics();
520       return nullptr;
521     }
522 
523     // We found a type within the ambiguous lookup; diagnose the
524     // ambiguity and then return that type. This might be the right
525     // answer, or it might not be, but it suppresses any attempt to
526     // perform the name lookup again.
527     break;
528 
529   case LookupResult::Found:
530     IIDecl = Result.getFoundDecl();
531     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
532     break;
533   }
534 
535   assert(IIDecl && "Didn't find decl");
536 
537   QualType T;
538   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
539     // C++ [class.qual]p2: A lookup that would find the injected-class-name
540     // instead names the constructors of the class, except when naming a class.
541     // This is ill-formed when we're not actually forming a ctor or dtor name.
542     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
543     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
544     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
545         FoundRD->isInjectedClassName() &&
546         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
547       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
548           << &II << /*Type*/1;
549 
550     DiagnoseUseOfDecl(IIDecl, NameLoc);
551 
552     T = Context.getTypeDeclType(TD);
553     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
554   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
555     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
556     if (!HasTrailingDot)
557       T = Context.getObjCInterfaceType(IDecl);
558     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
559   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
560     (void)DiagnoseUseOfDecl(UD, NameLoc);
561     // Recover with 'int'
562     return ParsedType::make(Context.IntTy);
563   } else if (AllowDeducedTemplate) {
564     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
565       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
566       TemplateName Template =
567           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
568       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
569                                                        false);
570       // Don't wrap in a further UsingType.
571       FoundUsingShadow = nullptr;
572     }
573   }
574 
575   if (T.isNull()) {
576     // If it's not plausibly a type, suppress diagnostics.
577     Result.suppressDiagnostics();
578     return nullptr;
579   }
580 
581   if (FoundUsingShadow)
582     T = Context.getUsingType(FoundUsingShadow, T);
583 
584   return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
585 }
586 
587 // Builds a fake NNS for the given decl context.
588 static NestedNameSpecifier *
589 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
590   for (;; DC = DC->getLookupParent()) {
591     DC = DC->getPrimaryContext();
592     auto *ND = dyn_cast<NamespaceDecl>(DC);
593     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
594       return NestedNameSpecifier::Create(Context, nullptr, ND);
595     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
596       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
597                                          RD->getTypeForDecl());
598     else if (isa<TranslationUnitDecl>(DC))
599       return NestedNameSpecifier::GlobalSpecifier(Context);
600   }
601   llvm_unreachable("something isn't in TU scope?");
602 }
603 
604 /// Find the parent class with dependent bases of the innermost enclosing method
605 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
606 /// up allowing unqualified dependent type names at class-level, which MSVC
607 /// correctly rejects.
608 static const CXXRecordDecl *
609 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
610   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
611     DC = DC->getPrimaryContext();
612     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
613       if (MD->getParent()->hasAnyDependentBases())
614         return MD->getParent();
615   }
616   return nullptr;
617 }
618 
619 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
620                                           SourceLocation NameLoc,
621                                           bool IsTemplateTypeArg) {
622   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
623 
624   NestedNameSpecifier *NNS = nullptr;
625   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
626     // If we weren't able to parse a default template argument, delay lookup
627     // until instantiation time by making a non-dependent DependentTypeName. We
628     // pretend we saw a NestedNameSpecifier referring to the current scope, and
629     // lookup is retried.
630     // FIXME: This hurts our diagnostic quality, since we get errors like "no
631     // type named 'Foo' in 'current_namespace'" when the user didn't write any
632     // name specifiers.
633     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
634     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
635   } else if (const CXXRecordDecl *RD =
636                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
637     // Build a DependentNameType that will perform lookup into RD at
638     // instantiation time.
639     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
640                                       RD->getTypeForDecl());
641 
642     // Diagnose that this identifier was undeclared, and retry the lookup during
643     // template instantiation.
644     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
645                                                                       << RD;
646   } else {
647     // This is not a situation that we should recover from.
648     return ParsedType();
649   }
650 
651   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
652 
653   // Build type location information.  We synthesized the qualifier, so we have
654   // to build a fake NestedNameSpecifierLoc.
655   NestedNameSpecifierLocBuilder NNSLocBuilder;
656   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
657   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
658 
659   TypeLocBuilder Builder;
660   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
661   DepTL.setNameLoc(NameLoc);
662   DepTL.setElaboratedKeywordLoc(SourceLocation());
663   DepTL.setQualifierLoc(QualifierLoc);
664   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
665 }
666 
667 /// isTagName() - This method is called *for error recovery purposes only*
668 /// to determine if the specified name is a valid tag name ("struct foo").  If
669 /// so, this returns the TST for the tag corresponding to it (TST_enum,
670 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
671 /// cases in C where the user forgot to specify the tag.
672 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
673   // Do a tag name lookup in this scope.
674   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
675   LookupName(R, S, false);
676   R.suppressDiagnostics();
677   if (R.getResultKind() == LookupResult::Found)
678     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
679       switch (TD->getTagKind()) {
680       case TTK_Struct: return DeclSpec::TST_struct;
681       case TTK_Interface: return DeclSpec::TST_interface;
682       case TTK_Union:  return DeclSpec::TST_union;
683       case TTK_Class:  return DeclSpec::TST_class;
684       case TTK_Enum:   return DeclSpec::TST_enum;
685       }
686     }
687 
688   return DeclSpec::TST_unspecified;
689 }
690 
691 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
692 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
693 /// then downgrade the missing typename error to a warning.
694 /// This is needed for MSVC compatibility; Example:
695 /// @code
696 /// template<class T> class A {
697 /// public:
698 ///   typedef int TYPE;
699 /// };
700 /// template<class T> class B : public A<T> {
701 /// public:
702 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
703 /// };
704 /// @endcode
705 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
706   if (CurContext->isRecord()) {
707     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
708       return true;
709 
710     const Type *Ty = SS->getScopeRep()->getAsType();
711 
712     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
713     for (const auto &Base : RD->bases())
714       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
715         return true;
716     return S->isFunctionPrototypeScope();
717   }
718   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
719 }
720 
721 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
722                                    SourceLocation IILoc,
723                                    Scope *S,
724                                    CXXScopeSpec *SS,
725                                    ParsedType &SuggestedType,
726                                    bool IsTemplateName) {
727   // Don't report typename errors for editor placeholders.
728   if (II->isEditorPlaceholder())
729     return;
730   // We don't have anything to suggest (yet).
731   SuggestedType = nullptr;
732 
733   // There may have been a typo in the name of the type. Look up typo
734   // results, in case we have something that we can suggest.
735   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
736                            /*AllowTemplates=*/IsTemplateName,
737                            /*AllowNonTemplates=*/!IsTemplateName);
738   if (TypoCorrection Corrected =
739           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
740                       CCC, CTK_ErrorRecovery)) {
741     // FIXME: Support error recovery for the template-name case.
742     bool CanRecover = !IsTemplateName;
743     if (Corrected.isKeyword()) {
744       // We corrected to a keyword.
745       diagnoseTypo(Corrected,
746                    PDiag(IsTemplateName ? diag::err_no_template_suggest
747                                         : diag::err_unknown_typename_suggest)
748                        << II);
749       II = Corrected.getCorrectionAsIdentifierInfo();
750     } else {
751       // We found a similarly-named type or interface; suggest that.
752       if (!SS || !SS->isSet()) {
753         diagnoseTypo(Corrected,
754                      PDiag(IsTemplateName ? diag::err_no_template_suggest
755                                           : diag::err_unknown_typename_suggest)
756                          << II, CanRecover);
757       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
758         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
759         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
760                                 II->getName().equals(CorrectedStr);
761         diagnoseTypo(Corrected,
762                      PDiag(IsTemplateName
763                                ? diag::err_no_member_template_suggest
764                                : diag::err_unknown_nested_typename_suggest)
765                          << II << DC << DroppedSpecifier << SS->getRange(),
766                      CanRecover);
767       } else {
768         llvm_unreachable("could not have corrected a typo here");
769       }
770 
771       if (!CanRecover)
772         return;
773 
774       CXXScopeSpec tmpSS;
775       if (Corrected.getCorrectionSpecifier())
776         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
777                           SourceRange(IILoc));
778       // FIXME: Support class template argument deduction here.
779       SuggestedType =
780           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
781                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
782                       /*IsCtorOrDtorName=*/false,
783                       /*WantNontrivialTypeSourceInfo=*/true);
784     }
785     return;
786   }
787 
788   if (getLangOpts().CPlusPlus && !IsTemplateName) {
789     // See if II is a class template that the user forgot to pass arguments to.
790     UnqualifiedId Name;
791     Name.setIdentifier(II, IILoc);
792     CXXScopeSpec EmptySS;
793     TemplateTy TemplateResult;
794     bool MemberOfUnknownSpecialization;
795     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
796                        Name, nullptr, true, TemplateResult,
797                        MemberOfUnknownSpecialization) == TNK_Type_template) {
798       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
799       return;
800     }
801   }
802 
803   // FIXME: Should we move the logic that tries to recover from a missing tag
804   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
805 
806   if (!SS || (!SS->isSet() && !SS->isInvalid()))
807     Diag(IILoc, IsTemplateName ? diag::err_no_template
808                                : diag::err_unknown_typename)
809         << II;
810   else if (DeclContext *DC = computeDeclContext(*SS, false))
811     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
812                                : diag::err_typename_nested_not_found)
813         << II << DC << SS->getRange();
814   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
815     SuggestedType =
816         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817   } else if (isDependentScopeSpecifier(*SS)) {
818     unsigned DiagID = diag::err_typename_missing;
819     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
820       DiagID = diag::ext_typename_missing;
821 
822     Diag(SS->getRange().getBegin(), DiagID)
823       << SS->getScopeRep() << II->getName()
824       << SourceRange(SS->getRange().getBegin(), IILoc)
825       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826     SuggestedType = ActOnTypenameType(S, SourceLocation(),
827                                       *SS, *II, IILoc).get();
828   } else {
829     assert(SS && SS->isInvalid() &&
830            "Invalid scope specifier has already been diagnosed");
831   }
832 }
833 
834 /// Determine whether the given result set contains either a type name
835 /// or
836 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
837   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
838                        NextToken.is(tok::less);
839 
840   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
841     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
842       return true;
843 
844     if (CheckTemplate && isa<TemplateDecl>(*I))
845       return true;
846   }
847 
848   return false;
849 }
850 
851 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
852                                     Scope *S, CXXScopeSpec &SS,
853                                     IdentifierInfo *&Name,
854                                     SourceLocation NameLoc) {
855   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
856   SemaRef.LookupParsedName(R, S, &SS);
857   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
858     StringRef FixItTagName;
859     switch (Tag->getTagKind()) {
860       case TTK_Class:
861         FixItTagName = "class ";
862         break;
863 
864       case TTK_Enum:
865         FixItTagName = "enum ";
866         break;
867 
868       case TTK_Struct:
869         FixItTagName = "struct ";
870         break;
871 
872       case TTK_Interface:
873         FixItTagName = "__interface ";
874         break;
875 
876       case TTK_Union:
877         FixItTagName = "union ";
878         break;
879     }
880 
881     StringRef TagName = FixItTagName.drop_back();
882     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
883       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
884       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
885 
886     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
887          I != IEnd; ++I)
888       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
889         << Name << TagName;
890 
891     // Replace lookup results with just the tag decl.
892     Result.clear(Sema::LookupTagName);
893     SemaRef.LookupParsedName(Result, S, &SS);
894     return true;
895   }
896 
897   return false;
898 }
899 
900 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
901                                             IdentifierInfo *&Name,
902                                             SourceLocation NameLoc,
903                                             const Token &NextToken,
904                                             CorrectionCandidateCallback *CCC) {
905   DeclarationNameInfo NameInfo(Name, NameLoc);
906   ObjCMethodDecl *CurMethod = getCurMethodDecl();
907 
908   assert(NextToken.isNot(tok::coloncolon) &&
909          "parse nested name specifiers before calling ClassifyName");
910   if (getLangOpts().CPlusPlus && SS.isSet() &&
911       isCurrentClassName(*Name, S, &SS)) {
912     // Per [class.qual]p2, this names the constructors of SS, not the
913     // injected-class-name. We don't have a classification for that.
914     // There's not much point caching this result, since the parser
915     // will reject it later.
916     return NameClassification::Unknown();
917   }
918 
919   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
920   LookupParsedName(Result, S, &SS, !CurMethod);
921 
922   if (SS.isInvalid())
923     return NameClassification::Error();
924 
925   // For unqualified lookup in a class template in MSVC mode, look into
926   // dependent base classes where the primary class template is known.
927   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
928     if (ParsedType TypeInBase =
929             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
930       return TypeInBase;
931   }
932 
933   // Perform lookup for Objective-C instance variables (including automatically
934   // synthesized instance variables), if we're in an Objective-C method.
935   // FIXME: This lookup really, really needs to be folded in to the normal
936   // unqualified lookup mechanism.
937   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
938     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
939     if (Ivar.isInvalid())
940       return NameClassification::Error();
941     if (Ivar.isUsable())
942       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
943 
944     // We defer builtin creation until after ivar lookup inside ObjC methods.
945     if (Result.empty())
946       LookupBuiltin(Result);
947   }
948 
949   bool SecondTry = false;
950   bool IsFilteredTemplateName = false;
951 
952 Corrected:
953   switch (Result.getResultKind()) {
954   case LookupResult::NotFound:
955     // If an unqualified-id is followed by a '(', then we have a function
956     // call.
957     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
958       // In C++, this is an ADL-only call.
959       // FIXME: Reference?
960       if (getLangOpts().CPlusPlus)
961         return NameClassification::UndeclaredNonType();
962 
963       // C90 6.3.2.2:
964       //   If the expression that precedes the parenthesized argument list in a
965       //   function call consists solely of an identifier, and if no
966       //   declaration is visible for this identifier, the identifier is
967       //   implicitly declared exactly as if, in the innermost block containing
968       //   the function call, the declaration
969       //
970       //     extern int identifier ();
971       //
972       //   appeared.
973       //
974       // We also allow this in C99 as an extension. However, this is not
975       // allowed in all language modes as functions without prototypes may not
976       // be supported.
977       if (getLangOpts().implicitFunctionsAllowed()) {
978         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979           return NameClassification::NonType(D);
980       }
981     }
982 
983     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
984       // In C++20 onwards, this could be an ADL-only call to a function
985       // template, and we're required to assume that this is a template name.
986       //
987       // FIXME: Find a way to still do typo correction in this case.
988       TemplateName Template =
989           Context.getAssumedTemplateName(NameInfo.getName());
990       return NameClassification::UndeclaredTemplate(Template);
991     }
992 
993     // In C, we first see whether there is a tag type by the same name, in
994     // which case it's likely that the user just forgot to write "enum",
995     // "struct", or "union".
996     if (!getLangOpts().CPlusPlus && !SecondTry &&
997         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
998       break;
999     }
1000 
1001     // Perform typo correction to determine if there is another name that is
1002     // close to this name.
1003     if (!SecondTry && CCC) {
1004       SecondTry = true;
1005       if (TypoCorrection Corrected =
1006               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1007                           &SS, *CCC, CTK_ErrorRecovery)) {
1008         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1009         unsigned QualifiedDiag = diag::err_no_member_suggest;
1010 
1011         NamedDecl *FirstDecl = Corrected.getFoundDecl();
1012         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1013         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1014             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1015           UnqualifiedDiag = diag::err_no_template_suggest;
1016           QualifiedDiag = diag::err_no_member_template_suggest;
1017         } else if (UnderlyingFirstDecl &&
1018                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
1019                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1020                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1021           UnqualifiedDiag = diag::err_unknown_typename_suggest;
1022           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1023         }
1024 
1025         if (SS.isEmpty()) {
1026           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1027         } else {// FIXME: is this even reachable? Test it.
1028           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1029           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1030                                   Name->getName().equals(CorrectedStr);
1031           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1032                                     << Name << computeDeclContext(SS, false)
1033                                     << DroppedSpecifier << SS.getRange());
1034         }
1035 
1036         // Update the name, so that the caller has the new name.
1037         Name = Corrected.getCorrectionAsIdentifierInfo();
1038 
1039         // Typo correction corrected to a keyword.
1040         if (Corrected.isKeyword())
1041           return Name;
1042 
1043         // Also update the LookupResult...
1044         // FIXME: This should probably go away at some point
1045         Result.clear();
1046         Result.setLookupName(Corrected.getCorrection());
1047         if (FirstDecl)
1048           Result.addDecl(FirstDecl);
1049 
1050         // If we found an Objective-C instance variable, let
1051         // LookupInObjCMethod build the appropriate expression to
1052         // reference the ivar.
1053         // FIXME: This is a gross hack.
1054         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1055           DeclResult R =
1056               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1057           if (R.isInvalid())
1058             return NameClassification::Error();
1059           if (R.isUsable())
1060             return NameClassification::NonType(Ivar);
1061         }
1062 
1063         goto Corrected;
1064       }
1065     }
1066 
1067     // We failed to correct; just fall through and let the parser deal with it.
1068     Result.suppressDiagnostics();
1069     return NameClassification::Unknown();
1070 
1071   case LookupResult::NotFoundInCurrentInstantiation: {
1072     // We performed name lookup into the current instantiation, and there were
1073     // dependent bases, so we treat this result the same way as any other
1074     // dependent nested-name-specifier.
1075 
1076     // C++ [temp.res]p2:
1077     //   A name used in a template declaration or definition and that is
1078     //   dependent on a template-parameter is assumed not to name a type
1079     //   unless the applicable name lookup finds a type name or the name is
1080     //   qualified by the keyword typename.
1081     //
1082     // FIXME: If the next token is '<', we might want to ask the parser to
1083     // perform some heroics to see if we actually have a
1084     // template-argument-list, which would indicate a missing 'template'
1085     // keyword here.
1086     return NameClassification::DependentNonType();
1087   }
1088 
1089   case LookupResult::Found:
1090   case LookupResult::FoundOverloaded:
1091   case LookupResult::FoundUnresolvedValue:
1092     break;
1093 
1094   case LookupResult::Ambiguous:
1095     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1097                                       /*AllowDependent=*/false)) {
1098       // C++ [temp.local]p3:
1099       //   A lookup that finds an injected-class-name (10.2) can result in an
1100       //   ambiguity in certain cases (for example, if it is found in more than
1101       //   one base class). If all of the injected-class-names that are found
1102       //   refer to specializations of the same class template, and if the name
1103       //   is followed by a template-argument-list, the reference refers to the
1104       //   class template itself and not a specialization thereof, and is not
1105       //   ambiguous.
1106       //
1107       // This filtering can make an ambiguous result into an unambiguous one,
1108       // so try again after filtering out template names.
1109       FilterAcceptableTemplateNames(Result);
1110       if (!Result.isAmbiguous()) {
1111         IsFilteredTemplateName = true;
1112         break;
1113       }
1114     }
1115 
1116     // Diagnose the ambiguity and return an error.
1117     return NameClassification::Error();
1118   }
1119 
1120   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1121       (IsFilteredTemplateName ||
1122        hasAnyAcceptableTemplateNames(
1123            Result, /*AllowFunctionTemplates=*/true,
1124            /*AllowDependent=*/false,
1125            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126                getLangOpts().CPlusPlus20))) {
1127     // C++ [temp.names]p3:
1128     //   After name lookup (3.4) finds that a name is a template-name or that
1129     //   an operator-function-id or a literal- operator-id refers to a set of
1130     //   overloaded functions any member of which is a function template if
1131     //   this is followed by a <, the < is always taken as the delimiter of a
1132     //   template-argument-list and never as the less-than operator.
1133     // C++2a [temp.names]p2:
1134     //   A name is also considered to refer to a template if it is an
1135     //   unqualified-id followed by a < and name lookup finds either one
1136     //   or more functions or finds nothing.
1137     if (!IsFilteredTemplateName)
1138       FilterAcceptableTemplateNames(Result);
1139 
1140     bool IsFunctionTemplate;
1141     bool IsVarTemplate;
1142     TemplateName Template;
1143     if (Result.end() - Result.begin() > 1) {
1144       IsFunctionTemplate = true;
1145       Template = Context.getOverloadedTemplateName(Result.begin(),
1146                                                    Result.end());
1147     } else if (!Result.empty()) {
1148       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1149           *Result.begin(), /*AllowFunctionTemplates=*/true,
1150           /*AllowDependent=*/false));
1151       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1152       IsVarTemplate = isa<VarTemplateDecl>(TD);
1153 
1154       UsingShadowDecl *FoundUsingShadow =
1155           dyn_cast<UsingShadowDecl>(*Result.begin());
1156       assert(!FoundUsingShadow ||
1157              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1158       Template =
1159           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1160       if (SS.isNotEmpty())
1161         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1162                                                     /*TemplateKeyword=*/false,
1163                                                     Template);
1164     } else {
1165       // All results were non-template functions. This is a function template
1166       // name.
1167       IsFunctionTemplate = true;
1168       Template = Context.getAssumedTemplateName(NameInfo.getName());
1169     }
1170 
1171     if (IsFunctionTemplate) {
1172       // Function templates always go through overload resolution, at which
1173       // point we'll perform the various checks (e.g., accessibility) we need
1174       // to based on which function we selected.
1175       Result.suppressDiagnostics();
1176 
1177       return NameClassification::FunctionTemplate(Template);
1178     }
1179 
1180     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1181                          : NameClassification::TypeTemplate(Template);
1182   }
1183 
1184   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1185     QualType T = Context.getTypeDeclType(Type);
1186     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1187       T = Context.getUsingType(USD, T);
1188     return buildNamedType(*this, &SS, T, NameLoc);
1189   };
1190 
1191   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1192   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1193     DiagnoseUseOfDecl(Type, NameLoc);
1194     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1195     return BuildTypeFor(Type, *Result.begin());
1196   }
1197 
1198   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1199   if (!Class) {
1200     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1201     if (ObjCCompatibleAliasDecl *Alias =
1202             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1203       Class = Alias->getClassInterface();
1204   }
1205 
1206   if (Class) {
1207     DiagnoseUseOfDecl(Class, NameLoc);
1208 
1209     if (NextToken.is(tok::period)) {
1210       // Interface. <something> is parsed as a property reference expression.
1211       // Just return "unknown" as a fall-through for now.
1212       Result.suppressDiagnostics();
1213       return NameClassification::Unknown();
1214     }
1215 
1216     QualType T = Context.getObjCInterfaceType(Class);
1217     return ParsedType::make(T);
1218   }
1219 
1220   if (isa<ConceptDecl>(FirstDecl))
1221     return NameClassification::Concept(
1222         TemplateName(cast<TemplateDecl>(FirstDecl)));
1223 
1224   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1225     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1226     return NameClassification::Error();
1227   }
1228 
1229   // We can have a type template here if we're classifying a template argument.
1230   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1231       !isa<VarTemplateDecl>(FirstDecl))
1232     return NameClassification::TypeTemplate(
1233         TemplateName(cast<TemplateDecl>(FirstDecl)));
1234 
1235   // Check for a tag type hidden by a non-type decl in a few cases where it
1236   // seems likely a type is wanted instead of the non-type that was found.
1237   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1238   if ((NextToken.is(tok::identifier) ||
1239        (NextIsOp &&
1240         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1241       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1242     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1243     DiagnoseUseOfDecl(Type, NameLoc);
1244     return BuildTypeFor(Type, *Result.begin());
1245   }
1246 
1247   // If we already know which single declaration is referenced, just annotate
1248   // that declaration directly. Defer resolving even non-overloaded class
1249   // member accesses, as we need to defer certain access checks until we know
1250   // the context.
1251   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1252   if (Result.isSingleResult() && !ADL &&
1253       (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1254     return NameClassification::NonType(Result.getRepresentativeDecl());
1255 
1256   // Otherwise, this is an overload set that we will need to resolve later.
1257   Result.suppressDiagnostics();
1258   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1259       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1260       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1261       Result.begin(), Result.end()));
1262 }
1263 
1264 ExprResult
1265 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1266                                              SourceLocation NameLoc) {
1267   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1268   CXXScopeSpec SS;
1269   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1270   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1271 }
1272 
1273 ExprResult
1274 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1275                                             IdentifierInfo *Name,
1276                                             SourceLocation NameLoc,
1277                                             bool IsAddressOfOperand) {
1278   DeclarationNameInfo NameInfo(Name, NameLoc);
1279   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1280                                     NameInfo, IsAddressOfOperand,
1281                                     /*TemplateArgs=*/nullptr);
1282 }
1283 
1284 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1285                                               NamedDecl *Found,
1286                                               SourceLocation NameLoc,
1287                                               const Token &NextToken) {
1288   if (getCurMethodDecl() && SS.isEmpty())
1289     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1290       return BuildIvarRefExpr(S, NameLoc, Ivar);
1291 
1292   // Reconstruct the lookup result.
1293   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1294   Result.addDecl(Found);
1295   Result.resolveKind();
1296 
1297   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1298   return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1299 }
1300 
1301 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1302   // For an implicit class member access, transform the result into a member
1303   // access expression if necessary.
1304   auto *ULE = cast<UnresolvedLookupExpr>(E);
1305   if ((*ULE->decls_begin())->isCXXClassMember()) {
1306     CXXScopeSpec SS;
1307     SS.Adopt(ULE->getQualifierLoc());
1308 
1309     // Reconstruct the lookup result.
1310     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1311                         LookupOrdinaryName);
1312     Result.setNamingClass(ULE->getNamingClass());
1313     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1314       Result.addDecl(*I, I.getAccess());
1315     Result.resolveKind();
1316     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1317                                            nullptr, S);
1318   }
1319 
1320   // Otherwise, this is already in the form we needed, and no further checks
1321   // are necessary.
1322   return ULE;
1323 }
1324 
1325 Sema::TemplateNameKindForDiagnostics
1326 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1327   auto *TD = Name.getAsTemplateDecl();
1328   if (!TD)
1329     return TemplateNameKindForDiagnostics::DependentTemplate;
1330   if (isa<ClassTemplateDecl>(TD))
1331     return TemplateNameKindForDiagnostics::ClassTemplate;
1332   if (isa<FunctionTemplateDecl>(TD))
1333     return TemplateNameKindForDiagnostics::FunctionTemplate;
1334   if (isa<VarTemplateDecl>(TD))
1335     return TemplateNameKindForDiagnostics::VarTemplate;
1336   if (isa<TypeAliasTemplateDecl>(TD))
1337     return TemplateNameKindForDiagnostics::AliasTemplate;
1338   if (isa<TemplateTemplateParmDecl>(TD))
1339     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1340   if (isa<ConceptDecl>(TD))
1341     return TemplateNameKindForDiagnostics::Concept;
1342   return TemplateNameKindForDiagnostics::DependentTemplate;
1343 }
1344 
1345 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1346   assert(DC->getLexicalParent() == CurContext &&
1347       "The next DeclContext should be lexically contained in the current one.");
1348   CurContext = DC;
1349   S->setEntity(DC);
1350 }
1351 
1352 void Sema::PopDeclContext() {
1353   assert(CurContext && "DeclContext imbalance!");
1354 
1355   CurContext = CurContext->getLexicalParent();
1356   assert(CurContext && "Popped translation unit!");
1357 }
1358 
1359 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1360                                                                     Decl *D) {
1361   // Unlike PushDeclContext, the context to which we return is not necessarily
1362   // the containing DC of TD, because the new context will be some pre-existing
1363   // TagDecl definition instead of a fresh one.
1364   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1365   CurContext = cast<TagDecl>(D)->getDefinition();
1366   assert(CurContext && "skipping definition of undefined tag");
1367   // Start lookups from the parent of the current context; we don't want to look
1368   // into the pre-existing complete definition.
1369   S->setEntity(CurContext->getLookupParent());
1370   return Result;
1371 }
1372 
1373 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1374   CurContext = static_cast<decltype(CurContext)>(Context);
1375 }
1376 
1377 /// EnterDeclaratorContext - Used when we must lookup names in the context
1378 /// of a declarator's nested name specifier.
1379 ///
1380 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1381   // C++0x [basic.lookup.unqual]p13:
1382   //   A name used in the definition of a static data member of class
1383   //   X (after the qualified-id of the static member) is looked up as
1384   //   if the name was used in a member function of X.
1385   // C++0x [basic.lookup.unqual]p14:
1386   //   If a variable member of a namespace is defined outside of the
1387   //   scope of its namespace then any name used in the definition of
1388   //   the variable member (after the declarator-id) is looked up as
1389   //   if the definition of the variable member occurred in its
1390   //   namespace.
1391   // Both of these imply that we should push a scope whose context
1392   // is the semantic context of the declaration.  We can't use
1393   // PushDeclContext here because that context is not necessarily
1394   // lexically contained in the current context.  Fortunately,
1395   // the containing scope should have the appropriate information.
1396 
1397   assert(!S->getEntity() && "scope already has entity");
1398 
1399 #ifndef NDEBUG
1400   Scope *Ancestor = S->getParent();
1401   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1402   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1403 #endif
1404 
1405   CurContext = DC;
1406   S->setEntity(DC);
1407 
1408   if (S->getParent()->isTemplateParamScope()) {
1409     // Also set the corresponding entities for all immediately-enclosing
1410     // template parameter scopes.
1411     EnterTemplatedContext(S->getParent(), DC);
1412   }
1413 }
1414 
1415 void Sema::ExitDeclaratorContext(Scope *S) {
1416   assert(S->getEntity() == CurContext && "Context imbalance!");
1417 
1418   // Switch back to the lexical context.  The safety of this is
1419   // enforced by an assert in EnterDeclaratorContext.
1420   Scope *Ancestor = S->getParent();
1421   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1422   CurContext = Ancestor->getEntity();
1423 
1424   // We don't need to do anything with the scope, which is going to
1425   // disappear.
1426 }
1427 
1428 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1429   assert(S->isTemplateParamScope() &&
1430          "expected to be initializing a template parameter scope");
1431 
1432   // C++20 [temp.local]p7:
1433   //   In the definition of a member of a class template that appears outside
1434   //   of the class template definition, the name of a member of the class
1435   //   template hides the name of a template-parameter of any enclosing class
1436   //   templates (but not a template-parameter of the member if the member is a
1437   //   class or function template).
1438   // C++20 [temp.local]p9:
1439   //   In the definition of a class template or in the definition of a member
1440   //   of such a template that appears outside of the template definition, for
1441   //   each non-dependent base class (13.8.2.1), if the name of the base class
1442   //   or the name of a member of the base class is the same as the name of a
1443   //   template-parameter, the base class name or member name hides the
1444   //   template-parameter name (6.4.10).
1445   //
1446   // This means that a template parameter scope should be searched immediately
1447   // after searching the DeclContext for which it is a template parameter
1448   // scope. For example, for
1449   //   template<typename T> template<typename U> template<typename V>
1450   //     void N::A<T>::B<U>::f(...)
1451   // we search V then B<U> (and base classes) then U then A<T> (and base
1452   // classes) then T then N then ::.
1453   unsigned ScopeDepth = getTemplateDepth(S);
1454   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1455     DeclContext *SearchDCAfterScope = DC;
1456     for (; DC; DC = DC->getLookupParent()) {
1457       if (const TemplateParameterList *TPL =
1458               cast<Decl>(DC)->getDescribedTemplateParams()) {
1459         unsigned DCDepth = TPL->getDepth() + 1;
1460         if (DCDepth > ScopeDepth)
1461           continue;
1462         if (ScopeDepth == DCDepth)
1463           SearchDCAfterScope = DC = DC->getLookupParent();
1464         break;
1465       }
1466     }
1467     S->setLookupEntity(SearchDCAfterScope);
1468   }
1469 }
1470 
1471 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1472   // We assume that the caller has already called
1473   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1474   FunctionDecl *FD = D->getAsFunction();
1475   if (!FD)
1476     return;
1477 
1478   // Same implementation as PushDeclContext, but enters the context
1479   // from the lexical parent, rather than the top-level class.
1480   assert(CurContext == FD->getLexicalParent() &&
1481     "The next DeclContext should be lexically contained in the current one.");
1482   CurContext = FD;
1483   S->setEntity(CurContext);
1484 
1485   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1486     ParmVarDecl *Param = FD->getParamDecl(P);
1487     // If the parameter has an identifier, then add it to the scope
1488     if (Param->getIdentifier()) {
1489       S->AddDecl(Param);
1490       IdResolver.AddDecl(Param);
1491     }
1492   }
1493 }
1494 
1495 void Sema::ActOnExitFunctionContext() {
1496   // Same implementation as PopDeclContext, but returns to the lexical parent,
1497   // rather than the top-level class.
1498   assert(CurContext && "DeclContext imbalance!");
1499   CurContext = CurContext->getLexicalParent();
1500   assert(CurContext && "Popped translation unit!");
1501 }
1502 
1503 /// Determine whether overloading is allowed for a new function
1504 /// declaration considering prior declarations of the same name.
1505 ///
1506 /// This routine determines whether overloading is possible, not
1507 /// whether a new declaration actually overloads a previous one.
1508 /// It will return true in C++ (where overloads are alway permitted)
1509 /// or, as a C extension, when either the new declaration or a
1510 /// previous one is declared with the 'overloadable' attribute.
1511 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1512                                        ASTContext &Context,
1513                                        const FunctionDecl *New) {
1514   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1515     return true;
1516 
1517   // Multiversion function declarations are not overloads in the
1518   // usual sense of that term, but lookup will report that an
1519   // overload set was found if more than one multiversion function
1520   // declaration is present for the same name. It is therefore
1521   // inadequate to assume that some prior declaration(s) had
1522   // the overloadable attribute; checking is required. Since one
1523   // declaration is permitted to omit the attribute, it is necessary
1524   // to check at least two; hence the 'any_of' check below. Note that
1525   // the overloadable attribute is implicitly added to declarations
1526   // that were required to have it but did not.
1527   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1528     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1529       return ND->hasAttr<OverloadableAttr>();
1530     });
1531   } else if (Previous.getResultKind() == LookupResult::Found)
1532     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1533 
1534   return false;
1535 }
1536 
1537 /// Add this decl to the scope shadowed decl chains.
1538 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1539   // Move up the scope chain until we find the nearest enclosing
1540   // non-transparent context. The declaration will be introduced into this
1541   // scope.
1542   while (S->getEntity() && S->getEntity()->isTransparentContext())
1543     S = S->getParent();
1544 
1545   // Add scoped declarations into their context, so that they can be
1546   // found later. Declarations without a context won't be inserted
1547   // into any context.
1548   if (AddToContext)
1549     CurContext->addDecl(D);
1550 
1551   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1552   // are function-local declarations.
1553   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1554     return;
1555 
1556   // Template instantiations should also not be pushed into scope.
1557   if (isa<FunctionDecl>(D) &&
1558       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1559     return;
1560 
1561   // If this replaces anything in the current scope,
1562   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1563                                IEnd = IdResolver.end();
1564   for (; I != IEnd; ++I) {
1565     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1566       S->RemoveDecl(*I);
1567       IdResolver.RemoveDecl(*I);
1568 
1569       // Should only need to replace one decl.
1570       break;
1571     }
1572   }
1573 
1574   S->AddDecl(D);
1575 
1576   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1577     // Implicitly-generated labels may end up getting generated in an order that
1578     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1579     // the label at the appropriate place in the identifier chain.
1580     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1581       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1582       if (IDC == CurContext) {
1583         if (!S->isDeclScope(*I))
1584           continue;
1585       } else if (IDC->Encloses(CurContext))
1586         break;
1587     }
1588 
1589     IdResolver.InsertDeclAfter(I, D);
1590   } else {
1591     IdResolver.AddDecl(D);
1592   }
1593   warnOnReservedIdentifier(D);
1594 }
1595 
1596 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1597                          bool AllowInlineNamespace) const {
1598   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1599 }
1600 
1601 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1602   DeclContext *TargetDC = DC->getPrimaryContext();
1603   do {
1604     if (DeclContext *ScopeDC = S->getEntity())
1605       if (ScopeDC->getPrimaryContext() == TargetDC)
1606         return S;
1607   } while ((S = S->getParent()));
1608 
1609   return nullptr;
1610 }
1611 
1612 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1613                                             DeclContext*,
1614                                             ASTContext&);
1615 
1616 /// Filters out lookup results that don't fall within the given scope
1617 /// as determined by isDeclInScope.
1618 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1619                                 bool ConsiderLinkage,
1620                                 bool AllowInlineNamespace) {
1621   LookupResult::Filter F = R.makeFilter();
1622   while (F.hasNext()) {
1623     NamedDecl *D = F.next();
1624 
1625     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1626       continue;
1627 
1628     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1629       continue;
1630 
1631     F.erase();
1632   }
1633 
1634   F.done();
1635 }
1636 
1637 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1638 /// have compatible owning modules.
1639 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1640   // [module.interface]p7:
1641   // A declaration is attached to a module as follows:
1642   // - If the declaration is a non-dependent friend declaration that nominates a
1643   // function with a declarator-id that is a qualified-id or template-id or that
1644   // nominates a class other than with an elaborated-type-specifier with neither
1645   // a nested-name-specifier nor a simple-template-id, it is attached to the
1646   // module to which the friend is attached ([basic.link]).
1647   if (New->getFriendObjectKind() &&
1648       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1649     New->setLocalOwningModule(Old->getOwningModule());
1650     makeMergedDefinitionVisible(New);
1651     return false;
1652   }
1653 
1654   Module *NewM = New->getOwningModule();
1655   Module *OldM = Old->getOwningModule();
1656 
1657   if (NewM && NewM->isPrivateModule())
1658     NewM = NewM->Parent;
1659   if (OldM && OldM->isPrivateModule())
1660     OldM = OldM->Parent;
1661 
1662   if (NewM == OldM)
1663     return false;
1664 
1665   if (NewM && OldM) {
1666     // A module implementation unit has visibility of the decls in its
1667     // implicitly imported interface.
1668     if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1669       return false;
1670 
1671     // Partitions are part of the module, but a partition could import another
1672     // module, so verify that the PMIs agree.
1673     if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1674         NewM->getPrimaryModuleInterfaceName() ==
1675             OldM->getPrimaryModuleInterfaceName())
1676       return false;
1677   }
1678 
1679   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1680   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1681   if (NewIsModuleInterface || OldIsModuleInterface) {
1682     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1683     //   if a declaration of D [...] appears in the purview of a module, all
1684     //   other such declarations shall appear in the purview of the same module
1685     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1686       << New
1687       << NewIsModuleInterface
1688       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1689       << OldIsModuleInterface
1690       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1691     Diag(Old->getLocation(), diag::note_previous_declaration);
1692     New->setInvalidDecl();
1693     return true;
1694   }
1695 
1696   return false;
1697 }
1698 
1699 // [module.interface]p6:
1700 // A redeclaration of an entity X is implicitly exported if X was introduced by
1701 // an exported declaration; otherwise it shall not be exported.
1702 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1703   // [module.interface]p1:
1704   // An export-declaration shall inhabit a namespace scope.
1705   //
1706   // So it is meaningless to talk about redeclaration which is not at namespace
1707   // scope.
1708   if (!New->getLexicalDeclContext()
1709            ->getNonTransparentContext()
1710            ->isFileContext() ||
1711       !Old->getLexicalDeclContext()
1712            ->getNonTransparentContext()
1713            ->isFileContext())
1714     return false;
1715 
1716   bool IsNewExported = New->isInExportDeclContext();
1717   bool IsOldExported = Old->isInExportDeclContext();
1718 
1719   // It should be irrevelant if both of them are not exported.
1720   if (!IsNewExported && !IsOldExported)
1721     return false;
1722 
1723   if (IsOldExported)
1724     return false;
1725 
1726   assert(IsNewExported);
1727 
1728   auto Lk = Old->getFormalLinkage();
1729   int S = 0;
1730   if (Lk == Linkage::InternalLinkage)
1731     S = 1;
1732   else if (Lk == Linkage::ModuleLinkage)
1733     S = 2;
1734   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1735   Diag(Old->getLocation(), diag::note_previous_declaration);
1736   return true;
1737 }
1738 
1739 // A wrapper function for checking the semantic restrictions of
1740 // a redeclaration within a module.
1741 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1742   if (CheckRedeclarationModuleOwnership(New, Old))
1743     return true;
1744 
1745   if (CheckRedeclarationExported(New, Old))
1746     return true;
1747 
1748   return false;
1749 }
1750 
1751 // Check the redefinition in C++20 Modules.
1752 //
1753 // [basic.def.odr]p14:
1754 // For any definable item D with definitions in multiple translation units,
1755 // - if D is a non-inline non-templated function or variable, or
1756 // - if the definitions in different translation units do not satisfy the
1757 // following requirements,
1758 //   the program is ill-formed; a diagnostic is required only if the definable
1759 //   item is attached to a named module and a prior definition is reachable at
1760 //   the point where a later definition occurs.
1761 // - Each such definition shall not be attached to a named module
1762 // ([module.unit]).
1763 // - Each such definition shall consist of the same sequence of tokens, ...
1764 // ...
1765 //
1766 // Return true if the redefinition is not allowed. Return false otherwise.
1767 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1768                                      const NamedDecl *Old) const {
1769   assert(getASTContext().isSameEntity(New, Old) &&
1770          "New and Old are not the same definition, we should diagnostic it "
1771          "immediately instead of checking it.");
1772   assert(const_cast<Sema *>(this)->isReachable(New) &&
1773          const_cast<Sema *>(this)->isReachable(Old) &&
1774          "We shouldn't see unreachable definitions here.");
1775 
1776   Module *NewM = New->getOwningModule();
1777   Module *OldM = Old->getOwningModule();
1778 
1779   // We only checks for named modules here. The header like modules is skipped.
1780   // FIXME: This is not right if we import the header like modules in the module
1781   // purview.
1782   //
1783   // For example, assuming "header.h" provides definition for `D`.
1784   // ```C++
1785   // //--- M.cppm
1786   // export module M;
1787   // import "header.h"; // or #include "header.h" but import it by clang modules
1788   // actually.
1789   //
1790   // //--- Use.cpp
1791   // import M;
1792   // import "header.h"; // or uses clang modules.
1793   // ```
1794   //
1795   // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1796   // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1797   // reject it. But the current implementation couldn't detect the case since we
1798   // don't record the information about the importee modules.
1799   //
1800   // But this might not be painful in practice. Since the design of C++20 Named
1801   // Modules suggests us to use headers in global module fragment instead of
1802   // module purview.
1803   if (NewM && NewM->isHeaderLikeModule())
1804     NewM = nullptr;
1805   if (OldM && OldM->isHeaderLikeModule())
1806     OldM = nullptr;
1807 
1808   if (!NewM && !OldM)
1809     return true;
1810 
1811   // [basic.def.odr]p14.3
1812   // Each such definition shall not be attached to a named module
1813   // ([module.unit]).
1814   if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1815     return true;
1816 
1817   // Then New and Old lives in the same TU if their share one same module unit.
1818   if (NewM)
1819     NewM = NewM->getTopLevelModule();
1820   if (OldM)
1821     OldM = OldM->getTopLevelModule();
1822   return OldM == NewM;
1823 }
1824 
1825 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1826   if (D->getDeclContext()->isFileContext())
1827     return false;
1828 
1829   return isa<UsingShadowDecl>(D) ||
1830          isa<UnresolvedUsingTypenameDecl>(D) ||
1831          isa<UnresolvedUsingValueDecl>(D);
1832 }
1833 
1834 /// Removes using shadow declarations not at class scope from the lookup
1835 /// results.
1836 static void RemoveUsingDecls(LookupResult &R) {
1837   LookupResult::Filter F = R.makeFilter();
1838   while (F.hasNext())
1839     if (isUsingDeclNotAtClassScope(F.next()))
1840       F.erase();
1841 
1842   F.done();
1843 }
1844 
1845 /// Check for this common pattern:
1846 /// @code
1847 /// class S {
1848 ///   S(const S&); // DO NOT IMPLEMENT
1849 ///   void operator=(const S&); // DO NOT IMPLEMENT
1850 /// };
1851 /// @endcode
1852 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1853   // FIXME: Should check for private access too but access is set after we get
1854   // the decl here.
1855   if (D->doesThisDeclarationHaveABody())
1856     return false;
1857 
1858   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1859     return CD->isCopyConstructor();
1860   return D->isCopyAssignmentOperator();
1861 }
1862 
1863 // We need this to handle
1864 //
1865 // typedef struct {
1866 //   void *foo() { return 0; }
1867 // } A;
1868 //
1869 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1870 // for example. If 'A', foo will have external linkage. If we have '*A',
1871 // foo will have no linkage. Since we can't know until we get to the end
1872 // of the typedef, this function finds out if D might have non-external linkage.
1873 // Callers should verify at the end of the TU if it D has external linkage or
1874 // not.
1875 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1876   const DeclContext *DC = D->getDeclContext();
1877   while (!DC->isTranslationUnit()) {
1878     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1879       if (!RD->hasNameForLinkage())
1880         return true;
1881     }
1882     DC = DC->getParent();
1883   }
1884 
1885   return !D->isExternallyVisible();
1886 }
1887 
1888 // FIXME: This needs to be refactored; some other isInMainFile users want
1889 // these semantics.
1890 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1891   if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1892     return false;
1893   return S.SourceMgr.isInMainFile(Loc);
1894 }
1895 
1896 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1897   assert(D);
1898 
1899   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1900     return false;
1901 
1902   // Ignore all entities declared within templates, and out-of-line definitions
1903   // of members of class templates.
1904   if (D->getDeclContext()->isDependentContext() ||
1905       D->getLexicalDeclContext()->isDependentContext())
1906     return false;
1907 
1908   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1909     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1910       return false;
1911     // A non-out-of-line declaration of a member specialization was implicitly
1912     // instantiated; it's the out-of-line declaration that we're interested in.
1913     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1914         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1915       return false;
1916 
1917     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1918       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1919         return false;
1920     } else {
1921       // 'static inline' functions are defined in headers; don't warn.
1922       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1923         return false;
1924     }
1925 
1926     if (FD->doesThisDeclarationHaveABody() &&
1927         Context.DeclMustBeEmitted(FD))
1928       return false;
1929   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1930     // Constants and utility variables are defined in headers with internal
1931     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1932     // like "inline".)
1933     if (!isMainFileLoc(*this, VD->getLocation()))
1934       return false;
1935 
1936     if (Context.DeclMustBeEmitted(VD))
1937       return false;
1938 
1939     if (VD->isStaticDataMember() &&
1940         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1941       return false;
1942     if (VD->isStaticDataMember() &&
1943         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1944         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1945       return false;
1946 
1947     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1948       return false;
1949   } else {
1950     return false;
1951   }
1952 
1953   // Only warn for unused decls internal to the translation unit.
1954   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1955   // for inline functions defined in the main source file, for instance.
1956   return mightHaveNonExternalLinkage(D);
1957 }
1958 
1959 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1960   if (!D)
1961     return;
1962 
1963   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1964     const FunctionDecl *First = FD->getFirstDecl();
1965     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1966       return; // First should already be in the vector.
1967   }
1968 
1969   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1970     const VarDecl *First = VD->getFirstDecl();
1971     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1972       return; // First should already be in the vector.
1973   }
1974 
1975   if (ShouldWarnIfUnusedFileScopedDecl(D))
1976     UnusedFileScopedDecls.push_back(D);
1977 }
1978 
1979 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1980   if (D->isInvalidDecl())
1981     return false;
1982 
1983   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1984     // For a decomposition declaration, warn if none of the bindings are
1985     // referenced, instead of if the variable itself is referenced (which
1986     // it is, by the bindings' expressions).
1987     for (auto *BD : DD->bindings())
1988       if (BD->isReferenced())
1989         return false;
1990   } else if (!D->getDeclName()) {
1991     return false;
1992   } else if (D->isReferenced() || D->isUsed()) {
1993     return false;
1994   }
1995 
1996   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1997       D->hasAttr<CleanupAttr>())
1998     return false;
1999 
2000   if (isa<LabelDecl>(D))
2001     return true;
2002 
2003   // Except for labels, we only care about unused decls that are local to
2004   // functions.
2005   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2006   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2007     // For dependent types, the diagnostic is deferred.
2008     WithinFunction =
2009         WithinFunction || (R->isLocalClass() && !R->isDependentType());
2010   if (!WithinFunction)
2011     return false;
2012 
2013   if (isa<TypedefNameDecl>(D))
2014     return true;
2015 
2016   // White-list anything that isn't a local variable.
2017   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2018     return false;
2019 
2020   // Types of valid local variables should be complete, so this should succeed.
2021   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2022 
2023     const Expr *Init = VD->getInit();
2024     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2025       Init = Cleanups->getSubExpr();
2026 
2027     const auto *Ty = VD->getType().getTypePtr();
2028 
2029     // Only look at the outermost level of typedef.
2030     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2031       // Allow anything marked with __attribute__((unused)).
2032       if (TT->getDecl()->hasAttr<UnusedAttr>())
2033         return false;
2034     }
2035 
2036     // Warn for reference variables whose initializtion performs lifetime
2037     // extension.
2038     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2039       if (MTE->getExtendingDecl()) {
2040         Ty = VD->getType().getNonReferenceType().getTypePtr();
2041         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2042       }
2043     }
2044 
2045     // If we failed to complete the type for some reason, or if the type is
2046     // dependent, don't diagnose the variable.
2047     if (Ty->isIncompleteType() || Ty->isDependentType())
2048       return false;
2049 
2050     // Look at the element type to ensure that the warning behaviour is
2051     // consistent for both scalars and arrays.
2052     Ty = Ty->getBaseElementTypeUnsafe();
2053 
2054     if (const TagType *TT = Ty->getAs<TagType>()) {
2055       const TagDecl *Tag = TT->getDecl();
2056       if (Tag->hasAttr<UnusedAttr>())
2057         return false;
2058 
2059       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2060         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2061           return false;
2062 
2063         if (Init) {
2064           const CXXConstructExpr *Construct =
2065             dyn_cast<CXXConstructExpr>(Init);
2066           if (Construct && !Construct->isElidable()) {
2067             CXXConstructorDecl *CD = Construct->getConstructor();
2068             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2069                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2070               return false;
2071           }
2072 
2073           // Suppress the warning if we don't know how this is constructed, and
2074           // it could possibly be non-trivial constructor.
2075           if (Init->isTypeDependent()) {
2076             for (const CXXConstructorDecl *Ctor : RD->ctors())
2077               if (!Ctor->isTrivial())
2078                 return false;
2079           }
2080 
2081           // Suppress the warning if the constructor is unresolved because
2082           // its arguments are dependent.
2083           if (isa<CXXUnresolvedConstructExpr>(Init))
2084             return false;
2085         }
2086       }
2087     }
2088 
2089     // TODO: __attribute__((unused)) templates?
2090   }
2091 
2092   return true;
2093 }
2094 
2095 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2096                                      FixItHint &Hint) {
2097   if (isa<LabelDecl>(D)) {
2098     SourceLocation AfterColon = Lexer::findLocationAfterToken(
2099         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2100         /*SkipTrailingWhitespaceAndNewline=*/false);
2101     if (AfterColon.isInvalid())
2102       return;
2103     Hint = FixItHint::CreateRemoval(
2104         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2105   }
2106 }
2107 
2108 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2109   DiagnoseUnusedNestedTypedefs(
2110       D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2111 }
2112 
2113 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2114                                         DiagReceiverTy DiagReceiver) {
2115   if (D->getTypeForDecl()->isDependentType())
2116     return;
2117 
2118   for (auto *TmpD : D->decls()) {
2119     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2120       DiagnoseUnusedDecl(T, DiagReceiver);
2121     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2122       DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2123   }
2124 }
2125 
2126 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2127   DiagnoseUnusedDecl(
2128       D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2129 }
2130 
2131 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2132 /// unless they are marked attr(unused).
2133 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2134   if (!ShouldDiagnoseUnusedDecl(D))
2135     return;
2136 
2137   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2138     // typedefs can be referenced later on, so the diagnostics are emitted
2139     // at end-of-translation-unit.
2140     UnusedLocalTypedefNameCandidates.insert(TD);
2141     return;
2142   }
2143 
2144   FixItHint Hint;
2145   GenerateFixForUnusedDecl(D, Context, Hint);
2146 
2147   unsigned DiagID;
2148   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2149     DiagID = diag::warn_unused_exception_param;
2150   else if (isa<LabelDecl>(D))
2151     DiagID = diag::warn_unused_label;
2152   else
2153     DiagID = diag::warn_unused_variable;
2154 
2155   SourceLocation DiagLoc = D->getLocation();
2156   DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2157 }
2158 
2159 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2160                                     DiagReceiverTy DiagReceiver) {
2161   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2162   // it's not really unused.
2163   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2164       VD->hasAttr<CleanupAttr>())
2165     return;
2166 
2167   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2168 
2169   if (Ty->isReferenceType() || Ty->isDependentType())
2170     return;
2171 
2172   if (const TagType *TT = Ty->getAs<TagType>()) {
2173     const TagDecl *Tag = TT->getDecl();
2174     if (Tag->hasAttr<UnusedAttr>())
2175       return;
2176     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2177     // mimic gcc's behavior.
2178     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2179       if (!RD->hasAttr<WarnUnusedAttr>())
2180         return;
2181     }
2182   }
2183 
2184   // Don't warn about __block Objective-C pointer variables, as they might
2185   // be assigned in the block but not used elsewhere for the purpose of lifetime
2186   // extension.
2187   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2188     return;
2189 
2190   // Don't warn about Objective-C pointer variables with precise lifetime
2191   // semantics; they can be used to ensure ARC releases the object at a known
2192   // time, which may mean assignment but no other references.
2193   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2194     return;
2195 
2196   auto iter = RefsMinusAssignments.find(VD);
2197   if (iter == RefsMinusAssignments.end())
2198     return;
2199 
2200   assert(iter->getSecond() >= 0 &&
2201          "Found a negative number of references to a VarDecl");
2202   if (iter->getSecond() != 0)
2203     return;
2204   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2205                                          : diag::warn_unused_but_set_variable;
2206   DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2207 }
2208 
2209 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2210                              Sema::DiagReceiverTy DiagReceiver) {
2211   // Verify that we have no forward references left.  If so, there was a goto
2212   // or address of a label taken, but no definition of it.  Label fwd
2213   // definitions are indicated with a null substmt which is also not a resolved
2214   // MS inline assembly label name.
2215   bool Diagnose = false;
2216   if (L->isMSAsmLabel())
2217     Diagnose = !L->isResolvedMSAsmLabel();
2218   else
2219     Diagnose = L->getStmt() == nullptr;
2220   if (Diagnose)
2221     DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2222                                        << L);
2223 }
2224 
2225 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2226   S->applyNRVO();
2227 
2228   if (S->decl_empty()) return;
2229   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2230          "Scope shouldn't contain decls!");
2231 
2232   /// We visit the decls in non-deterministic order, but we want diagnostics
2233   /// emitted in deterministic order. Collect any diagnostic that may be emitted
2234   /// and sort the diagnostics before emitting them, after we visited all decls.
2235   struct LocAndDiag {
2236     SourceLocation Loc;
2237     std::optional<SourceLocation> PreviousDeclLoc;
2238     PartialDiagnostic PD;
2239   };
2240   SmallVector<LocAndDiag, 16> DeclDiags;
2241   auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2242     DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2243   };
2244   auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2245                                       SourceLocation PreviousDeclLoc,
2246                                       PartialDiagnostic PD) {
2247     DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2248   };
2249 
2250   for (auto *TmpD : S->decls()) {
2251     assert(TmpD && "This decl didn't get pushed??");
2252 
2253     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2254     NamedDecl *D = cast<NamedDecl>(TmpD);
2255 
2256     // Diagnose unused variables in this scope.
2257     if (!S->hasUnrecoverableErrorOccurred()) {
2258       DiagnoseUnusedDecl(D, addDiag);
2259       if (const auto *RD = dyn_cast<RecordDecl>(D))
2260         DiagnoseUnusedNestedTypedefs(RD, addDiag);
2261       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2262         DiagnoseUnusedButSetDecl(VD, addDiag);
2263         RefsMinusAssignments.erase(VD);
2264       }
2265     }
2266 
2267     if (!D->getDeclName()) continue;
2268 
2269     // If this was a forward reference to a label, verify it was defined.
2270     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2271       CheckPoppedLabel(LD, *this, addDiag);
2272 
2273     // Remove this name from our lexical scope, and warn on it if we haven't
2274     // already.
2275     IdResolver.RemoveDecl(D);
2276     auto ShadowI = ShadowingDecls.find(D);
2277     if (ShadowI != ShadowingDecls.end()) {
2278       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2279         addDiagWithPrev(D->getLocation(), FD->getLocation(),
2280                         PDiag(diag::warn_ctor_parm_shadows_field)
2281                             << D << FD << FD->getParent());
2282       }
2283       ShadowingDecls.erase(ShadowI);
2284     }
2285   }
2286 
2287   llvm::sort(DeclDiags,
2288              [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2289                // The particular order for diagnostics is not important, as long
2290                // as the order is deterministic. Using the raw location is going
2291                // to generally be in source order unless there are macro
2292                // expansions involved.
2293                return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2294              });
2295   for (const LocAndDiag &D : DeclDiags) {
2296     Diag(D.Loc, D.PD);
2297     if (D.PreviousDeclLoc)
2298       Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2299   }
2300 }
2301 
2302 /// Look for an Objective-C class in the translation unit.
2303 ///
2304 /// \param Id The name of the Objective-C class we're looking for. If
2305 /// typo-correction fixes this name, the Id will be updated
2306 /// to the fixed name.
2307 ///
2308 /// \param IdLoc The location of the name in the translation unit.
2309 ///
2310 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2311 /// if there is no class with the given name.
2312 ///
2313 /// \returns The declaration of the named Objective-C class, or NULL if the
2314 /// class could not be found.
2315 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2316                                               SourceLocation IdLoc,
2317                                               bool DoTypoCorrection) {
2318   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2319   // creation from this context.
2320   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2321 
2322   if (!IDecl && DoTypoCorrection) {
2323     // Perform typo correction at the given location, but only if we
2324     // find an Objective-C class name.
2325     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2326     if (TypoCorrection C =
2327             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2328                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2329       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2330       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2331       Id = IDecl->getIdentifier();
2332     }
2333   }
2334   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2335   // This routine must always return a class definition, if any.
2336   if (Def && Def->getDefinition())
2337       Def = Def->getDefinition();
2338   return Def;
2339 }
2340 
2341 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2342 /// from S, where a non-field would be declared. This routine copes
2343 /// with the difference between C and C++ scoping rules in structs and
2344 /// unions. For example, the following code is well-formed in C but
2345 /// ill-formed in C++:
2346 /// @code
2347 /// struct S6 {
2348 ///   enum { BAR } e;
2349 /// };
2350 ///
2351 /// void test_S6() {
2352 ///   struct S6 a;
2353 ///   a.e = BAR;
2354 /// }
2355 /// @endcode
2356 /// For the declaration of BAR, this routine will return a different
2357 /// scope. The scope S will be the scope of the unnamed enumeration
2358 /// within S6. In C++, this routine will return the scope associated
2359 /// with S6, because the enumeration's scope is a transparent
2360 /// context but structures can contain non-field names. In C, this
2361 /// routine will return the translation unit scope, since the
2362 /// enumeration's scope is a transparent context and structures cannot
2363 /// contain non-field names.
2364 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2365   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2366          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2367          (S->isClassScope() && !getLangOpts().CPlusPlus))
2368     S = S->getParent();
2369   return S;
2370 }
2371 
2372 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2373                                ASTContext::GetBuiltinTypeError Error) {
2374   switch (Error) {
2375   case ASTContext::GE_None:
2376     return "";
2377   case ASTContext::GE_Missing_type:
2378     return BuiltinInfo.getHeaderName(ID);
2379   case ASTContext::GE_Missing_stdio:
2380     return "stdio.h";
2381   case ASTContext::GE_Missing_setjmp:
2382     return "setjmp.h";
2383   case ASTContext::GE_Missing_ucontext:
2384     return "ucontext.h";
2385   }
2386   llvm_unreachable("unhandled error kind");
2387 }
2388 
2389 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2390                                   unsigned ID, SourceLocation Loc) {
2391   DeclContext *Parent = Context.getTranslationUnitDecl();
2392 
2393   if (getLangOpts().CPlusPlus) {
2394     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2395         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2396     CLinkageDecl->setImplicit();
2397     Parent->addDecl(CLinkageDecl);
2398     Parent = CLinkageDecl;
2399   }
2400 
2401   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2402                                            /*TInfo=*/nullptr, SC_Extern,
2403                                            getCurFPFeatures().isFPConstrained(),
2404                                            false, Type->isFunctionProtoType());
2405   New->setImplicit();
2406   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2407 
2408   // Create Decl objects for each parameter, adding them to the
2409   // FunctionDecl.
2410   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2411     SmallVector<ParmVarDecl *, 16> Params;
2412     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2413       ParmVarDecl *parm = ParmVarDecl::Create(
2414           Context, New, SourceLocation(), SourceLocation(), nullptr,
2415           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2416       parm->setScopeInfo(0, i);
2417       Params.push_back(parm);
2418     }
2419     New->setParams(Params);
2420   }
2421 
2422   AddKnownFunctionAttributes(New);
2423   return New;
2424 }
2425 
2426 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2427 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2428 /// if we're creating this built-in in anticipation of redeclaring the
2429 /// built-in.
2430 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2431                                      Scope *S, bool ForRedeclaration,
2432                                      SourceLocation Loc) {
2433   LookupNecessaryTypesForBuiltin(S, ID);
2434 
2435   ASTContext::GetBuiltinTypeError Error;
2436   QualType R = Context.GetBuiltinType(ID, Error);
2437   if (Error) {
2438     if (!ForRedeclaration)
2439       return nullptr;
2440 
2441     // If we have a builtin without an associated type we should not emit a
2442     // warning when we were not able to find a type for it.
2443     if (Error == ASTContext::GE_Missing_type ||
2444         Context.BuiltinInfo.allowTypeMismatch(ID))
2445       return nullptr;
2446 
2447     // If we could not find a type for setjmp it is because the jmp_buf type was
2448     // not defined prior to the setjmp declaration.
2449     if (Error == ASTContext::GE_Missing_setjmp) {
2450       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2451           << Context.BuiltinInfo.getName(ID);
2452       return nullptr;
2453     }
2454 
2455     // Generally, we emit a warning that the declaration requires the
2456     // appropriate header.
2457     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2458         << getHeaderName(Context.BuiltinInfo, ID, Error)
2459         << Context.BuiltinInfo.getName(ID);
2460     return nullptr;
2461   }
2462 
2463   if (!ForRedeclaration &&
2464       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2465        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2466     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2467                            : diag::ext_implicit_lib_function_decl)
2468         << Context.BuiltinInfo.getName(ID) << R;
2469     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2470       Diag(Loc, diag::note_include_header_or_declare)
2471           << Header << Context.BuiltinInfo.getName(ID);
2472   }
2473 
2474   if (R.isNull())
2475     return nullptr;
2476 
2477   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2478   RegisterLocallyScopedExternCDecl(New, S);
2479 
2480   // TUScope is the translation-unit scope to insert this function into.
2481   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2482   // relate Scopes to DeclContexts, and probably eliminate CurContext
2483   // entirely, but we're not there yet.
2484   DeclContext *SavedContext = CurContext;
2485   CurContext = New->getDeclContext();
2486   PushOnScopeChains(New, TUScope);
2487   CurContext = SavedContext;
2488   return New;
2489 }
2490 
2491 /// Typedef declarations don't have linkage, but they still denote the same
2492 /// entity if their types are the same.
2493 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2494 /// isSameEntity.
2495 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2496                                                      TypedefNameDecl *Decl,
2497                                                      LookupResult &Previous) {
2498   // This is only interesting when modules are enabled.
2499   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2500     return;
2501 
2502   // Empty sets are uninteresting.
2503   if (Previous.empty())
2504     return;
2505 
2506   LookupResult::Filter Filter = Previous.makeFilter();
2507   while (Filter.hasNext()) {
2508     NamedDecl *Old = Filter.next();
2509 
2510     // Non-hidden declarations are never ignored.
2511     if (S.isVisible(Old))
2512       continue;
2513 
2514     // Declarations of the same entity are not ignored, even if they have
2515     // different linkages.
2516     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2517       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2518                                 Decl->getUnderlyingType()))
2519         continue;
2520 
2521       // If both declarations give a tag declaration a typedef name for linkage
2522       // purposes, then they declare the same entity.
2523       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2524           Decl->getAnonDeclWithTypedefName())
2525         continue;
2526     }
2527 
2528     Filter.erase();
2529   }
2530 
2531   Filter.done();
2532 }
2533 
2534 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2535   QualType OldType;
2536   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2537     OldType = OldTypedef->getUnderlyingType();
2538   else
2539     OldType = Context.getTypeDeclType(Old);
2540   QualType NewType = New->getUnderlyingType();
2541 
2542   if (NewType->isVariablyModifiedType()) {
2543     // Must not redefine a typedef with a variably-modified type.
2544     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2545     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2546       << Kind << NewType;
2547     if (Old->getLocation().isValid())
2548       notePreviousDefinition(Old, New->getLocation());
2549     New->setInvalidDecl();
2550     return true;
2551   }
2552 
2553   if (OldType != NewType &&
2554       !OldType->isDependentType() &&
2555       !NewType->isDependentType() &&
2556       !Context.hasSameType(OldType, NewType)) {
2557     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2558     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2559       << Kind << NewType << OldType;
2560     if (Old->getLocation().isValid())
2561       notePreviousDefinition(Old, New->getLocation());
2562     New->setInvalidDecl();
2563     return true;
2564   }
2565   return false;
2566 }
2567 
2568 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2569 /// same name and scope as a previous declaration 'Old'.  Figure out
2570 /// how to resolve this situation, merging decls or emitting
2571 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2572 ///
2573 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2574                                 LookupResult &OldDecls) {
2575   // If the new decl is known invalid already, don't bother doing any
2576   // merging checks.
2577   if (New->isInvalidDecl()) return;
2578 
2579   // Allow multiple definitions for ObjC built-in typedefs.
2580   // FIXME: Verify the underlying types are equivalent!
2581   if (getLangOpts().ObjC) {
2582     const IdentifierInfo *TypeID = New->getIdentifier();
2583     switch (TypeID->getLength()) {
2584     default: break;
2585     case 2:
2586       {
2587         if (!TypeID->isStr("id"))
2588           break;
2589         QualType T = New->getUnderlyingType();
2590         if (!T->isPointerType())
2591           break;
2592         if (!T->isVoidPointerType()) {
2593           QualType PT = T->castAs<PointerType>()->getPointeeType();
2594           if (!PT->isStructureType())
2595             break;
2596         }
2597         Context.setObjCIdRedefinitionType(T);
2598         // Install the built-in type for 'id', ignoring the current definition.
2599         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2600         return;
2601       }
2602     case 5:
2603       if (!TypeID->isStr("Class"))
2604         break;
2605       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2606       // Install the built-in type for 'Class', ignoring the current definition.
2607       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2608       return;
2609     case 3:
2610       if (!TypeID->isStr("SEL"))
2611         break;
2612       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2613       // Install the built-in type for 'SEL', ignoring the current definition.
2614       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2615       return;
2616     }
2617     // Fall through - the typedef name was not a builtin type.
2618   }
2619 
2620   // Verify the old decl was also a type.
2621   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2622   if (!Old) {
2623     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2624       << New->getDeclName();
2625 
2626     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2627     if (OldD->getLocation().isValid())
2628       notePreviousDefinition(OldD, New->getLocation());
2629 
2630     return New->setInvalidDecl();
2631   }
2632 
2633   // If the old declaration is invalid, just give up here.
2634   if (Old->isInvalidDecl())
2635     return New->setInvalidDecl();
2636 
2637   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2638     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2639     auto *NewTag = New->getAnonDeclWithTypedefName();
2640     NamedDecl *Hidden = nullptr;
2641     if (OldTag && NewTag &&
2642         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2643         !hasVisibleDefinition(OldTag, &Hidden)) {
2644       // There is a definition of this tag, but it is not visible. Use it
2645       // instead of our tag.
2646       New->setTypeForDecl(OldTD->getTypeForDecl());
2647       if (OldTD->isModed())
2648         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2649                                     OldTD->getUnderlyingType());
2650       else
2651         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2652 
2653       // Make the old tag definition visible.
2654       makeMergedDefinitionVisible(Hidden);
2655 
2656       // If this was an unscoped enumeration, yank all of its enumerators
2657       // out of the scope.
2658       if (isa<EnumDecl>(NewTag)) {
2659         Scope *EnumScope = getNonFieldDeclScope(S);
2660         for (auto *D : NewTag->decls()) {
2661           auto *ED = cast<EnumConstantDecl>(D);
2662           assert(EnumScope->isDeclScope(ED));
2663           EnumScope->RemoveDecl(ED);
2664           IdResolver.RemoveDecl(ED);
2665           ED->getLexicalDeclContext()->removeDecl(ED);
2666         }
2667       }
2668     }
2669   }
2670 
2671   // If the typedef types are not identical, reject them in all languages and
2672   // with any extensions enabled.
2673   if (isIncompatibleTypedef(Old, New))
2674     return;
2675 
2676   // The types match.  Link up the redeclaration chain and merge attributes if
2677   // the old declaration was a typedef.
2678   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2679     New->setPreviousDecl(Typedef);
2680     mergeDeclAttributes(New, Old);
2681   }
2682 
2683   if (getLangOpts().MicrosoftExt)
2684     return;
2685 
2686   if (getLangOpts().CPlusPlus) {
2687     // C++ [dcl.typedef]p2:
2688     //   In a given non-class scope, a typedef specifier can be used to
2689     //   redefine the name of any type declared in that scope to refer
2690     //   to the type to which it already refers.
2691     if (!isa<CXXRecordDecl>(CurContext))
2692       return;
2693 
2694     // C++0x [dcl.typedef]p4:
2695     //   In a given class scope, a typedef specifier can be used to redefine
2696     //   any class-name declared in that scope that is not also a typedef-name
2697     //   to refer to the type to which it already refers.
2698     //
2699     // This wording came in via DR424, which was a correction to the
2700     // wording in DR56, which accidentally banned code like:
2701     //
2702     //   struct S {
2703     //     typedef struct A { } A;
2704     //   };
2705     //
2706     // in the C++03 standard. We implement the C++0x semantics, which
2707     // allow the above but disallow
2708     //
2709     //   struct S {
2710     //     typedef int I;
2711     //     typedef int I;
2712     //   };
2713     //
2714     // since that was the intent of DR56.
2715     if (!isa<TypedefNameDecl>(Old))
2716       return;
2717 
2718     Diag(New->getLocation(), diag::err_redefinition)
2719       << New->getDeclName();
2720     notePreviousDefinition(Old, New->getLocation());
2721     return New->setInvalidDecl();
2722   }
2723 
2724   // Modules always permit redefinition of typedefs, as does C11.
2725   if (getLangOpts().Modules || getLangOpts().C11)
2726     return;
2727 
2728   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2729   // is normally mapped to an error, but can be controlled with
2730   // -Wtypedef-redefinition.  If either the original or the redefinition is
2731   // in a system header, don't emit this for compatibility with GCC.
2732   if (getDiagnostics().getSuppressSystemWarnings() &&
2733       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2734       (Old->isImplicit() ||
2735        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2736        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2737     return;
2738 
2739   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2740     << New->getDeclName();
2741   notePreviousDefinition(Old, New->getLocation());
2742 }
2743 
2744 /// DeclhasAttr - returns true if decl Declaration already has the target
2745 /// attribute.
2746 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2747   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2748   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2749   for (const auto *i : D->attrs())
2750     if (i->getKind() == A->getKind()) {
2751       if (Ann) {
2752         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2753           return true;
2754         continue;
2755       }
2756       // FIXME: Don't hardcode this check
2757       if (OA && isa<OwnershipAttr>(i))
2758         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2759       return true;
2760     }
2761 
2762   return false;
2763 }
2764 
2765 static bool isAttributeTargetADefinition(Decl *D) {
2766   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2767     return VD->isThisDeclarationADefinition();
2768   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2769     return TD->isCompleteDefinition() || TD->isBeingDefined();
2770   return true;
2771 }
2772 
2773 /// Merge alignment attributes from \p Old to \p New, taking into account the
2774 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2775 ///
2776 /// \return \c true if any attributes were added to \p New.
2777 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2778   // Look for alignas attributes on Old, and pick out whichever attribute
2779   // specifies the strictest alignment requirement.
2780   AlignedAttr *OldAlignasAttr = nullptr;
2781   AlignedAttr *OldStrictestAlignAttr = nullptr;
2782   unsigned OldAlign = 0;
2783   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2784     // FIXME: We have no way of representing inherited dependent alignments
2785     // in a case like:
2786     //   template<int A, int B> struct alignas(A) X;
2787     //   template<int A, int B> struct alignas(B) X {};
2788     // For now, we just ignore any alignas attributes which are not on the
2789     // definition in such a case.
2790     if (I->isAlignmentDependent())
2791       return false;
2792 
2793     if (I->isAlignas())
2794       OldAlignasAttr = I;
2795 
2796     unsigned Align = I->getAlignment(S.Context);
2797     if (Align > OldAlign) {
2798       OldAlign = Align;
2799       OldStrictestAlignAttr = I;
2800     }
2801   }
2802 
2803   // Look for alignas attributes on New.
2804   AlignedAttr *NewAlignasAttr = nullptr;
2805   unsigned NewAlign = 0;
2806   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2807     if (I->isAlignmentDependent())
2808       return false;
2809 
2810     if (I->isAlignas())
2811       NewAlignasAttr = I;
2812 
2813     unsigned Align = I->getAlignment(S.Context);
2814     if (Align > NewAlign)
2815       NewAlign = Align;
2816   }
2817 
2818   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2819     // Both declarations have 'alignas' attributes. We require them to match.
2820     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2821     // fall short. (If two declarations both have alignas, they must both match
2822     // every definition, and so must match each other if there is a definition.)
2823 
2824     // If either declaration only contains 'alignas(0)' specifiers, then it
2825     // specifies the natural alignment for the type.
2826     if (OldAlign == 0 || NewAlign == 0) {
2827       QualType Ty;
2828       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2829         Ty = VD->getType();
2830       else
2831         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2832 
2833       if (OldAlign == 0)
2834         OldAlign = S.Context.getTypeAlign(Ty);
2835       if (NewAlign == 0)
2836         NewAlign = S.Context.getTypeAlign(Ty);
2837     }
2838 
2839     if (OldAlign != NewAlign) {
2840       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2841         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2842         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2843       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2844     }
2845   }
2846 
2847   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2848     // C++11 [dcl.align]p6:
2849     //   if any declaration of an entity has an alignment-specifier,
2850     //   every defining declaration of that entity shall specify an
2851     //   equivalent alignment.
2852     // C11 6.7.5/7:
2853     //   If the definition of an object does not have an alignment
2854     //   specifier, any other declaration of that object shall also
2855     //   have no alignment specifier.
2856     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2857       << OldAlignasAttr;
2858     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2859       << OldAlignasAttr;
2860   }
2861 
2862   bool AnyAdded = false;
2863 
2864   // Ensure we have an attribute representing the strictest alignment.
2865   if (OldAlign > NewAlign) {
2866     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2867     Clone->setInherited(true);
2868     New->addAttr(Clone);
2869     AnyAdded = true;
2870   }
2871 
2872   // Ensure we have an alignas attribute if the old declaration had one.
2873   if (OldAlignasAttr && !NewAlignasAttr &&
2874       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2875     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2876     Clone->setInherited(true);
2877     New->addAttr(Clone);
2878     AnyAdded = true;
2879   }
2880 
2881   return AnyAdded;
2882 }
2883 
2884 #define WANT_DECL_MERGE_LOGIC
2885 #include "clang/Sema/AttrParsedAttrImpl.inc"
2886 #undef WANT_DECL_MERGE_LOGIC
2887 
2888 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2889                                const InheritableAttr *Attr,
2890                                Sema::AvailabilityMergeKind AMK) {
2891   // Diagnose any mutual exclusions between the attribute that we want to add
2892   // and attributes that already exist on the declaration.
2893   if (!DiagnoseMutualExclusions(S, D, Attr))
2894     return false;
2895 
2896   // This function copies an attribute Attr from a previous declaration to the
2897   // new declaration D if the new declaration doesn't itself have that attribute
2898   // yet or if that attribute allows duplicates.
2899   // If you're adding a new attribute that requires logic different from
2900   // "use explicit attribute on decl if present, else use attribute from
2901   // previous decl", for example if the attribute needs to be consistent
2902   // between redeclarations, you need to call a custom merge function here.
2903   InheritableAttr *NewAttr = nullptr;
2904   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2905     NewAttr = S.mergeAvailabilityAttr(
2906         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2907         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2908         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2909         AA->getPriority());
2910   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2911     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2912   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2913     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2914   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2915     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2916   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2917     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2918   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2919     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2920   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2921     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2922                                 FA->getFirstArg());
2923   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2924     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2925   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2926     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2927   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2928     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2929                                        IA->getInheritanceModel());
2930   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2931     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2932                                       &S.Context.Idents.get(AA->getSpelling()));
2933   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2934            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2935             isa<CUDAGlobalAttr>(Attr))) {
2936     // CUDA target attributes are part of function signature for
2937     // overloading purposes and must not be merged.
2938     return false;
2939   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2940     NewAttr = S.mergeMinSizeAttr(D, *MA);
2941   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2942     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2943   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2944     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2945   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2946     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2947   else if (isa<AlignedAttr>(Attr))
2948     // AlignedAttrs are handled separately, because we need to handle all
2949     // such attributes on a declaration at the same time.
2950     NewAttr = nullptr;
2951   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2952            (AMK == Sema::AMK_Override ||
2953             AMK == Sema::AMK_ProtocolImplementation ||
2954             AMK == Sema::AMK_OptionalProtocolImplementation))
2955     NewAttr = nullptr;
2956   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2957     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2958   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2959     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2960   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2961     NewAttr = S.mergeImportNameAttr(D, *INA);
2962   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2963     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2964   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2965     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2966   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2967     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2968   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2969     NewAttr =
2970         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2971   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2972     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2973   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2974     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2975 
2976   if (NewAttr) {
2977     NewAttr->setInherited(true);
2978     D->addAttr(NewAttr);
2979     if (isa<MSInheritanceAttr>(NewAttr))
2980       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2981     return true;
2982   }
2983 
2984   return false;
2985 }
2986 
2987 static const NamedDecl *getDefinition(const Decl *D) {
2988   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2989     return TD->getDefinition();
2990   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2991     const VarDecl *Def = VD->getDefinition();
2992     if (Def)
2993       return Def;
2994     return VD->getActingDefinition();
2995   }
2996   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2997     const FunctionDecl *Def = nullptr;
2998     if (FD->isDefined(Def, true))
2999       return Def;
3000   }
3001   return nullptr;
3002 }
3003 
3004 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3005   for (const auto *Attribute : D->attrs())
3006     if (Attribute->getKind() == Kind)
3007       return true;
3008   return false;
3009 }
3010 
3011 /// checkNewAttributesAfterDef - If we already have a definition, check that
3012 /// there are no new attributes in this declaration.
3013 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3014   if (!New->hasAttrs())
3015     return;
3016 
3017   const NamedDecl *Def = getDefinition(Old);
3018   if (!Def || Def == New)
3019     return;
3020 
3021   AttrVec &NewAttributes = New->getAttrs();
3022   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3023     const Attr *NewAttribute = NewAttributes[I];
3024 
3025     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3026       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3027         Sema::SkipBodyInfo SkipBody;
3028         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3029 
3030         // If we're skipping this definition, drop the "alias" attribute.
3031         if (SkipBody.ShouldSkip) {
3032           NewAttributes.erase(NewAttributes.begin() + I);
3033           --E;
3034           continue;
3035         }
3036       } else {
3037         VarDecl *VD = cast<VarDecl>(New);
3038         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3039                                 VarDecl::TentativeDefinition
3040                             ? diag::err_alias_after_tentative
3041                             : diag::err_redefinition;
3042         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3043         if (Diag == diag::err_redefinition)
3044           S.notePreviousDefinition(Def, VD->getLocation());
3045         else
3046           S.Diag(Def->getLocation(), diag::note_previous_definition);
3047         VD->setInvalidDecl();
3048       }
3049       ++I;
3050       continue;
3051     }
3052 
3053     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3054       // Tentative definitions are only interesting for the alias check above.
3055       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3056         ++I;
3057         continue;
3058       }
3059     }
3060 
3061     if (hasAttribute(Def, NewAttribute->getKind())) {
3062       ++I;
3063       continue; // regular attr merging will take care of validating this.
3064     }
3065 
3066     if (isa<C11NoReturnAttr>(NewAttribute)) {
3067       // C's _Noreturn is allowed to be added to a function after it is defined.
3068       ++I;
3069       continue;
3070     } else if (isa<UuidAttr>(NewAttribute)) {
3071       // msvc will allow a subsequent definition to add an uuid to a class
3072       ++I;
3073       continue;
3074     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3075       if (AA->isAlignas()) {
3076         // C++11 [dcl.align]p6:
3077         //   if any declaration of an entity has an alignment-specifier,
3078         //   every defining declaration of that entity shall specify an
3079         //   equivalent alignment.
3080         // C11 6.7.5/7:
3081         //   If the definition of an object does not have an alignment
3082         //   specifier, any other declaration of that object shall also
3083         //   have no alignment specifier.
3084         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3085           << AA;
3086         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3087           << AA;
3088         NewAttributes.erase(NewAttributes.begin() + I);
3089         --E;
3090         continue;
3091       }
3092     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3093       // If there is a C definition followed by a redeclaration with this
3094       // attribute then there are two different definitions. In C++, prefer the
3095       // standard diagnostics.
3096       if (!S.getLangOpts().CPlusPlus) {
3097         S.Diag(NewAttribute->getLocation(),
3098                diag::err_loader_uninitialized_redeclaration);
3099         S.Diag(Def->getLocation(), diag::note_previous_definition);
3100         NewAttributes.erase(NewAttributes.begin() + I);
3101         --E;
3102         continue;
3103       }
3104     } else if (isa<SelectAnyAttr>(NewAttribute) &&
3105                cast<VarDecl>(New)->isInline() &&
3106                !cast<VarDecl>(New)->isInlineSpecified()) {
3107       // Don't warn about applying selectany to implicitly inline variables.
3108       // Older compilers and language modes would require the use of selectany
3109       // to make such variables inline, and it would have no effect if we
3110       // honored it.
3111       ++I;
3112       continue;
3113     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3114       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3115       // declarations after definitions.
3116       ++I;
3117       continue;
3118     }
3119 
3120     S.Diag(NewAttribute->getLocation(),
3121            diag::warn_attribute_precede_definition);
3122     S.Diag(Def->getLocation(), diag::note_previous_definition);
3123     NewAttributes.erase(NewAttributes.begin() + I);
3124     --E;
3125   }
3126 }
3127 
3128 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3129                                      const ConstInitAttr *CIAttr,
3130                                      bool AttrBeforeInit) {
3131   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3132 
3133   // Figure out a good way to write this specifier on the old declaration.
3134   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3135   // enough of the attribute list spelling information to extract that without
3136   // heroics.
3137   std::string SuitableSpelling;
3138   if (S.getLangOpts().CPlusPlus20)
3139     SuitableSpelling = std::string(
3140         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3141   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3142     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3143         InsertLoc, {tok::l_square, tok::l_square,
3144                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3145                     S.PP.getIdentifierInfo("require_constant_initialization"),
3146                     tok::r_square, tok::r_square}));
3147   if (SuitableSpelling.empty())
3148     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3149         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3150                     S.PP.getIdentifierInfo("require_constant_initialization"),
3151                     tok::r_paren, tok::r_paren}));
3152   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3153     SuitableSpelling = "constinit";
3154   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3155     SuitableSpelling = "[[clang::require_constant_initialization]]";
3156   if (SuitableSpelling.empty())
3157     SuitableSpelling = "__attribute__((require_constant_initialization))";
3158   SuitableSpelling += " ";
3159 
3160   if (AttrBeforeInit) {
3161     // extern constinit int a;
3162     // int a = 0; // error (missing 'constinit'), accepted as extension
3163     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3164     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3165         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3166     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3167   } else {
3168     // int a = 0;
3169     // constinit extern int a; // error (missing 'constinit')
3170     S.Diag(CIAttr->getLocation(),
3171            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3172                                  : diag::warn_require_const_init_added_too_late)
3173         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3174     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3175         << CIAttr->isConstinit()
3176         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3177   }
3178 }
3179 
3180 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3181 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3182                                AvailabilityMergeKind AMK) {
3183   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3184     UsedAttr *NewAttr = OldAttr->clone(Context);
3185     NewAttr->setInherited(true);
3186     New->addAttr(NewAttr);
3187   }
3188   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3189     RetainAttr *NewAttr = OldAttr->clone(Context);
3190     NewAttr->setInherited(true);
3191     New->addAttr(NewAttr);
3192   }
3193 
3194   if (!Old->hasAttrs() && !New->hasAttrs())
3195     return;
3196 
3197   // [dcl.constinit]p1:
3198   //   If the [constinit] specifier is applied to any declaration of a
3199   //   variable, it shall be applied to the initializing declaration.
3200   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3201   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3202   if (bool(OldConstInit) != bool(NewConstInit)) {
3203     const auto *OldVD = cast<VarDecl>(Old);
3204     auto *NewVD = cast<VarDecl>(New);
3205 
3206     // Find the initializing declaration. Note that we might not have linked
3207     // the new declaration into the redeclaration chain yet.
3208     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3209     if (!InitDecl &&
3210         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3211       InitDecl = NewVD;
3212 
3213     if (InitDecl == NewVD) {
3214       // This is the initializing declaration. If it would inherit 'constinit',
3215       // that's ill-formed. (Note that we do not apply this to the attribute
3216       // form).
3217       if (OldConstInit && OldConstInit->isConstinit())
3218         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3219                                  /*AttrBeforeInit=*/true);
3220     } else if (NewConstInit) {
3221       // This is the first time we've been told that this declaration should
3222       // have a constant initializer. If we already saw the initializing
3223       // declaration, this is too late.
3224       if (InitDecl && InitDecl != NewVD) {
3225         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3226                                  /*AttrBeforeInit=*/false);
3227         NewVD->dropAttr<ConstInitAttr>();
3228       }
3229     }
3230   }
3231 
3232   // Attributes declared post-definition are currently ignored.
3233   checkNewAttributesAfterDef(*this, New, Old);
3234 
3235   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3236     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3237       if (!OldA->isEquivalent(NewA)) {
3238         // This redeclaration changes __asm__ label.
3239         Diag(New->getLocation(), diag::err_different_asm_label);
3240         Diag(OldA->getLocation(), diag::note_previous_declaration);
3241       }
3242     } else if (Old->isUsed()) {
3243       // This redeclaration adds an __asm__ label to a declaration that has
3244       // already been ODR-used.
3245       Diag(New->getLocation(), diag::err_late_asm_label_name)
3246         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3247     }
3248   }
3249 
3250   // Re-declaration cannot add abi_tag's.
3251   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3252     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3253       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3254         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3255           Diag(NewAbiTagAttr->getLocation(),
3256                diag::err_new_abi_tag_on_redeclaration)
3257               << NewTag;
3258           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3259         }
3260       }
3261     } else {
3262       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3263       Diag(Old->getLocation(), diag::note_previous_declaration);
3264     }
3265   }
3266 
3267   // This redeclaration adds a section attribute.
3268   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3269     if (auto *VD = dyn_cast<VarDecl>(New)) {
3270       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3271         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3272         Diag(Old->getLocation(), diag::note_previous_declaration);
3273       }
3274     }
3275   }
3276 
3277   // Redeclaration adds code-seg attribute.
3278   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3279   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3280       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3281     Diag(New->getLocation(), diag::warn_mismatched_section)
3282          << 0 /*codeseg*/;
3283     Diag(Old->getLocation(), diag::note_previous_declaration);
3284   }
3285 
3286   if (!Old->hasAttrs())
3287     return;
3288 
3289   bool foundAny = New->hasAttrs();
3290 
3291   // Ensure that any moving of objects within the allocated map is done before
3292   // we process them.
3293   if (!foundAny) New->setAttrs(AttrVec());
3294 
3295   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3296     // Ignore deprecated/unavailable/availability attributes if requested.
3297     AvailabilityMergeKind LocalAMK = AMK_None;
3298     if (isa<DeprecatedAttr>(I) ||
3299         isa<UnavailableAttr>(I) ||
3300         isa<AvailabilityAttr>(I)) {
3301       switch (AMK) {
3302       case AMK_None:
3303         continue;
3304 
3305       case AMK_Redeclaration:
3306       case AMK_Override:
3307       case AMK_ProtocolImplementation:
3308       case AMK_OptionalProtocolImplementation:
3309         LocalAMK = AMK;
3310         break;
3311       }
3312     }
3313 
3314     // Already handled.
3315     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3316       continue;
3317 
3318     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3319       foundAny = true;
3320   }
3321 
3322   if (mergeAlignedAttrs(*this, New, Old))
3323     foundAny = true;
3324 
3325   if (!foundAny) New->dropAttrs();
3326 }
3327 
3328 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3329 /// to the new one.
3330 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3331                                      const ParmVarDecl *oldDecl,
3332                                      Sema &S) {
3333   // C++11 [dcl.attr.depend]p2:
3334   //   The first declaration of a function shall specify the
3335   //   carries_dependency attribute for its declarator-id if any declaration
3336   //   of the function specifies the carries_dependency attribute.
3337   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3338   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3339     S.Diag(CDA->getLocation(),
3340            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3341     // Find the first declaration of the parameter.
3342     // FIXME: Should we build redeclaration chains for function parameters?
3343     const FunctionDecl *FirstFD =
3344       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3345     const ParmVarDecl *FirstVD =
3346       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3347     S.Diag(FirstVD->getLocation(),
3348            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3349   }
3350 
3351   if (!oldDecl->hasAttrs())
3352     return;
3353 
3354   bool foundAny = newDecl->hasAttrs();
3355 
3356   // Ensure that any moving of objects within the allocated map is
3357   // done before we process them.
3358   if (!foundAny) newDecl->setAttrs(AttrVec());
3359 
3360   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3361     if (!DeclHasAttr(newDecl, I)) {
3362       InheritableAttr *newAttr =
3363         cast<InheritableParamAttr>(I->clone(S.Context));
3364       newAttr->setInherited(true);
3365       newDecl->addAttr(newAttr);
3366       foundAny = true;
3367     }
3368   }
3369 
3370   if (!foundAny) newDecl->dropAttrs();
3371 }
3372 
3373 static bool EquivalentArrayTypes(QualType Old, QualType New,
3374                                  const ASTContext &Ctx) {
3375 
3376   auto NoSizeInfo = [&Ctx](QualType Ty) {
3377     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3378       return true;
3379     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3380       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3381     return false;
3382   };
3383 
3384   // `type[]` is equivalent to `type *` and `type[*]`.
3385   if (NoSizeInfo(Old) && NoSizeInfo(New))
3386     return true;
3387 
3388   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3389   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3390     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3391     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3392     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3393         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3394       return false;
3395     return true;
3396   }
3397 
3398   // Only compare size, ignore Size modifiers and CVR.
3399   if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3400     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3401            Ctx.getAsConstantArrayType(New)->getSize();
3402   }
3403 
3404   // Don't try to compare dependent sized array
3405   if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3406     return true;
3407   }
3408 
3409   return Old == New;
3410 }
3411 
3412 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3413                                 const ParmVarDecl *OldParam,
3414                                 Sema &S) {
3415   if (auto Oldnullability = OldParam->getType()->getNullability()) {
3416     if (auto Newnullability = NewParam->getType()->getNullability()) {
3417       if (*Oldnullability != *Newnullability) {
3418         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3419           << DiagNullabilityKind(
3420                *Newnullability,
3421                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3422                 != 0))
3423           << DiagNullabilityKind(
3424                *Oldnullability,
3425                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3426                 != 0));
3427         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3428       }
3429     } else {
3430       QualType NewT = NewParam->getType();
3431       NewT = S.Context.getAttributedType(
3432                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3433                          NewT, NewT);
3434       NewParam->setType(NewT);
3435     }
3436   }
3437   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3438   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3439   if (OldParamDT && NewParamDT &&
3440       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3441     QualType OldParamOT = OldParamDT->getOriginalType();
3442     QualType NewParamOT = NewParamDT->getOriginalType();
3443     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3444       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3445           << NewParam << NewParamOT;
3446       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3447           << OldParamOT;
3448     }
3449   }
3450 }
3451 
3452 namespace {
3453 
3454 /// Used in MergeFunctionDecl to keep track of function parameters in
3455 /// C.
3456 struct GNUCompatibleParamWarning {
3457   ParmVarDecl *OldParm;
3458   ParmVarDecl *NewParm;
3459   QualType PromotedType;
3460 };
3461 
3462 } // end anonymous namespace
3463 
3464 // Determine whether the previous declaration was a definition, implicit
3465 // declaration, or a declaration.
3466 template <typename T>
3467 static std::pair<diag::kind, SourceLocation>
3468 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3469   diag::kind PrevDiag;
3470   SourceLocation OldLocation = Old->getLocation();
3471   if (Old->isThisDeclarationADefinition())
3472     PrevDiag = diag::note_previous_definition;
3473   else if (Old->isImplicit()) {
3474     PrevDiag = diag::note_previous_implicit_declaration;
3475     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3476       if (FD->getBuiltinID())
3477         PrevDiag = diag::note_previous_builtin_declaration;
3478     }
3479     if (OldLocation.isInvalid())
3480       OldLocation = New->getLocation();
3481   } else
3482     PrevDiag = diag::note_previous_declaration;
3483   return std::make_pair(PrevDiag, OldLocation);
3484 }
3485 
3486 /// canRedefineFunction - checks if a function can be redefined. Currently,
3487 /// only extern inline functions can be redefined, and even then only in
3488 /// GNU89 mode.
3489 static bool canRedefineFunction(const FunctionDecl *FD,
3490                                 const LangOptions& LangOpts) {
3491   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3492           !LangOpts.CPlusPlus &&
3493           FD->isInlineSpecified() &&
3494           FD->getStorageClass() == SC_Extern);
3495 }
3496 
3497 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3498   const AttributedType *AT = T->getAs<AttributedType>();
3499   while (AT && !AT->isCallingConv())
3500     AT = AT->getModifiedType()->getAs<AttributedType>();
3501   return AT;
3502 }
3503 
3504 template <typename T>
3505 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3506   const DeclContext *DC = Old->getDeclContext();
3507   if (DC->isRecord())
3508     return false;
3509 
3510   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3511   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3512     return true;
3513   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3514     return true;
3515   return false;
3516 }
3517 
3518 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3519 static bool isExternC(VarTemplateDecl *) { return false; }
3520 static bool isExternC(FunctionTemplateDecl *) { return false; }
3521 
3522 /// Check whether a redeclaration of an entity introduced by a
3523 /// using-declaration is valid, given that we know it's not an overload
3524 /// (nor a hidden tag declaration).
3525 template<typename ExpectedDecl>
3526 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3527                                    ExpectedDecl *New) {
3528   // C++11 [basic.scope.declarative]p4:
3529   //   Given a set of declarations in a single declarative region, each of
3530   //   which specifies the same unqualified name,
3531   //   -- they shall all refer to the same entity, or all refer to functions
3532   //      and function templates; or
3533   //   -- exactly one declaration shall declare a class name or enumeration
3534   //      name that is not a typedef name and the other declarations shall all
3535   //      refer to the same variable or enumerator, or all refer to functions
3536   //      and function templates; in this case the class name or enumeration
3537   //      name is hidden (3.3.10).
3538 
3539   // C++11 [namespace.udecl]p14:
3540   //   If a function declaration in namespace scope or block scope has the
3541   //   same name and the same parameter-type-list as a function introduced
3542   //   by a using-declaration, and the declarations do not declare the same
3543   //   function, the program is ill-formed.
3544 
3545   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3546   if (Old &&
3547       !Old->getDeclContext()->getRedeclContext()->Equals(
3548           New->getDeclContext()->getRedeclContext()) &&
3549       !(isExternC(Old) && isExternC(New)))
3550     Old = nullptr;
3551 
3552   if (!Old) {
3553     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3554     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3555     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3556     return true;
3557   }
3558   return false;
3559 }
3560 
3561 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3562                                             const FunctionDecl *B) {
3563   assert(A->getNumParams() == B->getNumParams());
3564 
3565   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3566     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3567     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3568     if (AttrA == AttrB)
3569       return true;
3570     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3571            AttrA->isDynamic() == AttrB->isDynamic();
3572   };
3573 
3574   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3575 }
3576 
3577 /// If necessary, adjust the semantic declaration context for a qualified
3578 /// declaration to name the correct inline namespace within the qualifier.
3579 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3580                                                DeclaratorDecl *OldD) {
3581   // The only case where we need to update the DeclContext is when
3582   // redeclaration lookup for a qualified name finds a declaration
3583   // in an inline namespace within the context named by the qualifier:
3584   //
3585   //   inline namespace N { int f(); }
3586   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3587   //
3588   // For unqualified declarations, the semantic context *can* change
3589   // along the redeclaration chain (for local extern declarations,
3590   // extern "C" declarations, and friend declarations in particular).
3591   if (!NewD->getQualifier())
3592     return;
3593 
3594   // NewD is probably already in the right context.
3595   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3596   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3597   if (NamedDC->Equals(SemaDC))
3598     return;
3599 
3600   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3601           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3602          "unexpected context for redeclaration");
3603 
3604   auto *LexDC = NewD->getLexicalDeclContext();
3605   auto FixSemaDC = [=](NamedDecl *D) {
3606     if (!D)
3607       return;
3608     D->setDeclContext(SemaDC);
3609     D->setLexicalDeclContext(LexDC);
3610   };
3611 
3612   FixSemaDC(NewD);
3613   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3614     FixSemaDC(FD->getDescribedFunctionTemplate());
3615   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3616     FixSemaDC(VD->getDescribedVarTemplate());
3617 }
3618 
3619 /// MergeFunctionDecl - We just parsed a function 'New' from
3620 /// declarator D which has the same name and scope as a previous
3621 /// declaration 'Old'.  Figure out how to resolve this situation,
3622 /// merging decls or emitting diagnostics as appropriate.
3623 ///
3624 /// In C++, New and Old must be declarations that are not
3625 /// overloaded. Use IsOverload to determine whether New and Old are
3626 /// overloaded, and to select the Old declaration that New should be
3627 /// merged with.
3628 ///
3629 /// Returns true if there was an error, false otherwise.
3630 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3631                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3632   // Verify the old decl was also a function.
3633   FunctionDecl *Old = OldD->getAsFunction();
3634   if (!Old) {
3635     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3636       if (New->getFriendObjectKind()) {
3637         Diag(New->getLocation(), diag::err_using_decl_friend);
3638         Diag(Shadow->getTargetDecl()->getLocation(),
3639              diag::note_using_decl_target);
3640         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3641             << 0;
3642         return true;
3643       }
3644 
3645       // Check whether the two declarations might declare the same function or
3646       // function template.
3647       if (FunctionTemplateDecl *NewTemplate =
3648               New->getDescribedFunctionTemplate()) {
3649         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3650                                                          NewTemplate))
3651           return true;
3652         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3653                          ->getAsFunction();
3654       } else {
3655         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3656           return true;
3657         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3658       }
3659     } else {
3660       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3661         << New->getDeclName();
3662       notePreviousDefinition(OldD, New->getLocation());
3663       return true;
3664     }
3665   }
3666 
3667   // If the old declaration was found in an inline namespace and the new
3668   // declaration was qualified, update the DeclContext to match.
3669   adjustDeclContextForDeclaratorDecl(New, Old);
3670 
3671   // If the old declaration is invalid, just give up here.
3672   if (Old->isInvalidDecl())
3673     return true;
3674 
3675   // Disallow redeclaration of some builtins.
3676   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3677     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3678     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3679         << Old << Old->getType();
3680     return true;
3681   }
3682 
3683   diag::kind PrevDiag;
3684   SourceLocation OldLocation;
3685   std::tie(PrevDiag, OldLocation) =
3686       getNoteDiagForInvalidRedeclaration(Old, New);
3687 
3688   // Don't complain about this if we're in GNU89 mode and the old function
3689   // is an extern inline function.
3690   // Don't complain about specializations. They are not supposed to have
3691   // storage classes.
3692   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3693       New->getStorageClass() == SC_Static &&
3694       Old->hasExternalFormalLinkage() &&
3695       !New->getTemplateSpecializationInfo() &&
3696       !canRedefineFunction(Old, getLangOpts())) {
3697     if (getLangOpts().MicrosoftExt) {
3698       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3699       Diag(OldLocation, PrevDiag) << Old << Old->getType();
3700     } else {
3701       Diag(New->getLocation(), diag::err_static_non_static) << New;
3702       Diag(OldLocation, PrevDiag) << Old << Old->getType();
3703       return true;
3704     }
3705   }
3706 
3707   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3708     if (!Old->hasAttr<InternalLinkageAttr>()) {
3709       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3710           << ILA;
3711       Diag(Old->getLocation(), diag::note_previous_declaration);
3712       New->dropAttr<InternalLinkageAttr>();
3713     }
3714 
3715   if (auto *EA = New->getAttr<ErrorAttr>()) {
3716     if (!Old->hasAttr<ErrorAttr>()) {
3717       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3718       Diag(Old->getLocation(), diag::note_previous_declaration);
3719       New->dropAttr<ErrorAttr>();
3720     }
3721   }
3722 
3723   if (CheckRedeclarationInModule(New, Old))
3724     return true;
3725 
3726   if (!getLangOpts().CPlusPlus) {
3727     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3728     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3729       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3730         << New << OldOvl;
3731 
3732       // Try our best to find a decl that actually has the overloadable
3733       // attribute for the note. In most cases (e.g. programs with only one
3734       // broken declaration/definition), this won't matter.
3735       //
3736       // FIXME: We could do this if we juggled some extra state in
3737       // OverloadableAttr, rather than just removing it.
3738       const Decl *DiagOld = Old;
3739       if (OldOvl) {
3740         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3741           const auto *A = D->getAttr<OverloadableAttr>();
3742           return A && !A->isImplicit();
3743         });
3744         // If we've implicitly added *all* of the overloadable attrs to this
3745         // chain, emitting a "previous redecl" note is pointless.
3746         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3747       }
3748 
3749       if (DiagOld)
3750         Diag(DiagOld->getLocation(),
3751              diag::note_attribute_overloadable_prev_overload)
3752           << OldOvl;
3753 
3754       if (OldOvl)
3755         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3756       else
3757         New->dropAttr<OverloadableAttr>();
3758     }
3759   }
3760 
3761   // If a function is first declared with a calling convention, but is later
3762   // declared or defined without one, all following decls assume the calling
3763   // convention of the first.
3764   //
3765   // It's OK if a function is first declared without a calling convention,
3766   // but is later declared or defined with the default calling convention.
3767   //
3768   // To test if either decl has an explicit calling convention, we look for
3769   // AttributedType sugar nodes on the type as written.  If they are missing or
3770   // were canonicalized away, we assume the calling convention was implicit.
3771   //
3772   // Note also that we DO NOT return at this point, because we still have
3773   // other tests to run.
3774   QualType OldQType = Context.getCanonicalType(Old->getType());
3775   QualType NewQType = Context.getCanonicalType(New->getType());
3776   const FunctionType *OldType = cast<FunctionType>(OldQType);
3777   const FunctionType *NewType = cast<FunctionType>(NewQType);
3778   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3779   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3780   bool RequiresAdjustment = false;
3781 
3782   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3783     FunctionDecl *First = Old->getFirstDecl();
3784     const FunctionType *FT =
3785         First->getType().getCanonicalType()->castAs<FunctionType>();
3786     FunctionType::ExtInfo FI = FT->getExtInfo();
3787     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3788     if (!NewCCExplicit) {
3789       // Inherit the CC from the previous declaration if it was specified
3790       // there but not here.
3791       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3792       RequiresAdjustment = true;
3793     } else if (Old->getBuiltinID()) {
3794       // Builtin attribute isn't propagated to the new one yet at this point,
3795       // so we check if the old one is a builtin.
3796 
3797       // Calling Conventions on a Builtin aren't really useful and setting a
3798       // default calling convention and cdecl'ing some builtin redeclarations is
3799       // common, so warn and ignore the calling convention on the redeclaration.
3800       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3801           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3802           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3803       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3804       RequiresAdjustment = true;
3805     } else {
3806       // Calling conventions aren't compatible, so complain.
3807       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3808       Diag(New->getLocation(), diag::err_cconv_change)
3809         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3810         << !FirstCCExplicit
3811         << (!FirstCCExplicit ? "" :
3812             FunctionType::getNameForCallConv(FI.getCC()));
3813 
3814       // Put the note on the first decl, since it is the one that matters.
3815       Diag(First->getLocation(), diag::note_previous_declaration);
3816       return true;
3817     }
3818   }
3819 
3820   // FIXME: diagnose the other way around?
3821   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3822     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3823     RequiresAdjustment = true;
3824   }
3825 
3826   // Merge regparm attribute.
3827   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3828       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3829     if (NewTypeInfo.getHasRegParm()) {
3830       Diag(New->getLocation(), diag::err_regparm_mismatch)
3831         << NewType->getRegParmType()
3832         << OldType->getRegParmType();
3833       Diag(OldLocation, diag::note_previous_declaration);
3834       return true;
3835     }
3836 
3837     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3838     RequiresAdjustment = true;
3839   }
3840 
3841   // Merge ns_returns_retained attribute.
3842   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3843     if (NewTypeInfo.getProducesResult()) {
3844       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3845           << "'ns_returns_retained'";
3846       Diag(OldLocation, diag::note_previous_declaration);
3847       return true;
3848     }
3849 
3850     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3851     RequiresAdjustment = true;
3852   }
3853 
3854   if (OldTypeInfo.getNoCallerSavedRegs() !=
3855       NewTypeInfo.getNoCallerSavedRegs()) {
3856     if (NewTypeInfo.getNoCallerSavedRegs()) {
3857       AnyX86NoCallerSavedRegistersAttr *Attr =
3858         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3859       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3860       Diag(OldLocation, diag::note_previous_declaration);
3861       return true;
3862     }
3863 
3864     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3865     RequiresAdjustment = true;
3866   }
3867 
3868   if (RequiresAdjustment) {
3869     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3870     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3871     New->setType(QualType(AdjustedType, 0));
3872     NewQType = Context.getCanonicalType(New->getType());
3873   }
3874 
3875   // If this redeclaration makes the function inline, we may need to add it to
3876   // UndefinedButUsed.
3877   if (!Old->isInlined() && New->isInlined() &&
3878       !New->hasAttr<GNUInlineAttr>() &&
3879       !getLangOpts().GNUInline &&
3880       Old->isUsed(false) &&
3881       !Old->isDefined() && !New->isThisDeclarationADefinition())
3882     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3883                                            SourceLocation()));
3884 
3885   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3886   // about it.
3887   if (New->hasAttr<GNUInlineAttr>() &&
3888       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3889     UndefinedButUsed.erase(Old->getCanonicalDecl());
3890   }
3891 
3892   // If pass_object_size params don't match up perfectly, this isn't a valid
3893   // redeclaration.
3894   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3895       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3896     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3897         << New->getDeclName();
3898     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3899     return true;
3900   }
3901 
3902   if (getLangOpts().CPlusPlus) {
3903     // C++1z [over.load]p2
3904     //   Certain function declarations cannot be overloaded:
3905     //     -- Function declarations that differ only in the return type,
3906     //        the exception specification, or both cannot be overloaded.
3907 
3908     // Check the exception specifications match. This may recompute the type of
3909     // both Old and New if it resolved exception specifications, so grab the
3910     // types again after this. Because this updates the type, we do this before
3911     // any of the other checks below, which may update the "de facto" NewQType
3912     // but do not necessarily update the type of New.
3913     if (CheckEquivalentExceptionSpec(Old, New))
3914       return true;
3915     OldQType = Context.getCanonicalType(Old->getType());
3916     NewQType = Context.getCanonicalType(New->getType());
3917 
3918     // Go back to the type source info to compare the declared return types,
3919     // per C++1y [dcl.type.auto]p13:
3920     //   Redeclarations or specializations of a function or function template
3921     //   with a declared return type that uses a placeholder type shall also
3922     //   use that placeholder, not a deduced type.
3923     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3924     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3925     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3926         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3927                                        OldDeclaredReturnType)) {
3928       QualType ResQT;
3929       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3930           OldDeclaredReturnType->isObjCObjectPointerType())
3931         // FIXME: This does the wrong thing for a deduced return type.
3932         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3933       if (ResQT.isNull()) {
3934         if (New->isCXXClassMember() && New->isOutOfLine())
3935           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3936               << New << New->getReturnTypeSourceRange();
3937         else
3938           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3939               << New->getReturnTypeSourceRange();
3940         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3941                                     << Old->getReturnTypeSourceRange();
3942         return true;
3943       }
3944       else
3945         NewQType = ResQT;
3946     }
3947 
3948     QualType OldReturnType = OldType->getReturnType();
3949     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3950     if (OldReturnType != NewReturnType) {
3951       // If this function has a deduced return type and has already been
3952       // defined, copy the deduced value from the old declaration.
3953       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3954       if (OldAT && OldAT->isDeduced()) {
3955         QualType DT = OldAT->getDeducedType();
3956         if (DT.isNull()) {
3957           New->setType(SubstAutoTypeDependent(New->getType()));
3958           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3959         } else {
3960           New->setType(SubstAutoType(New->getType(), DT));
3961           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3962         }
3963       }
3964     }
3965 
3966     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3967     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3968     if (OldMethod && NewMethod) {
3969       // Preserve triviality.
3970       NewMethod->setTrivial(OldMethod->isTrivial());
3971 
3972       // MSVC allows explicit template specialization at class scope:
3973       // 2 CXXMethodDecls referring to the same function will be injected.
3974       // We don't want a redeclaration error.
3975       bool IsClassScopeExplicitSpecialization =
3976                               OldMethod->isFunctionTemplateSpecialization() &&
3977                               NewMethod->isFunctionTemplateSpecialization();
3978       bool isFriend = NewMethod->getFriendObjectKind();
3979 
3980       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3981           !IsClassScopeExplicitSpecialization) {
3982         //    -- Member function declarations with the same name and the
3983         //       same parameter types cannot be overloaded if any of them
3984         //       is a static member function declaration.
3985         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3986           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3987           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3988           return true;
3989         }
3990 
3991         // C++ [class.mem]p1:
3992         //   [...] A member shall not be declared twice in the
3993         //   member-specification, except that a nested class or member
3994         //   class template can be declared and then later defined.
3995         if (!inTemplateInstantiation()) {
3996           unsigned NewDiag;
3997           if (isa<CXXConstructorDecl>(OldMethod))
3998             NewDiag = diag::err_constructor_redeclared;
3999           else if (isa<CXXDestructorDecl>(NewMethod))
4000             NewDiag = diag::err_destructor_redeclared;
4001           else if (isa<CXXConversionDecl>(NewMethod))
4002             NewDiag = diag::err_conv_function_redeclared;
4003           else
4004             NewDiag = diag::err_member_redeclared;
4005 
4006           Diag(New->getLocation(), NewDiag);
4007         } else {
4008           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4009             << New << New->getType();
4010         }
4011         Diag(OldLocation, PrevDiag) << Old << Old->getType();
4012         return true;
4013 
4014       // Complain if this is an explicit declaration of a special
4015       // member that was initially declared implicitly.
4016       //
4017       // As an exception, it's okay to befriend such methods in order
4018       // to permit the implicit constructor/destructor/operator calls.
4019       } else if (OldMethod->isImplicit()) {
4020         if (isFriend) {
4021           NewMethod->setImplicit();
4022         } else {
4023           Diag(NewMethod->getLocation(),
4024                diag::err_definition_of_implicitly_declared_member)
4025             << New << getSpecialMember(OldMethod);
4026           return true;
4027         }
4028       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4029         Diag(NewMethod->getLocation(),
4030              diag::err_definition_of_explicitly_defaulted_member)
4031           << getSpecialMember(OldMethod);
4032         return true;
4033       }
4034     }
4035 
4036     // C++11 [dcl.attr.noreturn]p1:
4037     //   The first declaration of a function shall specify the noreturn
4038     //   attribute if any declaration of that function specifies the noreturn
4039     //   attribute.
4040     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4041       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4042         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4043             << NRA;
4044         Diag(Old->getLocation(), diag::note_previous_declaration);
4045       }
4046 
4047     // C++11 [dcl.attr.depend]p2:
4048     //   The first declaration of a function shall specify the
4049     //   carries_dependency attribute for its declarator-id if any declaration
4050     //   of the function specifies the carries_dependency attribute.
4051     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4052     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4053       Diag(CDA->getLocation(),
4054            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4055       Diag(Old->getFirstDecl()->getLocation(),
4056            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4057     }
4058 
4059     // (C++98 8.3.5p3):
4060     //   All declarations for a function shall agree exactly in both the
4061     //   return type and the parameter-type-list.
4062     // We also want to respect all the extended bits except noreturn.
4063 
4064     // noreturn should now match unless the old type info didn't have it.
4065     QualType OldQTypeForComparison = OldQType;
4066     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4067       auto *OldType = OldQType->castAs<FunctionProtoType>();
4068       const FunctionType *OldTypeForComparison
4069         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4070       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4071       assert(OldQTypeForComparison.isCanonical());
4072     }
4073 
4074     if (haveIncompatibleLanguageLinkages(Old, New)) {
4075       // As a special case, retain the language linkage from previous
4076       // declarations of a friend function as an extension.
4077       //
4078       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4079       // and is useful because there's otherwise no way to specify language
4080       // linkage within class scope.
4081       //
4082       // Check cautiously as the friend object kind isn't yet complete.
4083       if (New->getFriendObjectKind() != Decl::FOK_None) {
4084         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4085         Diag(OldLocation, PrevDiag);
4086       } else {
4087         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4088         Diag(OldLocation, PrevDiag);
4089         return true;
4090       }
4091     }
4092 
4093     // If the function types are compatible, merge the declarations. Ignore the
4094     // exception specifier because it was already checked above in
4095     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4096     // about incompatible types under -fms-compatibility.
4097     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4098                                                          NewQType))
4099       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4100 
4101     // If the types are imprecise (due to dependent constructs in friends or
4102     // local extern declarations), it's OK if they differ. We'll check again
4103     // during instantiation.
4104     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4105       return false;
4106 
4107     // Fall through for conflicting redeclarations and redefinitions.
4108   }
4109 
4110   // C: Function types need to be compatible, not identical. This handles
4111   // duplicate function decls like "void f(int); void f(enum X);" properly.
4112   if (!getLangOpts().CPlusPlus) {
4113     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4114     // type is specified by a function definition that contains a (possibly
4115     // empty) identifier list, both shall agree in the number of parameters
4116     // and the type of each parameter shall be compatible with the type that
4117     // results from the application of default argument promotions to the
4118     // type of the corresponding identifier. ...
4119     // This cannot be handled by ASTContext::typesAreCompatible() because that
4120     // doesn't know whether the function type is for a definition or not when
4121     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4122     // we need to cover here is that the number of arguments agree as the
4123     // default argument promotion rules were already checked by
4124     // ASTContext::typesAreCompatible().
4125     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4126         Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4127       if (Old->hasInheritedPrototype())
4128         Old = Old->getCanonicalDecl();
4129       Diag(New->getLocation(), diag::err_conflicting_types) << New;
4130       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4131       return true;
4132     }
4133 
4134     // If we are merging two functions where only one of them has a prototype,
4135     // we may have enough information to decide to issue a diagnostic that the
4136     // function without a protoype will change behavior in C2x. This handles
4137     // cases like:
4138     //   void i(); void i(int j);
4139     //   void i(int j); void i();
4140     //   void i(); void i(int j) {}
4141     // See ActOnFinishFunctionBody() for other cases of the behavior change
4142     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4143     // type without a prototype.
4144     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4145         !New->isImplicit() && !Old->isImplicit()) {
4146       const FunctionDecl *WithProto, *WithoutProto;
4147       if (New->hasWrittenPrototype()) {
4148         WithProto = New;
4149         WithoutProto = Old;
4150       } else {
4151         WithProto = Old;
4152         WithoutProto = New;
4153       }
4154 
4155       if (WithProto->getNumParams() != 0) {
4156         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4157           // The one without the prototype will be changing behavior in C2x, so
4158           // warn about that one so long as it's a user-visible declaration.
4159           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4160           if (WithoutProto == New)
4161             IsWithoutProtoADef = NewDeclIsDefn;
4162           else
4163             IsWithProtoADef = NewDeclIsDefn;
4164           Diag(WithoutProto->getLocation(),
4165                diag::warn_non_prototype_changes_behavior)
4166               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4167               << (WithoutProto == Old) << IsWithProtoADef;
4168 
4169           // The reason the one without the prototype will be changing behavior
4170           // is because of the one with the prototype, so note that so long as
4171           // it's a user-visible declaration. There is one exception to this:
4172           // when the new declaration is a definition without a prototype, the
4173           // old declaration with a prototype is not the cause of the issue,
4174           // and that does not need to be noted because the one with a
4175           // prototype will not change behavior in C2x.
4176           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4177               !IsWithoutProtoADef)
4178             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4179         }
4180       }
4181     }
4182 
4183     if (Context.typesAreCompatible(OldQType, NewQType)) {
4184       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4185       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4186       const FunctionProtoType *OldProto = nullptr;
4187       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4188           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4189         // The old declaration provided a function prototype, but the
4190         // new declaration does not. Merge in the prototype.
4191         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4192         NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4193                                            OldProto->getParamTypes(),
4194                                            OldProto->getExtProtoInfo());
4195         New->setType(NewQType);
4196         New->setHasInheritedPrototype();
4197 
4198         // Synthesize parameters with the same types.
4199         SmallVector<ParmVarDecl *, 16> Params;
4200         for (const auto &ParamType : OldProto->param_types()) {
4201           ParmVarDecl *Param = ParmVarDecl::Create(
4202               Context, New, SourceLocation(), SourceLocation(), nullptr,
4203               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4204           Param->setScopeInfo(0, Params.size());
4205           Param->setImplicit();
4206           Params.push_back(Param);
4207         }
4208 
4209         New->setParams(Params);
4210       }
4211 
4212       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4213     }
4214   }
4215 
4216   // Check if the function types are compatible when pointer size address
4217   // spaces are ignored.
4218   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4219     return false;
4220 
4221   // GNU C permits a K&R definition to follow a prototype declaration
4222   // if the declared types of the parameters in the K&R definition
4223   // match the types in the prototype declaration, even when the
4224   // promoted types of the parameters from the K&R definition differ
4225   // from the types in the prototype. GCC then keeps the types from
4226   // the prototype.
4227   //
4228   // If a variadic prototype is followed by a non-variadic K&R definition,
4229   // the K&R definition becomes variadic.  This is sort of an edge case, but
4230   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4231   // C99 6.9.1p8.
4232   if (!getLangOpts().CPlusPlus &&
4233       Old->hasPrototype() && !New->hasPrototype() &&
4234       New->getType()->getAs<FunctionProtoType>() &&
4235       Old->getNumParams() == New->getNumParams()) {
4236     SmallVector<QualType, 16> ArgTypes;
4237     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4238     const FunctionProtoType *OldProto
4239       = Old->getType()->getAs<FunctionProtoType>();
4240     const FunctionProtoType *NewProto
4241       = New->getType()->getAs<FunctionProtoType>();
4242 
4243     // Determine whether this is the GNU C extension.
4244     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4245                                                NewProto->getReturnType());
4246     bool LooseCompatible = !MergedReturn.isNull();
4247     for (unsigned Idx = 0, End = Old->getNumParams();
4248          LooseCompatible && Idx != End; ++Idx) {
4249       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4250       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4251       if (Context.typesAreCompatible(OldParm->getType(),
4252                                      NewProto->getParamType(Idx))) {
4253         ArgTypes.push_back(NewParm->getType());
4254       } else if (Context.typesAreCompatible(OldParm->getType(),
4255                                             NewParm->getType(),
4256                                             /*CompareUnqualified=*/true)) {
4257         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4258                                            NewProto->getParamType(Idx) };
4259         Warnings.push_back(Warn);
4260         ArgTypes.push_back(NewParm->getType());
4261       } else
4262         LooseCompatible = false;
4263     }
4264 
4265     if (LooseCompatible) {
4266       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4267         Diag(Warnings[Warn].NewParm->getLocation(),
4268              diag::ext_param_promoted_not_compatible_with_prototype)
4269           << Warnings[Warn].PromotedType
4270           << Warnings[Warn].OldParm->getType();
4271         if (Warnings[Warn].OldParm->getLocation().isValid())
4272           Diag(Warnings[Warn].OldParm->getLocation(),
4273                diag::note_previous_declaration);
4274       }
4275 
4276       if (MergeTypeWithOld)
4277         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4278                                              OldProto->getExtProtoInfo()));
4279       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4280     }
4281 
4282     // Fall through to diagnose conflicting types.
4283   }
4284 
4285   // A function that has already been declared has been redeclared or
4286   // defined with a different type; show an appropriate diagnostic.
4287 
4288   // If the previous declaration was an implicitly-generated builtin
4289   // declaration, then at the very least we should use a specialized note.
4290   unsigned BuiltinID;
4291   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4292     // If it's actually a library-defined builtin function like 'malloc'
4293     // or 'printf', just warn about the incompatible redeclaration.
4294     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4295       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4296       Diag(OldLocation, diag::note_previous_builtin_declaration)
4297         << Old << Old->getType();
4298       return false;
4299     }
4300 
4301     PrevDiag = diag::note_previous_builtin_declaration;
4302   }
4303 
4304   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4305   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4306   return true;
4307 }
4308 
4309 /// Completes the merge of two function declarations that are
4310 /// known to be compatible.
4311 ///
4312 /// This routine handles the merging of attributes and other
4313 /// properties of function declarations from the old declaration to
4314 /// the new declaration, once we know that New is in fact a
4315 /// redeclaration of Old.
4316 ///
4317 /// \returns false
4318 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4319                                         Scope *S, bool MergeTypeWithOld) {
4320   // Merge the attributes
4321   mergeDeclAttributes(New, Old);
4322 
4323   // Merge "pure" flag.
4324   if (Old->isPure())
4325     New->setPure();
4326 
4327   // Merge "used" flag.
4328   if (Old->getMostRecentDecl()->isUsed(false))
4329     New->setIsUsed();
4330 
4331   // Merge attributes from the parameters.  These can mismatch with K&R
4332   // declarations.
4333   if (New->getNumParams() == Old->getNumParams())
4334       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4335         ParmVarDecl *NewParam = New->getParamDecl(i);
4336         ParmVarDecl *OldParam = Old->getParamDecl(i);
4337         mergeParamDeclAttributes(NewParam, OldParam, *this);
4338         mergeParamDeclTypes(NewParam, OldParam, *this);
4339       }
4340 
4341   if (getLangOpts().CPlusPlus)
4342     return MergeCXXFunctionDecl(New, Old, S);
4343 
4344   // Merge the function types so the we get the composite types for the return
4345   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4346   // was visible.
4347   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4348   if (!Merged.isNull() && MergeTypeWithOld)
4349     New->setType(Merged);
4350 
4351   return false;
4352 }
4353 
4354 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4355                                 ObjCMethodDecl *oldMethod) {
4356   // Merge the attributes, including deprecated/unavailable
4357   AvailabilityMergeKind MergeKind =
4358       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4359           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4360                                      : AMK_ProtocolImplementation)
4361           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4362                                                            : AMK_Override;
4363 
4364   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4365 
4366   // Merge attributes from the parameters.
4367   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4368                                        oe = oldMethod->param_end();
4369   for (ObjCMethodDecl::param_iterator
4370          ni = newMethod->param_begin(), ne = newMethod->param_end();
4371        ni != ne && oi != oe; ++ni, ++oi)
4372     mergeParamDeclAttributes(*ni, *oi, *this);
4373 
4374   CheckObjCMethodOverride(newMethod, oldMethod);
4375 }
4376 
4377 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4378   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4379 
4380   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4381          ? diag::err_redefinition_different_type
4382          : diag::err_redeclaration_different_type)
4383     << New->getDeclName() << New->getType() << Old->getType();
4384 
4385   diag::kind PrevDiag;
4386   SourceLocation OldLocation;
4387   std::tie(PrevDiag, OldLocation)
4388     = getNoteDiagForInvalidRedeclaration(Old, New);
4389   S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4390   New->setInvalidDecl();
4391 }
4392 
4393 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4394 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4395 /// emitting diagnostics as appropriate.
4396 ///
4397 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4398 /// to here in AddInitializerToDecl. We can't check them before the initializer
4399 /// is attached.
4400 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4401                              bool MergeTypeWithOld) {
4402   if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4403     return;
4404 
4405   QualType MergedT;
4406   if (getLangOpts().CPlusPlus) {
4407     if (New->getType()->isUndeducedType()) {
4408       // We don't know what the new type is until the initializer is attached.
4409       return;
4410     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4411       // These could still be something that needs exception specs checked.
4412       return MergeVarDeclExceptionSpecs(New, Old);
4413     }
4414     // C++ [basic.link]p10:
4415     //   [...] the types specified by all declarations referring to a given
4416     //   object or function shall be identical, except that declarations for an
4417     //   array object can specify array types that differ by the presence or
4418     //   absence of a major array bound (8.3.4).
4419     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4420       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4421       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4422 
4423       // We are merging a variable declaration New into Old. If it has an array
4424       // bound, and that bound differs from Old's bound, we should diagnose the
4425       // mismatch.
4426       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4427         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4428              PrevVD = PrevVD->getPreviousDecl()) {
4429           QualType PrevVDTy = PrevVD->getType();
4430           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4431             continue;
4432 
4433           if (!Context.hasSameType(New->getType(), PrevVDTy))
4434             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4435         }
4436       }
4437 
4438       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4439         if (Context.hasSameType(OldArray->getElementType(),
4440                                 NewArray->getElementType()))
4441           MergedT = New->getType();
4442       }
4443       // FIXME: Check visibility. New is hidden but has a complete type. If New
4444       // has no array bound, it should not inherit one from Old, if Old is not
4445       // visible.
4446       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4447         if (Context.hasSameType(OldArray->getElementType(),
4448                                 NewArray->getElementType()))
4449           MergedT = Old->getType();
4450       }
4451     }
4452     else if (New->getType()->isObjCObjectPointerType() &&
4453                Old->getType()->isObjCObjectPointerType()) {
4454       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4455                                               Old->getType());
4456     }
4457   } else {
4458     // C 6.2.7p2:
4459     //   All declarations that refer to the same object or function shall have
4460     //   compatible type.
4461     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4462   }
4463   if (MergedT.isNull()) {
4464     // It's OK if we couldn't merge types if either type is dependent, for a
4465     // block-scope variable. In other cases (static data members of class
4466     // templates, variable templates, ...), we require the types to be
4467     // equivalent.
4468     // FIXME: The C++ standard doesn't say anything about this.
4469     if ((New->getType()->isDependentType() ||
4470          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4471       // If the old type was dependent, we can't merge with it, so the new type
4472       // becomes dependent for now. We'll reproduce the original type when we
4473       // instantiate the TypeSourceInfo for the variable.
4474       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4475         New->setType(Context.DependentTy);
4476       return;
4477     }
4478     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4479   }
4480 
4481   // Don't actually update the type on the new declaration if the old
4482   // declaration was an extern declaration in a different scope.
4483   if (MergeTypeWithOld)
4484     New->setType(MergedT);
4485 }
4486 
4487 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4488                                   LookupResult &Previous) {
4489   // C11 6.2.7p4:
4490   //   For an identifier with internal or external linkage declared
4491   //   in a scope in which a prior declaration of that identifier is
4492   //   visible, if the prior declaration specifies internal or
4493   //   external linkage, the type of the identifier at the later
4494   //   declaration becomes the composite type.
4495   //
4496   // If the variable isn't visible, we do not merge with its type.
4497   if (Previous.isShadowed())
4498     return false;
4499 
4500   if (S.getLangOpts().CPlusPlus) {
4501     // C++11 [dcl.array]p3:
4502     //   If there is a preceding declaration of the entity in the same
4503     //   scope in which the bound was specified, an omitted array bound
4504     //   is taken to be the same as in that earlier declaration.
4505     return NewVD->isPreviousDeclInSameBlockScope() ||
4506            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4507             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4508   } else {
4509     // If the old declaration was function-local, don't merge with its
4510     // type unless we're in the same function.
4511     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4512            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4513   }
4514 }
4515 
4516 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4517 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4518 /// situation, merging decls or emitting diagnostics as appropriate.
4519 ///
4520 /// Tentative definition rules (C99 6.9.2p2) are checked by
4521 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4522 /// definitions here, since the initializer hasn't been attached.
4523 ///
4524 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4525   // If the new decl is already invalid, don't do any other checking.
4526   if (New->isInvalidDecl())
4527     return;
4528 
4529   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4530     return;
4531 
4532   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4533 
4534   // Verify the old decl was also a variable or variable template.
4535   VarDecl *Old = nullptr;
4536   VarTemplateDecl *OldTemplate = nullptr;
4537   if (Previous.isSingleResult()) {
4538     if (NewTemplate) {
4539       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4540       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4541 
4542       if (auto *Shadow =
4543               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4544         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4545           return New->setInvalidDecl();
4546     } else {
4547       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4548 
4549       if (auto *Shadow =
4550               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4551         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4552           return New->setInvalidDecl();
4553     }
4554   }
4555   if (!Old) {
4556     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4557         << New->getDeclName();
4558     notePreviousDefinition(Previous.getRepresentativeDecl(),
4559                            New->getLocation());
4560     return New->setInvalidDecl();
4561   }
4562 
4563   // If the old declaration was found in an inline namespace and the new
4564   // declaration was qualified, update the DeclContext to match.
4565   adjustDeclContextForDeclaratorDecl(New, Old);
4566 
4567   // Ensure the template parameters are compatible.
4568   if (NewTemplate &&
4569       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4570                                       OldTemplate->getTemplateParameters(),
4571                                       /*Complain=*/true, TPL_TemplateMatch))
4572     return New->setInvalidDecl();
4573 
4574   // C++ [class.mem]p1:
4575   //   A member shall not be declared twice in the member-specification [...]
4576   //
4577   // Here, we need only consider static data members.
4578   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4579     Diag(New->getLocation(), diag::err_duplicate_member)
4580       << New->getIdentifier();
4581     Diag(Old->getLocation(), diag::note_previous_declaration);
4582     New->setInvalidDecl();
4583   }
4584 
4585   mergeDeclAttributes(New, Old);
4586   // Warn if an already-declared variable is made a weak_import in a subsequent
4587   // declaration
4588   if (New->hasAttr<WeakImportAttr>() &&
4589       Old->getStorageClass() == SC_None &&
4590       !Old->hasAttr<WeakImportAttr>()) {
4591     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4592     Diag(Old->getLocation(), diag::note_previous_declaration);
4593     // Remove weak_import attribute on new declaration.
4594     New->dropAttr<WeakImportAttr>();
4595   }
4596 
4597   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4598     if (!Old->hasAttr<InternalLinkageAttr>()) {
4599       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4600           << ILA;
4601       Diag(Old->getLocation(), diag::note_previous_declaration);
4602       New->dropAttr<InternalLinkageAttr>();
4603     }
4604 
4605   // Merge the types.
4606   VarDecl *MostRecent = Old->getMostRecentDecl();
4607   if (MostRecent != Old) {
4608     MergeVarDeclTypes(New, MostRecent,
4609                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4610     if (New->isInvalidDecl())
4611       return;
4612   }
4613 
4614   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4615   if (New->isInvalidDecl())
4616     return;
4617 
4618   diag::kind PrevDiag;
4619   SourceLocation OldLocation;
4620   std::tie(PrevDiag, OldLocation) =
4621       getNoteDiagForInvalidRedeclaration(Old, New);
4622 
4623   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4624   if (New->getStorageClass() == SC_Static &&
4625       !New->isStaticDataMember() &&
4626       Old->hasExternalFormalLinkage()) {
4627     if (getLangOpts().MicrosoftExt) {
4628       Diag(New->getLocation(), diag::ext_static_non_static)
4629           << New->getDeclName();
4630       Diag(OldLocation, PrevDiag);
4631     } else {
4632       Diag(New->getLocation(), diag::err_static_non_static)
4633           << New->getDeclName();
4634       Diag(OldLocation, PrevDiag);
4635       return New->setInvalidDecl();
4636     }
4637   }
4638   // C99 6.2.2p4:
4639   //   For an identifier declared with the storage-class specifier
4640   //   extern in a scope in which a prior declaration of that
4641   //   identifier is visible,23) if the prior declaration specifies
4642   //   internal or external linkage, the linkage of the identifier at
4643   //   the later declaration is the same as the linkage specified at
4644   //   the prior declaration. If no prior declaration is visible, or
4645   //   if the prior declaration specifies no linkage, then the
4646   //   identifier has external linkage.
4647   if (New->hasExternalStorage() && Old->hasLinkage())
4648     /* Okay */;
4649   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4650            !New->isStaticDataMember() &&
4651            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4652     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4653     Diag(OldLocation, PrevDiag);
4654     return New->setInvalidDecl();
4655   }
4656 
4657   // Check if extern is followed by non-extern and vice-versa.
4658   if (New->hasExternalStorage() &&
4659       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4660     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4661     Diag(OldLocation, PrevDiag);
4662     return New->setInvalidDecl();
4663   }
4664   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4665       !New->hasExternalStorage()) {
4666     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4667     Diag(OldLocation, PrevDiag);
4668     return New->setInvalidDecl();
4669   }
4670 
4671   if (CheckRedeclarationInModule(New, Old))
4672     return;
4673 
4674   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4675 
4676   // FIXME: The test for external storage here seems wrong? We still
4677   // need to check for mismatches.
4678   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4679       // Don't complain about out-of-line definitions of static members.
4680       !(Old->getLexicalDeclContext()->isRecord() &&
4681         !New->getLexicalDeclContext()->isRecord())) {
4682     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4683     Diag(OldLocation, PrevDiag);
4684     return New->setInvalidDecl();
4685   }
4686 
4687   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4688     if (VarDecl *Def = Old->getDefinition()) {
4689       // C++1z [dcl.fcn.spec]p4:
4690       //   If the definition of a variable appears in a translation unit before
4691       //   its first declaration as inline, the program is ill-formed.
4692       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4693       Diag(Def->getLocation(), diag::note_previous_definition);
4694     }
4695   }
4696 
4697   // If this redeclaration makes the variable inline, we may need to add it to
4698   // UndefinedButUsed.
4699   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4700       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4701     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4702                                            SourceLocation()));
4703 
4704   if (New->getTLSKind() != Old->getTLSKind()) {
4705     if (!Old->getTLSKind()) {
4706       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4707       Diag(OldLocation, PrevDiag);
4708     } else if (!New->getTLSKind()) {
4709       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4710       Diag(OldLocation, PrevDiag);
4711     } else {
4712       // Do not allow redeclaration to change the variable between requiring
4713       // static and dynamic initialization.
4714       // FIXME: GCC allows this, but uses the TLS keyword on the first
4715       // declaration to determine the kind. Do we need to be compatible here?
4716       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4717         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4718       Diag(OldLocation, PrevDiag);
4719     }
4720   }
4721 
4722   // C++ doesn't have tentative definitions, so go right ahead and check here.
4723   if (getLangOpts().CPlusPlus) {
4724     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4725         Old->getCanonicalDecl()->isConstexpr()) {
4726       // This definition won't be a definition any more once it's been merged.
4727       Diag(New->getLocation(),
4728            diag::warn_deprecated_redundant_constexpr_static_def);
4729     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4730       VarDecl *Def = Old->getDefinition();
4731       if (Def && checkVarDeclRedefinition(Def, New))
4732         return;
4733     }
4734   }
4735 
4736   if (haveIncompatibleLanguageLinkages(Old, New)) {
4737     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4738     Diag(OldLocation, PrevDiag);
4739     New->setInvalidDecl();
4740     return;
4741   }
4742 
4743   // Merge "used" flag.
4744   if (Old->getMostRecentDecl()->isUsed(false))
4745     New->setIsUsed();
4746 
4747   // Keep a chain of previous declarations.
4748   New->setPreviousDecl(Old);
4749   if (NewTemplate)
4750     NewTemplate->setPreviousDecl(OldTemplate);
4751 
4752   // Inherit access appropriately.
4753   New->setAccess(Old->getAccess());
4754   if (NewTemplate)
4755     NewTemplate->setAccess(New->getAccess());
4756 
4757   if (Old->isInline())
4758     New->setImplicitlyInline();
4759 }
4760 
4761 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4762   SourceManager &SrcMgr = getSourceManager();
4763   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4764   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4765   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4766   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4767   auto &HSI = PP.getHeaderSearchInfo();
4768   StringRef HdrFilename =
4769       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4770 
4771   auto noteFromModuleOrInclude = [&](Module *Mod,
4772                                      SourceLocation IncLoc) -> bool {
4773     // Redefinition errors with modules are common with non modular mapped
4774     // headers, example: a non-modular header H in module A that also gets
4775     // included directly in a TU. Pointing twice to the same header/definition
4776     // is confusing, try to get better diagnostics when modules is on.
4777     if (IncLoc.isValid()) {
4778       if (Mod) {
4779         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4780             << HdrFilename.str() << Mod->getFullModuleName();
4781         if (!Mod->DefinitionLoc.isInvalid())
4782           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4783               << Mod->getFullModuleName();
4784       } else {
4785         Diag(IncLoc, diag::note_redefinition_include_same_file)
4786             << HdrFilename.str();
4787       }
4788       return true;
4789     }
4790 
4791     return false;
4792   };
4793 
4794   // Is it the same file and same offset? Provide more information on why
4795   // this leads to a redefinition error.
4796   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4797     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4798     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4799     bool EmittedDiag =
4800         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4801     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4802 
4803     // If the header has no guards, emit a note suggesting one.
4804     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4805       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4806 
4807     if (EmittedDiag)
4808       return;
4809   }
4810 
4811   // Redefinition coming from different files or couldn't do better above.
4812   if (Old->getLocation().isValid())
4813     Diag(Old->getLocation(), diag::note_previous_definition);
4814 }
4815 
4816 /// We've just determined that \p Old and \p New both appear to be definitions
4817 /// of the same variable. Either diagnose or fix the problem.
4818 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4819   if (!hasVisibleDefinition(Old) &&
4820       (New->getFormalLinkage() == InternalLinkage ||
4821        New->isInline() ||
4822        isa<VarTemplateSpecializationDecl>(New) ||
4823        New->getDescribedVarTemplate() ||
4824        New->getNumTemplateParameterLists() ||
4825        New->getDeclContext()->isDependentContext())) {
4826     // The previous definition is hidden, and multiple definitions are
4827     // permitted (in separate TUs). Demote this to a declaration.
4828     New->demoteThisDefinitionToDeclaration();
4829 
4830     // Make the canonical definition visible.
4831     if (auto *OldTD = Old->getDescribedVarTemplate())
4832       makeMergedDefinitionVisible(OldTD);
4833     makeMergedDefinitionVisible(Old);
4834     return false;
4835   } else {
4836     Diag(New->getLocation(), diag::err_redefinition) << New;
4837     notePreviousDefinition(Old, New->getLocation());
4838     New->setInvalidDecl();
4839     return true;
4840   }
4841 }
4842 
4843 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4844 /// no declarator (e.g. "struct foo;") is parsed.
4845 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4846                                        DeclSpec &DS,
4847                                        const ParsedAttributesView &DeclAttrs,
4848                                        RecordDecl *&AnonRecord) {
4849   return ParsedFreeStandingDeclSpec(
4850       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4851 }
4852 
4853 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4854 // disambiguate entities defined in different scopes.
4855 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4856 // compatibility.
4857 // We will pick our mangling number depending on which version of MSVC is being
4858 // targeted.
4859 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4860   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4861              ? S->getMSCurManglingNumber()
4862              : S->getMSLastManglingNumber();
4863 }
4864 
4865 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4866   if (!Context.getLangOpts().CPlusPlus)
4867     return;
4868 
4869   if (isa<CXXRecordDecl>(Tag->getParent())) {
4870     // If this tag is the direct child of a class, number it if
4871     // it is anonymous.
4872     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4873       return;
4874     MangleNumberingContext &MCtx =
4875         Context.getManglingNumberContext(Tag->getParent());
4876     Context.setManglingNumber(
4877         Tag, MCtx.getManglingNumber(
4878                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4879     return;
4880   }
4881 
4882   // If this tag isn't a direct child of a class, number it if it is local.
4883   MangleNumberingContext *MCtx;
4884   Decl *ManglingContextDecl;
4885   std::tie(MCtx, ManglingContextDecl) =
4886       getCurrentMangleNumberContext(Tag->getDeclContext());
4887   if (MCtx) {
4888     Context.setManglingNumber(
4889         Tag, MCtx->getManglingNumber(
4890                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4891   }
4892 }
4893 
4894 namespace {
4895 struct NonCLikeKind {
4896   enum {
4897     None,
4898     BaseClass,
4899     DefaultMemberInit,
4900     Lambda,
4901     Friend,
4902     OtherMember,
4903     Invalid,
4904   } Kind = None;
4905   SourceRange Range;
4906 
4907   explicit operator bool() { return Kind != None; }
4908 };
4909 }
4910 
4911 /// Determine whether a class is C-like, according to the rules of C++
4912 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4913 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4914   if (RD->isInvalidDecl())
4915     return {NonCLikeKind::Invalid, {}};
4916 
4917   // C++ [dcl.typedef]p9: [P1766R1]
4918   //   An unnamed class with a typedef name for linkage purposes shall not
4919   //
4920   //    -- have any base classes
4921   if (RD->getNumBases())
4922     return {NonCLikeKind::BaseClass,
4923             SourceRange(RD->bases_begin()->getBeginLoc(),
4924                         RD->bases_end()[-1].getEndLoc())};
4925   bool Invalid = false;
4926   for (Decl *D : RD->decls()) {
4927     // Don't complain about things we already diagnosed.
4928     if (D->isInvalidDecl()) {
4929       Invalid = true;
4930       continue;
4931     }
4932 
4933     //  -- have any [...] default member initializers
4934     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4935       if (FD->hasInClassInitializer()) {
4936         auto *Init = FD->getInClassInitializer();
4937         return {NonCLikeKind::DefaultMemberInit,
4938                 Init ? Init->getSourceRange() : D->getSourceRange()};
4939       }
4940       continue;
4941     }
4942 
4943     // FIXME: We don't allow friend declarations. This violates the wording of
4944     // P1766, but not the intent.
4945     if (isa<FriendDecl>(D))
4946       return {NonCLikeKind::Friend, D->getSourceRange()};
4947 
4948     //  -- declare any members other than non-static data members, member
4949     //     enumerations, or member classes,
4950     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4951         isa<EnumDecl>(D))
4952       continue;
4953     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4954     if (!MemberRD) {
4955       if (D->isImplicit())
4956         continue;
4957       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4958     }
4959 
4960     //  -- contain a lambda-expression,
4961     if (MemberRD->isLambda())
4962       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4963 
4964     //  and all member classes shall also satisfy these requirements
4965     //  (recursively).
4966     if (MemberRD->isThisDeclarationADefinition()) {
4967       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4968         return Kind;
4969     }
4970   }
4971 
4972   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4973 }
4974 
4975 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4976                                         TypedefNameDecl *NewTD) {
4977   if (TagFromDeclSpec->isInvalidDecl())
4978     return;
4979 
4980   // Do nothing if the tag already has a name for linkage purposes.
4981   if (TagFromDeclSpec->hasNameForLinkage())
4982     return;
4983 
4984   // A well-formed anonymous tag must always be a TUK_Definition.
4985   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4986 
4987   // The type must match the tag exactly;  no qualifiers allowed.
4988   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4989                            Context.getTagDeclType(TagFromDeclSpec))) {
4990     if (getLangOpts().CPlusPlus)
4991       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4992     return;
4993   }
4994 
4995   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4996   //   An unnamed class with a typedef name for linkage purposes shall [be
4997   //   C-like].
4998   //
4999   // FIXME: Also diagnose if we've already computed the linkage. That ideally
5000   // shouldn't happen, but there are constructs that the language rule doesn't
5001   // disallow for which we can't reasonably avoid computing linkage early.
5002   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5003   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5004                              : NonCLikeKind();
5005   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5006   if (NonCLike || ChangesLinkage) {
5007     if (NonCLike.Kind == NonCLikeKind::Invalid)
5008       return;
5009 
5010     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5011     if (ChangesLinkage) {
5012       // If the linkage changes, we can't accept this as an extension.
5013       if (NonCLike.Kind == NonCLikeKind::None)
5014         DiagID = diag::err_typedef_changes_linkage;
5015       else
5016         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5017     }
5018 
5019     SourceLocation FixitLoc =
5020         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5021     llvm::SmallString<40> TextToInsert;
5022     TextToInsert += ' ';
5023     TextToInsert += NewTD->getIdentifier()->getName();
5024 
5025     Diag(FixitLoc, DiagID)
5026       << isa<TypeAliasDecl>(NewTD)
5027       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5028     if (NonCLike.Kind != NonCLikeKind::None) {
5029       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5030         << NonCLike.Kind - 1 << NonCLike.Range;
5031     }
5032     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5033       << NewTD << isa<TypeAliasDecl>(NewTD);
5034 
5035     if (ChangesLinkage)
5036       return;
5037   }
5038 
5039   // Otherwise, set this as the anon-decl typedef for the tag.
5040   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5041 }
5042 
5043 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5044   DeclSpec::TST T = DS.getTypeSpecType();
5045   switch (T) {
5046   case DeclSpec::TST_class:
5047     return 0;
5048   case DeclSpec::TST_struct:
5049     return 1;
5050   case DeclSpec::TST_interface:
5051     return 2;
5052   case DeclSpec::TST_union:
5053     return 3;
5054   case DeclSpec::TST_enum:
5055     if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5056       if (ED->isScopedUsingClassTag())
5057         return 5;
5058       if (ED->isScoped())
5059         return 6;
5060     }
5061     return 4;
5062   default:
5063     llvm_unreachable("unexpected type specifier");
5064   }
5065 }
5066 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5067 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5068 /// parameters to cope with template friend declarations.
5069 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5070                                        DeclSpec &DS,
5071                                        const ParsedAttributesView &DeclAttrs,
5072                                        MultiTemplateParamsArg TemplateParams,
5073                                        bool IsExplicitInstantiation,
5074                                        RecordDecl *&AnonRecord) {
5075   Decl *TagD = nullptr;
5076   TagDecl *Tag = nullptr;
5077   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5078       DS.getTypeSpecType() == DeclSpec::TST_struct ||
5079       DS.getTypeSpecType() == DeclSpec::TST_interface ||
5080       DS.getTypeSpecType() == DeclSpec::TST_union ||
5081       DS.getTypeSpecType() == DeclSpec::TST_enum) {
5082     TagD = DS.getRepAsDecl();
5083 
5084     if (!TagD) // We probably had an error
5085       return nullptr;
5086 
5087     // Note that the above type specs guarantee that the
5088     // type rep is a Decl, whereas in many of the others
5089     // it's a Type.
5090     if (isa<TagDecl>(TagD))
5091       Tag = cast<TagDecl>(TagD);
5092     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5093       Tag = CTD->getTemplatedDecl();
5094   }
5095 
5096   if (Tag) {
5097     handleTagNumbering(Tag, S);
5098     Tag->setFreeStanding();
5099     if (Tag->isInvalidDecl())
5100       return Tag;
5101   }
5102 
5103   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5104     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5105     // or incomplete types shall not be restrict-qualified."
5106     if (TypeQuals & DeclSpec::TQ_restrict)
5107       Diag(DS.getRestrictSpecLoc(),
5108            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5109            << DS.getSourceRange();
5110   }
5111 
5112   if (DS.isInlineSpecified())
5113     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5114         << getLangOpts().CPlusPlus17;
5115 
5116   if (DS.hasConstexprSpecifier()) {
5117     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5118     // and definitions of functions and variables.
5119     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5120     // the declaration of a function or function template
5121     if (Tag)
5122       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5123           << GetDiagnosticTypeSpecifierID(DS)
5124           << static_cast<int>(DS.getConstexprSpecifier());
5125     else
5126       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5127           << static_cast<int>(DS.getConstexprSpecifier());
5128     // Don't emit warnings after this error.
5129     return TagD;
5130   }
5131 
5132   DiagnoseFunctionSpecifiers(DS);
5133 
5134   if (DS.isFriendSpecified()) {
5135     // If we're dealing with a decl but not a TagDecl, assume that
5136     // whatever routines created it handled the friendship aspect.
5137     if (TagD && !Tag)
5138       return nullptr;
5139     return ActOnFriendTypeDecl(S, DS, TemplateParams);
5140   }
5141 
5142   const CXXScopeSpec &SS = DS.getTypeSpecScope();
5143   bool IsExplicitSpecialization =
5144     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5145   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5146       !IsExplicitInstantiation && !IsExplicitSpecialization &&
5147       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5148     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5149     // nested-name-specifier unless it is an explicit instantiation
5150     // or an explicit specialization.
5151     //
5152     // FIXME: We allow class template partial specializations here too, per the
5153     // obvious intent of DR1819.
5154     //
5155     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5156     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5157         << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5158     return nullptr;
5159   }
5160 
5161   // Track whether this decl-specifier declares anything.
5162   bool DeclaresAnything = true;
5163 
5164   // Handle anonymous struct definitions.
5165   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5166     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5167         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5168       if (getLangOpts().CPlusPlus ||
5169           Record->getDeclContext()->isRecord()) {
5170         // If CurContext is a DeclContext that can contain statements,
5171         // RecursiveASTVisitor won't visit the decls that
5172         // BuildAnonymousStructOrUnion() will put into CurContext.
5173         // Also store them here so that they can be part of the
5174         // DeclStmt that gets created in this case.
5175         // FIXME: Also return the IndirectFieldDecls created by
5176         // BuildAnonymousStructOr union, for the same reason?
5177         if (CurContext->isFunctionOrMethod())
5178           AnonRecord = Record;
5179         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5180                                            Context.getPrintingPolicy());
5181       }
5182 
5183       DeclaresAnything = false;
5184     }
5185   }
5186 
5187   // C11 6.7.2.1p2:
5188   //   A struct-declaration that does not declare an anonymous structure or
5189   //   anonymous union shall contain a struct-declarator-list.
5190   //
5191   // This rule also existed in C89 and C99; the grammar for struct-declaration
5192   // did not permit a struct-declaration without a struct-declarator-list.
5193   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5194       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5195     // Check for Microsoft C extension: anonymous struct/union member.
5196     // Handle 2 kinds of anonymous struct/union:
5197     //   struct STRUCT;
5198     //   union UNION;
5199     // and
5200     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5201     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5202     if ((Tag && Tag->getDeclName()) ||
5203         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5204       RecordDecl *Record = nullptr;
5205       if (Tag)
5206         Record = dyn_cast<RecordDecl>(Tag);
5207       else if (const RecordType *RT =
5208                    DS.getRepAsType().get()->getAsStructureType())
5209         Record = RT->getDecl();
5210       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5211         Record = UT->getDecl();
5212 
5213       if (Record && getLangOpts().MicrosoftExt) {
5214         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5215             << Record->isUnion() << DS.getSourceRange();
5216         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5217       }
5218 
5219       DeclaresAnything = false;
5220     }
5221   }
5222 
5223   // Skip all the checks below if we have a type error.
5224   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5225       (TagD && TagD->isInvalidDecl()))
5226     return TagD;
5227 
5228   if (getLangOpts().CPlusPlus &&
5229       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5230     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5231       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5232           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5233         DeclaresAnything = false;
5234 
5235   if (!DS.isMissingDeclaratorOk()) {
5236     // Customize diagnostic for a typedef missing a name.
5237     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5238       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5239           << DS.getSourceRange();
5240     else
5241       DeclaresAnything = false;
5242   }
5243 
5244   if (DS.isModulePrivateSpecified() &&
5245       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5246     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5247       << Tag->getTagKind()
5248       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5249 
5250   ActOnDocumentableDecl(TagD);
5251 
5252   // C 6.7/2:
5253   //   A declaration [...] shall declare at least a declarator [...], a tag,
5254   //   or the members of an enumeration.
5255   // C++ [dcl.dcl]p3:
5256   //   [If there are no declarators], and except for the declaration of an
5257   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5258   //   names into the program, or shall redeclare a name introduced by a
5259   //   previous declaration.
5260   if (!DeclaresAnything) {
5261     // In C, we allow this as a (popular) extension / bug. Don't bother
5262     // producing further diagnostics for redundant qualifiers after this.
5263     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5264                                ? diag::err_no_declarators
5265                                : diag::ext_no_declarators)
5266         << DS.getSourceRange();
5267     return TagD;
5268   }
5269 
5270   // C++ [dcl.stc]p1:
5271   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5272   //   init-declarator-list of the declaration shall not be empty.
5273   // C++ [dcl.fct.spec]p1:
5274   //   If a cv-qualifier appears in a decl-specifier-seq, the
5275   //   init-declarator-list of the declaration shall not be empty.
5276   //
5277   // Spurious qualifiers here appear to be valid in C.
5278   unsigned DiagID = diag::warn_standalone_specifier;
5279   if (getLangOpts().CPlusPlus)
5280     DiagID = diag::ext_standalone_specifier;
5281 
5282   // Note that a linkage-specification sets a storage class, but
5283   // 'extern "C" struct foo;' is actually valid and not theoretically
5284   // useless.
5285   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5286     if (SCS == DeclSpec::SCS_mutable)
5287       // Since mutable is not a viable storage class specifier in C, there is
5288       // no reason to treat it as an extension. Instead, diagnose as an error.
5289       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5290     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5291       Diag(DS.getStorageClassSpecLoc(), DiagID)
5292         << DeclSpec::getSpecifierName(SCS);
5293   }
5294 
5295   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5296     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5297       << DeclSpec::getSpecifierName(TSCS);
5298   if (DS.getTypeQualifiers()) {
5299     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5300       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5301     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5302       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5303     // Restrict is covered above.
5304     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5305       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5306     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5307       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5308   }
5309 
5310   // Warn about ignored type attributes, for example:
5311   // __attribute__((aligned)) struct A;
5312   // Attributes should be placed after tag to apply to type declaration.
5313   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5314     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5315     if (TypeSpecType == DeclSpec::TST_class ||
5316         TypeSpecType == DeclSpec::TST_struct ||
5317         TypeSpecType == DeclSpec::TST_interface ||
5318         TypeSpecType == DeclSpec::TST_union ||
5319         TypeSpecType == DeclSpec::TST_enum) {
5320       for (const ParsedAttr &AL : DS.getAttributes())
5321         Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5322                               ? diag::err_declspec_keyword_has_no_effect
5323                               : diag::warn_declspec_attribute_ignored)
5324             << AL << GetDiagnosticTypeSpecifierID(DS);
5325       for (const ParsedAttr &AL : DeclAttrs)
5326         Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5327                               ? diag::err_declspec_keyword_has_no_effect
5328                               : diag::warn_declspec_attribute_ignored)
5329             << AL << GetDiagnosticTypeSpecifierID(DS);
5330     }
5331   }
5332 
5333   return TagD;
5334 }
5335 
5336 /// We are trying to inject an anonymous member into the given scope;
5337 /// check if there's an existing declaration that can't be overloaded.
5338 ///
5339 /// \return true if this is a forbidden redeclaration
5340 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5341                                          Scope *S,
5342                                          DeclContext *Owner,
5343                                          DeclarationName Name,
5344                                          SourceLocation NameLoc,
5345                                          bool IsUnion) {
5346   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5347                  Sema::ForVisibleRedeclaration);
5348   if (!SemaRef.LookupName(R, S)) return false;
5349 
5350   // Pick a representative declaration.
5351   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5352   assert(PrevDecl && "Expected a non-null Decl");
5353 
5354   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5355     return false;
5356 
5357   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5358     << IsUnion << Name;
5359   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5360 
5361   return true;
5362 }
5363 
5364 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5365 /// anonymous struct or union AnonRecord into the owning context Owner
5366 /// and scope S. This routine will be invoked just after we realize
5367 /// that an unnamed union or struct is actually an anonymous union or
5368 /// struct, e.g.,
5369 ///
5370 /// @code
5371 /// union {
5372 ///   int i;
5373 ///   float f;
5374 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5375 ///    // f into the surrounding scope.x
5376 /// @endcode
5377 ///
5378 /// This routine is recursive, injecting the names of nested anonymous
5379 /// structs/unions into the owning context and scope as well.
5380 static bool
5381 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5382                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5383                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5384   bool Invalid = false;
5385 
5386   // Look every FieldDecl and IndirectFieldDecl with a name.
5387   for (auto *D : AnonRecord->decls()) {
5388     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5389         cast<NamedDecl>(D)->getDeclName()) {
5390       ValueDecl *VD = cast<ValueDecl>(D);
5391       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5392                                        VD->getLocation(),
5393                                        AnonRecord->isUnion())) {
5394         // C++ [class.union]p2:
5395         //   The names of the members of an anonymous union shall be
5396         //   distinct from the names of any other entity in the
5397         //   scope in which the anonymous union is declared.
5398         Invalid = true;
5399       } else {
5400         // C++ [class.union]p2:
5401         //   For the purpose of name lookup, after the anonymous union
5402         //   definition, the members of the anonymous union are
5403         //   considered to have been defined in the scope in which the
5404         //   anonymous union is declared.
5405         unsigned OldChainingSize = Chaining.size();
5406         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5407           Chaining.append(IF->chain_begin(), IF->chain_end());
5408         else
5409           Chaining.push_back(VD);
5410 
5411         assert(Chaining.size() >= 2);
5412         NamedDecl **NamedChain =
5413           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5414         for (unsigned i = 0; i < Chaining.size(); i++)
5415           NamedChain[i] = Chaining[i];
5416 
5417         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5418             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5419             VD->getType(), {NamedChain, Chaining.size()});
5420 
5421         for (const auto *Attr : VD->attrs())
5422           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5423 
5424         IndirectField->setAccess(AS);
5425         IndirectField->setImplicit();
5426         SemaRef.PushOnScopeChains(IndirectField, S);
5427 
5428         // That includes picking up the appropriate access specifier.
5429         if (AS != AS_none) IndirectField->setAccess(AS);
5430 
5431         Chaining.resize(OldChainingSize);
5432       }
5433     }
5434   }
5435 
5436   return Invalid;
5437 }
5438 
5439 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5440 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5441 /// illegal input values are mapped to SC_None.
5442 static StorageClass
5443 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5444   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5445   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5446          "Parser allowed 'typedef' as storage class VarDecl.");
5447   switch (StorageClassSpec) {
5448   case DeclSpec::SCS_unspecified:    return SC_None;
5449   case DeclSpec::SCS_extern:
5450     if (DS.isExternInLinkageSpec())
5451       return SC_None;
5452     return SC_Extern;
5453   case DeclSpec::SCS_static:         return SC_Static;
5454   case DeclSpec::SCS_auto:           return SC_Auto;
5455   case DeclSpec::SCS_register:       return SC_Register;
5456   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5457     // Illegal SCSs map to None: error reporting is up to the caller.
5458   case DeclSpec::SCS_mutable:        // Fall through.
5459   case DeclSpec::SCS_typedef:        return SC_None;
5460   }
5461   llvm_unreachable("unknown storage class specifier");
5462 }
5463 
5464 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5465   assert(Record->hasInClassInitializer());
5466 
5467   for (const auto *I : Record->decls()) {
5468     const auto *FD = dyn_cast<FieldDecl>(I);
5469     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5470       FD = IFD->getAnonField();
5471     if (FD && FD->hasInClassInitializer())
5472       return FD->getLocation();
5473   }
5474 
5475   llvm_unreachable("couldn't find in-class initializer");
5476 }
5477 
5478 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5479                                       SourceLocation DefaultInitLoc) {
5480   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5481     return;
5482 
5483   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5484   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5485 }
5486 
5487 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5488                                       CXXRecordDecl *AnonUnion) {
5489   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5490     return;
5491 
5492   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5493 }
5494 
5495 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5496 /// anonymous structure or union. Anonymous unions are a C++ feature
5497 /// (C++ [class.union]) and a C11 feature; anonymous structures
5498 /// are a C11 feature and GNU C++ extension.
5499 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5500                                         AccessSpecifier AS,
5501                                         RecordDecl *Record,
5502                                         const PrintingPolicy &Policy) {
5503   DeclContext *Owner = Record->getDeclContext();
5504 
5505   // Diagnose whether this anonymous struct/union is an extension.
5506   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5507     Diag(Record->getLocation(), diag::ext_anonymous_union);
5508   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5509     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5510   else if (!Record->isUnion() && !getLangOpts().C11)
5511     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5512 
5513   // C and C++ require different kinds of checks for anonymous
5514   // structs/unions.
5515   bool Invalid = false;
5516   if (getLangOpts().CPlusPlus) {
5517     const char *PrevSpec = nullptr;
5518     if (Record->isUnion()) {
5519       // C++ [class.union]p6:
5520       // C++17 [class.union.anon]p2:
5521       //   Anonymous unions declared in a named namespace or in the
5522       //   global namespace shall be declared static.
5523       unsigned DiagID;
5524       DeclContext *OwnerScope = Owner->getRedeclContext();
5525       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5526           (OwnerScope->isTranslationUnit() ||
5527            (OwnerScope->isNamespace() &&
5528             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5529         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5530           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5531 
5532         // Recover by adding 'static'.
5533         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5534                                PrevSpec, DiagID, Policy);
5535       }
5536       // C++ [class.union]p6:
5537       //   A storage class is not allowed in a declaration of an
5538       //   anonymous union in a class scope.
5539       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5540                isa<RecordDecl>(Owner)) {
5541         Diag(DS.getStorageClassSpecLoc(),
5542              diag::err_anonymous_union_with_storage_spec)
5543           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5544 
5545         // Recover by removing the storage specifier.
5546         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5547                                SourceLocation(),
5548                                PrevSpec, DiagID, Context.getPrintingPolicy());
5549       }
5550     }
5551 
5552     // Ignore const/volatile/restrict qualifiers.
5553     if (DS.getTypeQualifiers()) {
5554       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5555         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5556           << Record->isUnion() << "const"
5557           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5558       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5559         Diag(DS.getVolatileSpecLoc(),
5560              diag::ext_anonymous_struct_union_qualified)
5561           << Record->isUnion() << "volatile"
5562           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5563       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5564         Diag(DS.getRestrictSpecLoc(),
5565              diag::ext_anonymous_struct_union_qualified)
5566           << Record->isUnion() << "restrict"
5567           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5568       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5569         Diag(DS.getAtomicSpecLoc(),
5570              diag::ext_anonymous_struct_union_qualified)
5571           << Record->isUnion() << "_Atomic"
5572           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5573       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5574         Diag(DS.getUnalignedSpecLoc(),
5575              diag::ext_anonymous_struct_union_qualified)
5576           << Record->isUnion() << "__unaligned"
5577           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5578 
5579       DS.ClearTypeQualifiers();
5580     }
5581 
5582     // C++ [class.union]p2:
5583     //   The member-specification of an anonymous union shall only
5584     //   define non-static data members. [Note: nested types and
5585     //   functions cannot be declared within an anonymous union. ]
5586     for (auto *Mem : Record->decls()) {
5587       // Ignore invalid declarations; we already diagnosed them.
5588       if (Mem->isInvalidDecl())
5589         continue;
5590 
5591       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5592         // C++ [class.union]p3:
5593         //   An anonymous union shall not have private or protected
5594         //   members (clause 11).
5595         assert(FD->getAccess() != AS_none);
5596         if (FD->getAccess() != AS_public) {
5597           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5598             << Record->isUnion() << (FD->getAccess() == AS_protected);
5599           Invalid = true;
5600         }
5601 
5602         // C++ [class.union]p1
5603         //   An object of a class with a non-trivial constructor, a non-trivial
5604         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5605         //   assignment operator cannot be a member of a union, nor can an
5606         //   array of such objects.
5607         if (CheckNontrivialField(FD))
5608           Invalid = true;
5609       } else if (Mem->isImplicit()) {
5610         // Any implicit members are fine.
5611       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5612         // This is a type that showed up in an
5613         // elaborated-type-specifier inside the anonymous struct or
5614         // union, but which actually declares a type outside of the
5615         // anonymous struct or union. It's okay.
5616       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5617         if (!MemRecord->isAnonymousStructOrUnion() &&
5618             MemRecord->getDeclName()) {
5619           // Visual C++ allows type definition in anonymous struct or union.
5620           if (getLangOpts().MicrosoftExt)
5621             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5622               << Record->isUnion();
5623           else {
5624             // This is a nested type declaration.
5625             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5626               << Record->isUnion();
5627             Invalid = true;
5628           }
5629         } else {
5630           // This is an anonymous type definition within another anonymous type.
5631           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5632           // not part of standard C++.
5633           Diag(MemRecord->getLocation(),
5634                diag::ext_anonymous_record_with_anonymous_type)
5635             << Record->isUnion();
5636         }
5637       } else if (isa<AccessSpecDecl>(Mem)) {
5638         // Any access specifier is fine.
5639       } else if (isa<StaticAssertDecl>(Mem)) {
5640         // In C++1z, static_assert declarations are also fine.
5641       } else {
5642         // We have something that isn't a non-static data
5643         // member. Complain about it.
5644         unsigned DK = diag::err_anonymous_record_bad_member;
5645         if (isa<TypeDecl>(Mem))
5646           DK = diag::err_anonymous_record_with_type;
5647         else if (isa<FunctionDecl>(Mem))
5648           DK = diag::err_anonymous_record_with_function;
5649         else if (isa<VarDecl>(Mem))
5650           DK = diag::err_anonymous_record_with_static;
5651 
5652         // Visual C++ allows type definition in anonymous struct or union.
5653         if (getLangOpts().MicrosoftExt &&
5654             DK == diag::err_anonymous_record_with_type)
5655           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5656             << Record->isUnion();
5657         else {
5658           Diag(Mem->getLocation(), DK) << Record->isUnion();
5659           Invalid = true;
5660         }
5661       }
5662     }
5663 
5664     // C++11 [class.union]p8 (DR1460):
5665     //   At most one variant member of a union may have a
5666     //   brace-or-equal-initializer.
5667     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5668         Owner->isRecord())
5669       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5670                                 cast<CXXRecordDecl>(Record));
5671   }
5672 
5673   if (!Record->isUnion() && !Owner->isRecord()) {
5674     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5675       << getLangOpts().CPlusPlus;
5676     Invalid = true;
5677   }
5678 
5679   // C++ [dcl.dcl]p3:
5680   //   [If there are no declarators], and except for the declaration of an
5681   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5682   //   names into the program
5683   // C++ [class.mem]p2:
5684   //   each such member-declaration shall either declare at least one member
5685   //   name of the class or declare at least one unnamed bit-field
5686   //
5687   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5688   if (getLangOpts().CPlusPlus && Record->field_empty())
5689     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5690 
5691   // Mock up a declarator.
5692   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5693   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5694   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5695 
5696   // Create a declaration for this anonymous struct/union.
5697   NamedDecl *Anon = nullptr;
5698   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5699     Anon = FieldDecl::Create(
5700         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5701         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5702         /*BitWidth=*/nullptr, /*Mutable=*/false,
5703         /*InitStyle=*/ICIS_NoInit);
5704     Anon->setAccess(AS);
5705     ProcessDeclAttributes(S, Anon, Dc);
5706 
5707     if (getLangOpts().CPlusPlus)
5708       FieldCollector->Add(cast<FieldDecl>(Anon));
5709   } else {
5710     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5711     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5712     if (SCSpec == DeclSpec::SCS_mutable) {
5713       // mutable can only appear on non-static class members, so it's always
5714       // an error here
5715       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5716       Invalid = true;
5717       SC = SC_None;
5718     }
5719 
5720     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5721                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5722                            Context.getTypeDeclType(Record), TInfo, SC);
5723     ProcessDeclAttributes(S, Anon, Dc);
5724 
5725     // Default-initialize the implicit variable. This initialization will be
5726     // trivial in almost all cases, except if a union member has an in-class
5727     // initializer:
5728     //   union { int n = 0; };
5729     ActOnUninitializedDecl(Anon);
5730   }
5731   Anon->setImplicit();
5732 
5733   // Mark this as an anonymous struct/union type.
5734   Record->setAnonymousStructOrUnion(true);
5735 
5736   // Add the anonymous struct/union object to the current
5737   // context. We'll be referencing this object when we refer to one of
5738   // its members.
5739   Owner->addDecl(Anon);
5740 
5741   // Inject the members of the anonymous struct/union into the owning
5742   // context and into the identifier resolver chain for name lookup
5743   // purposes.
5744   SmallVector<NamedDecl*, 2> Chain;
5745   Chain.push_back(Anon);
5746 
5747   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5748     Invalid = true;
5749 
5750   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5751     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5752       MangleNumberingContext *MCtx;
5753       Decl *ManglingContextDecl;
5754       std::tie(MCtx, ManglingContextDecl) =
5755           getCurrentMangleNumberContext(NewVD->getDeclContext());
5756       if (MCtx) {
5757         Context.setManglingNumber(
5758             NewVD, MCtx->getManglingNumber(
5759                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5760         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5761       }
5762     }
5763   }
5764 
5765   if (Invalid)
5766     Anon->setInvalidDecl();
5767 
5768   return Anon;
5769 }
5770 
5771 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5772 /// Microsoft C anonymous structure.
5773 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5774 /// Example:
5775 ///
5776 /// struct A { int a; };
5777 /// struct B { struct A; int b; };
5778 ///
5779 /// void foo() {
5780 ///   B var;
5781 ///   var.a = 3;
5782 /// }
5783 ///
5784 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5785                                            RecordDecl *Record) {
5786   assert(Record && "expected a record!");
5787 
5788   // Mock up a declarator.
5789   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5790   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5791   assert(TInfo && "couldn't build declarator info for anonymous struct");
5792 
5793   auto *ParentDecl = cast<RecordDecl>(CurContext);
5794   QualType RecTy = Context.getTypeDeclType(Record);
5795 
5796   // Create a declaration for this anonymous struct.
5797   NamedDecl *Anon =
5798       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5799                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5800                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5801                         /*InitStyle=*/ICIS_NoInit);
5802   Anon->setImplicit();
5803 
5804   // Add the anonymous struct object to the current context.
5805   CurContext->addDecl(Anon);
5806 
5807   // Inject the members of the anonymous struct into the current
5808   // context and into the identifier resolver chain for name lookup
5809   // purposes.
5810   SmallVector<NamedDecl*, 2> Chain;
5811   Chain.push_back(Anon);
5812 
5813   RecordDecl *RecordDef = Record->getDefinition();
5814   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5815                                diag::err_field_incomplete_or_sizeless) ||
5816       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5817                                           AS_none, Chain)) {
5818     Anon->setInvalidDecl();
5819     ParentDecl->setInvalidDecl();
5820   }
5821 
5822   return Anon;
5823 }
5824 
5825 /// GetNameForDeclarator - Determine the full declaration name for the
5826 /// given Declarator.
5827 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5828   return GetNameFromUnqualifiedId(D.getName());
5829 }
5830 
5831 /// Retrieves the declaration name from a parsed unqualified-id.
5832 DeclarationNameInfo
5833 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5834   DeclarationNameInfo NameInfo;
5835   NameInfo.setLoc(Name.StartLocation);
5836 
5837   switch (Name.getKind()) {
5838 
5839   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5840   case UnqualifiedIdKind::IK_Identifier:
5841     NameInfo.setName(Name.Identifier);
5842     return NameInfo;
5843 
5844   case UnqualifiedIdKind::IK_DeductionGuideName: {
5845     // C++ [temp.deduct.guide]p3:
5846     //   The simple-template-id shall name a class template specialization.
5847     //   The template-name shall be the same identifier as the template-name
5848     //   of the simple-template-id.
5849     // These together intend to imply that the template-name shall name a
5850     // class template.
5851     // FIXME: template<typename T> struct X {};
5852     //        template<typename T> using Y = X<T>;
5853     //        Y(int) -> Y<int>;
5854     //   satisfies these rules but does not name a class template.
5855     TemplateName TN = Name.TemplateName.get().get();
5856     auto *Template = TN.getAsTemplateDecl();
5857     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5858       Diag(Name.StartLocation,
5859            diag::err_deduction_guide_name_not_class_template)
5860         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5861       if (Template)
5862         Diag(Template->getLocation(), diag::note_template_decl_here);
5863       return DeclarationNameInfo();
5864     }
5865 
5866     NameInfo.setName(
5867         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5868     return NameInfo;
5869   }
5870 
5871   case UnqualifiedIdKind::IK_OperatorFunctionId:
5872     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5873                                            Name.OperatorFunctionId.Operator));
5874     NameInfo.setCXXOperatorNameRange(SourceRange(
5875         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5876     return NameInfo;
5877 
5878   case UnqualifiedIdKind::IK_LiteralOperatorId:
5879     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5880                                                            Name.Identifier));
5881     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5882     return NameInfo;
5883 
5884   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5885     TypeSourceInfo *TInfo;
5886     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5887     if (Ty.isNull())
5888       return DeclarationNameInfo();
5889     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5890                                                Context.getCanonicalType(Ty)));
5891     NameInfo.setNamedTypeInfo(TInfo);
5892     return NameInfo;
5893   }
5894 
5895   case UnqualifiedIdKind::IK_ConstructorName: {
5896     TypeSourceInfo *TInfo;
5897     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5898     if (Ty.isNull())
5899       return DeclarationNameInfo();
5900     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5901                                               Context.getCanonicalType(Ty)));
5902     NameInfo.setNamedTypeInfo(TInfo);
5903     return NameInfo;
5904   }
5905 
5906   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5907     // In well-formed code, we can only have a constructor
5908     // template-id that refers to the current context, so go there
5909     // to find the actual type being constructed.
5910     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5911     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5912       return DeclarationNameInfo();
5913 
5914     // Determine the type of the class being constructed.
5915     QualType CurClassType = Context.getTypeDeclType(CurClass);
5916 
5917     // FIXME: Check two things: that the template-id names the same type as
5918     // CurClassType, and that the template-id does not occur when the name
5919     // was qualified.
5920 
5921     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5922                                     Context.getCanonicalType(CurClassType)));
5923     // FIXME: should we retrieve TypeSourceInfo?
5924     NameInfo.setNamedTypeInfo(nullptr);
5925     return NameInfo;
5926   }
5927 
5928   case UnqualifiedIdKind::IK_DestructorName: {
5929     TypeSourceInfo *TInfo;
5930     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5931     if (Ty.isNull())
5932       return DeclarationNameInfo();
5933     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5934                                               Context.getCanonicalType(Ty)));
5935     NameInfo.setNamedTypeInfo(TInfo);
5936     return NameInfo;
5937   }
5938 
5939   case UnqualifiedIdKind::IK_TemplateId: {
5940     TemplateName TName = Name.TemplateId->Template.get();
5941     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5942     return Context.getNameForTemplate(TName, TNameLoc);
5943   }
5944 
5945   } // switch (Name.getKind())
5946 
5947   llvm_unreachable("Unknown name kind");
5948 }
5949 
5950 static QualType getCoreType(QualType Ty) {
5951   do {
5952     if (Ty->isPointerType() || Ty->isReferenceType())
5953       Ty = Ty->getPointeeType();
5954     else if (Ty->isArrayType())
5955       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5956     else
5957       return Ty.withoutLocalFastQualifiers();
5958   } while (true);
5959 }
5960 
5961 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5962 /// and Definition have "nearly" matching parameters. This heuristic is
5963 /// used to improve diagnostics in the case where an out-of-line function
5964 /// definition doesn't match any declaration within the class or namespace.
5965 /// Also sets Params to the list of indices to the parameters that differ
5966 /// between the declaration and the definition. If hasSimilarParameters
5967 /// returns true and Params is empty, then all of the parameters match.
5968 static bool hasSimilarParameters(ASTContext &Context,
5969                                      FunctionDecl *Declaration,
5970                                      FunctionDecl *Definition,
5971                                      SmallVectorImpl<unsigned> &Params) {
5972   Params.clear();
5973   if (Declaration->param_size() != Definition->param_size())
5974     return false;
5975   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5976     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5977     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5978 
5979     // The parameter types are identical
5980     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5981       continue;
5982 
5983     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5984     QualType DefParamBaseTy = getCoreType(DefParamTy);
5985     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5986     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5987 
5988     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5989         (DeclTyName && DeclTyName == DefTyName))
5990       Params.push_back(Idx);
5991     else  // The two parameters aren't even close
5992       return false;
5993   }
5994 
5995   return true;
5996 }
5997 
5998 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5999 /// declarator needs to be rebuilt in the current instantiation.
6000 /// Any bits of declarator which appear before the name are valid for
6001 /// consideration here.  That's specifically the type in the decl spec
6002 /// and the base type in any member-pointer chunks.
6003 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6004                                                     DeclarationName Name) {
6005   // The types we specifically need to rebuild are:
6006   //   - typenames, typeofs, and decltypes
6007   //   - types which will become injected class names
6008   // Of course, we also need to rebuild any type referencing such a
6009   // type.  It's safest to just say "dependent", but we call out a
6010   // few cases here.
6011 
6012   DeclSpec &DS = D.getMutableDeclSpec();
6013   switch (DS.getTypeSpecType()) {
6014   case DeclSpec::TST_typename:
6015   case DeclSpec::TST_typeofType:
6016   case DeclSpec::TST_typeof_unqualType:
6017 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6018 #include "clang/Basic/TransformTypeTraits.def"
6019   case DeclSpec::TST_atomic: {
6020     // Grab the type from the parser.
6021     TypeSourceInfo *TSI = nullptr;
6022     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6023     if (T.isNull() || !T->isInstantiationDependentType()) break;
6024 
6025     // Make sure there's a type source info.  This isn't really much
6026     // of a waste; most dependent types should have type source info
6027     // attached already.
6028     if (!TSI)
6029       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6030 
6031     // Rebuild the type in the current instantiation.
6032     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6033     if (!TSI) return true;
6034 
6035     // Store the new type back in the decl spec.
6036     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6037     DS.UpdateTypeRep(LocType);
6038     break;
6039   }
6040 
6041   case DeclSpec::TST_decltype:
6042   case DeclSpec::TST_typeof_unqualExpr:
6043   case DeclSpec::TST_typeofExpr: {
6044     Expr *E = DS.getRepAsExpr();
6045     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6046     if (Result.isInvalid()) return true;
6047     DS.UpdateExprRep(Result.get());
6048     break;
6049   }
6050 
6051   default:
6052     // Nothing to do for these decl specs.
6053     break;
6054   }
6055 
6056   // It doesn't matter what order we do this in.
6057   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6058     DeclaratorChunk &Chunk = D.getTypeObject(I);
6059 
6060     // The only type information in the declarator which can come
6061     // before the declaration name is the base type of a member
6062     // pointer.
6063     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6064       continue;
6065 
6066     // Rebuild the scope specifier in-place.
6067     CXXScopeSpec &SS = Chunk.Mem.Scope();
6068     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6069       return true;
6070   }
6071 
6072   return false;
6073 }
6074 
6075 /// Returns true if the declaration is declared in a system header or from a
6076 /// system macro.
6077 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6078   return SM.isInSystemHeader(D->getLocation()) ||
6079          SM.isInSystemMacro(D->getLocation());
6080 }
6081 
6082 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6083   // Avoid warning twice on the same identifier, and don't warn on redeclaration
6084   // of system decl.
6085   if (D->getPreviousDecl() || D->isImplicit())
6086     return;
6087   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6088   if (Status != ReservedIdentifierStatus::NotReserved &&
6089       !isFromSystemHeader(Context.getSourceManager(), D)) {
6090     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6091         << D << static_cast<int>(Status);
6092   }
6093 }
6094 
6095 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6096   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6097 
6098   // Check if we are in an `omp begin/end declare variant` scope. Handle this
6099   // declaration only if the `bind_to_declaration` extension is set.
6100   SmallVector<FunctionDecl *, 4> Bases;
6101   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6102     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6103               implementation_extension_bind_to_declaration))
6104     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6105         S, D, MultiTemplateParamsArg(), Bases);
6106 
6107   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6108 
6109   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6110       Dcl && Dcl->getDeclContext()->isFileContext())
6111     Dcl->setTopLevelDeclInObjCContainer();
6112 
6113   if (!Bases.empty())
6114     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6115 
6116   return Dcl;
6117 }
6118 
6119 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6120 ///   If T is the name of a class, then each of the following shall have a
6121 ///   name different from T:
6122 ///     - every static data member of class T;
6123 ///     - every member function of class T
6124 ///     - every member of class T that is itself a type;
6125 /// \returns true if the declaration name violates these rules.
6126 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6127                                    DeclarationNameInfo NameInfo) {
6128   DeclarationName Name = NameInfo.getName();
6129 
6130   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6131   while (Record && Record->isAnonymousStructOrUnion())
6132     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6133   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6134     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6135     return true;
6136   }
6137 
6138   return false;
6139 }
6140 
6141 /// Diagnose a declaration whose declarator-id has the given
6142 /// nested-name-specifier.
6143 ///
6144 /// \param SS The nested-name-specifier of the declarator-id.
6145 ///
6146 /// \param DC The declaration context to which the nested-name-specifier
6147 /// resolves.
6148 ///
6149 /// \param Name The name of the entity being declared.
6150 ///
6151 /// \param Loc The location of the name of the entity being declared.
6152 ///
6153 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6154 /// we're declaring an explicit / partial specialization / instantiation.
6155 ///
6156 /// \returns true if we cannot safely recover from this error, false otherwise.
6157 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6158                                         DeclarationName Name,
6159                                         SourceLocation Loc, bool IsTemplateId) {
6160   DeclContext *Cur = CurContext;
6161   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6162     Cur = Cur->getParent();
6163 
6164   // If the user provided a superfluous scope specifier that refers back to the
6165   // class in which the entity is already declared, diagnose and ignore it.
6166   //
6167   // class X {
6168   //   void X::f();
6169   // };
6170   //
6171   // Note, it was once ill-formed to give redundant qualification in all
6172   // contexts, but that rule was removed by DR482.
6173   if (Cur->Equals(DC)) {
6174     if (Cur->isRecord()) {
6175       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6176                                       : diag::err_member_extra_qualification)
6177         << Name << FixItHint::CreateRemoval(SS.getRange());
6178       SS.clear();
6179     } else {
6180       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6181     }
6182     return false;
6183   }
6184 
6185   // Check whether the qualifying scope encloses the scope of the original
6186   // declaration. For a template-id, we perform the checks in
6187   // CheckTemplateSpecializationScope.
6188   if (!Cur->Encloses(DC) && !IsTemplateId) {
6189     if (Cur->isRecord())
6190       Diag(Loc, diag::err_member_qualification)
6191         << Name << SS.getRange();
6192     else if (isa<TranslationUnitDecl>(DC))
6193       Diag(Loc, diag::err_invalid_declarator_global_scope)
6194         << Name << SS.getRange();
6195     else if (isa<FunctionDecl>(Cur))
6196       Diag(Loc, diag::err_invalid_declarator_in_function)
6197         << Name << SS.getRange();
6198     else if (isa<BlockDecl>(Cur))
6199       Diag(Loc, diag::err_invalid_declarator_in_block)
6200         << Name << SS.getRange();
6201     else if (isa<ExportDecl>(Cur)) {
6202       if (!isa<NamespaceDecl>(DC))
6203         Diag(Loc, diag::err_export_non_namespace_scope_name)
6204             << Name << SS.getRange();
6205       else
6206         // The cases that DC is not NamespaceDecl should be handled in
6207         // CheckRedeclarationExported.
6208         return false;
6209     } else
6210       Diag(Loc, diag::err_invalid_declarator_scope)
6211       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6212 
6213     return true;
6214   }
6215 
6216   if (Cur->isRecord()) {
6217     // Cannot qualify members within a class.
6218     Diag(Loc, diag::err_member_qualification)
6219       << Name << SS.getRange();
6220     SS.clear();
6221 
6222     // C++ constructors and destructors with incorrect scopes can break
6223     // our AST invariants by having the wrong underlying types. If
6224     // that's the case, then drop this declaration entirely.
6225     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6226          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6227         !Context.hasSameType(Name.getCXXNameType(),
6228                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6229       return true;
6230 
6231     return false;
6232   }
6233 
6234   // C++11 [dcl.meaning]p1:
6235   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6236   //   not begin with a decltype-specifer"
6237   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6238   while (SpecLoc.getPrefix())
6239     SpecLoc = SpecLoc.getPrefix();
6240   if (isa_and_nonnull<DecltypeType>(
6241           SpecLoc.getNestedNameSpecifier()->getAsType()))
6242     Diag(Loc, diag::err_decltype_in_declarator)
6243       << SpecLoc.getTypeLoc().getSourceRange();
6244 
6245   return false;
6246 }
6247 
6248 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6249                                   MultiTemplateParamsArg TemplateParamLists) {
6250   // TODO: consider using NameInfo for diagnostic.
6251   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6252   DeclarationName Name = NameInfo.getName();
6253 
6254   // All of these full declarators require an identifier.  If it doesn't have
6255   // one, the ParsedFreeStandingDeclSpec action should be used.
6256   if (D.isDecompositionDeclarator()) {
6257     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6258   } else if (!Name) {
6259     if (!D.isInvalidType())  // Reject this if we think it is valid.
6260       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6261           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6262     return nullptr;
6263   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6264     return nullptr;
6265 
6266   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6267   // we find one that is.
6268   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6269          (S->getFlags() & Scope::TemplateParamScope) != 0)
6270     S = S->getParent();
6271 
6272   DeclContext *DC = CurContext;
6273   if (D.getCXXScopeSpec().isInvalid())
6274     D.setInvalidType();
6275   else if (D.getCXXScopeSpec().isSet()) {
6276     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6277                                         UPPC_DeclarationQualifier))
6278       return nullptr;
6279 
6280     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6281     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6282     if (!DC || isa<EnumDecl>(DC)) {
6283       // If we could not compute the declaration context, it's because the
6284       // declaration context is dependent but does not refer to a class,
6285       // class template, or class template partial specialization. Complain
6286       // and return early, to avoid the coming semantic disaster.
6287       Diag(D.getIdentifierLoc(),
6288            diag::err_template_qualified_declarator_no_match)
6289         << D.getCXXScopeSpec().getScopeRep()
6290         << D.getCXXScopeSpec().getRange();
6291       return nullptr;
6292     }
6293     bool IsDependentContext = DC->isDependentContext();
6294 
6295     if (!IsDependentContext &&
6296         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6297       return nullptr;
6298 
6299     // If a class is incomplete, do not parse entities inside it.
6300     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6301       Diag(D.getIdentifierLoc(),
6302            diag::err_member_def_undefined_record)
6303         << Name << DC << D.getCXXScopeSpec().getRange();
6304       return nullptr;
6305     }
6306     if (!D.getDeclSpec().isFriendSpecified()) {
6307       if (diagnoseQualifiedDeclaration(
6308               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6309               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6310         if (DC->isRecord())
6311           return nullptr;
6312 
6313         D.setInvalidType();
6314       }
6315     }
6316 
6317     // Check whether we need to rebuild the type of the given
6318     // declaration in the current instantiation.
6319     if (EnteringContext && IsDependentContext &&
6320         TemplateParamLists.size() != 0) {
6321       ContextRAII SavedContext(*this, DC);
6322       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6323         D.setInvalidType();
6324     }
6325   }
6326 
6327   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6328   QualType R = TInfo->getType();
6329 
6330   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6331                                       UPPC_DeclarationType))
6332     D.setInvalidType();
6333 
6334   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6335                         forRedeclarationInCurContext());
6336 
6337   // See if this is a redefinition of a variable in the same scope.
6338   if (!D.getCXXScopeSpec().isSet()) {
6339     bool IsLinkageLookup = false;
6340     bool CreateBuiltins = false;
6341 
6342     // If the declaration we're planning to build will be a function
6343     // or object with linkage, then look for another declaration with
6344     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6345     //
6346     // If the declaration we're planning to build will be declared with
6347     // external linkage in the translation unit, create any builtin with
6348     // the same name.
6349     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6350       /* Do nothing*/;
6351     else if (CurContext->isFunctionOrMethod() &&
6352              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6353               R->isFunctionType())) {
6354       IsLinkageLookup = true;
6355       CreateBuiltins =
6356           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6357     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6358                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6359       CreateBuiltins = true;
6360 
6361     if (IsLinkageLookup) {
6362       Previous.clear(LookupRedeclarationWithLinkage);
6363       Previous.setRedeclarationKind(ForExternalRedeclaration);
6364     }
6365 
6366     LookupName(Previous, S, CreateBuiltins);
6367   } else { // Something like "int foo::x;"
6368     LookupQualifiedName(Previous, DC);
6369 
6370     // C++ [dcl.meaning]p1:
6371     //   When the declarator-id is qualified, the declaration shall refer to a
6372     //  previously declared member of the class or namespace to which the
6373     //  qualifier refers (or, in the case of a namespace, of an element of the
6374     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6375     //  thereof; [...]
6376     //
6377     // Note that we already checked the context above, and that we do not have
6378     // enough information to make sure that Previous contains the declaration
6379     // we want to match. For example, given:
6380     //
6381     //   class X {
6382     //     void f();
6383     //     void f(float);
6384     //   };
6385     //
6386     //   void X::f(int) { } // ill-formed
6387     //
6388     // In this case, Previous will point to the overload set
6389     // containing the two f's declared in X, but neither of them
6390     // matches.
6391 
6392     RemoveUsingDecls(Previous);
6393   }
6394 
6395   if (Previous.isSingleResult() &&
6396       Previous.getFoundDecl()->isTemplateParameter()) {
6397     // Maybe we will complain about the shadowed template parameter.
6398     if (!D.isInvalidType())
6399       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6400                                       Previous.getFoundDecl());
6401 
6402     // Just pretend that we didn't see the previous declaration.
6403     Previous.clear();
6404   }
6405 
6406   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6407     // Forget that the previous declaration is the injected-class-name.
6408     Previous.clear();
6409 
6410   // In C++, the previous declaration we find might be a tag type
6411   // (class or enum). In this case, the new declaration will hide the
6412   // tag type. Note that this applies to functions, function templates, and
6413   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6414   if (Previous.isSingleTagDecl() &&
6415       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6416       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6417     Previous.clear();
6418 
6419   // Check that there are no default arguments other than in the parameters
6420   // of a function declaration (C++ only).
6421   if (getLangOpts().CPlusPlus)
6422     CheckExtraCXXDefaultArguments(D);
6423 
6424   NamedDecl *New;
6425 
6426   bool AddToScope = true;
6427   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6428     if (TemplateParamLists.size()) {
6429       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6430       return nullptr;
6431     }
6432 
6433     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6434   } else if (R->isFunctionType()) {
6435     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6436                                   TemplateParamLists,
6437                                   AddToScope);
6438   } else {
6439     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6440                                   AddToScope);
6441   }
6442 
6443   if (!New)
6444     return nullptr;
6445 
6446   // If this has an identifier and is not a function template specialization,
6447   // add it to the scope stack.
6448   if (New->getDeclName() && AddToScope)
6449     PushOnScopeChains(New, S);
6450 
6451   if (isInOpenMPDeclareTargetContext())
6452     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6453 
6454   return New;
6455 }
6456 
6457 /// Helper method to turn variable array types into constant array
6458 /// types in certain situations which would otherwise be errors (for
6459 /// GCC compatibility).
6460 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6461                                                     ASTContext &Context,
6462                                                     bool &SizeIsNegative,
6463                                                     llvm::APSInt &Oversized) {
6464   // This method tries to turn a variable array into a constant
6465   // array even when the size isn't an ICE.  This is necessary
6466   // for compatibility with code that depends on gcc's buggy
6467   // constant expression folding, like struct {char x[(int)(char*)2];}
6468   SizeIsNegative = false;
6469   Oversized = 0;
6470 
6471   if (T->isDependentType())
6472     return QualType();
6473 
6474   QualifierCollector Qs;
6475   const Type *Ty = Qs.strip(T);
6476 
6477   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6478     QualType Pointee = PTy->getPointeeType();
6479     QualType FixedType =
6480         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6481                                             Oversized);
6482     if (FixedType.isNull()) return FixedType;
6483     FixedType = Context.getPointerType(FixedType);
6484     return Qs.apply(Context, FixedType);
6485   }
6486   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6487     QualType Inner = PTy->getInnerType();
6488     QualType FixedType =
6489         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6490                                             Oversized);
6491     if (FixedType.isNull()) return FixedType;
6492     FixedType = Context.getParenType(FixedType);
6493     return Qs.apply(Context, FixedType);
6494   }
6495 
6496   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6497   if (!VLATy)
6498     return QualType();
6499 
6500   QualType ElemTy = VLATy->getElementType();
6501   if (ElemTy->isVariablyModifiedType()) {
6502     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6503                                                  SizeIsNegative, Oversized);
6504     if (ElemTy.isNull())
6505       return QualType();
6506   }
6507 
6508   Expr::EvalResult Result;
6509   if (!VLATy->getSizeExpr() ||
6510       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6511     return QualType();
6512 
6513   llvm::APSInt Res = Result.Val.getInt();
6514 
6515   // Check whether the array size is negative.
6516   if (Res.isSigned() && Res.isNegative()) {
6517     SizeIsNegative = true;
6518     return QualType();
6519   }
6520 
6521   // Check whether the array is too large to be addressed.
6522   unsigned ActiveSizeBits =
6523       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6524        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6525           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6526           : Res.getActiveBits();
6527   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6528     Oversized = Res;
6529     return QualType();
6530   }
6531 
6532   QualType FoldedArrayType = Context.getConstantArrayType(
6533       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6534   return Qs.apply(Context, FoldedArrayType);
6535 }
6536 
6537 static void
6538 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6539   SrcTL = SrcTL.getUnqualifiedLoc();
6540   DstTL = DstTL.getUnqualifiedLoc();
6541   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6542     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6543     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6544                                       DstPTL.getPointeeLoc());
6545     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6546     return;
6547   }
6548   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6549     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6550     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6551                                       DstPTL.getInnerLoc());
6552     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6553     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6554     return;
6555   }
6556   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6557   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6558   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6559   TypeLoc DstElemTL = DstATL.getElementLoc();
6560   if (VariableArrayTypeLoc SrcElemATL =
6561           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6562     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6563     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6564   } else {
6565     DstElemTL.initializeFullCopy(SrcElemTL);
6566   }
6567   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6568   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6569   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6570 }
6571 
6572 /// Helper method to turn variable array types into constant array
6573 /// types in certain situations which would otherwise be errors (for
6574 /// GCC compatibility).
6575 static TypeSourceInfo*
6576 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6577                                               ASTContext &Context,
6578                                               bool &SizeIsNegative,
6579                                               llvm::APSInt &Oversized) {
6580   QualType FixedTy
6581     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6582                                           SizeIsNegative, Oversized);
6583   if (FixedTy.isNull())
6584     return nullptr;
6585   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6586   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6587                                     FixedTInfo->getTypeLoc());
6588   return FixedTInfo;
6589 }
6590 
6591 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6592 /// true if we were successful.
6593 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6594                                            QualType &T, SourceLocation Loc,
6595                                            unsigned FailedFoldDiagID) {
6596   bool SizeIsNegative;
6597   llvm::APSInt Oversized;
6598   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6599       TInfo, Context, SizeIsNegative, Oversized);
6600   if (FixedTInfo) {
6601     Diag(Loc, diag::ext_vla_folded_to_constant);
6602     TInfo = FixedTInfo;
6603     T = FixedTInfo->getType();
6604     return true;
6605   }
6606 
6607   if (SizeIsNegative)
6608     Diag(Loc, diag::err_typecheck_negative_array_size);
6609   else if (Oversized.getBoolValue())
6610     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6611   else if (FailedFoldDiagID)
6612     Diag(Loc, FailedFoldDiagID);
6613   return false;
6614 }
6615 
6616 /// Register the given locally-scoped extern "C" declaration so
6617 /// that it can be found later for redeclarations. We include any extern "C"
6618 /// declaration that is not visible in the translation unit here, not just
6619 /// function-scope declarations.
6620 void
6621 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6622   if (!getLangOpts().CPlusPlus &&
6623       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6624     // Don't need to track declarations in the TU in C.
6625     return;
6626 
6627   // Note that we have a locally-scoped external with this name.
6628   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6629 }
6630 
6631 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6632   // FIXME: We can have multiple results via __attribute__((overloadable)).
6633   auto Result = Context.getExternCContextDecl()->lookup(Name);
6634   return Result.empty() ? nullptr : *Result.begin();
6635 }
6636 
6637 /// Diagnose function specifiers on a declaration of an identifier that
6638 /// does not identify a function.
6639 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6640   // FIXME: We should probably indicate the identifier in question to avoid
6641   // confusion for constructs like "virtual int a(), b;"
6642   if (DS.isVirtualSpecified())
6643     Diag(DS.getVirtualSpecLoc(),
6644          diag::err_virtual_non_function);
6645 
6646   if (DS.hasExplicitSpecifier())
6647     Diag(DS.getExplicitSpecLoc(),
6648          diag::err_explicit_non_function);
6649 
6650   if (DS.isNoreturnSpecified())
6651     Diag(DS.getNoreturnSpecLoc(),
6652          diag::err_noreturn_non_function);
6653 }
6654 
6655 NamedDecl*
6656 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6657                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6658   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6659   if (D.getCXXScopeSpec().isSet()) {
6660     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6661       << D.getCXXScopeSpec().getRange();
6662     D.setInvalidType();
6663     // Pretend we didn't see the scope specifier.
6664     DC = CurContext;
6665     Previous.clear();
6666   }
6667 
6668   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6669 
6670   if (D.getDeclSpec().isInlineSpecified())
6671     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6672         << getLangOpts().CPlusPlus17;
6673   if (D.getDeclSpec().hasConstexprSpecifier())
6674     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6675         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6676 
6677   if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6678     if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6679       Diag(D.getName().StartLocation,
6680            diag::err_deduction_guide_invalid_specifier)
6681           << "typedef";
6682     else
6683       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6684           << D.getName().getSourceRange();
6685     return nullptr;
6686   }
6687 
6688   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6689   if (!NewTD) return nullptr;
6690 
6691   // Handle attributes prior to checking for duplicates in MergeVarDecl
6692   ProcessDeclAttributes(S, NewTD, D);
6693 
6694   CheckTypedefForVariablyModifiedType(S, NewTD);
6695 
6696   bool Redeclaration = D.isRedeclaration();
6697   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6698   D.setRedeclaration(Redeclaration);
6699   return ND;
6700 }
6701 
6702 void
6703 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6704   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6705   // then it shall have block scope.
6706   // Note that variably modified types must be fixed before merging the decl so
6707   // that redeclarations will match.
6708   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6709   QualType T = TInfo->getType();
6710   if (T->isVariablyModifiedType()) {
6711     setFunctionHasBranchProtectedScope();
6712 
6713     if (S->getFnParent() == nullptr) {
6714       bool SizeIsNegative;
6715       llvm::APSInt Oversized;
6716       TypeSourceInfo *FixedTInfo =
6717         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6718                                                       SizeIsNegative,
6719                                                       Oversized);
6720       if (FixedTInfo) {
6721         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6722         NewTD->setTypeSourceInfo(FixedTInfo);
6723       } else {
6724         if (SizeIsNegative)
6725           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6726         else if (T->isVariableArrayType())
6727           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6728         else if (Oversized.getBoolValue())
6729           Diag(NewTD->getLocation(), diag::err_array_too_large)
6730             << toString(Oversized, 10);
6731         else
6732           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6733         NewTD->setInvalidDecl();
6734       }
6735     }
6736   }
6737 }
6738 
6739 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6740 /// declares a typedef-name, either using the 'typedef' type specifier or via
6741 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6742 NamedDecl*
6743 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6744                            LookupResult &Previous, bool &Redeclaration) {
6745 
6746   // Find the shadowed declaration before filtering for scope.
6747   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6748 
6749   // Merge the decl with the existing one if appropriate. If the decl is
6750   // in an outer scope, it isn't the same thing.
6751   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6752                        /*AllowInlineNamespace*/false);
6753   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6754   if (!Previous.empty()) {
6755     Redeclaration = true;
6756     MergeTypedefNameDecl(S, NewTD, Previous);
6757   } else {
6758     inferGslPointerAttribute(NewTD);
6759   }
6760 
6761   if (ShadowedDecl && !Redeclaration)
6762     CheckShadow(NewTD, ShadowedDecl, Previous);
6763 
6764   // If this is the C FILE type, notify the AST context.
6765   if (IdentifierInfo *II = NewTD->getIdentifier())
6766     if (!NewTD->isInvalidDecl() &&
6767         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6768       switch (II->getInterestingIdentifierID()) {
6769       case tok::InterestingIdentifierKind::FILE:
6770         Context.setFILEDecl(NewTD);
6771         break;
6772       case tok::InterestingIdentifierKind::jmp_buf:
6773         Context.setjmp_bufDecl(NewTD);
6774         break;
6775       case tok::InterestingIdentifierKind::sigjmp_buf:
6776         Context.setsigjmp_bufDecl(NewTD);
6777         break;
6778       case tok::InterestingIdentifierKind::ucontext_t:
6779         Context.setucontext_tDecl(NewTD);
6780         break;
6781       case tok::InterestingIdentifierKind::float_t:
6782       case tok::InterestingIdentifierKind::double_t:
6783         NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6784         break;
6785       default:
6786         break;
6787       }
6788     }
6789 
6790   return NewTD;
6791 }
6792 
6793 /// Determines whether the given declaration is an out-of-scope
6794 /// previous declaration.
6795 ///
6796 /// This routine should be invoked when name lookup has found a
6797 /// previous declaration (PrevDecl) that is not in the scope where a
6798 /// new declaration by the same name is being introduced. If the new
6799 /// declaration occurs in a local scope, previous declarations with
6800 /// linkage may still be considered previous declarations (C99
6801 /// 6.2.2p4-5, C++ [basic.link]p6).
6802 ///
6803 /// \param PrevDecl the previous declaration found by name
6804 /// lookup
6805 ///
6806 /// \param DC the context in which the new declaration is being
6807 /// declared.
6808 ///
6809 /// \returns true if PrevDecl is an out-of-scope previous declaration
6810 /// for a new delcaration with the same name.
6811 static bool
6812 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6813                                 ASTContext &Context) {
6814   if (!PrevDecl)
6815     return false;
6816 
6817   if (!PrevDecl->hasLinkage())
6818     return false;
6819 
6820   if (Context.getLangOpts().CPlusPlus) {
6821     // C++ [basic.link]p6:
6822     //   If there is a visible declaration of an entity with linkage
6823     //   having the same name and type, ignoring entities declared
6824     //   outside the innermost enclosing namespace scope, the block
6825     //   scope declaration declares that same entity and receives the
6826     //   linkage of the previous declaration.
6827     DeclContext *OuterContext = DC->getRedeclContext();
6828     if (!OuterContext->isFunctionOrMethod())
6829       // This rule only applies to block-scope declarations.
6830       return false;
6831 
6832     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6833     if (PrevOuterContext->isRecord())
6834       // We found a member function: ignore it.
6835       return false;
6836 
6837     // Find the innermost enclosing namespace for the new and
6838     // previous declarations.
6839     OuterContext = OuterContext->getEnclosingNamespaceContext();
6840     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6841 
6842     // The previous declaration is in a different namespace, so it
6843     // isn't the same function.
6844     if (!OuterContext->Equals(PrevOuterContext))
6845       return false;
6846   }
6847 
6848   return true;
6849 }
6850 
6851 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6852   CXXScopeSpec &SS = D.getCXXScopeSpec();
6853   if (!SS.isSet()) return;
6854   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6855 }
6856 
6857 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6858   QualType type = decl->getType();
6859   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6860   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6861     // Various kinds of declaration aren't allowed to be __autoreleasing.
6862     unsigned kind = -1U;
6863     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6864       if (var->hasAttr<BlocksAttr>())
6865         kind = 0; // __block
6866       else if (!var->hasLocalStorage())
6867         kind = 1; // global
6868     } else if (isa<ObjCIvarDecl>(decl)) {
6869       kind = 3; // ivar
6870     } else if (isa<FieldDecl>(decl)) {
6871       kind = 2; // field
6872     }
6873 
6874     if (kind != -1U) {
6875       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6876         << kind;
6877     }
6878   } else if (lifetime == Qualifiers::OCL_None) {
6879     // Try to infer lifetime.
6880     if (!type->isObjCLifetimeType())
6881       return false;
6882 
6883     lifetime = type->getObjCARCImplicitLifetime();
6884     type = Context.getLifetimeQualifiedType(type, lifetime);
6885     decl->setType(type);
6886   }
6887 
6888   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6889     // Thread-local variables cannot have lifetime.
6890     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6891         var->getTLSKind()) {
6892       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6893         << var->getType();
6894       return true;
6895     }
6896   }
6897 
6898   return false;
6899 }
6900 
6901 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6902   if (Decl->getType().hasAddressSpace())
6903     return;
6904   if (Decl->getType()->isDependentType())
6905     return;
6906   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6907     QualType Type = Var->getType();
6908     if (Type->isSamplerT() || Type->isVoidType())
6909       return;
6910     LangAS ImplAS = LangAS::opencl_private;
6911     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6912     // __opencl_c_program_scope_global_variables feature, the address space
6913     // for a variable at program scope or a static or extern variable inside
6914     // a function are inferred to be __global.
6915     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6916         Var->hasGlobalStorage())
6917       ImplAS = LangAS::opencl_global;
6918     // If the original type from a decayed type is an array type and that array
6919     // type has no address space yet, deduce it now.
6920     if (auto DT = dyn_cast<DecayedType>(Type)) {
6921       auto OrigTy = DT->getOriginalType();
6922       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6923         // Add the address space to the original array type and then propagate
6924         // that to the element type through `getAsArrayType`.
6925         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6926         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6927         // Re-generate the decayed type.
6928         Type = Context.getDecayedType(OrigTy);
6929       }
6930     }
6931     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6932     // Apply any qualifiers (including address space) from the array type to
6933     // the element type. This implements C99 6.7.3p8: "If the specification of
6934     // an array type includes any type qualifiers, the element type is so
6935     // qualified, not the array type."
6936     if (Type->isArrayType())
6937       Type = QualType(Context.getAsArrayType(Type), 0);
6938     Decl->setType(Type);
6939   }
6940 }
6941 
6942 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6943   // Ensure that an auto decl is deduced otherwise the checks below might cache
6944   // the wrong linkage.
6945   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6946 
6947   // 'weak' only applies to declarations with external linkage.
6948   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6949     if (!ND.isExternallyVisible()) {
6950       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6951       ND.dropAttr<WeakAttr>();
6952     }
6953   }
6954   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6955     if (ND.isExternallyVisible()) {
6956       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6957       ND.dropAttr<WeakRefAttr>();
6958       ND.dropAttr<AliasAttr>();
6959     }
6960   }
6961 
6962   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6963     if (VD->hasInit()) {
6964       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6965         assert(VD->isThisDeclarationADefinition() &&
6966                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6967         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6968         VD->dropAttr<AliasAttr>();
6969       }
6970     }
6971   }
6972 
6973   // 'selectany' only applies to externally visible variable declarations.
6974   // It does not apply to functions.
6975   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6976     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6977       S.Diag(Attr->getLocation(),
6978              diag::err_attribute_selectany_non_extern_data);
6979       ND.dropAttr<SelectAnyAttr>();
6980     }
6981   }
6982 
6983   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6984     auto *VD = dyn_cast<VarDecl>(&ND);
6985     bool IsAnonymousNS = false;
6986     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6987     if (VD) {
6988       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6989       while (NS && !IsAnonymousNS) {
6990         IsAnonymousNS = NS->isAnonymousNamespace();
6991         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6992       }
6993     }
6994     // dll attributes require external linkage. Static locals may have external
6995     // linkage but still cannot be explicitly imported or exported.
6996     // In Microsoft mode, a variable defined in anonymous namespace must have
6997     // external linkage in order to be exported.
6998     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6999     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7000         (!AnonNSInMicrosoftMode &&
7001          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7002       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7003         << &ND << Attr;
7004       ND.setInvalidDecl();
7005     }
7006   }
7007 
7008   // Check the attributes on the function type, if any.
7009   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7010     // Don't declare this variable in the second operand of the for-statement;
7011     // GCC miscompiles that by ending its lifetime before evaluating the
7012     // third operand. See gcc.gnu.org/PR86769.
7013     AttributedTypeLoc ATL;
7014     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7015          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7016          TL = ATL.getModifiedLoc()) {
7017       // The [[lifetimebound]] attribute can be applied to the implicit object
7018       // parameter of a non-static member function (other than a ctor or dtor)
7019       // by applying it to the function type.
7020       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7021         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7022         if (!MD || MD->isStatic()) {
7023           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7024               << !MD << A->getRange();
7025         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7026           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7027               << isa<CXXDestructorDecl>(MD) << A->getRange();
7028         }
7029       }
7030     }
7031   }
7032 }
7033 
7034 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7035                                            NamedDecl *NewDecl,
7036                                            bool IsSpecialization,
7037                                            bool IsDefinition) {
7038   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7039     return;
7040 
7041   bool IsTemplate = false;
7042   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7043     OldDecl = OldTD->getTemplatedDecl();
7044     IsTemplate = true;
7045     if (!IsSpecialization)
7046       IsDefinition = false;
7047   }
7048   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7049     NewDecl = NewTD->getTemplatedDecl();
7050     IsTemplate = true;
7051   }
7052 
7053   if (!OldDecl || !NewDecl)
7054     return;
7055 
7056   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7057   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7058   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7059   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7060 
7061   // dllimport and dllexport are inheritable attributes so we have to exclude
7062   // inherited attribute instances.
7063   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7064                     (NewExportAttr && !NewExportAttr->isInherited());
7065 
7066   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7067   // the only exception being explicit specializations.
7068   // Implicitly generated declarations are also excluded for now because there
7069   // is no other way to switch these to use dllimport or dllexport.
7070   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7071 
7072   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7073     // Allow with a warning for free functions and global variables.
7074     bool JustWarn = false;
7075     if (!OldDecl->isCXXClassMember()) {
7076       auto *VD = dyn_cast<VarDecl>(OldDecl);
7077       if (VD && !VD->getDescribedVarTemplate())
7078         JustWarn = true;
7079       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7080       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7081         JustWarn = true;
7082     }
7083 
7084     // We cannot change a declaration that's been used because IR has already
7085     // been emitted. Dllimported functions will still work though (modulo
7086     // address equality) as they can use the thunk.
7087     if (OldDecl->isUsed())
7088       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7089         JustWarn = false;
7090 
7091     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7092                                : diag::err_attribute_dll_redeclaration;
7093     S.Diag(NewDecl->getLocation(), DiagID)
7094         << NewDecl
7095         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7096     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7097     if (!JustWarn) {
7098       NewDecl->setInvalidDecl();
7099       return;
7100     }
7101   }
7102 
7103   // A redeclaration is not allowed to drop a dllimport attribute, the only
7104   // exceptions being inline function definitions (except for function
7105   // templates), local extern declarations, qualified friend declarations or
7106   // special MSVC extension: in the last case, the declaration is treated as if
7107   // it were marked dllexport.
7108   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7109   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7110   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7111     // Ignore static data because out-of-line definitions are diagnosed
7112     // separately.
7113     IsStaticDataMember = VD->isStaticDataMember();
7114     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7115                    VarDecl::DeclarationOnly;
7116   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7117     IsInline = FD->isInlined();
7118     IsQualifiedFriend = FD->getQualifier() &&
7119                         FD->getFriendObjectKind() == Decl::FOK_Declared;
7120   }
7121 
7122   if (OldImportAttr && !HasNewAttr &&
7123       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7124       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7125     if (IsMicrosoftABI && IsDefinition) {
7126       if (IsSpecialization) {
7127         S.Diag(
7128             NewDecl->getLocation(),
7129             diag::err_attribute_dllimport_function_specialization_definition);
7130         S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7131         NewDecl->dropAttr<DLLImportAttr>();
7132       } else {
7133         S.Diag(NewDecl->getLocation(),
7134                diag::warn_redeclaration_without_import_attribute)
7135             << NewDecl;
7136         S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7137         NewDecl->dropAttr<DLLImportAttr>();
7138         NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7139             S.Context, NewImportAttr->getRange()));
7140       }
7141     } else if (IsMicrosoftABI && IsSpecialization) {
7142       assert(!IsDefinition);
7143       // MSVC allows this. Keep the inherited attribute.
7144     } else {
7145       S.Diag(NewDecl->getLocation(),
7146              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7147           << NewDecl << OldImportAttr;
7148       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7149       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7150       OldDecl->dropAttr<DLLImportAttr>();
7151       NewDecl->dropAttr<DLLImportAttr>();
7152     }
7153   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7154     // In MinGW, seeing a function declared inline drops the dllimport
7155     // attribute.
7156     OldDecl->dropAttr<DLLImportAttr>();
7157     NewDecl->dropAttr<DLLImportAttr>();
7158     S.Diag(NewDecl->getLocation(),
7159            diag::warn_dllimport_dropped_from_inline_function)
7160         << NewDecl << OldImportAttr;
7161   }
7162 
7163   // A specialization of a class template member function is processed here
7164   // since it's a redeclaration. If the parent class is dllexport, the
7165   // specialization inherits that attribute. This doesn't happen automatically
7166   // since the parent class isn't instantiated until later.
7167   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7168     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7169         !NewImportAttr && !NewExportAttr) {
7170       if (const DLLExportAttr *ParentExportAttr =
7171               MD->getParent()->getAttr<DLLExportAttr>()) {
7172         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7173         NewAttr->setInherited(true);
7174         NewDecl->addAttr(NewAttr);
7175       }
7176     }
7177   }
7178 }
7179 
7180 /// Given that we are within the definition of the given function,
7181 /// will that definition behave like C99's 'inline', where the
7182 /// definition is discarded except for optimization purposes?
7183 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7184   // Try to avoid calling GetGVALinkageForFunction.
7185 
7186   // All cases of this require the 'inline' keyword.
7187   if (!FD->isInlined()) return false;
7188 
7189   // This is only possible in C++ with the gnu_inline attribute.
7190   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7191     return false;
7192 
7193   // Okay, go ahead and call the relatively-more-expensive function.
7194   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7195 }
7196 
7197 /// Determine whether a variable is extern "C" prior to attaching
7198 /// an initializer. We can't just call isExternC() here, because that
7199 /// will also compute and cache whether the declaration is externally
7200 /// visible, which might change when we attach the initializer.
7201 ///
7202 /// This can only be used if the declaration is known to not be a
7203 /// redeclaration of an internal linkage declaration.
7204 ///
7205 /// For instance:
7206 ///
7207 ///   auto x = []{};
7208 ///
7209 /// Attaching the initializer here makes this declaration not externally
7210 /// visible, because its type has internal linkage.
7211 ///
7212 /// FIXME: This is a hack.
7213 template<typename T>
7214 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7215   if (S.getLangOpts().CPlusPlus) {
7216     // In C++, the overloadable attribute negates the effects of extern "C".
7217     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7218       return false;
7219 
7220     // So do CUDA's host/device attributes.
7221     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7222                                  D->template hasAttr<CUDAHostAttr>()))
7223       return false;
7224   }
7225   return D->isExternC();
7226 }
7227 
7228 static bool shouldConsiderLinkage(const VarDecl *VD) {
7229   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7230   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7231       isa<OMPDeclareMapperDecl>(DC))
7232     return VD->hasExternalStorage();
7233   if (DC->isFileContext())
7234     return true;
7235   if (DC->isRecord())
7236     return false;
7237   if (DC->getDeclKind() == Decl::HLSLBuffer)
7238     return false;
7239 
7240   if (isa<RequiresExprBodyDecl>(DC))
7241     return false;
7242   llvm_unreachable("Unexpected context");
7243 }
7244 
7245 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7246   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7247   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7248       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7249     return true;
7250   if (DC->isRecord())
7251     return false;
7252   llvm_unreachable("Unexpected context");
7253 }
7254 
7255 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7256                           ParsedAttr::Kind Kind) {
7257   // Check decl attributes on the DeclSpec.
7258   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7259     return true;
7260 
7261   // Walk the declarator structure, checking decl attributes that were in a type
7262   // position to the decl itself.
7263   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7264     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7265       return true;
7266   }
7267 
7268   // Finally, check attributes on the decl itself.
7269   return PD.getAttributes().hasAttribute(Kind) ||
7270          PD.getDeclarationAttributes().hasAttribute(Kind);
7271 }
7272 
7273 /// Adjust the \c DeclContext for a function or variable that might be a
7274 /// function-local external declaration.
7275 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7276   if (!DC->isFunctionOrMethod())
7277     return false;
7278 
7279   // If this is a local extern function or variable declared within a function
7280   // template, don't add it into the enclosing namespace scope until it is
7281   // instantiated; it might have a dependent type right now.
7282   if (DC->isDependentContext())
7283     return true;
7284 
7285   // C++11 [basic.link]p7:
7286   //   When a block scope declaration of an entity with linkage is not found to
7287   //   refer to some other declaration, then that entity is a member of the
7288   //   innermost enclosing namespace.
7289   //
7290   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7291   // semantically-enclosing namespace, not a lexically-enclosing one.
7292   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7293     DC = DC->getParent();
7294   return true;
7295 }
7296 
7297 /// Returns true if given declaration has external C language linkage.
7298 static bool isDeclExternC(const Decl *D) {
7299   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7300     return FD->isExternC();
7301   if (const auto *VD = dyn_cast<VarDecl>(D))
7302     return VD->isExternC();
7303 
7304   llvm_unreachable("Unknown type of decl!");
7305 }
7306 
7307 /// Returns true if there hasn't been any invalid type diagnosed.
7308 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7309   DeclContext *DC = NewVD->getDeclContext();
7310   QualType R = NewVD->getType();
7311 
7312   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7313   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7314   // argument.
7315   if (R->isImageType() || R->isPipeType()) {
7316     Se.Diag(NewVD->getLocation(),
7317             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7318         << R;
7319     NewVD->setInvalidDecl();
7320     return false;
7321   }
7322 
7323   // OpenCL v1.2 s6.9.r:
7324   // The event type cannot be used to declare a program scope variable.
7325   // OpenCL v2.0 s6.9.q:
7326   // The clk_event_t and reserve_id_t types cannot be declared in program
7327   // scope.
7328   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7329     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7330       Se.Diag(NewVD->getLocation(),
7331               diag::err_invalid_type_for_program_scope_var)
7332           << R;
7333       NewVD->setInvalidDecl();
7334       return false;
7335     }
7336   }
7337 
7338   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7339   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7340                                                Se.getLangOpts())) {
7341     QualType NR = R.getCanonicalType();
7342     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7343            NR->isReferenceType()) {
7344       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7345           NR->isFunctionReferenceType()) {
7346         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7347             << NR->isReferenceType();
7348         NewVD->setInvalidDecl();
7349         return false;
7350       }
7351       NR = NR->getPointeeType();
7352     }
7353   }
7354 
7355   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7356                                                Se.getLangOpts())) {
7357     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7358     // half array type (unless the cl_khr_fp16 extension is enabled).
7359     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7360       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7361       NewVD->setInvalidDecl();
7362       return false;
7363     }
7364   }
7365 
7366   // OpenCL v1.2 s6.9.r:
7367   // The event type cannot be used with the __local, __constant and __global
7368   // address space qualifiers.
7369   if (R->isEventT()) {
7370     if (R.getAddressSpace() != LangAS::opencl_private) {
7371       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7372       NewVD->setInvalidDecl();
7373       return false;
7374     }
7375   }
7376 
7377   if (R->isSamplerT()) {
7378     // OpenCL v1.2 s6.9.b p4:
7379     // The sampler type cannot be used with the __local and __global address
7380     // space qualifiers.
7381     if (R.getAddressSpace() == LangAS::opencl_local ||
7382         R.getAddressSpace() == LangAS::opencl_global) {
7383       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7384       NewVD->setInvalidDecl();
7385     }
7386 
7387     // OpenCL v1.2 s6.12.14.1:
7388     // A global sampler must be declared with either the constant address
7389     // space qualifier or with the const qualifier.
7390     if (DC->isTranslationUnit() &&
7391         !(R.getAddressSpace() == LangAS::opencl_constant ||
7392           R.isConstQualified())) {
7393       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7394       NewVD->setInvalidDecl();
7395     }
7396     if (NewVD->isInvalidDecl())
7397       return false;
7398   }
7399 
7400   return true;
7401 }
7402 
7403 template <typename AttrTy>
7404 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7405   const TypedefNameDecl *TND = TT->getDecl();
7406   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7407     AttrTy *Clone = Attribute->clone(S.Context);
7408     Clone->setInherited(true);
7409     D->addAttr(Clone);
7410   }
7411 }
7412 
7413 // This function emits warning and a corresponding note based on the
7414 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7415 // declarations of an annotated type must be const qualified.
7416 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7417   QualType VarType = VD->getType().getCanonicalType();
7418 
7419   // Ignore local declarations (for now) and those with const qualification.
7420   // TODO: Local variables should not be allowed if their type declaration has
7421   // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7422   if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7423     return;
7424 
7425   if (VarType->isArrayType()) {
7426     // Retrieve element type for array declarations.
7427     VarType = S.getASTContext().getBaseElementType(VarType);
7428   }
7429 
7430   const RecordDecl *RD = VarType->getAsRecordDecl();
7431 
7432   // Check if the record declaration is present and if it has any attributes.
7433   if (RD == nullptr)
7434     return;
7435 
7436   if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7437     S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7438     S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7439     return;
7440   }
7441 }
7442 
7443 NamedDecl *Sema::ActOnVariableDeclarator(
7444     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7445     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7446     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7447   QualType R = TInfo->getType();
7448   DeclarationName Name = GetNameForDeclarator(D).getName();
7449 
7450   IdentifierInfo *II = Name.getAsIdentifierInfo();
7451 
7452   if (D.isDecompositionDeclarator()) {
7453     // Take the name of the first declarator as our name for diagnostic
7454     // purposes.
7455     auto &Decomp = D.getDecompositionDeclarator();
7456     if (!Decomp.bindings().empty()) {
7457       II = Decomp.bindings()[0].Name;
7458       Name = II;
7459     }
7460   } else if (!II) {
7461     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7462     return nullptr;
7463   }
7464 
7465 
7466   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7467   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7468 
7469   // dllimport globals without explicit storage class are treated as extern. We
7470   // have to change the storage class this early to get the right DeclContext.
7471   if (SC == SC_None && !DC->isRecord() &&
7472       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7473       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7474     SC = SC_Extern;
7475 
7476   DeclContext *OriginalDC = DC;
7477   bool IsLocalExternDecl = SC == SC_Extern &&
7478                            adjustContextForLocalExternDecl(DC);
7479 
7480   if (SCSpec == DeclSpec::SCS_mutable) {
7481     // mutable can only appear on non-static class members, so it's always
7482     // an error here
7483     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7484     D.setInvalidType();
7485     SC = SC_None;
7486   }
7487 
7488   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7489       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7490                               D.getDeclSpec().getStorageClassSpecLoc())) {
7491     // In C++11, the 'register' storage class specifier is deprecated.
7492     // Suppress the warning in system macros, it's used in macros in some
7493     // popular C system headers, such as in glibc's htonl() macro.
7494     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7495          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7496                                    : diag::warn_deprecated_register)
7497       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7498   }
7499 
7500   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7501 
7502   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7503     // C99 6.9p2: The storage-class specifiers auto and register shall not
7504     // appear in the declaration specifiers in an external declaration.
7505     // Global Register+Asm is a GNU extension we support.
7506     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7507       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7508       D.setInvalidType();
7509     }
7510   }
7511 
7512   // If this variable has a VLA type and an initializer, try to
7513   // fold to a constant-sized type. This is otherwise invalid.
7514   if (D.hasInitializer() && R->isVariableArrayType())
7515     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7516                                     /*DiagID=*/0);
7517 
7518   bool IsMemberSpecialization = false;
7519   bool IsVariableTemplateSpecialization = false;
7520   bool IsPartialSpecialization = false;
7521   bool IsVariableTemplate = false;
7522   VarDecl *NewVD = nullptr;
7523   VarTemplateDecl *NewTemplate = nullptr;
7524   TemplateParameterList *TemplateParams = nullptr;
7525   if (!getLangOpts().CPlusPlus) {
7526     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7527                             II, R, TInfo, SC);
7528 
7529     if (R->getContainedDeducedType())
7530       ParsingInitForAutoVars.insert(NewVD);
7531 
7532     if (D.isInvalidType())
7533       NewVD->setInvalidDecl();
7534 
7535     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7536         NewVD->hasLocalStorage())
7537       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7538                             NTCUC_AutoVar, NTCUK_Destruct);
7539   } else {
7540     bool Invalid = false;
7541 
7542     if (DC->isRecord() && !CurContext->isRecord()) {
7543       // This is an out-of-line definition of a static data member.
7544       switch (SC) {
7545       case SC_None:
7546         break;
7547       case SC_Static:
7548         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7549              diag::err_static_out_of_line)
7550           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7551         break;
7552       case SC_Auto:
7553       case SC_Register:
7554       case SC_Extern:
7555         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7556         // to names of variables declared in a block or to function parameters.
7557         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7558         // of class members
7559 
7560         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7561              diag::err_storage_class_for_static_member)
7562           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7563         break;
7564       case SC_PrivateExtern:
7565         llvm_unreachable("C storage class in c++!");
7566       }
7567     }
7568 
7569     if (SC == SC_Static && CurContext->isRecord()) {
7570       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7571         // Walk up the enclosing DeclContexts to check for any that are
7572         // incompatible with static data members.
7573         const DeclContext *FunctionOrMethod = nullptr;
7574         const CXXRecordDecl *AnonStruct = nullptr;
7575         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7576           if (Ctxt->isFunctionOrMethod()) {
7577             FunctionOrMethod = Ctxt;
7578             break;
7579           }
7580           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7581           if (ParentDecl && !ParentDecl->getDeclName()) {
7582             AnonStruct = ParentDecl;
7583             break;
7584           }
7585         }
7586         if (FunctionOrMethod) {
7587           // C++ [class.static.data]p5: A local class shall not have static data
7588           // members.
7589           Diag(D.getIdentifierLoc(),
7590                diag::err_static_data_member_not_allowed_in_local_class)
7591             << Name << RD->getDeclName() << RD->getTagKind();
7592         } else if (AnonStruct) {
7593           // C++ [class.static.data]p4: Unnamed classes and classes contained
7594           // directly or indirectly within unnamed classes shall not contain
7595           // static data members.
7596           Diag(D.getIdentifierLoc(),
7597                diag::err_static_data_member_not_allowed_in_anon_struct)
7598             << Name << AnonStruct->getTagKind();
7599           Invalid = true;
7600         } else if (RD->isUnion()) {
7601           // C++98 [class.union]p1: If a union contains a static data member,
7602           // the program is ill-formed. C++11 drops this restriction.
7603           Diag(D.getIdentifierLoc(),
7604                getLangOpts().CPlusPlus11
7605                  ? diag::warn_cxx98_compat_static_data_member_in_union
7606                  : diag::ext_static_data_member_in_union) << Name;
7607         }
7608       }
7609     }
7610 
7611     // Match up the template parameter lists with the scope specifier, then
7612     // determine whether we have a template or a template specialization.
7613     bool InvalidScope = false;
7614     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7615         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7616         D.getCXXScopeSpec(),
7617         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7618             ? D.getName().TemplateId
7619             : nullptr,
7620         TemplateParamLists,
7621         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7622     Invalid |= InvalidScope;
7623 
7624     if (TemplateParams) {
7625       if (!TemplateParams->size() &&
7626           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7627         // There is an extraneous 'template<>' for this variable. Complain
7628         // about it, but allow the declaration of the variable.
7629         Diag(TemplateParams->getTemplateLoc(),
7630              diag::err_template_variable_noparams)
7631           << II
7632           << SourceRange(TemplateParams->getTemplateLoc(),
7633                          TemplateParams->getRAngleLoc());
7634         TemplateParams = nullptr;
7635       } else {
7636         // Check that we can declare a template here.
7637         if (CheckTemplateDeclScope(S, TemplateParams))
7638           return nullptr;
7639 
7640         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7641           // This is an explicit specialization or a partial specialization.
7642           IsVariableTemplateSpecialization = true;
7643           IsPartialSpecialization = TemplateParams->size() > 0;
7644         } else { // if (TemplateParams->size() > 0)
7645           // This is a template declaration.
7646           IsVariableTemplate = true;
7647 
7648           // Only C++1y supports variable templates (N3651).
7649           Diag(D.getIdentifierLoc(),
7650                getLangOpts().CPlusPlus14
7651                    ? diag::warn_cxx11_compat_variable_template
7652                    : diag::ext_variable_template);
7653         }
7654       }
7655     } else {
7656       // Check that we can declare a member specialization here.
7657       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7658           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7659         return nullptr;
7660       assert((Invalid ||
7661               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7662              "should have a 'template<>' for this decl");
7663     }
7664 
7665     if (IsVariableTemplateSpecialization) {
7666       SourceLocation TemplateKWLoc =
7667           TemplateParamLists.size() > 0
7668               ? TemplateParamLists[0]->getTemplateLoc()
7669               : SourceLocation();
7670       DeclResult Res = ActOnVarTemplateSpecialization(
7671           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7672           IsPartialSpecialization);
7673       if (Res.isInvalid())
7674         return nullptr;
7675       NewVD = cast<VarDecl>(Res.get());
7676       AddToScope = false;
7677     } else if (D.isDecompositionDeclarator()) {
7678       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7679                                         D.getIdentifierLoc(), R, TInfo, SC,
7680                                         Bindings);
7681     } else
7682       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7683                               D.getIdentifierLoc(), II, R, TInfo, SC);
7684 
7685     // If this is supposed to be a variable template, create it as such.
7686     if (IsVariableTemplate) {
7687       NewTemplate =
7688           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7689                                   TemplateParams, NewVD);
7690       NewVD->setDescribedVarTemplate(NewTemplate);
7691     }
7692 
7693     // If this decl has an auto type in need of deduction, make a note of the
7694     // Decl so we can diagnose uses of it in its own initializer.
7695     if (R->getContainedDeducedType())
7696       ParsingInitForAutoVars.insert(NewVD);
7697 
7698     if (D.isInvalidType() || Invalid) {
7699       NewVD->setInvalidDecl();
7700       if (NewTemplate)
7701         NewTemplate->setInvalidDecl();
7702     }
7703 
7704     SetNestedNameSpecifier(*this, NewVD, D);
7705 
7706     // If we have any template parameter lists that don't directly belong to
7707     // the variable (matching the scope specifier), store them.
7708     // An explicit variable template specialization does not own any template
7709     // parameter lists.
7710     bool IsExplicitSpecialization =
7711         IsVariableTemplateSpecialization && !IsPartialSpecialization;
7712     unsigned VDTemplateParamLists =
7713         (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7714     if (TemplateParamLists.size() > VDTemplateParamLists)
7715       NewVD->setTemplateParameterListsInfo(
7716           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7717   }
7718 
7719   if (D.getDeclSpec().isInlineSpecified()) {
7720     if (!getLangOpts().CPlusPlus) {
7721       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7722           << 0;
7723     } else if (CurContext->isFunctionOrMethod()) {
7724       // 'inline' is not allowed on block scope variable declaration.
7725       Diag(D.getDeclSpec().getInlineSpecLoc(),
7726            diag::err_inline_declaration_block_scope) << Name
7727         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7728     } else {
7729       Diag(D.getDeclSpec().getInlineSpecLoc(),
7730            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7731                                      : diag::ext_inline_variable);
7732       NewVD->setInlineSpecified();
7733     }
7734   }
7735 
7736   // Set the lexical context. If the declarator has a C++ scope specifier, the
7737   // lexical context will be different from the semantic context.
7738   NewVD->setLexicalDeclContext(CurContext);
7739   if (NewTemplate)
7740     NewTemplate->setLexicalDeclContext(CurContext);
7741 
7742   if (IsLocalExternDecl) {
7743     if (D.isDecompositionDeclarator())
7744       for (auto *B : Bindings)
7745         B->setLocalExternDecl();
7746     else
7747       NewVD->setLocalExternDecl();
7748   }
7749 
7750   bool EmitTLSUnsupportedError = false;
7751   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7752     // C++11 [dcl.stc]p4:
7753     //   When thread_local is applied to a variable of block scope the
7754     //   storage-class-specifier static is implied if it does not appear
7755     //   explicitly.
7756     // Core issue: 'static' is not implied if the variable is declared
7757     //   'extern'.
7758     if (NewVD->hasLocalStorage() &&
7759         (SCSpec != DeclSpec::SCS_unspecified ||
7760          TSCS != DeclSpec::TSCS_thread_local ||
7761          !DC->isFunctionOrMethod()))
7762       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7763            diag::err_thread_non_global)
7764         << DeclSpec::getSpecifierName(TSCS);
7765     else if (!Context.getTargetInfo().isTLSSupported()) {
7766       if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7767           getLangOpts().SYCLIsDevice) {
7768         // Postpone error emission until we've collected attributes required to
7769         // figure out whether it's a host or device variable and whether the
7770         // error should be ignored.
7771         EmitTLSUnsupportedError = true;
7772         // We still need to mark the variable as TLS so it shows up in AST with
7773         // proper storage class for other tools to use even if we're not going
7774         // to emit any code for it.
7775         NewVD->setTSCSpec(TSCS);
7776       } else
7777         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7778              diag::err_thread_unsupported);
7779     } else
7780       NewVD->setTSCSpec(TSCS);
7781   }
7782 
7783   switch (D.getDeclSpec().getConstexprSpecifier()) {
7784   case ConstexprSpecKind::Unspecified:
7785     break;
7786 
7787   case ConstexprSpecKind::Consteval:
7788     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7789          diag::err_constexpr_wrong_decl_kind)
7790         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7791     [[fallthrough]];
7792 
7793   case ConstexprSpecKind::Constexpr:
7794     NewVD->setConstexpr(true);
7795     // C++1z [dcl.spec.constexpr]p1:
7796     //   A static data member declared with the constexpr specifier is
7797     //   implicitly an inline variable.
7798     if (NewVD->isStaticDataMember() &&
7799         (getLangOpts().CPlusPlus17 ||
7800          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7801       NewVD->setImplicitlyInline();
7802     break;
7803 
7804   case ConstexprSpecKind::Constinit:
7805     if (!NewVD->hasGlobalStorage())
7806       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7807            diag::err_constinit_local_variable);
7808     else
7809       NewVD->addAttr(
7810           ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7811                                 ConstInitAttr::Keyword_constinit));
7812     break;
7813   }
7814 
7815   // C99 6.7.4p3
7816   //   An inline definition of a function with external linkage shall
7817   //   not contain a definition of a modifiable object with static or
7818   //   thread storage duration...
7819   // We only apply this when the function is required to be defined
7820   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7821   // that a local variable with thread storage duration still has to
7822   // be marked 'static'.  Also note that it's possible to get these
7823   // semantics in C++ using __attribute__((gnu_inline)).
7824   if (SC == SC_Static && S->getFnParent() != nullptr &&
7825       !NewVD->getType().isConstQualified()) {
7826     FunctionDecl *CurFD = getCurFunctionDecl();
7827     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7828       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7829            diag::warn_static_local_in_extern_inline);
7830       MaybeSuggestAddingStaticToDecl(CurFD);
7831     }
7832   }
7833 
7834   if (D.getDeclSpec().isModulePrivateSpecified()) {
7835     if (IsVariableTemplateSpecialization)
7836       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7837           << (IsPartialSpecialization ? 1 : 0)
7838           << FixItHint::CreateRemoval(
7839                  D.getDeclSpec().getModulePrivateSpecLoc());
7840     else if (IsMemberSpecialization)
7841       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7842         << 2
7843         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7844     else if (NewVD->hasLocalStorage())
7845       Diag(NewVD->getLocation(), diag::err_module_private_local)
7846           << 0 << NewVD
7847           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7848           << FixItHint::CreateRemoval(
7849                  D.getDeclSpec().getModulePrivateSpecLoc());
7850     else {
7851       NewVD->setModulePrivate();
7852       if (NewTemplate)
7853         NewTemplate->setModulePrivate();
7854       for (auto *B : Bindings)
7855         B->setModulePrivate();
7856     }
7857   }
7858 
7859   if (getLangOpts().OpenCL) {
7860     deduceOpenCLAddressSpace(NewVD);
7861 
7862     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7863     if (TSC != TSCS_unspecified) {
7864       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7865            diag::err_opencl_unknown_type_specifier)
7866           << getLangOpts().getOpenCLVersionString()
7867           << DeclSpec::getSpecifierName(TSC) << 1;
7868       NewVD->setInvalidDecl();
7869     }
7870   }
7871 
7872   // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7873   // address space if the table has local storage (semantic checks elsewhere
7874   // will produce an error anyway).
7875   if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7876     if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7877         !NewVD->hasLocalStorage()) {
7878       QualType Type = Context.getAddrSpaceQualType(
7879           NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7880       NewVD->setType(Type);
7881     }
7882   }
7883 
7884   // Handle attributes prior to checking for duplicates in MergeVarDecl
7885   ProcessDeclAttributes(S, NewVD, D);
7886 
7887   // FIXME: This is probably the wrong location to be doing this and we should
7888   // probably be doing this for more attributes (especially for function
7889   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7890   // the code to copy attributes would be generated by TableGen.
7891   if (R->isFunctionPointerType())
7892     if (const auto *TT = R->getAs<TypedefType>())
7893       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7894 
7895   if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7896       getLangOpts().SYCLIsDevice) {
7897     if (EmitTLSUnsupportedError &&
7898         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7899          (getLangOpts().OpenMPIsTargetDevice &&
7900           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7901       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7902            diag::err_thread_unsupported);
7903 
7904     if (EmitTLSUnsupportedError &&
7905         (LangOpts.SYCLIsDevice ||
7906          (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7907       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7908     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7909     // storage [duration]."
7910     if (SC == SC_None && S->getFnParent() != nullptr &&
7911         (NewVD->hasAttr<CUDASharedAttr>() ||
7912          NewVD->hasAttr<CUDAConstantAttr>())) {
7913       NewVD->setStorageClass(SC_Static);
7914     }
7915   }
7916 
7917   // Ensure that dllimport globals without explicit storage class are treated as
7918   // extern. The storage class is set above using parsed attributes. Now we can
7919   // check the VarDecl itself.
7920   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7921          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7922          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7923 
7924   // In auto-retain/release, infer strong retension for variables of
7925   // retainable type.
7926   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7927     NewVD->setInvalidDecl();
7928 
7929   // Handle GNU asm-label extension (encoded as an attribute).
7930   if (Expr *E = (Expr*)D.getAsmLabel()) {
7931     // The parser guarantees this is a string.
7932     StringLiteral *SE = cast<StringLiteral>(E);
7933     StringRef Label = SE->getString();
7934     if (S->getFnParent() != nullptr) {
7935       switch (SC) {
7936       case SC_None:
7937       case SC_Auto:
7938         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7939         break;
7940       case SC_Register:
7941         // Local Named register
7942         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7943             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7944           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7945         break;
7946       case SC_Static:
7947       case SC_Extern:
7948       case SC_PrivateExtern:
7949         break;
7950       }
7951     } else if (SC == SC_Register) {
7952       // Global Named register
7953       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7954         const auto &TI = Context.getTargetInfo();
7955         bool HasSizeMismatch;
7956 
7957         if (!TI.isValidGCCRegisterName(Label))
7958           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7959         else if (!TI.validateGlobalRegisterVariable(Label,
7960                                                     Context.getTypeSize(R),
7961                                                     HasSizeMismatch))
7962           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7963         else if (HasSizeMismatch)
7964           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7965       }
7966 
7967       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7968         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7969         NewVD->setInvalidDecl(true);
7970       }
7971     }
7972 
7973     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7974                                         /*IsLiteralLabel=*/true,
7975                                         SE->getStrTokenLoc(0)));
7976   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7977     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7978       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7979     if (I != ExtnameUndeclaredIdentifiers.end()) {
7980       if (isDeclExternC(NewVD)) {
7981         NewVD->addAttr(I->second);
7982         ExtnameUndeclaredIdentifiers.erase(I);
7983       } else
7984         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7985             << /*Variable*/1 << NewVD;
7986     }
7987   }
7988 
7989   // Find the shadowed declaration before filtering for scope.
7990   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7991                                 ? getShadowedDeclaration(NewVD, Previous)
7992                                 : nullptr;
7993 
7994   // Don't consider existing declarations that are in a different
7995   // scope and are out-of-semantic-context declarations (if the new
7996   // declaration has linkage).
7997   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7998                        D.getCXXScopeSpec().isNotEmpty() ||
7999                        IsMemberSpecialization ||
8000                        IsVariableTemplateSpecialization);
8001 
8002   // Check whether the previous declaration is in the same block scope. This
8003   // affects whether we merge types with it, per C++11 [dcl.array]p3.
8004   if (getLangOpts().CPlusPlus &&
8005       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8006     NewVD->setPreviousDeclInSameBlockScope(
8007         Previous.isSingleResult() && !Previous.isShadowed() &&
8008         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8009 
8010   if (!getLangOpts().CPlusPlus) {
8011     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8012   } else {
8013     // If this is an explicit specialization of a static data member, check it.
8014     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8015         CheckMemberSpecialization(NewVD, Previous))
8016       NewVD->setInvalidDecl();
8017 
8018     // Merge the decl with the existing one if appropriate.
8019     if (!Previous.empty()) {
8020       if (Previous.isSingleResult() &&
8021           isa<FieldDecl>(Previous.getFoundDecl()) &&
8022           D.getCXXScopeSpec().isSet()) {
8023         // The user tried to define a non-static data member
8024         // out-of-line (C++ [dcl.meaning]p1).
8025         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8026           << D.getCXXScopeSpec().getRange();
8027         Previous.clear();
8028         NewVD->setInvalidDecl();
8029       }
8030     } else if (D.getCXXScopeSpec().isSet()) {
8031       // No previous declaration in the qualifying scope.
8032       Diag(D.getIdentifierLoc(), diag::err_no_member)
8033         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8034         << D.getCXXScopeSpec().getRange();
8035       NewVD->setInvalidDecl();
8036     }
8037 
8038     if (!IsVariableTemplateSpecialization)
8039       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8040 
8041     // CheckVariableDeclaration will set NewVD as invalid if something is in
8042     // error like WebAssembly tables being declared as arrays with a non-zero
8043     // size, but then parsing continues and emits further errors on that line.
8044     // To avoid that we check here if it happened and return nullptr.
8045     if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8046       return nullptr;
8047 
8048     if (NewTemplate) {
8049       VarTemplateDecl *PrevVarTemplate =
8050           NewVD->getPreviousDecl()
8051               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8052               : nullptr;
8053 
8054       // Check the template parameter list of this declaration, possibly
8055       // merging in the template parameter list from the previous variable
8056       // template declaration.
8057       if (CheckTemplateParameterList(
8058               TemplateParams,
8059               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8060                               : nullptr,
8061               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8062                DC->isDependentContext())
8063                   ? TPC_ClassTemplateMember
8064                   : TPC_VarTemplate))
8065         NewVD->setInvalidDecl();
8066 
8067       // If we are providing an explicit specialization of a static variable
8068       // template, make a note of that.
8069       if (PrevVarTemplate &&
8070           PrevVarTemplate->getInstantiatedFromMemberTemplate())
8071         PrevVarTemplate->setMemberSpecialization();
8072     }
8073   }
8074 
8075   // Diagnose shadowed variables iff this isn't a redeclaration.
8076   if (ShadowedDecl && !D.isRedeclaration())
8077     CheckShadow(NewVD, ShadowedDecl, Previous);
8078 
8079   ProcessPragmaWeak(S, NewVD);
8080 
8081   // If this is the first declaration of an extern C variable, update
8082   // the map of such variables.
8083   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8084       isIncompleteDeclExternC(*this, NewVD))
8085     RegisterLocallyScopedExternCDecl(NewVD, S);
8086 
8087   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8088     MangleNumberingContext *MCtx;
8089     Decl *ManglingContextDecl;
8090     std::tie(MCtx, ManglingContextDecl) =
8091         getCurrentMangleNumberContext(NewVD->getDeclContext());
8092     if (MCtx) {
8093       Context.setManglingNumber(
8094           NewVD, MCtx->getManglingNumber(
8095                      NewVD, getMSManglingNumber(getLangOpts(), S)));
8096       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8097     }
8098   }
8099 
8100   // Special handling of variable named 'main'.
8101   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8102       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8103       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8104 
8105     // C++ [basic.start.main]p3
8106     // A program that declares a variable main at global scope is ill-formed.
8107     if (getLangOpts().CPlusPlus)
8108       Diag(D.getBeginLoc(), diag::err_main_global_variable);
8109 
8110     // In C, and external-linkage variable named main results in undefined
8111     // behavior.
8112     else if (NewVD->hasExternalFormalLinkage())
8113       Diag(D.getBeginLoc(), diag::warn_main_redefined);
8114   }
8115 
8116   if (D.isRedeclaration() && !Previous.empty()) {
8117     NamedDecl *Prev = Previous.getRepresentativeDecl();
8118     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8119                                    D.isFunctionDefinition());
8120   }
8121 
8122   if (NewTemplate) {
8123     if (NewVD->isInvalidDecl())
8124       NewTemplate->setInvalidDecl();
8125     ActOnDocumentableDecl(NewTemplate);
8126     return NewTemplate;
8127   }
8128 
8129   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8130     CompleteMemberSpecialization(NewVD, Previous);
8131 
8132   emitReadOnlyPlacementAttrWarning(*this, NewVD);
8133 
8134   return NewVD;
8135 }
8136 
8137 /// Enum describing the %select options in diag::warn_decl_shadow.
8138 enum ShadowedDeclKind {
8139   SDK_Local,
8140   SDK_Global,
8141   SDK_StaticMember,
8142   SDK_Field,
8143   SDK_Typedef,
8144   SDK_Using,
8145   SDK_StructuredBinding
8146 };
8147 
8148 /// Determine what kind of declaration we're shadowing.
8149 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8150                                                 const DeclContext *OldDC) {
8151   if (isa<TypeAliasDecl>(ShadowedDecl))
8152     return SDK_Using;
8153   else if (isa<TypedefDecl>(ShadowedDecl))
8154     return SDK_Typedef;
8155   else if (isa<BindingDecl>(ShadowedDecl))
8156     return SDK_StructuredBinding;
8157   else if (isa<RecordDecl>(OldDC))
8158     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8159 
8160   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8161 }
8162 
8163 /// Return the location of the capture if the given lambda captures the given
8164 /// variable \p VD, or an invalid source location otherwise.
8165 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8166                                          const VarDecl *VD) {
8167   for (const Capture &Capture : LSI->Captures) {
8168     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8169       return Capture.getLocation();
8170   }
8171   return SourceLocation();
8172 }
8173 
8174 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8175                                      const LookupResult &R) {
8176   // Only diagnose if we're shadowing an unambiguous field or variable.
8177   if (R.getResultKind() != LookupResult::Found)
8178     return false;
8179 
8180   // Return false if warning is ignored.
8181   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8182 }
8183 
8184 /// Return the declaration shadowed by the given variable \p D, or null
8185 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8186 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8187                                         const LookupResult &R) {
8188   if (!shouldWarnIfShadowedDecl(Diags, R))
8189     return nullptr;
8190 
8191   // Don't diagnose declarations at file scope.
8192   if (D->hasGlobalStorage() && !D->isStaticLocal())
8193     return nullptr;
8194 
8195   NamedDecl *ShadowedDecl = R.getFoundDecl();
8196   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8197                                                             : nullptr;
8198 }
8199 
8200 /// Return the declaration shadowed by the given typedef \p D, or null
8201 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8202 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8203                                         const LookupResult &R) {
8204   // Don't warn if typedef declaration is part of a class
8205   if (D->getDeclContext()->isRecord())
8206     return nullptr;
8207 
8208   if (!shouldWarnIfShadowedDecl(Diags, R))
8209     return nullptr;
8210 
8211   NamedDecl *ShadowedDecl = R.getFoundDecl();
8212   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8213 }
8214 
8215 /// Return the declaration shadowed by the given variable \p D, or null
8216 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8217 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8218                                         const LookupResult &R) {
8219   if (!shouldWarnIfShadowedDecl(Diags, R))
8220     return nullptr;
8221 
8222   NamedDecl *ShadowedDecl = R.getFoundDecl();
8223   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8224                                                             : nullptr;
8225 }
8226 
8227 /// Diagnose variable or built-in function shadowing.  Implements
8228 /// -Wshadow.
8229 ///
8230 /// This method is called whenever a VarDecl is added to a "useful"
8231 /// scope.
8232 ///
8233 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8234 /// \param R the lookup of the name
8235 ///
8236 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8237                        const LookupResult &R) {
8238   DeclContext *NewDC = D->getDeclContext();
8239 
8240   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8241     // Fields are not shadowed by variables in C++ static methods.
8242     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8243       if (MD->isStatic())
8244         return;
8245 
8246     // Fields shadowed by constructor parameters are a special case. Usually
8247     // the constructor initializes the field with the parameter.
8248     if (isa<CXXConstructorDecl>(NewDC))
8249       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8250         // Remember that this was shadowed so we can either warn about its
8251         // modification or its existence depending on warning settings.
8252         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8253         return;
8254       }
8255   }
8256 
8257   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8258     if (shadowedVar->isExternC()) {
8259       // For shadowing external vars, make sure that we point to the global
8260       // declaration, not a locally scoped extern declaration.
8261       for (auto *I : shadowedVar->redecls())
8262         if (I->isFileVarDecl()) {
8263           ShadowedDecl = I;
8264           break;
8265         }
8266     }
8267 
8268   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8269 
8270   unsigned WarningDiag = diag::warn_decl_shadow;
8271   SourceLocation CaptureLoc;
8272   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8273       isa<CXXMethodDecl>(NewDC)) {
8274     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8275       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8276         if (RD->getLambdaCaptureDefault() == LCD_None) {
8277           // Try to avoid warnings for lambdas with an explicit capture list.
8278           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8279           // Warn only when the lambda captures the shadowed decl explicitly.
8280           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8281           if (CaptureLoc.isInvalid())
8282             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8283         } else {
8284           // Remember that this was shadowed so we can avoid the warning if the
8285           // shadowed decl isn't captured and the warning settings allow it.
8286           cast<LambdaScopeInfo>(getCurFunction())
8287               ->ShadowingDecls.push_back(
8288                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8289           return;
8290         }
8291       }
8292 
8293       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8294         // A variable can't shadow a local variable in an enclosing scope, if
8295         // they are separated by a non-capturing declaration context.
8296         for (DeclContext *ParentDC = NewDC;
8297              ParentDC && !ParentDC->Equals(OldDC);
8298              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8299           // Only block literals, captured statements, and lambda expressions
8300           // can capture; other scopes don't.
8301           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8302               !isLambdaCallOperator(ParentDC)) {
8303             return;
8304           }
8305         }
8306       }
8307     }
8308   }
8309 
8310   // Only warn about certain kinds of shadowing for class members.
8311   if (NewDC && NewDC->isRecord()) {
8312     // In particular, don't warn about shadowing non-class members.
8313     if (!OldDC->isRecord())
8314       return;
8315 
8316     // TODO: should we warn about static data members shadowing
8317     // static data members from base classes?
8318 
8319     // TODO: don't diagnose for inaccessible shadowed members.
8320     // This is hard to do perfectly because we might friend the
8321     // shadowing context, but that's just a false negative.
8322   }
8323 
8324 
8325   DeclarationName Name = R.getLookupName();
8326 
8327   // Emit warning and note.
8328   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8329   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8330   if (!CaptureLoc.isInvalid())
8331     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8332         << Name << /*explicitly*/ 1;
8333   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8334 }
8335 
8336 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8337 /// when these variables are captured by the lambda.
8338 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8339   for (const auto &Shadow : LSI->ShadowingDecls) {
8340     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8341     // Try to avoid the warning when the shadowed decl isn't captured.
8342     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8343     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8344     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8345                                        ? diag::warn_decl_shadow_uncaptured_local
8346                                        : diag::warn_decl_shadow)
8347         << Shadow.VD->getDeclName()
8348         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8349     if (!CaptureLoc.isInvalid())
8350       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8351           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8352     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8353   }
8354 }
8355 
8356 /// Check -Wshadow without the advantage of a previous lookup.
8357 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8358   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8359     return;
8360 
8361   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8362                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8363   LookupName(R, S);
8364   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8365     CheckShadow(D, ShadowedDecl, R);
8366 }
8367 
8368 /// Check if 'E', which is an expression that is about to be modified, refers
8369 /// to a constructor parameter that shadows a field.
8370 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8371   // Quickly ignore expressions that can't be shadowing ctor parameters.
8372   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8373     return;
8374   E = E->IgnoreParenImpCasts();
8375   auto *DRE = dyn_cast<DeclRefExpr>(E);
8376   if (!DRE)
8377     return;
8378   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8379   auto I = ShadowingDecls.find(D);
8380   if (I == ShadowingDecls.end())
8381     return;
8382   const NamedDecl *ShadowedDecl = I->second;
8383   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8384   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8385   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8386   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8387 
8388   // Avoid issuing multiple warnings about the same decl.
8389   ShadowingDecls.erase(I);
8390 }
8391 
8392 /// Check for conflict between this global or extern "C" declaration and
8393 /// previous global or extern "C" declarations. This is only used in C++.
8394 template<typename T>
8395 static bool checkGlobalOrExternCConflict(
8396     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8397   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8398   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8399 
8400   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8401     // The common case: this global doesn't conflict with any extern "C"
8402     // declaration.
8403     return false;
8404   }
8405 
8406   if (Prev) {
8407     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8408       // Both the old and new declarations have C language linkage. This is a
8409       // redeclaration.
8410       Previous.clear();
8411       Previous.addDecl(Prev);
8412       return true;
8413     }
8414 
8415     // This is a global, non-extern "C" declaration, and there is a previous
8416     // non-global extern "C" declaration. Diagnose if this is a variable
8417     // declaration.
8418     if (!isa<VarDecl>(ND))
8419       return false;
8420   } else {
8421     // The declaration is extern "C". Check for any declaration in the
8422     // translation unit which might conflict.
8423     if (IsGlobal) {
8424       // We have already performed the lookup into the translation unit.
8425       IsGlobal = false;
8426       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8427            I != E; ++I) {
8428         if (isa<VarDecl>(*I)) {
8429           Prev = *I;
8430           break;
8431         }
8432       }
8433     } else {
8434       DeclContext::lookup_result R =
8435           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8436       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8437            I != E; ++I) {
8438         if (isa<VarDecl>(*I)) {
8439           Prev = *I;
8440           break;
8441         }
8442         // FIXME: If we have any other entity with this name in global scope,
8443         // the declaration is ill-formed, but that is a defect: it breaks the
8444         // 'stat' hack, for instance. Only variables can have mangled name
8445         // clashes with extern "C" declarations, so only they deserve a
8446         // diagnostic.
8447       }
8448     }
8449 
8450     if (!Prev)
8451       return false;
8452   }
8453 
8454   // Use the first declaration's location to ensure we point at something which
8455   // is lexically inside an extern "C" linkage-spec.
8456   assert(Prev && "should have found a previous declaration to diagnose");
8457   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8458     Prev = FD->getFirstDecl();
8459   else
8460     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8461 
8462   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8463     << IsGlobal << ND;
8464   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8465     << IsGlobal;
8466   return false;
8467 }
8468 
8469 /// Apply special rules for handling extern "C" declarations. Returns \c true
8470 /// if we have found that this is a redeclaration of some prior entity.
8471 ///
8472 /// Per C++ [dcl.link]p6:
8473 ///   Two declarations [for a function or variable] with C language linkage
8474 ///   with the same name that appear in different scopes refer to the same
8475 ///   [entity]. An entity with C language linkage shall not be declared with
8476 ///   the same name as an entity in global scope.
8477 template<typename T>
8478 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8479                                                   LookupResult &Previous) {
8480   if (!S.getLangOpts().CPlusPlus) {
8481     // In C, when declaring a global variable, look for a corresponding 'extern'
8482     // variable declared in function scope. We don't need this in C++, because
8483     // we find local extern decls in the surrounding file-scope DeclContext.
8484     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8485       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8486         Previous.clear();
8487         Previous.addDecl(Prev);
8488         return true;
8489       }
8490     }
8491     return false;
8492   }
8493 
8494   // A declaration in the translation unit can conflict with an extern "C"
8495   // declaration.
8496   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8497     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8498 
8499   // An extern "C" declaration can conflict with a declaration in the
8500   // translation unit or can be a redeclaration of an extern "C" declaration
8501   // in another scope.
8502   if (isIncompleteDeclExternC(S,ND))
8503     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8504 
8505   // Neither global nor extern "C": nothing to do.
8506   return false;
8507 }
8508 
8509 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8510   // If the decl is already known invalid, don't check it.
8511   if (NewVD->isInvalidDecl())
8512     return;
8513 
8514   QualType T = NewVD->getType();
8515 
8516   // Defer checking an 'auto' type until its initializer is attached.
8517   if (T->isUndeducedType())
8518     return;
8519 
8520   if (NewVD->hasAttrs())
8521     CheckAlignasUnderalignment(NewVD);
8522 
8523   if (T->isObjCObjectType()) {
8524     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8525       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8526     T = Context.getObjCObjectPointerType(T);
8527     NewVD->setType(T);
8528   }
8529 
8530   // Emit an error if an address space was applied to decl with local storage.
8531   // This includes arrays of objects with address space qualifiers, but not
8532   // automatic variables that point to other address spaces.
8533   // ISO/IEC TR 18037 S5.1.2
8534   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8535       T.getAddressSpace() != LangAS::Default) {
8536     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8537     NewVD->setInvalidDecl();
8538     return;
8539   }
8540 
8541   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8542   // scope.
8543   if (getLangOpts().OpenCLVersion == 120 &&
8544       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8545                                             getLangOpts()) &&
8546       NewVD->isStaticLocal()) {
8547     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8548     NewVD->setInvalidDecl();
8549     return;
8550   }
8551 
8552   if (getLangOpts().OpenCL) {
8553     if (!diagnoseOpenCLTypes(*this, NewVD))
8554       return;
8555 
8556     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8557     if (NewVD->hasAttr<BlocksAttr>()) {
8558       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8559       return;
8560     }
8561 
8562     if (T->isBlockPointerType()) {
8563       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8564       // can't use 'extern' storage class.
8565       if (!T.isConstQualified()) {
8566         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8567             << 0 /*const*/;
8568         NewVD->setInvalidDecl();
8569         return;
8570       }
8571       if (NewVD->hasExternalStorage()) {
8572         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8573         NewVD->setInvalidDecl();
8574         return;
8575       }
8576     }
8577 
8578     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8579     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8580         NewVD->hasExternalStorage()) {
8581       if (!T->isSamplerT() && !T->isDependentType() &&
8582           !(T.getAddressSpace() == LangAS::opencl_constant ||
8583             (T.getAddressSpace() == LangAS::opencl_global &&
8584              getOpenCLOptions().areProgramScopeVariablesSupported(
8585                  getLangOpts())))) {
8586         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8587         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8588           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8589               << Scope << "global or constant";
8590         else
8591           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8592               << Scope << "constant";
8593         NewVD->setInvalidDecl();
8594         return;
8595       }
8596     } else {
8597       if (T.getAddressSpace() == LangAS::opencl_global) {
8598         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8599             << 1 /*is any function*/ << "global";
8600         NewVD->setInvalidDecl();
8601         return;
8602       }
8603       if (T.getAddressSpace() == LangAS::opencl_constant ||
8604           T.getAddressSpace() == LangAS::opencl_local) {
8605         FunctionDecl *FD = getCurFunctionDecl();
8606         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8607         // in functions.
8608         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8609           if (T.getAddressSpace() == LangAS::opencl_constant)
8610             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8611                 << 0 /*non-kernel only*/ << "constant";
8612           else
8613             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8614                 << 0 /*non-kernel only*/ << "local";
8615           NewVD->setInvalidDecl();
8616           return;
8617         }
8618         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8619         // in the outermost scope of a kernel function.
8620         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8621           if (!getCurScope()->isFunctionScope()) {
8622             if (T.getAddressSpace() == LangAS::opencl_constant)
8623               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8624                   << "constant";
8625             else
8626               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8627                   << "local";
8628             NewVD->setInvalidDecl();
8629             return;
8630           }
8631         }
8632       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8633                  // If we are parsing a template we didn't deduce an addr
8634                  // space yet.
8635                  T.getAddressSpace() != LangAS::Default) {
8636         // Do not allow other address spaces on automatic variable.
8637         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8638         NewVD->setInvalidDecl();
8639         return;
8640       }
8641     }
8642   }
8643 
8644   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8645       && !NewVD->hasAttr<BlocksAttr>()) {
8646     if (getLangOpts().getGC() != LangOptions::NonGC)
8647       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8648     else {
8649       assert(!getLangOpts().ObjCAutoRefCount);
8650       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8651     }
8652   }
8653 
8654   // WebAssembly tables must be static with a zero length and can't be
8655   // declared within functions.
8656   if (T->isWebAssemblyTableType()) {
8657     if (getCurScope()->getParent()) { // Parent is null at top-level
8658       Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8659       NewVD->setInvalidDecl();
8660       return;
8661     }
8662     if (NewVD->getStorageClass() != SC_Static) {
8663       Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8664       NewVD->setInvalidDecl();
8665       return;
8666     }
8667     const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8668     if (!ATy || ATy->getSize().getSExtValue() != 0) {
8669       Diag(NewVD->getLocation(),
8670            diag::err_typecheck_wasm_table_must_have_zero_length);
8671       NewVD->setInvalidDecl();
8672       return;
8673     }
8674   }
8675 
8676   bool isVM = T->isVariablyModifiedType();
8677   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8678       NewVD->hasAttr<BlocksAttr>())
8679     setFunctionHasBranchProtectedScope();
8680 
8681   if ((isVM && NewVD->hasLinkage()) ||
8682       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8683     bool SizeIsNegative;
8684     llvm::APSInt Oversized;
8685     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8686         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8687     QualType FixedT;
8688     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8689       FixedT = FixedTInfo->getType();
8690     else if (FixedTInfo) {
8691       // Type and type-as-written are canonically different. We need to fix up
8692       // both types separately.
8693       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8694                                                    Oversized);
8695     }
8696     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8697       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8698       // FIXME: This won't give the correct result for
8699       // int a[10][n];
8700       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8701 
8702       if (NewVD->isFileVarDecl())
8703         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8704         << SizeRange;
8705       else if (NewVD->isStaticLocal())
8706         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8707         << SizeRange;
8708       else
8709         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8710         << SizeRange;
8711       NewVD->setInvalidDecl();
8712       return;
8713     }
8714 
8715     if (!FixedTInfo) {
8716       if (NewVD->isFileVarDecl())
8717         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8718       else
8719         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8720       NewVD->setInvalidDecl();
8721       return;
8722     }
8723 
8724     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8725     NewVD->setType(FixedT);
8726     NewVD->setTypeSourceInfo(FixedTInfo);
8727   }
8728 
8729   if (T->isVoidType()) {
8730     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8731     //                    of objects and functions.
8732     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8733       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8734         << T;
8735       NewVD->setInvalidDecl();
8736       return;
8737     }
8738   }
8739 
8740   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8741     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8742     NewVD->setInvalidDecl();
8743     return;
8744   }
8745 
8746   if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8747       !T.isWebAssemblyReferenceType()) {
8748     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8749     NewVD->setInvalidDecl();
8750     return;
8751   }
8752 
8753   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8754     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8755     NewVD->setInvalidDecl();
8756     return;
8757   }
8758 
8759   if (NewVD->isConstexpr() && !T->isDependentType() &&
8760       RequireLiteralType(NewVD->getLocation(), T,
8761                          diag::err_constexpr_var_non_literal)) {
8762     NewVD->setInvalidDecl();
8763     return;
8764   }
8765 
8766   // PPC MMA non-pointer types are not allowed as non-local variable types.
8767   if (Context.getTargetInfo().getTriple().isPPC64() &&
8768       !NewVD->isLocalVarDecl() &&
8769       CheckPPCMMAType(T, NewVD->getLocation())) {
8770     NewVD->setInvalidDecl();
8771     return;
8772   }
8773 
8774   // Check that SVE types are only used in functions with SVE available.
8775   if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8776     const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8777     llvm::StringMap<bool> CallerFeatureMap;
8778     Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8779     if (!Builtin::evaluateRequiredTargetFeatures(
8780         "sve", CallerFeatureMap)) {
8781       Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8782       NewVD->setInvalidDecl();
8783       return;
8784     }
8785   }
8786 
8787   if (T->isRVVType())
8788     checkRVVTypeSupport(T, NewVD->getLocation(), cast<ValueDecl>(CurContext));
8789 }
8790 
8791 /// Perform semantic checking on a newly-created variable
8792 /// declaration.
8793 ///
8794 /// This routine performs all of the type-checking required for a
8795 /// variable declaration once it has been built. It is used both to
8796 /// check variables after they have been parsed and their declarators
8797 /// have been translated into a declaration, and to check variables
8798 /// that have been instantiated from a template.
8799 ///
8800 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8801 ///
8802 /// Returns true if the variable declaration is a redeclaration.
8803 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8804   CheckVariableDeclarationType(NewVD);
8805 
8806   // If the decl is already known invalid, don't check it.
8807   if (NewVD->isInvalidDecl())
8808     return false;
8809 
8810   // If we did not find anything by this name, look for a non-visible
8811   // extern "C" declaration with the same name.
8812   if (Previous.empty() &&
8813       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8814     Previous.setShadowed();
8815 
8816   if (!Previous.empty()) {
8817     MergeVarDecl(NewVD, Previous);
8818     return true;
8819   }
8820   return false;
8821 }
8822 
8823 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8824 /// and if so, check that it's a valid override and remember it.
8825 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8826   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8827 
8828   // Look for methods in base classes that this method might override.
8829   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8830                      /*DetectVirtual=*/false);
8831   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8832     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8833     DeclarationName Name = MD->getDeclName();
8834 
8835     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8836       // We really want to find the base class destructor here.
8837       QualType T = Context.getTypeDeclType(BaseRecord);
8838       CanQualType CT = Context.getCanonicalType(T);
8839       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8840     }
8841 
8842     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8843       CXXMethodDecl *BaseMD =
8844           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8845       if (!BaseMD || !BaseMD->isVirtual() ||
8846           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8847                      /*ConsiderCudaAttrs=*/true,
8848                      // C++2a [class.virtual]p2 does not consider requires
8849                      // clauses when overriding.
8850                      /*ConsiderRequiresClauses=*/false))
8851         continue;
8852 
8853       if (Overridden.insert(BaseMD).second) {
8854         MD->addOverriddenMethod(BaseMD);
8855         CheckOverridingFunctionReturnType(MD, BaseMD);
8856         CheckOverridingFunctionAttributes(MD, BaseMD);
8857         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8858         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8859       }
8860 
8861       // A method can only override one function from each base class. We
8862       // don't track indirectly overridden methods from bases of bases.
8863       return true;
8864     }
8865 
8866     return false;
8867   };
8868 
8869   DC->lookupInBases(VisitBase, Paths);
8870   return !Overridden.empty();
8871 }
8872 
8873 namespace {
8874   // Struct for holding all of the extra arguments needed by
8875   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8876   struct ActOnFDArgs {
8877     Scope *S;
8878     Declarator &D;
8879     MultiTemplateParamsArg TemplateParamLists;
8880     bool AddToScope;
8881   };
8882 } // end anonymous namespace
8883 
8884 namespace {
8885 
8886 // Callback to only accept typo corrections that have a non-zero edit distance.
8887 // Also only accept corrections that have the same parent decl.
8888 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8889  public:
8890   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8891                             CXXRecordDecl *Parent)
8892       : Context(Context), OriginalFD(TypoFD),
8893         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8894 
8895   bool ValidateCandidate(const TypoCorrection &candidate) override {
8896     if (candidate.getEditDistance() == 0)
8897       return false;
8898 
8899     SmallVector<unsigned, 1> MismatchedParams;
8900     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8901                                           CDeclEnd = candidate.end();
8902          CDecl != CDeclEnd; ++CDecl) {
8903       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8904 
8905       if (FD && !FD->hasBody() &&
8906           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8907         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8908           CXXRecordDecl *Parent = MD->getParent();
8909           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8910             return true;
8911         } else if (!ExpectedParent) {
8912           return true;
8913         }
8914       }
8915     }
8916 
8917     return false;
8918   }
8919 
8920   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8921     return std::make_unique<DifferentNameValidatorCCC>(*this);
8922   }
8923 
8924  private:
8925   ASTContext &Context;
8926   FunctionDecl *OriginalFD;
8927   CXXRecordDecl *ExpectedParent;
8928 };
8929 
8930 } // end anonymous namespace
8931 
8932 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8933   TypoCorrectedFunctionDefinitions.insert(F);
8934 }
8935 
8936 /// Generate diagnostics for an invalid function redeclaration.
8937 ///
8938 /// This routine handles generating the diagnostic messages for an invalid
8939 /// function redeclaration, including finding possible similar declarations
8940 /// or performing typo correction if there are no previous declarations with
8941 /// the same name.
8942 ///
8943 /// Returns a NamedDecl iff typo correction was performed and substituting in
8944 /// the new declaration name does not cause new errors.
8945 static NamedDecl *DiagnoseInvalidRedeclaration(
8946     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8947     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8948   DeclarationName Name = NewFD->getDeclName();
8949   DeclContext *NewDC = NewFD->getDeclContext();
8950   SmallVector<unsigned, 1> MismatchedParams;
8951   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8952   TypoCorrection Correction;
8953   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8954   unsigned DiagMsg =
8955     IsLocalFriend ? diag::err_no_matching_local_friend :
8956     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8957     diag::err_member_decl_does_not_match;
8958   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8959                     IsLocalFriend ? Sema::LookupLocalFriendName
8960                                   : Sema::LookupOrdinaryName,
8961                     Sema::ForVisibleRedeclaration);
8962 
8963   NewFD->setInvalidDecl();
8964   if (IsLocalFriend)
8965     SemaRef.LookupName(Prev, S);
8966   else
8967     SemaRef.LookupQualifiedName(Prev, NewDC);
8968   assert(!Prev.isAmbiguous() &&
8969          "Cannot have an ambiguity in previous-declaration lookup");
8970   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8971   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8972                                 MD ? MD->getParent() : nullptr);
8973   if (!Prev.empty()) {
8974     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8975          Func != FuncEnd; ++Func) {
8976       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8977       if (FD &&
8978           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8979         // Add 1 to the index so that 0 can mean the mismatch didn't
8980         // involve a parameter
8981         unsigned ParamNum =
8982             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8983         NearMatches.push_back(std::make_pair(FD, ParamNum));
8984       }
8985     }
8986   // If the qualified name lookup yielded nothing, try typo correction
8987   } else if ((Correction = SemaRef.CorrectTypo(
8988                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8989                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8990                   IsLocalFriend ? nullptr : NewDC))) {
8991     // Set up everything for the call to ActOnFunctionDeclarator
8992     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8993                               ExtraArgs.D.getIdentifierLoc());
8994     Previous.clear();
8995     Previous.setLookupName(Correction.getCorrection());
8996     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8997                                     CDeclEnd = Correction.end();
8998          CDecl != CDeclEnd; ++CDecl) {
8999       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9000       if (FD && !FD->hasBody() &&
9001           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9002         Previous.addDecl(FD);
9003       }
9004     }
9005     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9006 
9007     NamedDecl *Result;
9008     // Retry building the function declaration with the new previous
9009     // declarations, and with errors suppressed.
9010     {
9011       // Trap errors.
9012       Sema::SFINAETrap Trap(SemaRef);
9013 
9014       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9015       // pieces need to verify the typo-corrected C++ declaration and hopefully
9016       // eliminate the need for the parameter pack ExtraArgs.
9017       Result = SemaRef.ActOnFunctionDeclarator(
9018           ExtraArgs.S, ExtraArgs.D,
9019           Correction.getCorrectionDecl()->getDeclContext(),
9020           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9021           ExtraArgs.AddToScope);
9022 
9023       if (Trap.hasErrorOccurred())
9024         Result = nullptr;
9025     }
9026 
9027     if (Result) {
9028       // Determine which correction we picked.
9029       Decl *Canonical = Result->getCanonicalDecl();
9030       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9031            I != E; ++I)
9032         if ((*I)->getCanonicalDecl() == Canonical)
9033           Correction.setCorrectionDecl(*I);
9034 
9035       // Let Sema know about the correction.
9036       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9037       SemaRef.diagnoseTypo(
9038           Correction,
9039           SemaRef.PDiag(IsLocalFriend
9040                           ? diag::err_no_matching_local_friend_suggest
9041                           : diag::err_member_decl_does_not_match_suggest)
9042             << Name << NewDC << IsDefinition);
9043       return Result;
9044     }
9045 
9046     // Pretend the typo correction never occurred
9047     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9048                               ExtraArgs.D.getIdentifierLoc());
9049     ExtraArgs.D.setRedeclaration(wasRedeclaration);
9050     Previous.clear();
9051     Previous.setLookupName(Name);
9052   }
9053 
9054   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9055       << Name << NewDC << IsDefinition << NewFD->getLocation();
9056 
9057   bool NewFDisConst = false;
9058   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9059     NewFDisConst = NewMD->isConst();
9060 
9061   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9062        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9063        NearMatch != NearMatchEnd; ++NearMatch) {
9064     FunctionDecl *FD = NearMatch->first;
9065     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9066     bool FDisConst = MD && MD->isConst();
9067     bool IsMember = MD || !IsLocalFriend;
9068 
9069     // FIXME: These notes are poorly worded for the local friend case.
9070     if (unsigned Idx = NearMatch->second) {
9071       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9072       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9073       if (Loc.isInvalid()) Loc = FD->getLocation();
9074       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9075                                  : diag::note_local_decl_close_param_match)
9076         << Idx << FDParam->getType()
9077         << NewFD->getParamDecl(Idx - 1)->getType();
9078     } else if (FDisConst != NewFDisConst) {
9079       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9080           << NewFDisConst << FD->getSourceRange().getEnd()
9081           << (NewFDisConst
9082                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9083                                                  .getConstQualifierLoc())
9084                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9085                                                    .getRParenLoc()
9086                                                    .getLocWithOffset(1),
9087                                                " const"));
9088     } else
9089       SemaRef.Diag(FD->getLocation(),
9090                    IsMember ? diag::note_member_def_close_match
9091                             : diag::note_local_decl_close_match);
9092   }
9093   return nullptr;
9094 }
9095 
9096 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9097   switch (D.getDeclSpec().getStorageClassSpec()) {
9098   default: llvm_unreachable("Unknown storage class!");
9099   case DeclSpec::SCS_auto:
9100   case DeclSpec::SCS_register:
9101   case DeclSpec::SCS_mutable:
9102     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9103                  diag::err_typecheck_sclass_func);
9104     D.getMutableDeclSpec().ClearStorageClassSpecs();
9105     D.setInvalidType();
9106     break;
9107   case DeclSpec::SCS_unspecified: break;
9108   case DeclSpec::SCS_extern:
9109     if (D.getDeclSpec().isExternInLinkageSpec())
9110       return SC_None;
9111     return SC_Extern;
9112   case DeclSpec::SCS_static: {
9113     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9114       // C99 6.7.1p5:
9115       //   The declaration of an identifier for a function that has
9116       //   block scope shall have no explicit storage-class specifier
9117       //   other than extern
9118       // See also (C++ [dcl.stc]p4).
9119       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9120                    diag::err_static_block_func);
9121       break;
9122     } else
9123       return SC_Static;
9124   }
9125   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9126   }
9127 
9128   // No explicit storage class has already been returned
9129   return SC_None;
9130 }
9131 
9132 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9133                                            DeclContext *DC, QualType &R,
9134                                            TypeSourceInfo *TInfo,
9135                                            StorageClass SC,
9136                                            bool &IsVirtualOkay) {
9137   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9138   DeclarationName Name = NameInfo.getName();
9139 
9140   FunctionDecl *NewFD = nullptr;
9141   bool isInline = D.getDeclSpec().isInlineSpecified();
9142 
9143   if (!SemaRef.getLangOpts().CPlusPlus) {
9144     // Determine whether the function was written with a prototype. This is
9145     // true when:
9146     //   - there is a prototype in the declarator, or
9147     //   - the type R of the function is some kind of typedef or other non-
9148     //     attributed reference to a type name (which eventually refers to a
9149     //     function type). Note, we can't always look at the adjusted type to
9150     //     check this case because attributes may cause a non-function
9151     //     declarator to still have a function type. e.g.,
9152     //       typedef void func(int a);
9153     //       __attribute__((noreturn)) func other_func; // This has a prototype
9154     bool HasPrototype =
9155         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9156         (D.getDeclSpec().isTypeRep() &&
9157          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
9158         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9159     assert(
9160         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9161         "Strict prototypes are required");
9162 
9163     NewFD = FunctionDecl::Create(
9164         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9165         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9166         ConstexprSpecKind::Unspecified,
9167         /*TrailingRequiresClause=*/nullptr);
9168     if (D.isInvalidType())
9169       NewFD->setInvalidDecl();
9170 
9171     return NewFD;
9172   }
9173 
9174   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9175 
9176   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9177   if (ConstexprKind == ConstexprSpecKind::Constinit) {
9178     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9179                  diag::err_constexpr_wrong_decl_kind)
9180         << static_cast<int>(ConstexprKind);
9181     ConstexprKind = ConstexprSpecKind::Unspecified;
9182     D.getMutableDeclSpec().ClearConstexprSpec();
9183   }
9184   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9185 
9186   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9187     // This is a C++ constructor declaration.
9188     assert(DC->isRecord() &&
9189            "Constructors can only be declared in a member context");
9190 
9191     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9192     return CXXConstructorDecl::Create(
9193         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9194         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9195         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9196         InheritedConstructor(), TrailingRequiresClause);
9197 
9198   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9199     // This is a C++ destructor declaration.
9200     if (DC->isRecord()) {
9201       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9202       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9203       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9204           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9205           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9206           /*isImplicitlyDeclared=*/false, ConstexprKind,
9207           TrailingRequiresClause);
9208       // User defined destructors start as not selected if the class definition is still
9209       // not done.
9210       if (Record->isBeingDefined())
9211         NewDD->setIneligibleOrNotSelected(true);
9212 
9213       // If the destructor needs an implicit exception specification, set it
9214       // now. FIXME: It'd be nice to be able to create the right type to start
9215       // with, but the type needs to reference the destructor declaration.
9216       if (SemaRef.getLangOpts().CPlusPlus11)
9217         SemaRef.AdjustDestructorExceptionSpec(NewDD);
9218 
9219       IsVirtualOkay = true;
9220       return NewDD;
9221 
9222     } else {
9223       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9224       D.setInvalidType();
9225 
9226       // Create a FunctionDecl to satisfy the function definition parsing
9227       // code path.
9228       return FunctionDecl::Create(
9229           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9230           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9231           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9232     }
9233 
9234   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9235     if (!DC->isRecord()) {
9236       SemaRef.Diag(D.getIdentifierLoc(),
9237            diag::err_conv_function_not_member);
9238       return nullptr;
9239     }
9240 
9241     SemaRef.CheckConversionDeclarator(D, R, SC);
9242     if (D.isInvalidType())
9243       return nullptr;
9244 
9245     IsVirtualOkay = true;
9246     return CXXConversionDecl::Create(
9247         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9248         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9249         ExplicitSpecifier, ConstexprKind, SourceLocation(),
9250         TrailingRequiresClause);
9251 
9252   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9253     if (TrailingRequiresClause)
9254       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9255                    diag::err_trailing_requires_clause_on_deduction_guide)
9256           << TrailingRequiresClause->getSourceRange();
9257     if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9258       return nullptr;
9259     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9260                                          ExplicitSpecifier, NameInfo, R, TInfo,
9261                                          D.getEndLoc());
9262   } else if (DC->isRecord()) {
9263     // If the name of the function is the same as the name of the record,
9264     // then this must be an invalid constructor that has a return type.
9265     // (The parser checks for a return type and makes the declarator a
9266     // constructor if it has no return type).
9267     if (Name.getAsIdentifierInfo() &&
9268         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9269       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9270         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9271         << SourceRange(D.getIdentifierLoc());
9272       return nullptr;
9273     }
9274 
9275     // This is a C++ method declaration.
9276     CXXMethodDecl *Ret = CXXMethodDecl::Create(
9277         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9278         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9279         ConstexprKind, SourceLocation(), TrailingRequiresClause);
9280     IsVirtualOkay = !Ret->isStatic();
9281     return Ret;
9282   } else {
9283     bool isFriend =
9284         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9285     if (!isFriend && SemaRef.CurContext->isRecord())
9286       return nullptr;
9287 
9288     // Determine whether the function was written with a
9289     // prototype. This true when:
9290     //   - we're in C++ (where every function has a prototype),
9291     return FunctionDecl::Create(
9292         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9293         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9294         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9295   }
9296 }
9297 
9298 enum OpenCLParamType {
9299   ValidKernelParam,
9300   PtrPtrKernelParam,
9301   PtrKernelParam,
9302   InvalidAddrSpacePtrKernelParam,
9303   InvalidKernelParam,
9304   RecordKernelParam
9305 };
9306 
9307 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9308   // Size dependent types are just typedefs to normal integer types
9309   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9310   // integers other than by their names.
9311   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9312 
9313   // Remove typedefs one by one until we reach a typedef
9314   // for a size dependent type.
9315   QualType DesugaredTy = Ty;
9316   do {
9317     ArrayRef<StringRef> Names(SizeTypeNames);
9318     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9319     if (Names.end() != Match)
9320       return true;
9321 
9322     Ty = DesugaredTy;
9323     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9324   } while (DesugaredTy != Ty);
9325 
9326   return false;
9327 }
9328 
9329 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9330   if (PT->isDependentType())
9331     return InvalidKernelParam;
9332 
9333   if (PT->isPointerType() || PT->isReferenceType()) {
9334     QualType PointeeType = PT->getPointeeType();
9335     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9336         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9337         PointeeType.getAddressSpace() == LangAS::Default)
9338       return InvalidAddrSpacePtrKernelParam;
9339 
9340     if (PointeeType->isPointerType()) {
9341       // This is a pointer to pointer parameter.
9342       // Recursively check inner type.
9343       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9344       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9345           ParamKind == InvalidKernelParam)
9346         return ParamKind;
9347 
9348       // OpenCL v3.0 s6.11.a:
9349       // A restriction to pass pointers to pointers only applies to OpenCL C
9350       // v1.2 or below.
9351       if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9352         return ValidKernelParam;
9353 
9354       return PtrPtrKernelParam;
9355     }
9356 
9357     // C++ for OpenCL v1.0 s2.4:
9358     // Moreover the types used in parameters of the kernel functions must be:
9359     // Standard layout types for pointer parameters. The same applies to
9360     // reference if an implementation supports them in kernel parameters.
9361     if (S.getLangOpts().OpenCLCPlusPlus &&
9362         !S.getOpenCLOptions().isAvailableOption(
9363             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9364      auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9365      bool IsStandardLayoutType = true;
9366      if (CXXRec) {
9367        // If template type is not ODR-used its definition is only available
9368        // in the template definition not its instantiation.
9369        // FIXME: This logic doesn't work for types that depend on template
9370        // parameter (PR58590).
9371        if (!CXXRec->hasDefinition())
9372          CXXRec = CXXRec->getTemplateInstantiationPattern();
9373        if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9374          IsStandardLayoutType = false;
9375      }
9376      if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9377         !IsStandardLayoutType)
9378       return InvalidKernelParam;
9379     }
9380 
9381     // OpenCL v1.2 s6.9.p:
9382     // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9383     if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9384       return ValidKernelParam;
9385 
9386     return PtrKernelParam;
9387   }
9388 
9389   // OpenCL v1.2 s6.9.k:
9390   // Arguments to kernel functions in a program cannot be declared with the
9391   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9392   // uintptr_t or a struct and/or union that contain fields declared to be one
9393   // of these built-in scalar types.
9394   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9395     return InvalidKernelParam;
9396 
9397   if (PT->isImageType())
9398     return PtrKernelParam;
9399 
9400   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9401     return InvalidKernelParam;
9402 
9403   // OpenCL extension spec v1.2 s9.5:
9404   // This extension adds support for half scalar and vector types as built-in
9405   // types that can be used for arithmetic operations, conversions etc.
9406   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9407       PT->isHalfType())
9408     return InvalidKernelParam;
9409 
9410   // Look into an array argument to check if it has a forbidden type.
9411   if (PT->isArrayType()) {
9412     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9413     // Call ourself to check an underlying type of an array. Since the
9414     // getPointeeOrArrayElementType returns an innermost type which is not an
9415     // array, this recursive call only happens once.
9416     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9417   }
9418 
9419   // C++ for OpenCL v1.0 s2.4:
9420   // Moreover the types used in parameters of the kernel functions must be:
9421   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9422   // types) for parameters passed by value;
9423   if (S.getLangOpts().OpenCLCPlusPlus &&
9424       !S.getOpenCLOptions().isAvailableOption(
9425           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9426       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9427     return InvalidKernelParam;
9428 
9429   if (PT->isRecordType())
9430     return RecordKernelParam;
9431 
9432   return ValidKernelParam;
9433 }
9434 
9435 static void checkIsValidOpenCLKernelParameter(
9436   Sema &S,
9437   Declarator &D,
9438   ParmVarDecl *Param,
9439   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9440   QualType PT = Param->getType();
9441 
9442   // Cache the valid types we encounter to avoid rechecking structs that are
9443   // used again
9444   if (ValidTypes.count(PT.getTypePtr()))
9445     return;
9446 
9447   switch (getOpenCLKernelParameterType(S, PT)) {
9448   case PtrPtrKernelParam:
9449     // OpenCL v3.0 s6.11.a:
9450     // A kernel function argument cannot be declared as a pointer to a pointer
9451     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9452     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9453     D.setInvalidType();
9454     return;
9455 
9456   case InvalidAddrSpacePtrKernelParam:
9457     // OpenCL v1.0 s6.5:
9458     // __kernel function arguments declared to be a pointer of a type can point
9459     // to one of the following address spaces only : __global, __local or
9460     // __constant.
9461     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9462     D.setInvalidType();
9463     return;
9464 
9465     // OpenCL v1.2 s6.9.k:
9466     // Arguments to kernel functions in a program cannot be declared with the
9467     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9468     // uintptr_t or a struct and/or union that contain fields declared to be
9469     // one of these built-in scalar types.
9470 
9471   case InvalidKernelParam:
9472     // OpenCL v1.2 s6.8 n:
9473     // A kernel function argument cannot be declared
9474     // of event_t type.
9475     // Do not diagnose half type since it is diagnosed as invalid argument
9476     // type for any function elsewhere.
9477     if (!PT->isHalfType()) {
9478       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9479 
9480       // Explain what typedefs are involved.
9481       const TypedefType *Typedef = nullptr;
9482       while ((Typedef = PT->getAs<TypedefType>())) {
9483         SourceLocation Loc = Typedef->getDecl()->getLocation();
9484         // SourceLocation may be invalid for a built-in type.
9485         if (Loc.isValid())
9486           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9487         PT = Typedef->desugar();
9488       }
9489     }
9490 
9491     D.setInvalidType();
9492     return;
9493 
9494   case PtrKernelParam:
9495   case ValidKernelParam:
9496     ValidTypes.insert(PT.getTypePtr());
9497     return;
9498 
9499   case RecordKernelParam:
9500     break;
9501   }
9502 
9503   // Track nested structs we will inspect
9504   SmallVector<const Decl *, 4> VisitStack;
9505 
9506   // Track where we are in the nested structs. Items will migrate from
9507   // VisitStack to HistoryStack as we do the DFS for bad field.
9508   SmallVector<const FieldDecl *, 4> HistoryStack;
9509   HistoryStack.push_back(nullptr);
9510 
9511   // At this point we already handled everything except of a RecordType or
9512   // an ArrayType of a RecordType.
9513   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9514   const RecordType *RecTy =
9515       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9516   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9517 
9518   VisitStack.push_back(RecTy->getDecl());
9519   assert(VisitStack.back() && "First decl null?");
9520 
9521   do {
9522     const Decl *Next = VisitStack.pop_back_val();
9523     if (!Next) {
9524       assert(!HistoryStack.empty());
9525       // Found a marker, we have gone up a level
9526       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9527         ValidTypes.insert(Hist->getType().getTypePtr());
9528 
9529       continue;
9530     }
9531 
9532     // Adds everything except the original parameter declaration (which is not a
9533     // field itself) to the history stack.
9534     const RecordDecl *RD;
9535     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9536       HistoryStack.push_back(Field);
9537 
9538       QualType FieldTy = Field->getType();
9539       // Other field types (known to be valid or invalid) are handled while we
9540       // walk around RecordDecl::fields().
9541       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9542              "Unexpected type.");
9543       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9544 
9545       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9546     } else {
9547       RD = cast<RecordDecl>(Next);
9548     }
9549 
9550     // Add a null marker so we know when we've gone back up a level
9551     VisitStack.push_back(nullptr);
9552 
9553     for (const auto *FD : RD->fields()) {
9554       QualType QT = FD->getType();
9555 
9556       if (ValidTypes.count(QT.getTypePtr()))
9557         continue;
9558 
9559       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9560       if (ParamType == ValidKernelParam)
9561         continue;
9562 
9563       if (ParamType == RecordKernelParam) {
9564         VisitStack.push_back(FD);
9565         continue;
9566       }
9567 
9568       // OpenCL v1.2 s6.9.p:
9569       // Arguments to kernel functions that are declared to be a struct or union
9570       // do not allow OpenCL objects to be passed as elements of the struct or
9571       // union. This restriction was lifted in OpenCL v2.0 with the introduction
9572       // of SVM.
9573       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9574           ParamType == InvalidAddrSpacePtrKernelParam) {
9575         S.Diag(Param->getLocation(),
9576                diag::err_record_with_pointers_kernel_param)
9577           << PT->isUnionType()
9578           << PT;
9579       } else {
9580         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9581       }
9582 
9583       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9584           << OrigRecDecl->getDeclName();
9585 
9586       // We have an error, now let's go back up through history and show where
9587       // the offending field came from
9588       for (ArrayRef<const FieldDecl *>::const_iterator
9589                I = HistoryStack.begin() + 1,
9590                E = HistoryStack.end();
9591            I != E; ++I) {
9592         const FieldDecl *OuterField = *I;
9593         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9594           << OuterField->getType();
9595       }
9596 
9597       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9598         << QT->isPointerType()
9599         << QT;
9600       D.setInvalidType();
9601       return;
9602     }
9603   } while (!VisitStack.empty());
9604 }
9605 
9606 /// Find the DeclContext in which a tag is implicitly declared if we see an
9607 /// elaborated type specifier in the specified context, and lookup finds
9608 /// nothing.
9609 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9610   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9611     DC = DC->getParent();
9612   return DC;
9613 }
9614 
9615 /// Find the Scope in which a tag is implicitly declared if we see an
9616 /// elaborated type specifier in the specified context, and lookup finds
9617 /// nothing.
9618 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9619   while (S->isClassScope() ||
9620          (LangOpts.CPlusPlus &&
9621           S->isFunctionPrototypeScope()) ||
9622          ((S->getFlags() & Scope::DeclScope) == 0) ||
9623          (S->getEntity() && S->getEntity()->isTransparentContext()))
9624     S = S->getParent();
9625   return S;
9626 }
9627 
9628 /// Determine whether a declaration matches a known function in namespace std.
9629 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9630                          unsigned BuiltinID) {
9631   switch (BuiltinID) {
9632   case Builtin::BI__GetExceptionInfo:
9633     // No type checking whatsoever.
9634     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9635 
9636   case Builtin::BIaddressof:
9637   case Builtin::BI__addressof:
9638   case Builtin::BIforward:
9639   case Builtin::BIforward_like:
9640   case Builtin::BImove:
9641   case Builtin::BImove_if_noexcept:
9642   case Builtin::BIas_const: {
9643     // Ensure that we don't treat the algorithm
9644     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9645     // as the builtin std::move.
9646     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9647     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9648   }
9649 
9650   default:
9651     return false;
9652   }
9653 }
9654 
9655 NamedDecl*
9656 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9657                               TypeSourceInfo *TInfo, LookupResult &Previous,
9658                               MultiTemplateParamsArg TemplateParamListsRef,
9659                               bool &AddToScope) {
9660   QualType R = TInfo->getType();
9661 
9662   assert(R->isFunctionType());
9663   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9664     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9665 
9666   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9667   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9668   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9669     if (!TemplateParamLists.empty() &&
9670         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9671       TemplateParamLists.back() = Invented;
9672     else
9673       TemplateParamLists.push_back(Invented);
9674   }
9675 
9676   // TODO: consider using NameInfo for diagnostic.
9677   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9678   DeclarationName Name = NameInfo.getName();
9679   StorageClass SC = getFunctionStorageClass(*this, D);
9680 
9681   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9682     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9683          diag::err_invalid_thread)
9684       << DeclSpec::getSpecifierName(TSCS);
9685 
9686   if (D.isFirstDeclarationOfMember())
9687     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9688                            D.getIdentifierLoc());
9689 
9690   bool isFriend = false;
9691   FunctionTemplateDecl *FunctionTemplate = nullptr;
9692   bool isMemberSpecialization = false;
9693   bool isFunctionTemplateSpecialization = false;
9694 
9695   bool isDependentClassScopeExplicitSpecialization = false;
9696   bool HasExplicitTemplateArgs = false;
9697   TemplateArgumentListInfo TemplateArgs;
9698 
9699   bool isVirtualOkay = false;
9700 
9701   DeclContext *OriginalDC = DC;
9702   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9703 
9704   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9705                                               isVirtualOkay);
9706   if (!NewFD) return nullptr;
9707 
9708   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9709     NewFD->setTopLevelDeclInObjCContainer();
9710 
9711   // Set the lexical context. If this is a function-scope declaration, or has a
9712   // C++ scope specifier, or is the object of a friend declaration, the lexical
9713   // context will be different from the semantic context.
9714   NewFD->setLexicalDeclContext(CurContext);
9715 
9716   if (IsLocalExternDecl)
9717     NewFD->setLocalExternDecl();
9718 
9719   if (getLangOpts().CPlusPlus) {
9720     // The rules for implicit inlines changed in C++20 for methods and friends
9721     // with an in-class definition (when such a definition is not attached to
9722     // the global module).  User-specified 'inline' overrides this (set when
9723     // the function decl is created above).
9724     // FIXME: We need a better way to separate C++ standard and clang modules.
9725     bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9726                                !NewFD->getOwningModule() ||
9727                                NewFD->getOwningModule()->isGlobalModule() ||
9728                                NewFD->getOwningModule()->isHeaderLikeModule();
9729     bool isInline = D.getDeclSpec().isInlineSpecified();
9730     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9731     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9732     isFriend = D.getDeclSpec().isFriendSpecified();
9733     if (isFriend && !isInline && D.isFunctionDefinition()) {
9734       // Pre-C++20 [class.friend]p5
9735       //   A function can be defined in a friend declaration of a
9736       //   class . . . . Such a function is implicitly inline.
9737       // Post C++20 [class.friend]p7
9738       //   Such a function is implicitly an inline function if it is attached
9739       //   to the global module.
9740       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9741     }
9742 
9743     // If this is a method defined in an __interface, and is not a constructor
9744     // or an overloaded operator, then set the pure flag (isVirtual will already
9745     // return true).
9746     if (const CXXRecordDecl *Parent =
9747           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9748       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9749         NewFD->setPure(true);
9750 
9751       // C++ [class.union]p2
9752       //   A union can have member functions, but not virtual functions.
9753       if (isVirtual && Parent->isUnion()) {
9754         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9755         NewFD->setInvalidDecl();
9756       }
9757       if ((Parent->isClass() || Parent->isStruct()) &&
9758           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9759           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9760           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9761         if (auto *Def = Parent->getDefinition())
9762           Def->setInitMethod(true);
9763       }
9764     }
9765 
9766     SetNestedNameSpecifier(*this, NewFD, D);
9767     isMemberSpecialization = false;
9768     isFunctionTemplateSpecialization = false;
9769     if (D.isInvalidType())
9770       NewFD->setInvalidDecl();
9771 
9772     // Match up the template parameter lists with the scope specifier, then
9773     // determine whether we have a template or a template specialization.
9774     bool Invalid = false;
9775     TemplateParameterList *TemplateParams =
9776         MatchTemplateParametersToScopeSpecifier(
9777             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9778             D.getCXXScopeSpec(),
9779             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9780                 ? D.getName().TemplateId
9781                 : nullptr,
9782             TemplateParamLists, isFriend, isMemberSpecialization,
9783             Invalid);
9784     if (TemplateParams) {
9785       // Check that we can declare a template here.
9786       if (CheckTemplateDeclScope(S, TemplateParams))
9787         NewFD->setInvalidDecl();
9788 
9789       if (TemplateParams->size() > 0) {
9790         // This is a function template
9791 
9792         // A destructor cannot be a template.
9793         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9794           Diag(NewFD->getLocation(), diag::err_destructor_template);
9795           NewFD->setInvalidDecl();
9796         }
9797 
9798         // If we're adding a template to a dependent context, we may need to
9799         // rebuilding some of the types used within the template parameter list,
9800         // now that we know what the current instantiation is.
9801         if (DC->isDependentContext()) {
9802           ContextRAII SavedContext(*this, DC);
9803           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9804             Invalid = true;
9805         }
9806 
9807         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9808                                                         NewFD->getLocation(),
9809                                                         Name, TemplateParams,
9810                                                         NewFD);
9811         FunctionTemplate->setLexicalDeclContext(CurContext);
9812         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9813 
9814         // For source fidelity, store the other template param lists.
9815         if (TemplateParamLists.size() > 1) {
9816           NewFD->setTemplateParameterListsInfo(Context,
9817               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9818                   .drop_back(1));
9819         }
9820       } else {
9821         // This is a function template specialization.
9822         isFunctionTemplateSpecialization = true;
9823         // For source fidelity, store all the template param lists.
9824         if (TemplateParamLists.size() > 0)
9825           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9826 
9827         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9828         if (isFriend) {
9829           // We want to remove the "template<>", found here.
9830           SourceRange RemoveRange = TemplateParams->getSourceRange();
9831 
9832           // If we remove the template<> and the name is not a
9833           // template-id, we're actually silently creating a problem:
9834           // the friend declaration will refer to an untemplated decl,
9835           // and clearly the user wants a template specialization.  So
9836           // we need to insert '<>' after the name.
9837           SourceLocation InsertLoc;
9838           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9839             InsertLoc = D.getName().getSourceRange().getEnd();
9840             InsertLoc = getLocForEndOfToken(InsertLoc);
9841           }
9842 
9843           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9844             << Name << RemoveRange
9845             << FixItHint::CreateRemoval(RemoveRange)
9846             << FixItHint::CreateInsertion(InsertLoc, "<>");
9847           Invalid = true;
9848         }
9849       }
9850     } else {
9851       // Check that we can declare a template here.
9852       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9853           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9854         NewFD->setInvalidDecl();
9855 
9856       // All template param lists were matched against the scope specifier:
9857       // this is NOT (an explicit specialization of) a template.
9858       if (TemplateParamLists.size() > 0)
9859         // For source fidelity, store all the template param lists.
9860         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9861     }
9862 
9863     if (Invalid) {
9864       NewFD->setInvalidDecl();
9865       if (FunctionTemplate)
9866         FunctionTemplate->setInvalidDecl();
9867     }
9868 
9869     // C++ [dcl.fct.spec]p5:
9870     //   The virtual specifier shall only be used in declarations of
9871     //   nonstatic class member functions that appear within a
9872     //   member-specification of a class declaration; see 10.3.
9873     //
9874     if (isVirtual && !NewFD->isInvalidDecl()) {
9875       if (!isVirtualOkay) {
9876         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9877              diag::err_virtual_non_function);
9878       } else if (!CurContext->isRecord()) {
9879         // 'virtual' was specified outside of the class.
9880         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9881              diag::err_virtual_out_of_class)
9882           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9883       } else if (NewFD->getDescribedFunctionTemplate()) {
9884         // C++ [temp.mem]p3:
9885         //  A member function template shall not be virtual.
9886         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9887              diag::err_virtual_member_function_template)
9888           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9889       } else {
9890         // Okay: Add virtual to the method.
9891         NewFD->setVirtualAsWritten(true);
9892       }
9893 
9894       if (getLangOpts().CPlusPlus14 &&
9895           NewFD->getReturnType()->isUndeducedType())
9896         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9897     }
9898 
9899     if (getLangOpts().CPlusPlus14 &&
9900         (NewFD->isDependentContext() ||
9901          (isFriend && CurContext->isDependentContext())) &&
9902         NewFD->getReturnType()->isUndeducedType()) {
9903       // If the function template is referenced directly (for instance, as a
9904       // member of the current instantiation), pretend it has a dependent type.
9905       // This is not really justified by the standard, but is the only sane
9906       // thing to do.
9907       // FIXME: For a friend function, we have not marked the function as being
9908       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9909       const FunctionProtoType *FPT =
9910           NewFD->getType()->castAs<FunctionProtoType>();
9911       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9912       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9913                                              FPT->getExtProtoInfo()));
9914     }
9915 
9916     // C++ [dcl.fct.spec]p3:
9917     //  The inline specifier shall not appear on a block scope function
9918     //  declaration.
9919     if (isInline && !NewFD->isInvalidDecl()) {
9920       if (CurContext->isFunctionOrMethod()) {
9921         // 'inline' is not allowed on block scope function declaration.
9922         Diag(D.getDeclSpec().getInlineSpecLoc(),
9923              diag::err_inline_declaration_block_scope) << Name
9924           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9925       }
9926     }
9927 
9928     // C++ [dcl.fct.spec]p6:
9929     //  The explicit specifier shall be used only in the declaration of a
9930     //  constructor or conversion function within its class definition;
9931     //  see 12.3.1 and 12.3.2.
9932     if (hasExplicit && !NewFD->isInvalidDecl() &&
9933         !isa<CXXDeductionGuideDecl>(NewFD)) {
9934       if (!CurContext->isRecord()) {
9935         // 'explicit' was specified outside of the class.
9936         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9937              diag::err_explicit_out_of_class)
9938             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9939       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9940                  !isa<CXXConversionDecl>(NewFD)) {
9941         // 'explicit' was specified on a function that wasn't a constructor
9942         // or conversion function.
9943         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9944              diag::err_explicit_non_ctor_or_conv_function)
9945             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9946       }
9947     }
9948 
9949     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9950     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9951       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9952       // are implicitly inline.
9953       NewFD->setImplicitlyInline();
9954 
9955       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9956       // be either constructors or to return a literal type. Therefore,
9957       // destructors cannot be declared constexpr.
9958       if (isa<CXXDestructorDecl>(NewFD) &&
9959           (!getLangOpts().CPlusPlus20 ||
9960            ConstexprKind == ConstexprSpecKind::Consteval)) {
9961         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9962             << static_cast<int>(ConstexprKind);
9963         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9964                                     ? ConstexprSpecKind::Unspecified
9965                                     : ConstexprSpecKind::Constexpr);
9966       }
9967       // C++20 [dcl.constexpr]p2: An allocation function, or a
9968       // deallocation function shall not be declared with the consteval
9969       // specifier.
9970       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9971           (NewFD->getOverloadedOperator() == OO_New ||
9972            NewFD->getOverloadedOperator() == OO_Array_New ||
9973            NewFD->getOverloadedOperator() == OO_Delete ||
9974            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9975         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9976              diag::err_invalid_consteval_decl_kind)
9977             << NewFD;
9978         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9979       }
9980     }
9981 
9982     // If __module_private__ was specified, mark the function accordingly.
9983     if (D.getDeclSpec().isModulePrivateSpecified()) {
9984       if (isFunctionTemplateSpecialization) {
9985         SourceLocation ModulePrivateLoc
9986           = D.getDeclSpec().getModulePrivateSpecLoc();
9987         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9988           << 0
9989           << FixItHint::CreateRemoval(ModulePrivateLoc);
9990       } else {
9991         NewFD->setModulePrivate();
9992         if (FunctionTemplate)
9993           FunctionTemplate->setModulePrivate();
9994       }
9995     }
9996 
9997     if (isFriend) {
9998       if (FunctionTemplate) {
9999         FunctionTemplate->setObjectOfFriendDecl();
10000         FunctionTemplate->setAccess(AS_public);
10001       }
10002       NewFD->setObjectOfFriendDecl();
10003       NewFD->setAccess(AS_public);
10004     }
10005 
10006     // If a function is defined as defaulted or deleted, mark it as such now.
10007     // We'll do the relevant checks on defaulted / deleted functions later.
10008     switch (D.getFunctionDefinitionKind()) {
10009     case FunctionDefinitionKind::Declaration:
10010     case FunctionDefinitionKind::Definition:
10011       break;
10012 
10013     case FunctionDefinitionKind::Defaulted:
10014       NewFD->setDefaulted();
10015       break;
10016 
10017     case FunctionDefinitionKind::Deleted:
10018       NewFD->setDeletedAsWritten();
10019       break;
10020     }
10021 
10022     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10023         D.isFunctionDefinition() && !isInline) {
10024       // Pre C++20 [class.mfct]p2:
10025       //   A member function may be defined (8.4) in its class definition, in
10026       //   which case it is an inline member function (7.1.2)
10027       // Post C++20 [class.mfct]p1:
10028       //   If a member function is attached to the global module and is defined
10029       //   in its class definition, it is inline.
10030       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10031     }
10032 
10033     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10034         !CurContext->isRecord()) {
10035       // C++ [class.static]p1:
10036       //   A data or function member of a class may be declared static
10037       //   in a class definition, in which case it is a static member of
10038       //   the class.
10039 
10040       // Complain about the 'static' specifier if it's on an out-of-line
10041       // member function definition.
10042 
10043       // MSVC permits the use of a 'static' storage specifier on an out-of-line
10044       // member function template declaration and class member template
10045       // declaration (MSVC versions before 2015), warn about this.
10046       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10047            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10048              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10049            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10050            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10051         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10052     }
10053 
10054     // C++11 [except.spec]p15:
10055     //   A deallocation function with no exception-specification is treated
10056     //   as if it were specified with noexcept(true).
10057     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10058     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10059          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10060         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10061       NewFD->setType(Context.getFunctionType(
10062           FPT->getReturnType(), FPT->getParamTypes(),
10063           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10064 
10065     // C++20 [dcl.inline]/7
10066     // If an inline function or variable that is attached to a named module
10067     // is declared in a definition domain, it shall be defined in that
10068     // domain.
10069     // So, if the current declaration does not have a definition, we must
10070     // check at the end of the TU (or when the PMF starts) to see that we
10071     // have a definition at that point.
10072     if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10073         NewFD->hasOwningModule() &&
10074         NewFD->getOwningModule()->isModulePurview()) {
10075       PendingInlineFuncDecls.insert(NewFD);
10076     }
10077   }
10078 
10079   // Filter out previous declarations that don't match the scope.
10080   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10081                        D.getCXXScopeSpec().isNotEmpty() ||
10082                        isMemberSpecialization ||
10083                        isFunctionTemplateSpecialization);
10084 
10085   // Handle GNU asm-label extension (encoded as an attribute).
10086   if (Expr *E = (Expr*) D.getAsmLabel()) {
10087     // The parser guarantees this is a string.
10088     StringLiteral *SE = cast<StringLiteral>(E);
10089     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10090                                         /*IsLiteralLabel=*/true,
10091                                         SE->getStrTokenLoc(0)));
10092   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10093     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10094       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10095     if (I != ExtnameUndeclaredIdentifiers.end()) {
10096       if (isDeclExternC(NewFD)) {
10097         NewFD->addAttr(I->second);
10098         ExtnameUndeclaredIdentifiers.erase(I);
10099       } else
10100         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10101             << /*Variable*/0 << NewFD;
10102     }
10103   }
10104 
10105   // Copy the parameter declarations from the declarator D to the function
10106   // declaration NewFD, if they are available.  First scavenge them into Params.
10107   SmallVector<ParmVarDecl*, 16> Params;
10108   unsigned FTIIdx;
10109   if (D.isFunctionDeclarator(FTIIdx)) {
10110     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10111 
10112     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10113     // function that takes no arguments, not a function that takes a
10114     // single void argument.
10115     // We let through "const void" here because Sema::GetTypeForDeclarator
10116     // already checks for that case.
10117     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10118       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10119         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10120         assert(Param->getDeclContext() != NewFD && "Was set before ?");
10121         Param->setDeclContext(NewFD);
10122         Params.push_back(Param);
10123 
10124         if (Param->isInvalidDecl())
10125           NewFD->setInvalidDecl();
10126       }
10127     }
10128 
10129     if (!getLangOpts().CPlusPlus) {
10130       // In C, find all the tag declarations from the prototype and move them
10131       // into the function DeclContext. Remove them from the surrounding tag
10132       // injection context of the function, which is typically but not always
10133       // the TU.
10134       DeclContext *PrototypeTagContext =
10135           getTagInjectionContext(NewFD->getLexicalDeclContext());
10136       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10137         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10138 
10139         // We don't want to reparent enumerators. Look at their parent enum
10140         // instead.
10141         if (!TD) {
10142           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10143             TD = cast<EnumDecl>(ECD->getDeclContext());
10144         }
10145         if (!TD)
10146           continue;
10147         DeclContext *TagDC = TD->getLexicalDeclContext();
10148         if (!TagDC->containsDecl(TD))
10149           continue;
10150         TagDC->removeDecl(TD);
10151         TD->setDeclContext(NewFD);
10152         NewFD->addDecl(TD);
10153 
10154         // Preserve the lexical DeclContext if it is not the surrounding tag
10155         // injection context of the FD. In this example, the semantic context of
10156         // E will be f and the lexical context will be S, while both the
10157         // semantic and lexical contexts of S will be f:
10158         //   void f(struct S { enum E { a } f; } s);
10159         if (TagDC != PrototypeTagContext)
10160           TD->setLexicalDeclContext(TagDC);
10161       }
10162     }
10163   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10164     // When we're declaring a function with a typedef, typeof, etc as in the
10165     // following example, we'll need to synthesize (unnamed)
10166     // parameters for use in the declaration.
10167     //
10168     // @code
10169     // typedef void fn(int);
10170     // fn f;
10171     // @endcode
10172 
10173     // Synthesize a parameter for each argument type.
10174     for (const auto &AI : FT->param_types()) {
10175       ParmVarDecl *Param =
10176           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10177       Param->setScopeInfo(0, Params.size());
10178       Params.push_back(Param);
10179     }
10180   } else {
10181     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10182            "Should not need args for typedef of non-prototype fn");
10183   }
10184 
10185   // Finally, we know we have the right number of parameters, install them.
10186   NewFD->setParams(Params);
10187 
10188   if (D.getDeclSpec().isNoreturnSpecified())
10189     NewFD->addAttr(
10190         C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10191 
10192   // Functions returning a variably modified type violate C99 6.7.5.2p2
10193   // because all functions have linkage.
10194   if (!NewFD->isInvalidDecl() &&
10195       NewFD->getReturnType()->isVariablyModifiedType()) {
10196     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10197     NewFD->setInvalidDecl();
10198   }
10199 
10200   // Apply an implicit SectionAttr if '#pragma clang section text' is active
10201   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10202       !NewFD->hasAttr<SectionAttr>())
10203     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10204         Context, PragmaClangTextSection.SectionName,
10205         PragmaClangTextSection.PragmaLocation));
10206 
10207   // Apply an implicit SectionAttr if #pragma code_seg is active.
10208   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10209       !NewFD->hasAttr<SectionAttr>()) {
10210     NewFD->addAttr(SectionAttr::CreateImplicit(
10211         Context, CodeSegStack.CurrentValue->getString(),
10212         CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10213     if (UnifySection(CodeSegStack.CurrentValue->getString(),
10214                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10215                          ASTContext::PSF_Read,
10216                      NewFD))
10217       NewFD->dropAttr<SectionAttr>();
10218   }
10219 
10220   // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10221   // active.
10222   if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10223       !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10224     NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10225         Context, PragmaClangTextSection.PragmaLocation));
10226 
10227   // Apply an implicit CodeSegAttr from class declspec or
10228   // apply an implicit SectionAttr from #pragma code_seg if active.
10229   if (!NewFD->hasAttr<CodeSegAttr>()) {
10230     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10231                                                                  D.isFunctionDefinition())) {
10232       NewFD->addAttr(SAttr);
10233     }
10234   }
10235 
10236   // Handle attributes.
10237   ProcessDeclAttributes(S, NewFD, D);
10238   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10239   if (NewTVA && !NewTVA->isDefaultVersion() &&
10240       !Context.getTargetInfo().hasFeature("fmv")) {
10241     // Don't add to scope fmv functions declarations if fmv disabled
10242     AddToScope = false;
10243     return NewFD;
10244   }
10245 
10246   if (getLangOpts().OpenCL) {
10247     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10248     // type declaration will generate a compilation error.
10249     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10250     if (AddressSpace != LangAS::Default) {
10251       Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10252       NewFD->setInvalidDecl();
10253     }
10254   }
10255 
10256   if (getLangOpts().HLSL) {
10257     auto &TargetInfo = getASTContext().getTargetInfo();
10258     // Skip operator overload which not identifier.
10259     // Also make sure NewFD is in translation-unit scope.
10260     if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10261         NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10262         S->getDepth() == 0) {
10263       CheckHLSLEntryPoint(NewFD);
10264       if (!NewFD->isInvalidDecl()) {
10265         auto Env = TargetInfo.getTriple().getEnvironment();
10266         HLSLShaderAttr::ShaderType ShaderType =
10267             static_cast<HLSLShaderAttr::ShaderType>(
10268                 hlsl::getStageFromEnvironment(Env));
10269         // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10270         // function.
10271         if (HLSLShaderAttr *NT = NewFD->getAttr<HLSLShaderAttr>()) {
10272           if (NT->getType() != ShaderType)
10273             Diag(NT->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
10274                 << NT;
10275         } else {
10276           NewFD->addAttr(HLSLShaderAttr::Create(Context, ShaderType,
10277                                                 NewFD->getBeginLoc()));
10278         }
10279       }
10280     }
10281     // HLSL does not support specifying an address space on a function return
10282     // type.
10283     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10284     if (AddressSpace != LangAS::Default) {
10285       Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10286       NewFD->setInvalidDecl();
10287     }
10288   }
10289 
10290   if (!getLangOpts().CPlusPlus) {
10291     // Perform semantic checking on the function declaration.
10292     if (!NewFD->isInvalidDecl() && NewFD->isMain())
10293       CheckMain(NewFD, D.getDeclSpec());
10294 
10295     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10296       CheckMSVCRTEntryPoint(NewFD);
10297 
10298     if (!NewFD->isInvalidDecl())
10299       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10300                                                   isMemberSpecialization,
10301                                                   D.isFunctionDefinition()));
10302     else if (!Previous.empty())
10303       // Recover gracefully from an invalid redeclaration.
10304       D.setRedeclaration(true);
10305     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10306             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10307            "previous declaration set still overloaded");
10308 
10309     // Diagnose no-prototype function declarations with calling conventions that
10310     // don't support variadic calls. Only do this in C and do it after merging
10311     // possibly prototyped redeclarations.
10312     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10313     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10314       CallingConv CC = FT->getExtInfo().getCC();
10315       if (!supportsVariadicCall(CC)) {
10316         // Windows system headers sometimes accidentally use stdcall without
10317         // (void) parameters, so we relax this to a warning.
10318         int DiagID =
10319             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10320         Diag(NewFD->getLocation(), DiagID)
10321             << FunctionType::getNameForCallConv(CC);
10322       }
10323     }
10324 
10325    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10326        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10327      checkNonTrivialCUnion(NewFD->getReturnType(),
10328                            NewFD->getReturnTypeSourceRange().getBegin(),
10329                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10330   } else {
10331     // C++11 [replacement.functions]p3:
10332     //  The program's definitions shall not be specified as inline.
10333     //
10334     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10335     //
10336     // Suppress the diagnostic if the function is __attribute__((used)), since
10337     // that forces an external definition to be emitted.
10338     if (D.getDeclSpec().isInlineSpecified() &&
10339         NewFD->isReplaceableGlobalAllocationFunction() &&
10340         !NewFD->hasAttr<UsedAttr>())
10341       Diag(D.getDeclSpec().getInlineSpecLoc(),
10342            diag::ext_operator_new_delete_declared_inline)
10343         << NewFD->getDeclName();
10344 
10345     // If the declarator is a template-id, translate the parser's template
10346     // argument list into our AST format.
10347     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10348       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10349       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10350       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10351       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10352                                          TemplateId->NumArgs);
10353       translateTemplateArguments(TemplateArgsPtr,
10354                                  TemplateArgs);
10355 
10356       HasExplicitTemplateArgs = true;
10357 
10358       if (NewFD->isInvalidDecl()) {
10359         HasExplicitTemplateArgs = false;
10360       } else if (FunctionTemplate) {
10361         // Function template with explicit template arguments.
10362         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10363           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10364 
10365         HasExplicitTemplateArgs = false;
10366       } else {
10367         assert((isFunctionTemplateSpecialization ||
10368                 D.getDeclSpec().isFriendSpecified()) &&
10369                "should have a 'template<>' for this decl");
10370         // "friend void foo<>(int);" is an implicit specialization decl.
10371         isFunctionTemplateSpecialization = true;
10372       }
10373     } else if (isFriend && isFunctionTemplateSpecialization) {
10374       // This combination is only possible in a recovery case;  the user
10375       // wrote something like:
10376       //   template <> friend void foo(int);
10377       // which we're recovering from as if the user had written:
10378       //   friend void foo<>(int);
10379       // Go ahead and fake up a template id.
10380       HasExplicitTemplateArgs = true;
10381       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10382       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10383     }
10384 
10385     // We do not add HD attributes to specializations here because
10386     // they may have different constexpr-ness compared to their
10387     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10388     // may end up with different effective targets. Instead, a
10389     // specialization inherits its target attributes from its template
10390     // in the CheckFunctionTemplateSpecialization() call below.
10391     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10392       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10393 
10394     // If it's a friend (and only if it's a friend), it's possible
10395     // that either the specialized function type or the specialized
10396     // template is dependent, and therefore matching will fail.  In
10397     // this case, don't check the specialization yet.
10398     if (isFunctionTemplateSpecialization && isFriend &&
10399         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10400          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10401              TemplateArgs.arguments()))) {
10402       assert(HasExplicitTemplateArgs &&
10403              "friend function specialization without template args");
10404       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10405                                                        Previous))
10406         NewFD->setInvalidDecl();
10407     } else if (isFunctionTemplateSpecialization) {
10408       if (CurContext->isDependentContext() && CurContext->isRecord()
10409           && !isFriend) {
10410         isDependentClassScopeExplicitSpecialization = true;
10411       } else if (!NewFD->isInvalidDecl() &&
10412                  CheckFunctionTemplateSpecialization(
10413                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10414                      Previous))
10415         NewFD->setInvalidDecl();
10416 
10417       // C++ [dcl.stc]p1:
10418       //   A storage-class-specifier shall not be specified in an explicit
10419       //   specialization (14.7.3)
10420       FunctionTemplateSpecializationInfo *Info =
10421           NewFD->getTemplateSpecializationInfo();
10422       if (Info && SC != SC_None) {
10423         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10424           Diag(NewFD->getLocation(),
10425                diag::err_explicit_specialization_inconsistent_storage_class)
10426             << SC
10427             << FixItHint::CreateRemoval(
10428                                       D.getDeclSpec().getStorageClassSpecLoc());
10429 
10430         else
10431           Diag(NewFD->getLocation(),
10432                diag::ext_explicit_specialization_storage_class)
10433             << FixItHint::CreateRemoval(
10434                                       D.getDeclSpec().getStorageClassSpecLoc());
10435       }
10436     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10437       if (CheckMemberSpecialization(NewFD, Previous))
10438           NewFD->setInvalidDecl();
10439     }
10440 
10441     // Perform semantic checking on the function declaration.
10442     if (!isDependentClassScopeExplicitSpecialization) {
10443       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10444         CheckMain(NewFD, D.getDeclSpec());
10445 
10446       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10447         CheckMSVCRTEntryPoint(NewFD);
10448 
10449       if (!NewFD->isInvalidDecl())
10450         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10451                                                     isMemberSpecialization,
10452                                                     D.isFunctionDefinition()));
10453       else if (!Previous.empty())
10454         // Recover gracefully from an invalid redeclaration.
10455         D.setRedeclaration(true);
10456     }
10457 
10458     assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10459             !D.isRedeclaration() ||
10460             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10461            "previous declaration set still overloaded");
10462 
10463     NamedDecl *PrincipalDecl = (FunctionTemplate
10464                                 ? cast<NamedDecl>(FunctionTemplate)
10465                                 : NewFD);
10466 
10467     if (isFriend && NewFD->getPreviousDecl()) {
10468       AccessSpecifier Access = AS_public;
10469       if (!NewFD->isInvalidDecl())
10470         Access = NewFD->getPreviousDecl()->getAccess();
10471 
10472       NewFD->setAccess(Access);
10473       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10474     }
10475 
10476     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10477         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10478       PrincipalDecl->setNonMemberOperator();
10479 
10480     // If we have a function template, check the template parameter
10481     // list. This will check and merge default template arguments.
10482     if (FunctionTemplate) {
10483       FunctionTemplateDecl *PrevTemplate =
10484                                      FunctionTemplate->getPreviousDecl();
10485       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10486                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10487                                     : nullptr,
10488                             D.getDeclSpec().isFriendSpecified()
10489                               ? (D.isFunctionDefinition()
10490                                    ? TPC_FriendFunctionTemplateDefinition
10491                                    : TPC_FriendFunctionTemplate)
10492                               : (D.getCXXScopeSpec().isSet() &&
10493                                  DC && DC->isRecord() &&
10494                                  DC->isDependentContext())
10495                                   ? TPC_ClassTemplateMember
10496                                   : TPC_FunctionTemplate);
10497     }
10498 
10499     if (NewFD->isInvalidDecl()) {
10500       // Ignore all the rest of this.
10501     } else if (!D.isRedeclaration()) {
10502       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10503                                        AddToScope };
10504       // Fake up an access specifier if it's supposed to be a class member.
10505       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10506         NewFD->setAccess(AS_public);
10507 
10508       // Qualified decls generally require a previous declaration.
10509       if (D.getCXXScopeSpec().isSet()) {
10510         // ...with the major exception of templated-scope or
10511         // dependent-scope friend declarations.
10512 
10513         // TODO: we currently also suppress this check in dependent
10514         // contexts because (1) the parameter depth will be off when
10515         // matching friend templates and (2) we might actually be
10516         // selecting a friend based on a dependent factor.  But there
10517         // are situations where these conditions don't apply and we
10518         // can actually do this check immediately.
10519         //
10520         // Unless the scope is dependent, it's always an error if qualified
10521         // redeclaration lookup found nothing at all. Diagnose that now;
10522         // nothing will diagnose that error later.
10523         if (isFriend &&
10524             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10525              (!Previous.empty() && CurContext->isDependentContext()))) {
10526           // ignore these
10527         } else if (NewFD->isCPUDispatchMultiVersion() ||
10528                    NewFD->isCPUSpecificMultiVersion()) {
10529           // ignore this, we allow the redeclaration behavior here to create new
10530           // versions of the function.
10531         } else {
10532           // The user tried to provide an out-of-line definition for a
10533           // function that is a member of a class or namespace, but there
10534           // was no such member function declared (C++ [class.mfct]p2,
10535           // C++ [namespace.memdef]p2). For example:
10536           //
10537           // class X {
10538           //   void f() const;
10539           // };
10540           //
10541           // void X::f() { } // ill-formed
10542           //
10543           // Complain about this problem, and attempt to suggest close
10544           // matches (e.g., those that differ only in cv-qualifiers and
10545           // whether the parameter types are references).
10546 
10547           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10548                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10549             AddToScope = ExtraArgs.AddToScope;
10550             return Result;
10551           }
10552         }
10553 
10554         // Unqualified local friend declarations are required to resolve
10555         // to something.
10556       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10557         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10558                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10559           AddToScope = ExtraArgs.AddToScope;
10560           return Result;
10561         }
10562       }
10563     } else if (!D.isFunctionDefinition() &&
10564                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10565                !isFriend && !isFunctionTemplateSpecialization &&
10566                !isMemberSpecialization) {
10567       // An out-of-line member function declaration must also be a
10568       // definition (C++ [class.mfct]p2).
10569       // Note that this is not the case for explicit specializations of
10570       // function templates or member functions of class templates, per
10571       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10572       // extension for compatibility with old SWIG code which likes to
10573       // generate them.
10574       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10575         << D.getCXXScopeSpec().getRange();
10576     }
10577   }
10578 
10579   // If this is the first declaration of a library builtin function, add
10580   // attributes as appropriate.
10581   if (!D.isRedeclaration()) {
10582     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10583       if (unsigned BuiltinID = II->getBuiltinID()) {
10584         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10585         if (!InStdNamespace &&
10586             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10587           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10588             // Validate the type matches unless this builtin is specified as
10589             // matching regardless of its declared type.
10590             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10591               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10592             } else {
10593               ASTContext::GetBuiltinTypeError Error;
10594               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10595               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10596 
10597               if (!Error && !BuiltinType.isNull() &&
10598                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10599                       NewFD->getType(), BuiltinType))
10600                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10601             }
10602           }
10603         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10604                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10605           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10606         }
10607       }
10608     }
10609   }
10610 
10611   ProcessPragmaWeak(S, NewFD);
10612   checkAttributesAfterMerging(*this, *NewFD);
10613 
10614   AddKnownFunctionAttributes(NewFD);
10615 
10616   if (NewFD->hasAttr<OverloadableAttr>() &&
10617       !NewFD->getType()->getAs<FunctionProtoType>()) {
10618     Diag(NewFD->getLocation(),
10619          diag::err_attribute_overloadable_no_prototype)
10620       << NewFD;
10621     NewFD->dropAttr<OverloadableAttr>();
10622   }
10623 
10624   // If there's a #pragma GCC visibility in scope, and this isn't a class
10625   // member, set the visibility of this function.
10626   if (!DC->isRecord() && NewFD->isExternallyVisible())
10627     AddPushedVisibilityAttribute(NewFD);
10628 
10629   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10630   // marking the function.
10631   AddCFAuditedAttribute(NewFD);
10632 
10633   // If this is a function definition, check if we have to apply any
10634   // attributes (i.e. optnone and no_builtin) due to a pragma.
10635   if (D.isFunctionDefinition()) {
10636     AddRangeBasedOptnone(NewFD);
10637     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10638     AddSectionMSAllocText(NewFD);
10639     ModifyFnAttributesMSPragmaOptimize(NewFD);
10640   }
10641 
10642   // If this is the first declaration of an extern C variable, update
10643   // the map of such variables.
10644   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10645       isIncompleteDeclExternC(*this, NewFD))
10646     RegisterLocallyScopedExternCDecl(NewFD, S);
10647 
10648   // Set this FunctionDecl's range up to the right paren.
10649   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10650 
10651   if (D.isRedeclaration() && !Previous.empty()) {
10652     NamedDecl *Prev = Previous.getRepresentativeDecl();
10653     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10654                                    isMemberSpecialization ||
10655                                        isFunctionTemplateSpecialization,
10656                                    D.isFunctionDefinition());
10657   }
10658 
10659   if (getLangOpts().CUDA) {
10660     IdentifierInfo *II = NewFD->getIdentifier();
10661     if (II && II->isStr(getCudaConfigureFuncName()) &&
10662         !NewFD->isInvalidDecl() &&
10663         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10664       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10665         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10666             << getCudaConfigureFuncName();
10667       Context.setcudaConfigureCallDecl(NewFD);
10668     }
10669 
10670     // Variadic functions, other than a *declaration* of printf, are not allowed
10671     // in device-side CUDA code, unless someone passed
10672     // -fcuda-allow-variadic-functions.
10673     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10674         (NewFD->hasAttr<CUDADeviceAttr>() ||
10675          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10676         !(II && II->isStr("printf") && NewFD->isExternC() &&
10677           !D.isFunctionDefinition())) {
10678       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10679     }
10680   }
10681 
10682   MarkUnusedFileScopedDecl(NewFD);
10683 
10684 
10685 
10686   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10687     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10688     if (SC == SC_Static) {
10689       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10690       D.setInvalidType();
10691     }
10692 
10693     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10694     if (!NewFD->getReturnType()->isVoidType()) {
10695       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10696       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10697           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10698                                 : FixItHint());
10699       D.setInvalidType();
10700     }
10701 
10702     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10703     for (auto *Param : NewFD->parameters())
10704       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10705 
10706     if (getLangOpts().OpenCLCPlusPlus) {
10707       if (DC->isRecord()) {
10708         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10709         D.setInvalidType();
10710       }
10711       if (FunctionTemplate) {
10712         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10713         D.setInvalidType();
10714       }
10715     }
10716   }
10717 
10718   if (getLangOpts().CPlusPlus) {
10719     // Precalculate whether this is a friend function template with a constraint
10720     // that depends on an enclosing template, per [temp.friend]p9.
10721     if (isFriend && FunctionTemplate &&
10722         FriendConstraintsDependOnEnclosingTemplate(NewFD))
10723       NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10724 
10725     if (FunctionTemplate) {
10726       if (NewFD->isInvalidDecl())
10727         FunctionTemplate->setInvalidDecl();
10728       return FunctionTemplate;
10729     }
10730 
10731     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10732       CompleteMemberSpecialization(NewFD, Previous);
10733   }
10734 
10735   for (const ParmVarDecl *Param : NewFD->parameters()) {
10736     QualType PT = Param->getType();
10737 
10738     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10739     // types.
10740     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10741       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10742         QualType ElemTy = PipeTy->getElementType();
10743           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10744             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10745             D.setInvalidType();
10746           }
10747       }
10748     }
10749     // WebAssembly tables can't be used as function parameters.
10750     if (Context.getTargetInfo().getTriple().isWasm()) {
10751       if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10752         Diag(Param->getTypeSpecStartLoc(),
10753              diag::err_wasm_table_as_function_parameter);
10754         D.setInvalidType();
10755       }
10756     }
10757   }
10758 
10759   // Here we have an function template explicit specialization at class scope.
10760   // The actual specialization will be postponed to template instatiation
10761   // time via the ClassScopeFunctionSpecializationDecl node.
10762   if (isDependentClassScopeExplicitSpecialization) {
10763     ClassScopeFunctionSpecializationDecl *NewSpec =
10764                          ClassScopeFunctionSpecializationDecl::Create(
10765                                 Context, CurContext, NewFD->getLocation(),
10766                                 cast<CXXMethodDecl>(NewFD),
10767                                 HasExplicitTemplateArgs, TemplateArgs);
10768     CurContext->addDecl(NewSpec);
10769     AddToScope = false;
10770   }
10771 
10772   // Diagnose availability attributes. Availability cannot be used on functions
10773   // that are run during load/unload.
10774   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10775     if (NewFD->hasAttr<ConstructorAttr>()) {
10776       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10777           << 1;
10778       NewFD->dropAttr<AvailabilityAttr>();
10779     }
10780     if (NewFD->hasAttr<DestructorAttr>()) {
10781       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10782           << 2;
10783       NewFD->dropAttr<AvailabilityAttr>();
10784     }
10785   }
10786 
10787   // Diagnose no_builtin attribute on function declaration that are not a
10788   // definition.
10789   // FIXME: We should really be doing this in
10790   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10791   // the FunctionDecl and at this point of the code
10792   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10793   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10794   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10795     switch (D.getFunctionDefinitionKind()) {
10796     case FunctionDefinitionKind::Defaulted:
10797     case FunctionDefinitionKind::Deleted:
10798       Diag(NBA->getLocation(),
10799            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10800           << NBA->getSpelling();
10801       break;
10802     case FunctionDefinitionKind::Declaration:
10803       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10804           << NBA->getSpelling();
10805       break;
10806     case FunctionDefinitionKind::Definition:
10807       break;
10808     }
10809 
10810   return NewFD;
10811 }
10812 
10813 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10814 /// when __declspec(code_seg) "is applied to a class, all member functions of
10815 /// the class and nested classes -- this includes compiler-generated special
10816 /// member functions -- are put in the specified segment."
10817 /// The actual behavior is a little more complicated. The Microsoft compiler
10818 /// won't check outer classes if there is an active value from #pragma code_seg.
10819 /// The CodeSeg is always applied from the direct parent but only from outer
10820 /// classes when the #pragma code_seg stack is empty. See:
10821 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10822 /// available since MS has removed the page.
10823 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10824   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10825   if (!Method)
10826     return nullptr;
10827   const CXXRecordDecl *Parent = Method->getParent();
10828   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10829     Attr *NewAttr = SAttr->clone(S.getASTContext());
10830     NewAttr->setImplicit(true);
10831     return NewAttr;
10832   }
10833 
10834   // The Microsoft compiler won't check outer classes for the CodeSeg
10835   // when the #pragma code_seg stack is active.
10836   if (S.CodeSegStack.CurrentValue)
10837    return nullptr;
10838 
10839   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10840     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10841       Attr *NewAttr = SAttr->clone(S.getASTContext());
10842       NewAttr->setImplicit(true);
10843       return NewAttr;
10844     }
10845   }
10846   return nullptr;
10847 }
10848 
10849 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10850 /// containing class. Otherwise it will return implicit SectionAttr if the
10851 /// function is a definition and there is an active value on CodeSegStack
10852 /// (from the current #pragma code-seg value).
10853 ///
10854 /// \param FD Function being declared.
10855 /// \param IsDefinition Whether it is a definition or just a declaration.
10856 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10857 ///          nullptr if no attribute should be added.
10858 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10859                                                        bool IsDefinition) {
10860   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10861     return A;
10862   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10863       CodeSegStack.CurrentValue)
10864     return SectionAttr::CreateImplicit(
10865         getASTContext(), CodeSegStack.CurrentValue->getString(),
10866         CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10867   return nullptr;
10868 }
10869 
10870 /// Determines if we can perform a correct type check for \p D as a
10871 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10872 /// best-effort check.
10873 ///
10874 /// \param NewD The new declaration.
10875 /// \param OldD The old declaration.
10876 /// \param NewT The portion of the type of the new declaration to check.
10877 /// \param OldT The portion of the type of the old declaration to check.
10878 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10879                                           QualType NewT, QualType OldT) {
10880   if (!NewD->getLexicalDeclContext()->isDependentContext())
10881     return true;
10882 
10883   // For dependently-typed local extern declarations and friends, we can't
10884   // perform a correct type check in general until instantiation:
10885   //
10886   //   int f();
10887   //   template<typename T> void g() { T f(); }
10888   //
10889   // (valid if g() is only instantiated with T = int).
10890   if (NewT->isDependentType() &&
10891       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10892     return false;
10893 
10894   // Similarly, if the previous declaration was a dependent local extern
10895   // declaration, we don't really know its type yet.
10896   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10897     return false;
10898 
10899   return true;
10900 }
10901 
10902 /// Checks if the new declaration declared in dependent context must be
10903 /// put in the same redeclaration chain as the specified declaration.
10904 ///
10905 /// \param D Declaration that is checked.
10906 /// \param PrevDecl Previous declaration found with proper lookup method for the
10907 ///                 same declaration name.
10908 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10909 ///          belongs to.
10910 ///
10911 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10912   if (!D->getLexicalDeclContext()->isDependentContext())
10913     return true;
10914 
10915   // Don't chain dependent friend function definitions until instantiation, to
10916   // permit cases like
10917   //
10918   //   void func();
10919   //   template<typename T> class C1 { friend void func() {} };
10920   //   template<typename T> class C2 { friend void func() {} };
10921   //
10922   // ... which is valid if only one of C1 and C2 is ever instantiated.
10923   //
10924   // FIXME: This need only apply to function definitions. For now, we proxy
10925   // this by checking for a file-scope function. We do not want this to apply
10926   // to friend declarations nominating member functions, because that gets in
10927   // the way of access checks.
10928   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10929     return false;
10930 
10931   auto *VD = dyn_cast<ValueDecl>(D);
10932   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10933   return !VD || !PrevVD ||
10934          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10935                                         PrevVD->getType());
10936 }
10937 
10938 /// Check the target or target_version attribute of the function for
10939 /// MultiVersion validity.
10940 ///
10941 /// Returns true if there was an error, false otherwise.
10942 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10943   const auto *TA = FD->getAttr<TargetAttr>();
10944   const auto *TVA = FD->getAttr<TargetVersionAttr>();
10945   assert(
10946       (TA || TVA) &&
10947       "MultiVersion candidate requires a target or target_version attribute");
10948   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10949   enum ErrType { Feature = 0, Architecture = 1 };
10950 
10951   if (TA) {
10952     ParsedTargetAttr ParseInfo =
10953         S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10954     if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10955       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10956           << Architecture << ParseInfo.CPU;
10957       return true;
10958     }
10959     for (const auto &Feat : ParseInfo.Features) {
10960       auto BareFeat = StringRef{Feat}.substr(1);
10961       if (Feat[0] == '-') {
10962         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10963             << Feature << ("no-" + BareFeat).str();
10964         return true;
10965       }
10966 
10967       if (!TargetInfo.validateCpuSupports(BareFeat) ||
10968           !TargetInfo.isValidFeatureName(BareFeat)) {
10969         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10970             << Feature << BareFeat;
10971         return true;
10972       }
10973     }
10974   }
10975 
10976   if (TVA) {
10977     llvm::SmallVector<StringRef, 8> Feats;
10978     TVA->getFeatures(Feats);
10979     for (const auto &Feat : Feats) {
10980       if (!TargetInfo.validateCpuSupports(Feat)) {
10981         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10982             << Feature << Feat;
10983         return true;
10984       }
10985     }
10986   }
10987   return false;
10988 }
10989 
10990 // Provide a white-list of attributes that are allowed to be combined with
10991 // multiversion functions.
10992 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10993                                            MultiVersionKind MVKind) {
10994   // Note: this list/diagnosis must match the list in
10995   // checkMultiversionAttributesAllSame.
10996   switch (Kind) {
10997   default:
10998     return false;
10999   case attr::Used:
11000     return MVKind == MultiVersionKind::Target;
11001   case attr::NonNull:
11002   case attr::NoThrow:
11003     return true;
11004   }
11005 }
11006 
11007 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11008                                                  const FunctionDecl *FD,
11009                                                  const FunctionDecl *CausedFD,
11010                                                  MultiVersionKind MVKind) {
11011   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11012     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11013         << static_cast<unsigned>(MVKind) << A;
11014     if (CausedFD)
11015       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11016     return true;
11017   };
11018 
11019   for (const Attr *A : FD->attrs()) {
11020     switch (A->getKind()) {
11021     case attr::CPUDispatch:
11022     case attr::CPUSpecific:
11023       if (MVKind != MultiVersionKind::CPUDispatch &&
11024           MVKind != MultiVersionKind::CPUSpecific)
11025         return Diagnose(S, A);
11026       break;
11027     case attr::Target:
11028       if (MVKind != MultiVersionKind::Target)
11029         return Diagnose(S, A);
11030       break;
11031     case attr::TargetVersion:
11032       if (MVKind != MultiVersionKind::TargetVersion)
11033         return Diagnose(S, A);
11034       break;
11035     case attr::TargetClones:
11036       if (MVKind != MultiVersionKind::TargetClones)
11037         return Diagnose(S, A);
11038       break;
11039     default:
11040       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11041         return Diagnose(S, A);
11042       break;
11043     }
11044   }
11045   return false;
11046 }
11047 
11048 bool Sema::areMultiversionVariantFunctionsCompatible(
11049     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11050     const PartialDiagnostic &NoProtoDiagID,
11051     const PartialDiagnosticAt &NoteCausedDiagIDAt,
11052     const PartialDiagnosticAt &NoSupportDiagIDAt,
11053     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11054     bool ConstexprSupported, bool CLinkageMayDiffer) {
11055   enum DoesntSupport {
11056     FuncTemplates = 0,
11057     VirtFuncs = 1,
11058     DeducedReturn = 2,
11059     Constructors = 3,
11060     Destructors = 4,
11061     DeletedFuncs = 5,
11062     DefaultedFuncs = 6,
11063     ConstexprFuncs = 7,
11064     ConstevalFuncs = 8,
11065     Lambda = 9,
11066   };
11067   enum Different {
11068     CallingConv = 0,
11069     ReturnType = 1,
11070     ConstexprSpec = 2,
11071     InlineSpec = 3,
11072     Linkage = 4,
11073     LanguageLinkage = 5,
11074   };
11075 
11076   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11077       !OldFD->getType()->getAs<FunctionProtoType>()) {
11078     Diag(OldFD->getLocation(), NoProtoDiagID);
11079     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11080     return true;
11081   }
11082 
11083   if (NoProtoDiagID.getDiagID() != 0 &&
11084       !NewFD->getType()->getAs<FunctionProtoType>())
11085     return Diag(NewFD->getLocation(), NoProtoDiagID);
11086 
11087   if (!TemplatesSupported &&
11088       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11089     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11090            << FuncTemplates;
11091 
11092   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11093     if (NewCXXFD->isVirtual())
11094       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11095              << VirtFuncs;
11096 
11097     if (isa<CXXConstructorDecl>(NewCXXFD))
11098       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11099              << Constructors;
11100 
11101     if (isa<CXXDestructorDecl>(NewCXXFD))
11102       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11103              << Destructors;
11104   }
11105 
11106   if (NewFD->isDeleted())
11107     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11108            << DeletedFuncs;
11109 
11110   if (NewFD->isDefaulted())
11111     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11112            << DefaultedFuncs;
11113 
11114   if (!ConstexprSupported && NewFD->isConstexpr())
11115     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11116            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11117 
11118   QualType NewQType = Context.getCanonicalType(NewFD->getType());
11119   const auto *NewType = cast<FunctionType>(NewQType);
11120   QualType NewReturnType = NewType->getReturnType();
11121 
11122   if (NewReturnType->isUndeducedType())
11123     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11124            << DeducedReturn;
11125 
11126   // Ensure the return type is identical.
11127   if (OldFD) {
11128     QualType OldQType = Context.getCanonicalType(OldFD->getType());
11129     const auto *OldType = cast<FunctionType>(OldQType);
11130     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11131     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11132 
11133     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11134       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11135 
11136     QualType OldReturnType = OldType->getReturnType();
11137 
11138     if (OldReturnType != NewReturnType)
11139       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11140 
11141     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11142       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11143 
11144     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11145       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11146 
11147     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11148       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11149 
11150     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11151       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11152 
11153     if (CheckEquivalentExceptionSpec(
11154             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11155             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11156       return true;
11157   }
11158   return false;
11159 }
11160 
11161 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11162                                              const FunctionDecl *NewFD,
11163                                              bool CausesMV,
11164                                              MultiVersionKind MVKind) {
11165   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11166     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11167     if (OldFD)
11168       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11169     return true;
11170   }
11171 
11172   bool IsCPUSpecificCPUDispatchMVKind =
11173       MVKind == MultiVersionKind::CPUDispatch ||
11174       MVKind == MultiVersionKind::CPUSpecific;
11175 
11176   if (CausesMV && OldFD &&
11177       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11178     return true;
11179 
11180   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11181     return true;
11182 
11183   // Only allow transition to MultiVersion if it hasn't been used.
11184   if (OldFD && CausesMV && OldFD->isUsed(false))
11185     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11186 
11187   return S.areMultiversionVariantFunctionsCompatible(
11188       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11189       PartialDiagnosticAt(NewFD->getLocation(),
11190                           S.PDiag(diag::note_multiversioning_caused_here)),
11191       PartialDiagnosticAt(NewFD->getLocation(),
11192                           S.PDiag(diag::err_multiversion_doesnt_support)
11193                               << static_cast<unsigned>(MVKind)),
11194       PartialDiagnosticAt(NewFD->getLocation(),
11195                           S.PDiag(diag::err_multiversion_diff)),
11196       /*TemplatesSupported=*/false,
11197       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11198       /*CLinkageMayDiffer=*/false);
11199 }
11200 
11201 /// Check the validity of a multiversion function declaration that is the
11202 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11203 ///
11204 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11205 ///
11206 /// Returns true if there was an error, false otherwise.
11207 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11208   MultiVersionKind MVKind = FD->getMultiVersionKind();
11209   assert(MVKind != MultiVersionKind::None &&
11210          "Function lacks multiversion attribute");
11211   const auto *TA = FD->getAttr<TargetAttr>();
11212   const auto *TVA = FD->getAttr<TargetVersionAttr>();
11213   // Target and target_version only causes MV if it is default, otherwise this
11214   // is a normal function.
11215   if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11216     return false;
11217 
11218   if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11219     FD->setInvalidDecl();
11220     return true;
11221   }
11222 
11223   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11224     FD->setInvalidDecl();
11225     return true;
11226   }
11227 
11228   FD->setIsMultiVersion();
11229   return false;
11230 }
11231 
11232 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11233   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11234     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11235       return true;
11236   }
11237 
11238   return false;
11239 }
11240 
11241 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11242                                              FunctionDecl *NewFD,
11243                                              bool &Redeclaration,
11244                                              NamedDecl *&OldDecl,
11245                                              LookupResult &Previous) {
11246   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11247   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11248   const auto *OldTA = OldFD->getAttr<TargetAttr>();
11249   const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11250   // If the old decl is NOT MultiVersioned yet, and we don't cause that
11251   // to change, this is a simple redeclaration.
11252   if ((NewTA && !NewTA->isDefaultVersion() &&
11253        (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11254       (NewTVA && !NewTVA->isDefaultVersion() &&
11255        (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11256     return false;
11257 
11258   // Otherwise, this decl causes MultiVersioning.
11259   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11260                                        NewTVA ? MultiVersionKind::TargetVersion
11261                                               : MultiVersionKind::Target)) {
11262     NewFD->setInvalidDecl();
11263     return true;
11264   }
11265 
11266   if (CheckMultiVersionValue(S, NewFD)) {
11267     NewFD->setInvalidDecl();
11268     return true;
11269   }
11270 
11271   // If this is 'default', permit the forward declaration.
11272   if (!OldFD->isMultiVersion() &&
11273       ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11274        (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11275     Redeclaration = true;
11276     OldDecl = OldFD;
11277     OldFD->setIsMultiVersion();
11278     NewFD->setIsMultiVersion();
11279     return false;
11280   }
11281 
11282   if (CheckMultiVersionValue(S, OldFD)) {
11283     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11284     NewFD->setInvalidDecl();
11285     return true;
11286   }
11287 
11288   if (NewTA) {
11289     ParsedTargetAttr OldParsed =
11290         S.getASTContext().getTargetInfo().parseTargetAttr(
11291             OldTA->getFeaturesStr());
11292     llvm::sort(OldParsed.Features);
11293     ParsedTargetAttr NewParsed =
11294         S.getASTContext().getTargetInfo().parseTargetAttr(
11295             NewTA->getFeaturesStr());
11296     // Sort order doesn't matter, it just needs to be consistent.
11297     llvm::sort(NewParsed.Features);
11298     if (OldParsed == NewParsed) {
11299       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11300       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11301       NewFD->setInvalidDecl();
11302       return true;
11303     }
11304   }
11305 
11306   if (NewTVA) {
11307     llvm::SmallVector<StringRef, 8> Feats;
11308     OldTVA->getFeatures(Feats);
11309     llvm::sort(Feats);
11310     llvm::SmallVector<StringRef, 8> NewFeats;
11311     NewTVA->getFeatures(NewFeats);
11312     llvm::sort(NewFeats);
11313 
11314     if (Feats == NewFeats) {
11315       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11316       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11317       NewFD->setInvalidDecl();
11318       return true;
11319     }
11320   }
11321 
11322   for (const auto *FD : OldFD->redecls()) {
11323     const auto *CurTA = FD->getAttr<TargetAttr>();
11324     const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11325     // We allow forward declarations before ANY multiversioning attributes, but
11326     // nothing after the fact.
11327     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11328         ((NewTA && (!CurTA || CurTA->isInherited())) ||
11329          (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11330       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11331           << (NewTA ? 0 : 2);
11332       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11333       NewFD->setInvalidDecl();
11334       return true;
11335     }
11336   }
11337 
11338   OldFD->setIsMultiVersion();
11339   NewFD->setIsMultiVersion();
11340   Redeclaration = false;
11341   OldDecl = nullptr;
11342   Previous.clear();
11343   return false;
11344 }
11345 
11346 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11347                                         MultiVersionKind New) {
11348   if (Old == New || Old == MultiVersionKind::None ||
11349       New == MultiVersionKind::None)
11350     return true;
11351 
11352   return (Old == MultiVersionKind::CPUDispatch &&
11353           New == MultiVersionKind::CPUSpecific) ||
11354          (Old == MultiVersionKind::CPUSpecific &&
11355           New == MultiVersionKind::CPUDispatch);
11356 }
11357 
11358 /// Check the validity of a new function declaration being added to an existing
11359 /// multiversioned declaration collection.
11360 static bool CheckMultiVersionAdditionalDecl(
11361     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11362     MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11363     const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11364     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11365   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11366   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11367   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11368   // Disallow mixing of multiversioning types.
11369   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11370     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11371     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11372     NewFD->setInvalidDecl();
11373     return true;
11374   }
11375 
11376   ParsedTargetAttr NewParsed;
11377   if (NewTA) {
11378     NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11379         NewTA->getFeaturesStr());
11380     llvm::sort(NewParsed.Features);
11381   }
11382   llvm::SmallVector<StringRef, 8> NewFeats;
11383   if (NewTVA) {
11384     NewTVA->getFeatures(NewFeats);
11385     llvm::sort(NewFeats);
11386   }
11387 
11388   bool UseMemberUsingDeclRules =
11389       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11390 
11391   bool MayNeedOverloadableChecks =
11392       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11393 
11394   // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11395   // of a previous member of the MultiVersion set.
11396   for (NamedDecl *ND : Previous) {
11397     FunctionDecl *CurFD = ND->getAsFunction();
11398     if (!CurFD || CurFD->isInvalidDecl())
11399       continue;
11400     if (MayNeedOverloadableChecks &&
11401         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11402       continue;
11403 
11404     if (NewMVKind == MultiVersionKind::None &&
11405         OldMVKind == MultiVersionKind::TargetVersion) {
11406       NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11407           S.Context, "default", NewFD->getSourceRange()));
11408       NewFD->setIsMultiVersion();
11409       NewMVKind = MultiVersionKind::TargetVersion;
11410       if (!NewTVA) {
11411         NewTVA = NewFD->getAttr<TargetVersionAttr>();
11412         NewTVA->getFeatures(NewFeats);
11413         llvm::sort(NewFeats);
11414       }
11415     }
11416 
11417     switch (NewMVKind) {
11418     case MultiVersionKind::None:
11419       assert(OldMVKind == MultiVersionKind::TargetClones &&
11420              "Only target_clones can be omitted in subsequent declarations");
11421       break;
11422     case MultiVersionKind::Target: {
11423       const auto *CurTA = CurFD->getAttr<TargetAttr>();
11424       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11425         NewFD->setIsMultiVersion();
11426         Redeclaration = true;
11427         OldDecl = ND;
11428         return false;
11429       }
11430 
11431       ParsedTargetAttr CurParsed =
11432           S.getASTContext().getTargetInfo().parseTargetAttr(
11433               CurTA->getFeaturesStr());
11434       llvm::sort(CurParsed.Features);
11435       if (CurParsed == NewParsed) {
11436         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11437         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11438         NewFD->setInvalidDecl();
11439         return true;
11440       }
11441       break;
11442     }
11443     case MultiVersionKind::TargetVersion: {
11444       const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11445       if (CurTVA->getName() == NewTVA->getName()) {
11446         NewFD->setIsMultiVersion();
11447         Redeclaration = true;
11448         OldDecl = ND;
11449         return false;
11450       }
11451       llvm::SmallVector<StringRef, 8> CurFeats;
11452       if (CurTVA) {
11453         CurTVA->getFeatures(CurFeats);
11454         llvm::sort(CurFeats);
11455       }
11456       if (CurFeats == NewFeats) {
11457         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11458         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11459         NewFD->setInvalidDecl();
11460         return true;
11461       }
11462       break;
11463     }
11464     case MultiVersionKind::TargetClones: {
11465       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11466       Redeclaration = true;
11467       OldDecl = CurFD;
11468       NewFD->setIsMultiVersion();
11469 
11470       if (CurClones && NewClones &&
11471           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11472            !std::equal(CurClones->featuresStrs_begin(),
11473                        CurClones->featuresStrs_end(),
11474                        NewClones->featuresStrs_begin()))) {
11475         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11476         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11477         NewFD->setInvalidDecl();
11478         return true;
11479       }
11480 
11481       return false;
11482     }
11483     case MultiVersionKind::CPUSpecific:
11484     case MultiVersionKind::CPUDispatch: {
11485       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11486       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11487       // Handle CPUDispatch/CPUSpecific versions.
11488       // Only 1 CPUDispatch function is allowed, this will make it go through
11489       // the redeclaration errors.
11490       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11491           CurFD->hasAttr<CPUDispatchAttr>()) {
11492         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11493             std::equal(
11494                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11495                 NewCPUDisp->cpus_begin(),
11496                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11497                   return Cur->getName() == New->getName();
11498                 })) {
11499           NewFD->setIsMultiVersion();
11500           Redeclaration = true;
11501           OldDecl = ND;
11502           return false;
11503         }
11504 
11505         // If the declarations don't match, this is an error condition.
11506         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11507         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11508         NewFD->setInvalidDecl();
11509         return true;
11510       }
11511       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11512         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11513             std::equal(
11514                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11515                 NewCPUSpec->cpus_begin(),
11516                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11517                   return Cur->getName() == New->getName();
11518                 })) {
11519           NewFD->setIsMultiVersion();
11520           Redeclaration = true;
11521           OldDecl = ND;
11522           return false;
11523         }
11524 
11525         // Only 1 version of CPUSpecific is allowed for each CPU.
11526         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11527           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11528             if (CurII == NewII) {
11529               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11530                   << NewII;
11531               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11532               NewFD->setInvalidDecl();
11533               return true;
11534             }
11535           }
11536         }
11537       }
11538       break;
11539     }
11540     }
11541   }
11542 
11543   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11544   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11545   // handled in the attribute adding step.
11546   if ((NewMVKind == MultiVersionKind::TargetVersion ||
11547        NewMVKind == MultiVersionKind::Target) &&
11548       CheckMultiVersionValue(S, NewFD)) {
11549     NewFD->setInvalidDecl();
11550     return true;
11551   }
11552 
11553   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11554                                        !OldFD->isMultiVersion(), NewMVKind)) {
11555     NewFD->setInvalidDecl();
11556     return true;
11557   }
11558 
11559   // Permit forward declarations in the case where these two are compatible.
11560   if (!OldFD->isMultiVersion()) {
11561     OldFD->setIsMultiVersion();
11562     NewFD->setIsMultiVersion();
11563     Redeclaration = true;
11564     OldDecl = OldFD;
11565     return false;
11566   }
11567 
11568   NewFD->setIsMultiVersion();
11569   Redeclaration = false;
11570   OldDecl = nullptr;
11571   Previous.clear();
11572   return false;
11573 }
11574 
11575 /// Check the validity of a mulitversion function declaration.
11576 /// Also sets the multiversion'ness' of the function itself.
11577 ///
11578 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11579 ///
11580 /// Returns true if there was an error, false otherwise.
11581 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11582                                       bool &Redeclaration, NamedDecl *&OldDecl,
11583                                       LookupResult &Previous) {
11584   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11585   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11586   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11587   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11588   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11589   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11590 
11591   // Main isn't allowed to become a multiversion function, however it IS
11592   // permitted to have 'main' be marked with the 'target' optimization hint,
11593   // for 'target_version' only default is allowed.
11594   if (NewFD->isMain()) {
11595     if (MVKind != MultiVersionKind::None &&
11596         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11597         !(MVKind == MultiVersionKind::TargetVersion &&
11598           NewTVA->isDefaultVersion())) {
11599       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11600       NewFD->setInvalidDecl();
11601       return true;
11602     }
11603     return false;
11604   }
11605 
11606   // Target attribute on AArch64 is not used for multiversioning
11607   if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11608     return false;
11609 
11610   if (!OldDecl || !OldDecl->getAsFunction() ||
11611       OldDecl->getDeclContext()->getRedeclContext() !=
11612           NewFD->getDeclContext()->getRedeclContext()) {
11613     // If there's no previous declaration, AND this isn't attempting to cause
11614     // multiversioning, this isn't an error condition.
11615     if (MVKind == MultiVersionKind::None)
11616       return false;
11617     return CheckMultiVersionFirstFunction(S, NewFD);
11618   }
11619 
11620   FunctionDecl *OldFD = OldDecl->getAsFunction();
11621 
11622   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11623     // No target_version attributes mean default
11624     if (!NewTVA) {
11625       const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11626       if (OldTVA) {
11627         NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11628             S.Context, "default", NewFD->getSourceRange()));
11629         NewFD->setIsMultiVersion();
11630         OldFD->setIsMultiVersion();
11631         OldDecl = OldFD;
11632         Redeclaration = true;
11633         return true;
11634       }
11635     }
11636     return false;
11637   }
11638 
11639   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11640   // for target_clones and target_version.
11641   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11642       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11643       OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11644     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11645         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11646     NewFD->setInvalidDecl();
11647     return true;
11648   }
11649 
11650   if (!OldFD->isMultiVersion()) {
11651     switch (MVKind) {
11652     case MultiVersionKind::Target:
11653     case MultiVersionKind::TargetVersion:
11654       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11655                                               OldDecl, Previous);
11656     case MultiVersionKind::TargetClones:
11657       if (OldFD->isUsed(false)) {
11658         NewFD->setInvalidDecl();
11659         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11660       }
11661       OldFD->setIsMultiVersion();
11662       break;
11663 
11664     case MultiVersionKind::CPUDispatch:
11665     case MultiVersionKind::CPUSpecific:
11666     case MultiVersionKind::None:
11667       break;
11668     }
11669   }
11670 
11671   // At this point, we have a multiversion function decl (in OldFD) AND an
11672   // appropriate attribute in the current function decl.  Resolve that these are
11673   // still compatible with previous declarations.
11674   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11675                                          NewCPUSpec, NewClones, Redeclaration,
11676                                          OldDecl, Previous);
11677 }
11678 
11679 /// Perform semantic checking of a new function declaration.
11680 ///
11681 /// Performs semantic analysis of the new function declaration
11682 /// NewFD. This routine performs all semantic checking that does not
11683 /// require the actual declarator involved in the declaration, and is
11684 /// used both for the declaration of functions as they are parsed
11685 /// (called via ActOnDeclarator) and for the declaration of functions
11686 /// that have been instantiated via C++ template instantiation (called
11687 /// via InstantiateDecl).
11688 ///
11689 /// \param IsMemberSpecialization whether this new function declaration is
11690 /// a member specialization (that replaces any definition provided by the
11691 /// previous declaration).
11692 ///
11693 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11694 ///
11695 /// \returns true if the function declaration is a redeclaration.
11696 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11697                                     LookupResult &Previous,
11698                                     bool IsMemberSpecialization,
11699                                     bool DeclIsDefn) {
11700   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11701          "Variably modified return types are not handled here");
11702 
11703   // Determine whether the type of this function should be merged with
11704   // a previous visible declaration. This never happens for functions in C++,
11705   // and always happens in C if the previous declaration was visible.
11706   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11707                                !Previous.isShadowed();
11708 
11709   bool Redeclaration = false;
11710   NamedDecl *OldDecl = nullptr;
11711   bool MayNeedOverloadableChecks = false;
11712 
11713   // Merge or overload the declaration with an existing declaration of
11714   // the same name, if appropriate.
11715   if (!Previous.empty()) {
11716     // Determine whether NewFD is an overload of PrevDecl or
11717     // a declaration that requires merging. If it's an overload,
11718     // there's no more work to do here; we'll just add the new
11719     // function to the scope.
11720     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11721       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11722       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11723         Redeclaration = true;
11724         OldDecl = Candidate;
11725       }
11726     } else {
11727       MayNeedOverloadableChecks = true;
11728       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11729                             /*NewIsUsingDecl*/ false)) {
11730       case Ovl_Match:
11731         Redeclaration = true;
11732         break;
11733 
11734       case Ovl_NonFunction:
11735         Redeclaration = true;
11736         break;
11737 
11738       case Ovl_Overload:
11739         Redeclaration = false;
11740         break;
11741       }
11742     }
11743   }
11744 
11745   // Check for a previous extern "C" declaration with this name.
11746   if (!Redeclaration &&
11747       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11748     if (!Previous.empty()) {
11749       // This is an extern "C" declaration with the same name as a previous
11750       // declaration, and thus redeclares that entity...
11751       Redeclaration = true;
11752       OldDecl = Previous.getFoundDecl();
11753       MergeTypeWithPrevious = false;
11754 
11755       // ... except in the presence of __attribute__((overloadable)).
11756       if (OldDecl->hasAttr<OverloadableAttr>() ||
11757           NewFD->hasAttr<OverloadableAttr>()) {
11758         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11759           MayNeedOverloadableChecks = true;
11760           Redeclaration = false;
11761           OldDecl = nullptr;
11762         }
11763       }
11764     }
11765   }
11766 
11767   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11768     return Redeclaration;
11769 
11770   // PPC MMA non-pointer types are not allowed as function return types.
11771   if (Context.getTargetInfo().getTriple().isPPC64() &&
11772       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11773     NewFD->setInvalidDecl();
11774   }
11775 
11776   // C++11 [dcl.constexpr]p8:
11777   //   A constexpr specifier for a non-static member function that is not
11778   //   a constructor declares that member function to be const.
11779   //
11780   // This needs to be delayed until we know whether this is an out-of-line
11781   // definition of a static member function.
11782   //
11783   // This rule is not present in C++1y, so we produce a backwards
11784   // compatibility warning whenever it happens in C++11.
11785   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11786   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11787       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11788       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11789     CXXMethodDecl *OldMD = nullptr;
11790     if (OldDecl)
11791       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11792     if (!OldMD || !OldMD->isStatic()) {
11793       const FunctionProtoType *FPT =
11794         MD->getType()->castAs<FunctionProtoType>();
11795       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11796       EPI.TypeQuals.addConst();
11797       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11798                                           FPT->getParamTypes(), EPI));
11799 
11800       // Warn that we did this, if we're not performing template instantiation.
11801       // In that case, we'll have warned already when the template was defined.
11802       if (!inTemplateInstantiation()) {
11803         SourceLocation AddConstLoc;
11804         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11805                 .IgnoreParens().getAs<FunctionTypeLoc>())
11806           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11807 
11808         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11809           << FixItHint::CreateInsertion(AddConstLoc, " const");
11810       }
11811     }
11812   }
11813 
11814   if (Redeclaration) {
11815     // NewFD and OldDecl represent declarations that need to be
11816     // merged.
11817     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11818                           DeclIsDefn)) {
11819       NewFD->setInvalidDecl();
11820       return Redeclaration;
11821     }
11822 
11823     Previous.clear();
11824     Previous.addDecl(OldDecl);
11825 
11826     if (FunctionTemplateDecl *OldTemplateDecl =
11827             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11828       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11829       FunctionTemplateDecl *NewTemplateDecl
11830         = NewFD->getDescribedFunctionTemplate();
11831       assert(NewTemplateDecl && "Template/non-template mismatch");
11832 
11833       // The call to MergeFunctionDecl above may have created some state in
11834       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11835       // can add it as a redeclaration.
11836       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11837 
11838       NewFD->setPreviousDeclaration(OldFD);
11839       if (NewFD->isCXXClassMember()) {
11840         NewFD->setAccess(OldTemplateDecl->getAccess());
11841         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11842       }
11843 
11844       // If this is an explicit specialization of a member that is a function
11845       // template, mark it as a member specialization.
11846       if (IsMemberSpecialization &&
11847           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11848         NewTemplateDecl->setMemberSpecialization();
11849         assert(OldTemplateDecl->isMemberSpecialization());
11850         // Explicit specializations of a member template do not inherit deleted
11851         // status from the parent member template that they are specializing.
11852         if (OldFD->isDeleted()) {
11853           // FIXME: This assert will not hold in the presence of modules.
11854           assert(OldFD->getCanonicalDecl() == OldFD);
11855           // FIXME: We need an update record for this AST mutation.
11856           OldFD->setDeletedAsWritten(false);
11857         }
11858       }
11859 
11860     } else {
11861       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11862         auto *OldFD = cast<FunctionDecl>(OldDecl);
11863         // This needs to happen first so that 'inline' propagates.
11864         NewFD->setPreviousDeclaration(OldFD);
11865         if (NewFD->isCXXClassMember())
11866           NewFD->setAccess(OldFD->getAccess());
11867       }
11868     }
11869   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11870              !NewFD->getAttr<OverloadableAttr>()) {
11871     assert((Previous.empty() ||
11872             llvm::any_of(Previous,
11873                          [](const NamedDecl *ND) {
11874                            return ND->hasAttr<OverloadableAttr>();
11875                          })) &&
11876            "Non-redecls shouldn't happen without overloadable present");
11877 
11878     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11879       const auto *FD = dyn_cast<FunctionDecl>(ND);
11880       return FD && !FD->hasAttr<OverloadableAttr>();
11881     });
11882 
11883     if (OtherUnmarkedIter != Previous.end()) {
11884       Diag(NewFD->getLocation(),
11885            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11886       Diag((*OtherUnmarkedIter)->getLocation(),
11887            diag::note_attribute_overloadable_prev_overload)
11888           << false;
11889 
11890       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11891     }
11892   }
11893 
11894   if (LangOpts.OpenMP)
11895     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11896 
11897   // Semantic checking for this function declaration (in isolation).
11898 
11899   if (getLangOpts().CPlusPlus) {
11900     // C++-specific checks.
11901     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11902       CheckConstructor(Constructor);
11903     } else if (CXXDestructorDecl *Destructor =
11904                    dyn_cast<CXXDestructorDecl>(NewFD)) {
11905       // We check here for invalid destructor names.
11906       // If we have a friend destructor declaration that is dependent, we can't
11907       // diagnose right away because cases like this are still valid:
11908       // template <class T> struct A { friend T::X::~Y(); };
11909       // struct B { struct Y { ~Y(); }; using X = Y; };
11910       // template struct A<B>;
11911       if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11912           !Destructor->getThisType()->isDependentType()) {
11913         CXXRecordDecl *Record = Destructor->getParent();
11914         QualType ClassType = Context.getTypeDeclType(Record);
11915 
11916         DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11917             Context.getCanonicalType(ClassType));
11918         if (NewFD->getDeclName() != Name) {
11919           Diag(NewFD->getLocation(), diag::err_destructor_name);
11920           NewFD->setInvalidDecl();
11921           return Redeclaration;
11922         }
11923       }
11924     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11925       if (auto *TD = Guide->getDescribedFunctionTemplate())
11926         CheckDeductionGuideTemplate(TD);
11927 
11928       // A deduction guide is not on the list of entities that can be
11929       // explicitly specialized.
11930       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11931         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11932             << /*explicit specialization*/ 1;
11933     }
11934 
11935     // Find any virtual functions that this function overrides.
11936     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11937       if (!Method->isFunctionTemplateSpecialization() &&
11938           !Method->getDescribedFunctionTemplate() &&
11939           Method->isCanonicalDecl()) {
11940         AddOverriddenMethods(Method->getParent(), Method);
11941       }
11942       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11943         // C++2a [class.virtual]p6
11944         // A virtual method shall not have a requires-clause.
11945         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11946              diag::err_constrained_virtual_method);
11947 
11948       if (Method->isStatic())
11949         checkThisInStaticMemberFunctionType(Method);
11950     }
11951 
11952     // C++20: dcl.decl.general p4:
11953     // The optional requires-clause ([temp.pre]) in an init-declarator or
11954     // member-declarator shall be present only if the declarator declares a
11955     // templated function ([dcl.fct]).
11956     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11957       // [temp.pre]/8:
11958       // An entity is templated if it is
11959       // - a template,
11960       // - an entity defined ([basic.def]) or created ([class.temporary]) in a
11961       // templated entity,
11962       // - a member of a templated entity,
11963       // - an enumerator for an enumeration that is a templated entity, or
11964       // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
11965       // appearing in the declaration of a templated entity. [Note 6: A local
11966       // class, a local or block variable, or a friend function defined in a
11967       // templated entity is a templated entity.  — end note]
11968       //
11969       // A templated function is a function template or a function that is
11970       // templated. A templated class is a class template or a class that is
11971       // templated. A templated variable is a variable template or a variable
11972       // that is templated.
11973 
11974       if (!NewFD->getDescribedFunctionTemplate() && // -a template
11975           // defined... in a templated entity
11976           !(DeclIsDefn && NewFD->isTemplated()) &&
11977           // a member of a templated entity
11978           !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
11979           // Don't complain about instantiations, they've already had these
11980           // rules + others enforced.
11981           !NewFD->isTemplateInstantiation()) {
11982         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11983       }
11984     }
11985 
11986     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11987       ActOnConversionDeclarator(Conversion);
11988 
11989     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11990     if (NewFD->isOverloadedOperator() &&
11991         CheckOverloadedOperatorDeclaration(NewFD)) {
11992       NewFD->setInvalidDecl();
11993       return Redeclaration;
11994     }
11995 
11996     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11997     if (NewFD->getLiteralIdentifier() &&
11998         CheckLiteralOperatorDeclaration(NewFD)) {
11999       NewFD->setInvalidDecl();
12000       return Redeclaration;
12001     }
12002 
12003     // In C++, check default arguments now that we have merged decls. Unless
12004     // the lexical context is the class, because in this case this is done
12005     // during delayed parsing anyway.
12006     if (!CurContext->isRecord())
12007       CheckCXXDefaultArguments(NewFD);
12008 
12009     // If this function is declared as being extern "C", then check to see if
12010     // the function returns a UDT (class, struct, or union type) that is not C
12011     // compatible, and if it does, warn the user.
12012     // But, issue any diagnostic on the first declaration only.
12013     if (Previous.empty() && NewFD->isExternC()) {
12014       QualType R = NewFD->getReturnType();
12015       if (R->isIncompleteType() && !R->isVoidType())
12016         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12017             << NewFD << R;
12018       else if (!R.isPODType(Context) && !R->isVoidType() &&
12019                !R->isObjCObjectPointerType())
12020         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12021     }
12022 
12023     // C++1z [dcl.fct]p6:
12024     //   [...] whether the function has a non-throwing exception-specification
12025     //   [is] part of the function type
12026     //
12027     // This results in an ABI break between C++14 and C++17 for functions whose
12028     // declared type includes an exception-specification in a parameter or
12029     // return type. (Exception specifications on the function itself are OK in
12030     // most cases, and exception specifications are not permitted in most other
12031     // contexts where they could make it into a mangling.)
12032     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12033       auto HasNoexcept = [&](QualType T) -> bool {
12034         // Strip off declarator chunks that could be between us and a function
12035         // type. We don't need to look far, exception specifications are very
12036         // restricted prior to C++17.
12037         if (auto *RT = T->getAs<ReferenceType>())
12038           T = RT->getPointeeType();
12039         else if (T->isAnyPointerType())
12040           T = T->getPointeeType();
12041         else if (auto *MPT = T->getAs<MemberPointerType>())
12042           T = MPT->getPointeeType();
12043         if (auto *FPT = T->getAs<FunctionProtoType>())
12044           if (FPT->isNothrow())
12045             return true;
12046         return false;
12047       };
12048 
12049       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12050       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12051       for (QualType T : FPT->param_types())
12052         AnyNoexcept |= HasNoexcept(T);
12053       if (AnyNoexcept)
12054         Diag(NewFD->getLocation(),
12055              diag::warn_cxx17_compat_exception_spec_in_signature)
12056             << NewFD;
12057     }
12058 
12059     if (!Redeclaration && LangOpts.CUDA)
12060       checkCUDATargetOverload(NewFD, Previous);
12061   }
12062   return Redeclaration;
12063 }
12064 
12065 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12066   // C++11 [basic.start.main]p3:
12067   //   A program that [...] declares main to be inline, static or
12068   //   constexpr is ill-formed.
12069   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
12070   //   appear in a declaration of main.
12071   // static main is not an error under C99, but we should warn about it.
12072   // We accept _Noreturn main as an extension.
12073   if (FD->getStorageClass() == SC_Static)
12074     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12075          ? diag::err_static_main : diag::warn_static_main)
12076       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12077   if (FD->isInlineSpecified())
12078     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12079       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12080   if (DS.isNoreturnSpecified()) {
12081     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12082     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12083     Diag(NoreturnLoc, diag::ext_noreturn_main);
12084     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12085       << FixItHint::CreateRemoval(NoreturnRange);
12086   }
12087   if (FD->isConstexpr()) {
12088     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12089         << FD->isConsteval()
12090         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12091     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12092   }
12093 
12094   if (getLangOpts().OpenCL) {
12095     Diag(FD->getLocation(), diag::err_opencl_no_main)
12096         << FD->hasAttr<OpenCLKernelAttr>();
12097     FD->setInvalidDecl();
12098     return;
12099   }
12100 
12101   // Functions named main in hlsl are default entries, but don't have specific
12102   // signatures they are required to conform to.
12103   if (getLangOpts().HLSL)
12104     return;
12105 
12106   QualType T = FD->getType();
12107   assert(T->isFunctionType() && "function decl is not of function type");
12108   const FunctionType* FT = T->castAs<FunctionType>();
12109 
12110   // Set default calling convention for main()
12111   if (FT->getCallConv() != CC_C) {
12112     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12113     FD->setType(QualType(FT, 0));
12114     T = Context.getCanonicalType(FD->getType());
12115   }
12116 
12117   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12118     // In C with GNU extensions we allow main() to have non-integer return
12119     // type, but we should warn about the extension, and we disable the
12120     // implicit-return-zero rule.
12121 
12122     // GCC in C mode accepts qualified 'int'.
12123     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12124       FD->setHasImplicitReturnZero(true);
12125     else {
12126       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12127       SourceRange RTRange = FD->getReturnTypeSourceRange();
12128       if (RTRange.isValid())
12129         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12130             << FixItHint::CreateReplacement(RTRange, "int");
12131     }
12132   } else {
12133     // In C and C++, main magically returns 0 if you fall off the end;
12134     // set the flag which tells us that.
12135     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12136 
12137     // All the standards say that main() should return 'int'.
12138     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12139       FD->setHasImplicitReturnZero(true);
12140     else {
12141       // Otherwise, this is just a flat-out error.
12142       SourceRange RTRange = FD->getReturnTypeSourceRange();
12143       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12144           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12145                                 : FixItHint());
12146       FD->setInvalidDecl(true);
12147     }
12148   }
12149 
12150   // Treat protoless main() as nullary.
12151   if (isa<FunctionNoProtoType>(FT)) return;
12152 
12153   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12154   unsigned nparams = FTP->getNumParams();
12155   assert(FD->getNumParams() == nparams);
12156 
12157   bool HasExtraParameters = (nparams > 3);
12158 
12159   if (FTP->isVariadic()) {
12160     Diag(FD->getLocation(), diag::ext_variadic_main);
12161     // FIXME: if we had information about the location of the ellipsis, we
12162     // could add a FixIt hint to remove it as a parameter.
12163   }
12164 
12165   // Darwin passes an undocumented fourth argument of type char**.  If
12166   // other platforms start sprouting these, the logic below will start
12167   // getting shifty.
12168   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12169     HasExtraParameters = false;
12170 
12171   if (HasExtraParameters) {
12172     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12173     FD->setInvalidDecl(true);
12174     nparams = 3;
12175   }
12176 
12177   // FIXME: a lot of the following diagnostics would be improved
12178   // if we had some location information about types.
12179 
12180   QualType CharPP =
12181     Context.getPointerType(Context.getPointerType(Context.CharTy));
12182   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12183 
12184   for (unsigned i = 0; i < nparams; ++i) {
12185     QualType AT = FTP->getParamType(i);
12186 
12187     bool mismatch = true;
12188 
12189     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12190       mismatch = false;
12191     else if (Expected[i] == CharPP) {
12192       // As an extension, the following forms are okay:
12193       //   char const **
12194       //   char const * const *
12195       //   char * const *
12196 
12197       QualifierCollector qs;
12198       const PointerType* PT;
12199       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12200           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12201           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12202                               Context.CharTy)) {
12203         qs.removeConst();
12204         mismatch = !qs.empty();
12205       }
12206     }
12207 
12208     if (mismatch) {
12209       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12210       // TODO: suggest replacing given type with expected type
12211       FD->setInvalidDecl(true);
12212     }
12213   }
12214 
12215   if (nparams == 1 && !FD->isInvalidDecl()) {
12216     Diag(FD->getLocation(), diag::warn_main_one_arg);
12217   }
12218 
12219   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12220     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12221     FD->setInvalidDecl();
12222   }
12223 }
12224 
12225 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12226 
12227   // Default calling convention for main and wmain is __cdecl
12228   if (FD->getName() == "main" || FD->getName() == "wmain")
12229     return false;
12230 
12231   // Default calling convention for MinGW is __cdecl
12232   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12233   if (T.isWindowsGNUEnvironment())
12234     return false;
12235 
12236   // Default calling convention for WinMain, wWinMain and DllMain
12237   // is __stdcall on 32 bit Windows
12238   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12239     return true;
12240 
12241   return false;
12242 }
12243 
12244 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12245   QualType T = FD->getType();
12246   assert(T->isFunctionType() && "function decl is not of function type");
12247   const FunctionType *FT = T->castAs<FunctionType>();
12248 
12249   // Set an implicit return of 'zero' if the function can return some integral,
12250   // enumeration, pointer or nullptr type.
12251   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12252       FT->getReturnType()->isAnyPointerType() ||
12253       FT->getReturnType()->isNullPtrType())
12254     // DllMain is exempt because a return value of zero means it failed.
12255     if (FD->getName() != "DllMain")
12256       FD->setHasImplicitReturnZero(true);
12257 
12258   // Explicity specified calling conventions are applied to MSVC entry points
12259   if (!hasExplicitCallingConv(T)) {
12260     if (isDefaultStdCall(FD, *this)) {
12261       if (FT->getCallConv() != CC_X86StdCall) {
12262         FT = Context.adjustFunctionType(
12263             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12264         FD->setType(QualType(FT, 0));
12265       }
12266     } else if (FT->getCallConv() != CC_C) {
12267       FT = Context.adjustFunctionType(FT,
12268                                       FT->getExtInfo().withCallingConv(CC_C));
12269       FD->setType(QualType(FT, 0));
12270     }
12271   }
12272 
12273   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12274     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12275     FD->setInvalidDecl();
12276   }
12277 }
12278 
12279 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12280   auto &TargetInfo = getASTContext().getTargetInfo();
12281   auto const Triple = TargetInfo.getTriple();
12282   switch (Triple.getEnvironment()) {
12283   default:
12284     // FIXME: check all shader profiles.
12285     break;
12286   case llvm::Triple::EnvironmentType::Compute:
12287     if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12288       Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12289           << Triple.getEnvironmentName();
12290       FD->setInvalidDecl();
12291     }
12292     break;
12293   }
12294 
12295   for (const auto *Param : FD->parameters()) {
12296     if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12297       // FIXME: Handle struct parameters where annotations are on struct fields.
12298       // See: https://github.com/llvm/llvm-project/issues/57875
12299       Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12300       Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12301       FD->setInvalidDecl();
12302     }
12303   }
12304   // FIXME: Verify return type semantic annotation.
12305 }
12306 
12307 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12308   // FIXME: Need strict checking.  In C89, we need to check for
12309   // any assignment, increment, decrement, function-calls, or
12310   // commas outside of a sizeof.  In C99, it's the same list,
12311   // except that the aforementioned are allowed in unevaluated
12312   // expressions.  Everything else falls under the
12313   // "may accept other forms of constant expressions" exception.
12314   //
12315   // Regular C++ code will not end up here (exceptions: language extensions,
12316   // OpenCL C++ etc), so the constant expression rules there don't matter.
12317   if (Init->isValueDependent()) {
12318     assert(Init->containsErrors() &&
12319            "Dependent code should only occur in error-recovery path.");
12320     return true;
12321   }
12322   const Expr *Culprit;
12323   if (Init->isConstantInitializer(Context, false, &Culprit))
12324     return false;
12325   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12326     << Culprit->getSourceRange();
12327   return true;
12328 }
12329 
12330 namespace {
12331   // Visits an initialization expression to see if OrigDecl is evaluated in
12332   // its own initialization and throws a warning if it does.
12333   class SelfReferenceChecker
12334       : public EvaluatedExprVisitor<SelfReferenceChecker> {
12335     Sema &S;
12336     Decl *OrigDecl;
12337     bool isRecordType;
12338     bool isPODType;
12339     bool isReferenceType;
12340 
12341     bool isInitList;
12342     llvm::SmallVector<unsigned, 4> InitFieldIndex;
12343 
12344   public:
12345     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12346 
12347     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12348                                                     S(S), OrigDecl(OrigDecl) {
12349       isPODType = false;
12350       isRecordType = false;
12351       isReferenceType = false;
12352       isInitList = false;
12353       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12354         isPODType = VD->getType().isPODType(S.Context);
12355         isRecordType = VD->getType()->isRecordType();
12356         isReferenceType = VD->getType()->isReferenceType();
12357       }
12358     }
12359 
12360     // For most expressions, just call the visitor.  For initializer lists,
12361     // track the index of the field being initialized since fields are
12362     // initialized in order allowing use of previously initialized fields.
12363     void CheckExpr(Expr *E) {
12364       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12365       if (!InitList) {
12366         Visit(E);
12367         return;
12368       }
12369 
12370       // Track and increment the index here.
12371       isInitList = true;
12372       InitFieldIndex.push_back(0);
12373       for (auto *Child : InitList->children()) {
12374         CheckExpr(cast<Expr>(Child));
12375         ++InitFieldIndex.back();
12376       }
12377       InitFieldIndex.pop_back();
12378     }
12379 
12380     // Returns true if MemberExpr is checked and no further checking is needed.
12381     // Returns false if additional checking is required.
12382     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12383       llvm::SmallVector<FieldDecl*, 4> Fields;
12384       Expr *Base = E;
12385       bool ReferenceField = false;
12386 
12387       // Get the field members used.
12388       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12389         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12390         if (!FD)
12391           return false;
12392         Fields.push_back(FD);
12393         if (FD->getType()->isReferenceType())
12394           ReferenceField = true;
12395         Base = ME->getBase()->IgnoreParenImpCasts();
12396       }
12397 
12398       // Keep checking only if the base Decl is the same.
12399       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12400       if (!DRE || DRE->getDecl() != OrigDecl)
12401         return false;
12402 
12403       // A reference field can be bound to an unininitialized field.
12404       if (CheckReference && !ReferenceField)
12405         return true;
12406 
12407       // Convert FieldDecls to their index number.
12408       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12409       for (const FieldDecl *I : llvm::reverse(Fields))
12410         UsedFieldIndex.push_back(I->getFieldIndex());
12411 
12412       // See if a warning is needed by checking the first difference in index
12413       // numbers.  If field being used has index less than the field being
12414       // initialized, then the use is safe.
12415       for (auto UsedIter = UsedFieldIndex.begin(),
12416                 UsedEnd = UsedFieldIndex.end(),
12417                 OrigIter = InitFieldIndex.begin(),
12418                 OrigEnd = InitFieldIndex.end();
12419            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12420         if (*UsedIter < *OrigIter)
12421           return true;
12422         if (*UsedIter > *OrigIter)
12423           break;
12424       }
12425 
12426       // TODO: Add a different warning which will print the field names.
12427       HandleDeclRefExpr(DRE);
12428       return true;
12429     }
12430 
12431     // For most expressions, the cast is directly above the DeclRefExpr.
12432     // For conditional operators, the cast can be outside the conditional
12433     // operator if both expressions are DeclRefExpr's.
12434     void HandleValue(Expr *E) {
12435       E = E->IgnoreParens();
12436       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12437         HandleDeclRefExpr(DRE);
12438         return;
12439       }
12440 
12441       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12442         Visit(CO->getCond());
12443         HandleValue(CO->getTrueExpr());
12444         HandleValue(CO->getFalseExpr());
12445         return;
12446       }
12447 
12448       if (BinaryConditionalOperator *BCO =
12449               dyn_cast<BinaryConditionalOperator>(E)) {
12450         Visit(BCO->getCond());
12451         HandleValue(BCO->getFalseExpr());
12452         return;
12453       }
12454 
12455       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12456         HandleValue(OVE->getSourceExpr());
12457         return;
12458       }
12459 
12460       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12461         if (BO->getOpcode() == BO_Comma) {
12462           Visit(BO->getLHS());
12463           HandleValue(BO->getRHS());
12464           return;
12465         }
12466       }
12467 
12468       if (isa<MemberExpr>(E)) {
12469         if (isInitList) {
12470           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12471                                       false /*CheckReference*/))
12472             return;
12473         }
12474 
12475         Expr *Base = E->IgnoreParenImpCasts();
12476         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12477           // Check for static member variables and don't warn on them.
12478           if (!isa<FieldDecl>(ME->getMemberDecl()))
12479             return;
12480           Base = ME->getBase()->IgnoreParenImpCasts();
12481         }
12482         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12483           HandleDeclRefExpr(DRE);
12484         return;
12485       }
12486 
12487       Visit(E);
12488     }
12489 
12490     // Reference types not handled in HandleValue are handled here since all
12491     // uses of references are bad, not just r-value uses.
12492     void VisitDeclRefExpr(DeclRefExpr *E) {
12493       if (isReferenceType)
12494         HandleDeclRefExpr(E);
12495     }
12496 
12497     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12498       if (E->getCastKind() == CK_LValueToRValue) {
12499         HandleValue(E->getSubExpr());
12500         return;
12501       }
12502 
12503       Inherited::VisitImplicitCastExpr(E);
12504     }
12505 
12506     void VisitMemberExpr(MemberExpr *E) {
12507       if (isInitList) {
12508         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12509           return;
12510       }
12511 
12512       // Don't warn on arrays since they can be treated as pointers.
12513       if (E->getType()->canDecayToPointerType()) return;
12514 
12515       // Warn when a non-static method call is followed by non-static member
12516       // field accesses, which is followed by a DeclRefExpr.
12517       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12518       bool Warn = (MD && !MD->isStatic());
12519       Expr *Base = E->getBase()->IgnoreParenImpCasts();
12520       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12521         if (!isa<FieldDecl>(ME->getMemberDecl()))
12522           Warn = false;
12523         Base = ME->getBase()->IgnoreParenImpCasts();
12524       }
12525 
12526       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12527         if (Warn)
12528           HandleDeclRefExpr(DRE);
12529         return;
12530       }
12531 
12532       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12533       // Visit that expression.
12534       Visit(Base);
12535     }
12536 
12537     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12538       Expr *Callee = E->getCallee();
12539 
12540       if (isa<UnresolvedLookupExpr>(Callee))
12541         return Inherited::VisitCXXOperatorCallExpr(E);
12542 
12543       Visit(Callee);
12544       for (auto Arg: E->arguments())
12545         HandleValue(Arg->IgnoreParenImpCasts());
12546     }
12547 
12548     void VisitUnaryOperator(UnaryOperator *E) {
12549       // For POD record types, addresses of its own members are well-defined.
12550       if (E->getOpcode() == UO_AddrOf && isRecordType &&
12551           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12552         if (!isPODType)
12553           HandleValue(E->getSubExpr());
12554         return;
12555       }
12556 
12557       if (E->isIncrementDecrementOp()) {
12558         HandleValue(E->getSubExpr());
12559         return;
12560       }
12561 
12562       Inherited::VisitUnaryOperator(E);
12563     }
12564 
12565     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12566 
12567     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12568       if (E->getConstructor()->isCopyConstructor()) {
12569         Expr *ArgExpr = E->getArg(0);
12570         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12571           if (ILE->getNumInits() == 1)
12572             ArgExpr = ILE->getInit(0);
12573         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12574           if (ICE->getCastKind() == CK_NoOp)
12575             ArgExpr = ICE->getSubExpr();
12576         HandleValue(ArgExpr);
12577         return;
12578       }
12579       Inherited::VisitCXXConstructExpr(E);
12580     }
12581 
12582     void VisitCallExpr(CallExpr *E) {
12583       // Treat std::move as a use.
12584       if (E->isCallToStdMove()) {
12585         HandleValue(E->getArg(0));
12586         return;
12587       }
12588 
12589       Inherited::VisitCallExpr(E);
12590     }
12591 
12592     void VisitBinaryOperator(BinaryOperator *E) {
12593       if (E->isCompoundAssignmentOp()) {
12594         HandleValue(E->getLHS());
12595         Visit(E->getRHS());
12596         return;
12597       }
12598 
12599       Inherited::VisitBinaryOperator(E);
12600     }
12601 
12602     // A custom visitor for BinaryConditionalOperator is needed because the
12603     // regular visitor would check the condition and true expression separately
12604     // but both point to the same place giving duplicate diagnostics.
12605     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12606       Visit(E->getCond());
12607       Visit(E->getFalseExpr());
12608     }
12609 
12610     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12611       Decl* ReferenceDecl = DRE->getDecl();
12612       if (OrigDecl != ReferenceDecl) return;
12613       unsigned diag;
12614       if (isReferenceType) {
12615         diag = diag::warn_uninit_self_reference_in_reference_init;
12616       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12617         diag = diag::warn_static_self_reference_in_init;
12618       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12619                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12620                  DRE->getDecl()->getType()->isRecordType()) {
12621         diag = diag::warn_uninit_self_reference_in_init;
12622       } else {
12623         // Local variables will be handled by the CFG analysis.
12624         return;
12625       }
12626 
12627       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12628                             S.PDiag(diag)
12629                                 << DRE->getDecl() << OrigDecl->getLocation()
12630                                 << DRE->getSourceRange());
12631     }
12632   };
12633 
12634   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12635   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12636                                  bool DirectInit) {
12637     // Parameters arguments are occassionially constructed with itself,
12638     // for instance, in recursive functions.  Skip them.
12639     if (isa<ParmVarDecl>(OrigDecl))
12640       return;
12641 
12642     E = E->IgnoreParens();
12643 
12644     // Skip checking T a = a where T is not a record or reference type.
12645     // Doing so is a way to silence uninitialized warnings.
12646     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12647       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12648         if (ICE->getCastKind() == CK_LValueToRValue)
12649           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12650             if (DRE->getDecl() == OrigDecl)
12651               return;
12652 
12653     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12654   }
12655 } // end anonymous namespace
12656 
12657 namespace {
12658   // Simple wrapper to add the name of a variable or (if no variable is
12659   // available) a DeclarationName into a diagnostic.
12660   struct VarDeclOrName {
12661     VarDecl *VDecl;
12662     DeclarationName Name;
12663 
12664     friend const Sema::SemaDiagnosticBuilder &
12665     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12666       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12667     }
12668   };
12669 } // end anonymous namespace
12670 
12671 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12672                                             DeclarationName Name, QualType Type,
12673                                             TypeSourceInfo *TSI,
12674                                             SourceRange Range, bool DirectInit,
12675                                             Expr *Init) {
12676   bool IsInitCapture = !VDecl;
12677   assert((!VDecl || !VDecl->isInitCapture()) &&
12678          "init captures are expected to be deduced prior to initialization");
12679 
12680   VarDeclOrName VN{VDecl, Name};
12681 
12682   DeducedType *Deduced = Type->getContainedDeducedType();
12683   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12684 
12685   // C++11 [dcl.spec.auto]p3
12686   if (!Init) {
12687     assert(VDecl && "no init for init capture deduction?");
12688 
12689     // Except for class argument deduction, and then for an initializing
12690     // declaration only, i.e. no static at class scope or extern.
12691     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12692         VDecl->hasExternalStorage() ||
12693         VDecl->isStaticDataMember()) {
12694       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12695         << VDecl->getDeclName() << Type;
12696       return QualType();
12697     }
12698   }
12699 
12700   ArrayRef<Expr*> DeduceInits;
12701   if (Init)
12702     DeduceInits = Init;
12703 
12704   auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12705   if (DirectInit && PL)
12706     DeduceInits = PL->exprs();
12707 
12708   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12709     assert(VDecl && "non-auto type for init capture deduction?");
12710     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12711     InitializationKind Kind = InitializationKind::CreateForInit(
12712         VDecl->getLocation(), DirectInit, Init);
12713     // FIXME: Initialization should not be taking a mutable list of inits.
12714     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12715     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12716                                                        InitsCopy, PL);
12717   }
12718 
12719   if (DirectInit) {
12720     if (auto *IL = dyn_cast<InitListExpr>(Init))
12721       DeduceInits = IL->inits();
12722   }
12723 
12724   // Deduction only works if we have exactly one source expression.
12725   if (DeduceInits.empty()) {
12726     // It isn't possible to write this directly, but it is possible to
12727     // end up in this situation with "auto x(some_pack...);"
12728     Diag(Init->getBeginLoc(), IsInitCapture
12729                                   ? diag::err_init_capture_no_expression
12730                                   : diag::err_auto_var_init_no_expression)
12731         << VN << Type << Range;
12732     return QualType();
12733   }
12734 
12735   if (DeduceInits.size() > 1) {
12736     Diag(DeduceInits[1]->getBeginLoc(),
12737          IsInitCapture ? diag::err_init_capture_multiple_expressions
12738                        : diag::err_auto_var_init_multiple_expressions)
12739         << VN << Type << Range;
12740     return QualType();
12741   }
12742 
12743   Expr *DeduceInit = DeduceInits[0];
12744   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12745     Diag(Init->getBeginLoc(), IsInitCapture
12746                                   ? diag::err_init_capture_paren_braces
12747                                   : diag::err_auto_var_init_paren_braces)
12748         << isa<InitListExpr>(Init) << VN << Type << Range;
12749     return QualType();
12750   }
12751 
12752   // Expressions default to 'id' when we're in a debugger.
12753   bool DefaultedAnyToId = false;
12754   if (getLangOpts().DebuggerCastResultToId &&
12755       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12756     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12757     if (Result.isInvalid()) {
12758       return QualType();
12759     }
12760     Init = Result.get();
12761     DefaultedAnyToId = true;
12762   }
12763 
12764   // C++ [dcl.decomp]p1:
12765   //   If the assignment-expression [...] has array type A and no ref-qualifier
12766   //   is present, e has type cv A
12767   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12768       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12769       DeduceInit->getType()->isConstantArrayType())
12770     return Context.getQualifiedType(DeduceInit->getType(),
12771                                     Type.getQualifiers());
12772 
12773   QualType DeducedType;
12774   TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12775   TemplateDeductionResult Result =
12776       DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12777   if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12778     if (!IsInitCapture)
12779       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12780     else if (isa<InitListExpr>(Init))
12781       Diag(Range.getBegin(),
12782            diag::err_init_capture_deduction_failure_from_init_list)
12783           << VN
12784           << (DeduceInit->getType().isNull() ? TSI->getType()
12785                                              : DeduceInit->getType())
12786           << DeduceInit->getSourceRange();
12787     else
12788       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12789           << VN << TSI->getType()
12790           << (DeduceInit->getType().isNull() ? TSI->getType()
12791                                              : DeduceInit->getType())
12792           << DeduceInit->getSourceRange();
12793   }
12794 
12795   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12796   // 'id' instead of a specific object type prevents most of our usual
12797   // checks.
12798   // We only want to warn outside of template instantiations, though:
12799   // inside a template, the 'id' could have come from a parameter.
12800   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12801       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12802     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12803     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12804   }
12805 
12806   return DeducedType;
12807 }
12808 
12809 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12810                                          Expr *Init) {
12811   assert(!Init || !Init->containsErrors());
12812   QualType DeducedType = deduceVarTypeFromInitializer(
12813       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12814       VDecl->getSourceRange(), DirectInit, Init);
12815   if (DeducedType.isNull()) {
12816     VDecl->setInvalidDecl();
12817     return true;
12818   }
12819 
12820   VDecl->setType(DeducedType);
12821   assert(VDecl->isLinkageValid());
12822 
12823   // In ARC, infer lifetime.
12824   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12825     VDecl->setInvalidDecl();
12826 
12827   if (getLangOpts().OpenCL)
12828     deduceOpenCLAddressSpace(VDecl);
12829 
12830   // If this is a redeclaration, check that the type we just deduced matches
12831   // the previously declared type.
12832   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12833     // We never need to merge the type, because we cannot form an incomplete
12834     // array of auto, nor deduce such a type.
12835     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12836   }
12837 
12838   // Check the deduced type is valid for a variable declaration.
12839   CheckVariableDeclarationType(VDecl);
12840   return VDecl->isInvalidDecl();
12841 }
12842 
12843 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12844                                               SourceLocation Loc) {
12845   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12846     Init = EWC->getSubExpr();
12847 
12848   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12849     Init = CE->getSubExpr();
12850 
12851   QualType InitType = Init->getType();
12852   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12853           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12854          "shouldn't be called if type doesn't have a non-trivial C struct");
12855   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12856     for (auto *I : ILE->inits()) {
12857       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12858           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12859         continue;
12860       SourceLocation SL = I->getExprLoc();
12861       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12862     }
12863     return;
12864   }
12865 
12866   if (isa<ImplicitValueInitExpr>(Init)) {
12867     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12868       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12869                             NTCUK_Init);
12870   } else {
12871     // Assume all other explicit initializers involving copying some existing
12872     // object.
12873     // TODO: ignore any explicit initializers where we can guarantee
12874     // copy-elision.
12875     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12876       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12877   }
12878 }
12879 
12880 namespace {
12881 
12882 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12883   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12884   // in the source code or implicitly by the compiler if it is in a union
12885   // defined in a system header and has non-trivial ObjC ownership
12886   // qualifications. We don't want those fields to participate in determining
12887   // whether the containing union is non-trivial.
12888   return FD->hasAttr<UnavailableAttr>();
12889 }
12890 
12891 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12892     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12893                                     void> {
12894   using Super =
12895       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12896                                     void>;
12897 
12898   DiagNonTrivalCUnionDefaultInitializeVisitor(
12899       QualType OrigTy, SourceLocation OrigLoc,
12900       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12901       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12902 
12903   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12904                      const FieldDecl *FD, bool InNonTrivialUnion) {
12905     if (const auto *AT = S.Context.getAsArrayType(QT))
12906       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12907                                      InNonTrivialUnion);
12908     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12909   }
12910 
12911   void visitARCStrong(QualType QT, const FieldDecl *FD,
12912                       bool InNonTrivialUnion) {
12913     if (InNonTrivialUnion)
12914       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12915           << 1 << 0 << QT << FD->getName();
12916   }
12917 
12918   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12919     if (InNonTrivialUnion)
12920       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12921           << 1 << 0 << QT << FD->getName();
12922   }
12923 
12924   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12925     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12926     if (RD->isUnion()) {
12927       if (OrigLoc.isValid()) {
12928         bool IsUnion = false;
12929         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12930           IsUnion = OrigRD->isUnion();
12931         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12932             << 0 << OrigTy << IsUnion << UseContext;
12933         // Reset OrigLoc so that this diagnostic is emitted only once.
12934         OrigLoc = SourceLocation();
12935       }
12936       InNonTrivialUnion = true;
12937     }
12938 
12939     if (InNonTrivialUnion)
12940       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12941           << 0 << 0 << QT.getUnqualifiedType() << "";
12942 
12943     for (const FieldDecl *FD : RD->fields())
12944       if (!shouldIgnoreForRecordTriviality(FD))
12945         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12946   }
12947 
12948   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12949 
12950   // The non-trivial C union type or the struct/union type that contains a
12951   // non-trivial C union.
12952   QualType OrigTy;
12953   SourceLocation OrigLoc;
12954   Sema::NonTrivialCUnionContext UseContext;
12955   Sema &S;
12956 };
12957 
12958 struct DiagNonTrivalCUnionDestructedTypeVisitor
12959     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12960   using Super =
12961       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12962 
12963   DiagNonTrivalCUnionDestructedTypeVisitor(
12964       QualType OrigTy, SourceLocation OrigLoc,
12965       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12966       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12967 
12968   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12969                      const FieldDecl *FD, bool InNonTrivialUnion) {
12970     if (const auto *AT = S.Context.getAsArrayType(QT))
12971       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12972                                      InNonTrivialUnion);
12973     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12974   }
12975 
12976   void visitARCStrong(QualType QT, const FieldDecl *FD,
12977                       bool InNonTrivialUnion) {
12978     if (InNonTrivialUnion)
12979       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12980           << 1 << 1 << QT << FD->getName();
12981   }
12982 
12983   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12984     if (InNonTrivialUnion)
12985       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12986           << 1 << 1 << QT << FD->getName();
12987   }
12988 
12989   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12990     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12991     if (RD->isUnion()) {
12992       if (OrigLoc.isValid()) {
12993         bool IsUnion = false;
12994         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12995           IsUnion = OrigRD->isUnion();
12996         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12997             << 1 << OrigTy << IsUnion << UseContext;
12998         // Reset OrigLoc so that this diagnostic is emitted only once.
12999         OrigLoc = SourceLocation();
13000       }
13001       InNonTrivialUnion = true;
13002     }
13003 
13004     if (InNonTrivialUnion)
13005       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13006           << 0 << 1 << QT.getUnqualifiedType() << "";
13007 
13008     for (const FieldDecl *FD : RD->fields())
13009       if (!shouldIgnoreForRecordTriviality(FD))
13010         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13011   }
13012 
13013   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13014   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13015                           bool InNonTrivialUnion) {}
13016 
13017   // The non-trivial C union type or the struct/union type that contains a
13018   // non-trivial C union.
13019   QualType OrigTy;
13020   SourceLocation OrigLoc;
13021   Sema::NonTrivialCUnionContext UseContext;
13022   Sema &S;
13023 };
13024 
13025 struct DiagNonTrivalCUnionCopyVisitor
13026     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13027   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13028 
13029   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13030                                  Sema::NonTrivialCUnionContext UseContext,
13031                                  Sema &S)
13032       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13033 
13034   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13035                      const FieldDecl *FD, bool InNonTrivialUnion) {
13036     if (const auto *AT = S.Context.getAsArrayType(QT))
13037       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13038                                      InNonTrivialUnion);
13039     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13040   }
13041 
13042   void visitARCStrong(QualType QT, const FieldDecl *FD,
13043                       bool InNonTrivialUnion) {
13044     if (InNonTrivialUnion)
13045       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13046           << 1 << 2 << QT << FD->getName();
13047   }
13048 
13049   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13050     if (InNonTrivialUnion)
13051       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13052           << 1 << 2 << QT << FD->getName();
13053   }
13054 
13055   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13056     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13057     if (RD->isUnion()) {
13058       if (OrigLoc.isValid()) {
13059         bool IsUnion = false;
13060         if (auto *OrigRD = OrigTy->getAsRecordDecl())
13061           IsUnion = OrigRD->isUnion();
13062         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13063             << 2 << OrigTy << IsUnion << UseContext;
13064         // Reset OrigLoc so that this diagnostic is emitted only once.
13065         OrigLoc = SourceLocation();
13066       }
13067       InNonTrivialUnion = true;
13068     }
13069 
13070     if (InNonTrivialUnion)
13071       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13072           << 0 << 2 << QT.getUnqualifiedType() << "";
13073 
13074     for (const FieldDecl *FD : RD->fields())
13075       if (!shouldIgnoreForRecordTriviality(FD))
13076         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13077   }
13078 
13079   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13080                 const FieldDecl *FD, bool InNonTrivialUnion) {}
13081   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13082   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13083                             bool InNonTrivialUnion) {}
13084 
13085   // The non-trivial C union type or the struct/union type that contains a
13086   // non-trivial C union.
13087   QualType OrigTy;
13088   SourceLocation OrigLoc;
13089   Sema::NonTrivialCUnionContext UseContext;
13090   Sema &S;
13091 };
13092 
13093 } // namespace
13094 
13095 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13096                                  NonTrivialCUnionContext UseContext,
13097                                  unsigned NonTrivialKind) {
13098   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13099           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13100           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13101          "shouldn't be called if type doesn't have a non-trivial C union");
13102 
13103   if ((NonTrivialKind & NTCUK_Init) &&
13104       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13105     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13106         .visit(QT, nullptr, false);
13107   if ((NonTrivialKind & NTCUK_Destruct) &&
13108       QT.hasNonTrivialToPrimitiveDestructCUnion())
13109     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13110         .visit(QT, nullptr, false);
13111   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13112     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13113         .visit(QT, nullptr, false);
13114 }
13115 
13116 /// AddInitializerToDecl - Adds the initializer Init to the
13117 /// declaration dcl. If DirectInit is true, this is C++ direct
13118 /// initialization rather than copy initialization.
13119 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13120   // If there is no declaration, there was an error parsing it.  Just ignore
13121   // the initializer.
13122   if (!RealDecl || RealDecl->isInvalidDecl()) {
13123     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13124     return;
13125   }
13126 
13127   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13128     // Pure-specifiers are handled in ActOnPureSpecifier.
13129     Diag(Method->getLocation(), diag::err_member_function_initialization)
13130       << Method->getDeclName() << Init->getSourceRange();
13131     Method->setInvalidDecl();
13132     return;
13133   }
13134 
13135   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13136   if (!VDecl) {
13137     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13138     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13139     RealDecl->setInvalidDecl();
13140     return;
13141   }
13142 
13143   // WebAssembly tables can't be used to initialise a variable.
13144   if (Init && !Init->getType().isNull() &&
13145       Init->getType()->isWebAssemblyTableType()) {
13146     Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13147     VDecl->setInvalidDecl();
13148     return;
13149   }
13150 
13151   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13152   if (VDecl->getType()->isUndeducedType()) {
13153     // Attempt typo correction early so that the type of the init expression can
13154     // be deduced based on the chosen correction if the original init contains a
13155     // TypoExpr.
13156     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13157     if (!Res.isUsable()) {
13158       // There are unresolved typos in Init, just drop them.
13159       // FIXME: improve the recovery strategy to preserve the Init.
13160       RealDecl->setInvalidDecl();
13161       return;
13162     }
13163     if (Res.get()->containsErrors()) {
13164       // Invalidate the decl as we don't know the type for recovery-expr yet.
13165       RealDecl->setInvalidDecl();
13166       VDecl->setInit(Res.get());
13167       return;
13168     }
13169     Init = Res.get();
13170 
13171     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13172       return;
13173   }
13174 
13175   // dllimport cannot be used on variable definitions.
13176   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13177     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13178     VDecl->setInvalidDecl();
13179     return;
13180   }
13181 
13182   // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13183   // the identifier has external or internal linkage, the declaration shall
13184   // have no initializer for the identifier.
13185   // C++14 [dcl.init]p5 is the same restriction for C++.
13186   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13187     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13188     VDecl->setInvalidDecl();
13189     return;
13190   }
13191 
13192   if (!VDecl->getType()->isDependentType()) {
13193     // A definition must end up with a complete type, which means it must be
13194     // complete with the restriction that an array type might be completed by
13195     // the initializer; note that later code assumes this restriction.
13196     QualType BaseDeclType = VDecl->getType();
13197     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13198       BaseDeclType = Array->getElementType();
13199     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13200                             diag::err_typecheck_decl_incomplete_type)) {
13201       RealDecl->setInvalidDecl();
13202       return;
13203     }
13204 
13205     // The variable can not have an abstract class type.
13206     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13207                                diag::err_abstract_type_in_decl,
13208                                AbstractVariableType))
13209       VDecl->setInvalidDecl();
13210   }
13211 
13212   // C++ [module.import/6] external definitions are not permitted in header
13213   // units.
13214   if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13215       !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13216       VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
13217       !VDecl->isInline() && !VDecl->isTemplated() &&
13218       !isa<VarTemplateSpecializationDecl>(VDecl)) {
13219     Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13220     VDecl->setInvalidDecl();
13221   }
13222 
13223   // If adding the initializer will turn this declaration into a definition,
13224   // and we already have a definition for this variable, diagnose or otherwise
13225   // handle the situation.
13226   if (VarDecl *Def = VDecl->getDefinition())
13227     if (Def != VDecl &&
13228         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13229         !VDecl->isThisDeclarationADemotedDefinition() &&
13230         checkVarDeclRedefinition(Def, VDecl))
13231       return;
13232 
13233   if (getLangOpts().CPlusPlus) {
13234     // C++ [class.static.data]p4
13235     //   If a static data member is of const integral or const
13236     //   enumeration type, its declaration in the class definition can
13237     //   specify a constant-initializer which shall be an integral
13238     //   constant expression (5.19). In that case, the member can appear
13239     //   in integral constant expressions. The member shall still be
13240     //   defined in a namespace scope if it is used in the program and the
13241     //   namespace scope definition shall not contain an initializer.
13242     //
13243     // We already performed a redefinition check above, but for static
13244     // data members we also need to check whether there was an in-class
13245     // declaration with an initializer.
13246     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13247       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13248           << VDecl->getDeclName();
13249       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13250            diag::note_previous_initializer)
13251           << 0;
13252       return;
13253     }
13254 
13255     if (VDecl->hasLocalStorage())
13256       setFunctionHasBranchProtectedScope();
13257 
13258     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13259       VDecl->setInvalidDecl();
13260       return;
13261     }
13262   }
13263 
13264   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13265   // a kernel function cannot be initialized."
13266   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13267     Diag(VDecl->getLocation(), diag::err_local_cant_init);
13268     VDecl->setInvalidDecl();
13269     return;
13270   }
13271 
13272   // The LoaderUninitialized attribute acts as a definition (of undef).
13273   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13274     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13275     VDecl->setInvalidDecl();
13276     return;
13277   }
13278 
13279   // Get the decls type and save a reference for later, since
13280   // CheckInitializerTypes may change it.
13281   QualType DclT = VDecl->getType(), SavT = DclT;
13282 
13283   // Expressions default to 'id' when we're in a debugger
13284   // and we are assigning it to a variable of Objective-C pointer type.
13285   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13286       Init->getType() == Context.UnknownAnyTy) {
13287     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13288     if (Result.isInvalid()) {
13289       VDecl->setInvalidDecl();
13290       return;
13291     }
13292     Init = Result.get();
13293   }
13294 
13295   // Perform the initialization.
13296   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13297   bool IsParenListInit = false;
13298   if (!VDecl->isInvalidDecl()) {
13299     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13300     InitializationKind Kind = InitializationKind::CreateForInit(
13301         VDecl->getLocation(), DirectInit, Init);
13302 
13303     MultiExprArg Args = Init;
13304     if (CXXDirectInit)
13305       Args = MultiExprArg(CXXDirectInit->getExprs(),
13306                           CXXDirectInit->getNumExprs());
13307 
13308     // Try to correct any TypoExprs in the initialization arguments.
13309     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13310       ExprResult Res = CorrectDelayedTyposInExpr(
13311           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13312           [this, Entity, Kind](Expr *E) {
13313             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13314             return Init.Failed() ? ExprError() : E;
13315           });
13316       if (Res.isInvalid()) {
13317         VDecl->setInvalidDecl();
13318       } else if (Res.get() != Args[Idx]) {
13319         Args[Idx] = Res.get();
13320       }
13321     }
13322     if (VDecl->isInvalidDecl())
13323       return;
13324 
13325     InitializationSequence InitSeq(*this, Entity, Kind, Args,
13326                                    /*TopLevelOfInitList=*/false,
13327                                    /*TreatUnavailableAsInvalid=*/false);
13328     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13329     if (Result.isInvalid()) {
13330       // If the provided initializer fails to initialize the var decl,
13331       // we attach a recovery expr for better recovery.
13332       auto RecoveryExpr =
13333           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13334       if (RecoveryExpr.get())
13335         VDecl->setInit(RecoveryExpr.get());
13336       return;
13337     }
13338 
13339     Init = Result.getAs<Expr>();
13340     IsParenListInit = !InitSeq.steps().empty() &&
13341                       InitSeq.step_begin()->Kind ==
13342                           InitializationSequence::SK_ParenthesizedListInit;
13343   }
13344 
13345   // Check for self-references within variable initializers.
13346   // Variables declared within a function/method body (except for references)
13347   // are handled by a dataflow analysis.
13348   // This is undefined behavior in C++, but valid in C.
13349   if (getLangOpts().CPlusPlus)
13350     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13351         VDecl->getType()->isReferenceType())
13352       CheckSelfReference(*this, RealDecl, Init, DirectInit);
13353 
13354   // If the type changed, it means we had an incomplete type that was
13355   // completed by the initializer. For example:
13356   //   int ary[] = { 1, 3, 5 };
13357   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13358   if (!VDecl->isInvalidDecl() && (DclT != SavT))
13359     VDecl->setType(DclT);
13360 
13361   if (!VDecl->isInvalidDecl()) {
13362     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13363 
13364     if (VDecl->hasAttr<BlocksAttr>())
13365       checkRetainCycles(VDecl, Init);
13366 
13367     // It is safe to assign a weak reference into a strong variable.
13368     // Although this code can still have problems:
13369     //   id x = self.weakProp;
13370     //   id y = self.weakProp;
13371     // we do not warn to warn spuriously when 'x' and 'y' are on separate
13372     // paths through the function. This should be revisited if
13373     // -Wrepeated-use-of-weak is made flow-sensitive.
13374     if (FunctionScopeInfo *FSI = getCurFunction())
13375       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13376            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13377           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13378                            Init->getBeginLoc()))
13379         FSI->markSafeWeakUse(Init);
13380   }
13381 
13382   // The initialization is usually a full-expression.
13383   //
13384   // FIXME: If this is a braced initialization of an aggregate, it is not
13385   // an expression, and each individual field initializer is a separate
13386   // full-expression. For instance, in:
13387   //
13388   //   struct Temp { ~Temp(); };
13389   //   struct S { S(Temp); };
13390   //   struct T { S a, b; } t = { Temp(), Temp() }
13391   //
13392   // we should destroy the first Temp before constructing the second.
13393   ExprResult Result =
13394       ActOnFinishFullExpr(Init, VDecl->getLocation(),
13395                           /*DiscardedValue*/ false, VDecl->isConstexpr());
13396   if (Result.isInvalid()) {
13397     VDecl->setInvalidDecl();
13398     return;
13399   }
13400   Init = Result.get();
13401 
13402   // Attach the initializer to the decl.
13403   VDecl->setInit(Init);
13404 
13405   if (VDecl->isLocalVarDecl()) {
13406     // Don't check the initializer if the declaration is malformed.
13407     if (VDecl->isInvalidDecl()) {
13408       // do nothing
13409 
13410     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13411     // This is true even in C++ for OpenCL.
13412     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13413       CheckForConstantInitializer(Init, DclT);
13414 
13415     // Otherwise, C++ does not restrict the initializer.
13416     } else if (getLangOpts().CPlusPlus) {
13417       // do nothing
13418 
13419     // C99 6.7.8p4: All the expressions in an initializer for an object that has
13420     // static storage duration shall be constant expressions or string literals.
13421     } else if (VDecl->getStorageClass() == SC_Static) {
13422       CheckForConstantInitializer(Init, DclT);
13423 
13424     // C89 is stricter than C99 for aggregate initializers.
13425     // C89 6.5.7p3: All the expressions [...] in an initializer list
13426     // for an object that has aggregate or union type shall be
13427     // constant expressions.
13428     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13429                isa<InitListExpr>(Init)) {
13430       const Expr *Culprit;
13431       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13432         Diag(Culprit->getExprLoc(),
13433              diag::ext_aggregate_init_not_constant)
13434           << Culprit->getSourceRange();
13435       }
13436     }
13437 
13438     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13439       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13440         if (VDecl->hasLocalStorage())
13441           BE->getBlockDecl()->setCanAvoidCopyToHeap();
13442   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13443              VDecl->getLexicalDeclContext()->isRecord()) {
13444     // This is an in-class initialization for a static data member, e.g.,
13445     //
13446     // struct S {
13447     //   static const int value = 17;
13448     // };
13449 
13450     // C++ [class.mem]p4:
13451     //   A member-declarator can contain a constant-initializer only
13452     //   if it declares a static member (9.4) of const integral or
13453     //   const enumeration type, see 9.4.2.
13454     //
13455     // C++11 [class.static.data]p3:
13456     //   If a non-volatile non-inline const static data member is of integral
13457     //   or enumeration type, its declaration in the class definition can
13458     //   specify a brace-or-equal-initializer in which every initializer-clause
13459     //   that is an assignment-expression is a constant expression. A static
13460     //   data member of literal type can be declared in the class definition
13461     //   with the constexpr specifier; if so, its declaration shall specify a
13462     //   brace-or-equal-initializer in which every initializer-clause that is
13463     //   an assignment-expression is a constant expression.
13464 
13465     // Do nothing on dependent types.
13466     if (DclT->isDependentType()) {
13467 
13468     // Allow any 'static constexpr' members, whether or not they are of literal
13469     // type. We separately check that every constexpr variable is of literal
13470     // type.
13471     } else if (VDecl->isConstexpr()) {
13472 
13473     // Require constness.
13474     } else if (!DclT.isConstQualified()) {
13475       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13476         << Init->getSourceRange();
13477       VDecl->setInvalidDecl();
13478 
13479     // We allow integer constant expressions in all cases.
13480     } else if (DclT->isIntegralOrEnumerationType()) {
13481       // Check whether the expression is a constant expression.
13482       SourceLocation Loc;
13483       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13484         // In C++11, a non-constexpr const static data member with an
13485         // in-class initializer cannot be volatile.
13486         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13487       else if (Init->isValueDependent())
13488         ; // Nothing to check.
13489       else if (Init->isIntegerConstantExpr(Context, &Loc))
13490         ; // Ok, it's an ICE!
13491       else if (Init->getType()->isScopedEnumeralType() &&
13492                Init->isCXX11ConstantExpr(Context))
13493         ; // Ok, it is a scoped-enum constant expression.
13494       else if (Init->isEvaluatable(Context)) {
13495         // If we can constant fold the initializer through heroics, accept it,
13496         // but report this as a use of an extension for -pedantic.
13497         Diag(Loc, diag::ext_in_class_initializer_non_constant)
13498           << Init->getSourceRange();
13499       } else {
13500         // Otherwise, this is some crazy unknown case.  Report the issue at the
13501         // location provided by the isIntegerConstantExpr failed check.
13502         Diag(Loc, diag::err_in_class_initializer_non_constant)
13503           << Init->getSourceRange();
13504         VDecl->setInvalidDecl();
13505       }
13506 
13507     // We allow foldable floating-point constants as an extension.
13508     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13509       // In C++98, this is a GNU extension. In C++11, it is not, but we support
13510       // it anyway and provide a fixit to add the 'constexpr'.
13511       if (getLangOpts().CPlusPlus11) {
13512         Diag(VDecl->getLocation(),
13513              diag::ext_in_class_initializer_float_type_cxx11)
13514             << DclT << Init->getSourceRange();
13515         Diag(VDecl->getBeginLoc(),
13516              diag::note_in_class_initializer_float_type_cxx11)
13517             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13518       } else {
13519         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13520           << DclT << Init->getSourceRange();
13521 
13522         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13523           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13524             << Init->getSourceRange();
13525           VDecl->setInvalidDecl();
13526         }
13527       }
13528 
13529     // Suggest adding 'constexpr' in C++11 for literal types.
13530     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13531       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13532           << DclT << Init->getSourceRange()
13533           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13534       VDecl->setConstexpr(true);
13535 
13536     } else {
13537       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13538         << DclT << Init->getSourceRange();
13539       VDecl->setInvalidDecl();
13540     }
13541   } else if (VDecl->isFileVarDecl()) {
13542     // In C, extern is typically used to avoid tentative definitions when
13543     // declaring variables in headers, but adding an intializer makes it a
13544     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13545     // In C++, extern is often used to give implictly static const variables
13546     // external linkage, so don't warn in that case. If selectany is present,
13547     // this might be header code intended for C and C++ inclusion, so apply the
13548     // C++ rules.
13549     if (VDecl->getStorageClass() == SC_Extern &&
13550         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13551          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13552         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13553         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13554       Diag(VDecl->getLocation(), diag::warn_extern_init);
13555 
13556     // In Microsoft C++ mode, a const variable defined in namespace scope has
13557     // external linkage by default if the variable is declared with
13558     // __declspec(dllexport).
13559     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13560         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13561         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13562       VDecl->setStorageClass(SC_Extern);
13563 
13564     // C99 6.7.8p4. All file scoped initializers need to be constant.
13565     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13566       CheckForConstantInitializer(Init, DclT);
13567   }
13568 
13569   QualType InitType = Init->getType();
13570   if (!InitType.isNull() &&
13571       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13572        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13573     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13574 
13575   // We will represent direct-initialization similarly to copy-initialization:
13576   //    int x(1);  -as-> int x = 1;
13577   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13578   //
13579   // Clients that want to distinguish between the two forms, can check for
13580   // direct initializer using VarDecl::getInitStyle().
13581   // A major benefit is that clients that don't particularly care about which
13582   // exactly form was it (like the CodeGen) can handle both cases without
13583   // special case code.
13584 
13585   // C++ 8.5p11:
13586   // The form of initialization (using parentheses or '=') is generally
13587   // insignificant, but does matter when the entity being initialized has a
13588   // class type.
13589   if (CXXDirectInit) {
13590     assert(DirectInit && "Call-style initializer must be direct init.");
13591     VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13592                                         : VarDecl::CallInit);
13593   } else if (DirectInit) {
13594     // This must be list-initialization. No other way is direct-initialization.
13595     VDecl->setInitStyle(VarDecl::ListInit);
13596   }
13597 
13598   if (LangOpts.OpenMP &&
13599       (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13600       VDecl->isFileVarDecl())
13601     DeclsToCheckForDeferredDiags.insert(VDecl);
13602   CheckCompleteVariableDeclaration(VDecl);
13603 }
13604 
13605 /// ActOnInitializerError - Given that there was an error parsing an
13606 /// initializer for the given declaration, try to at least re-establish
13607 /// invariants such as whether a variable's type is either dependent or
13608 /// complete.
13609 void Sema::ActOnInitializerError(Decl *D) {
13610   // Our main concern here is re-establishing invariants like "a
13611   // variable's type is either dependent or complete".
13612   if (!D || D->isInvalidDecl()) return;
13613 
13614   VarDecl *VD = dyn_cast<VarDecl>(D);
13615   if (!VD) return;
13616 
13617   // Bindings are not usable if we can't make sense of the initializer.
13618   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13619     for (auto *BD : DD->bindings())
13620       BD->setInvalidDecl();
13621 
13622   // Auto types are meaningless if we can't make sense of the initializer.
13623   if (VD->getType()->isUndeducedType()) {
13624     D->setInvalidDecl();
13625     return;
13626   }
13627 
13628   QualType Ty = VD->getType();
13629   if (Ty->isDependentType()) return;
13630 
13631   // Require a complete type.
13632   if (RequireCompleteType(VD->getLocation(),
13633                           Context.getBaseElementType(Ty),
13634                           diag::err_typecheck_decl_incomplete_type)) {
13635     VD->setInvalidDecl();
13636     return;
13637   }
13638 
13639   // Require a non-abstract type.
13640   if (RequireNonAbstractType(VD->getLocation(), Ty,
13641                              diag::err_abstract_type_in_decl,
13642                              AbstractVariableType)) {
13643     VD->setInvalidDecl();
13644     return;
13645   }
13646 
13647   // Don't bother complaining about constructors or destructors,
13648   // though.
13649 }
13650 
13651 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13652   // If there is no declaration, there was an error parsing it. Just ignore it.
13653   if (!RealDecl)
13654     return;
13655 
13656   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13657     QualType Type = Var->getType();
13658 
13659     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13660     if (isa<DecompositionDecl>(RealDecl)) {
13661       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13662       Var->setInvalidDecl();
13663       return;
13664     }
13665 
13666     if (Type->isUndeducedType() &&
13667         DeduceVariableDeclarationType(Var, false, nullptr))
13668       return;
13669 
13670     // C++11 [class.static.data]p3: A static data member can be declared with
13671     // the constexpr specifier; if so, its declaration shall specify
13672     // a brace-or-equal-initializer.
13673     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13674     // the definition of a variable [...] or the declaration of a static data
13675     // member.
13676     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13677         !Var->isThisDeclarationADemotedDefinition()) {
13678       if (Var->isStaticDataMember()) {
13679         // C++1z removes the relevant rule; the in-class declaration is always
13680         // a definition there.
13681         if (!getLangOpts().CPlusPlus17 &&
13682             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13683           Diag(Var->getLocation(),
13684                diag::err_constexpr_static_mem_var_requires_init)
13685               << Var;
13686           Var->setInvalidDecl();
13687           return;
13688         }
13689       } else {
13690         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13691         Var->setInvalidDecl();
13692         return;
13693       }
13694     }
13695 
13696     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13697     // be initialized.
13698     if (!Var->isInvalidDecl() &&
13699         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13700         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13701       bool HasConstExprDefaultConstructor = false;
13702       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13703         for (auto *Ctor : RD->ctors()) {
13704           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13705               Ctor->getMethodQualifiers().getAddressSpace() ==
13706                   LangAS::opencl_constant) {
13707             HasConstExprDefaultConstructor = true;
13708           }
13709         }
13710       }
13711       if (!HasConstExprDefaultConstructor) {
13712         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13713         Var->setInvalidDecl();
13714         return;
13715       }
13716     }
13717 
13718     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13719       if (Var->getStorageClass() == SC_Extern) {
13720         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13721             << Var;
13722         Var->setInvalidDecl();
13723         return;
13724       }
13725       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13726                               diag::err_typecheck_decl_incomplete_type)) {
13727         Var->setInvalidDecl();
13728         return;
13729       }
13730       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13731         if (!RD->hasTrivialDefaultConstructor()) {
13732           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13733           Var->setInvalidDecl();
13734           return;
13735         }
13736       }
13737       // The declaration is unitialized, no need for further checks.
13738       return;
13739     }
13740 
13741     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13742     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13743         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13744       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13745                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13746 
13747 
13748     switch (DefKind) {
13749     case VarDecl::Definition:
13750       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13751         break;
13752 
13753       // We have an out-of-line definition of a static data member
13754       // that has an in-class initializer, so we type-check this like
13755       // a declaration.
13756       //
13757       [[fallthrough]];
13758 
13759     case VarDecl::DeclarationOnly:
13760       // It's only a declaration.
13761 
13762       // Block scope. C99 6.7p7: If an identifier for an object is
13763       // declared with no linkage (C99 6.2.2p6), the type for the
13764       // object shall be complete.
13765       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13766           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13767           RequireCompleteType(Var->getLocation(), Type,
13768                               diag::err_typecheck_decl_incomplete_type))
13769         Var->setInvalidDecl();
13770 
13771       // Make sure that the type is not abstract.
13772       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13773           RequireNonAbstractType(Var->getLocation(), Type,
13774                                  diag::err_abstract_type_in_decl,
13775                                  AbstractVariableType))
13776         Var->setInvalidDecl();
13777       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13778           Var->getStorageClass() == SC_PrivateExtern) {
13779         Diag(Var->getLocation(), diag::warn_private_extern);
13780         Diag(Var->getLocation(), diag::note_private_extern);
13781       }
13782 
13783       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13784           !Var->isInvalidDecl())
13785         ExternalDeclarations.push_back(Var);
13786 
13787       return;
13788 
13789     case VarDecl::TentativeDefinition:
13790       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13791       // object that has file scope without an initializer, and without a
13792       // storage-class specifier or with the storage-class specifier "static",
13793       // constitutes a tentative definition. Note: A tentative definition with
13794       // external linkage is valid (C99 6.2.2p5).
13795       if (!Var->isInvalidDecl()) {
13796         if (const IncompleteArrayType *ArrayT
13797                                     = Context.getAsIncompleteArrayType(Type)) {
13798           if (RequireCompleteSizedType(
13799                   Var->getLocation(), ArrayT->getElementType(),
13800                   diag::err_array_incomplete_or_sizeless_type))
13801             Var->setInvalidDecl();
13802         } else if (Var->getStorageClass() == SC_Static) {
13803           // C99 6.9.2p3: If the declaration of an identifier for an object is
13804           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13805           // declared type shall not be an incomplete type.
13806           // NOTE: code such as the following
13807           //     static struct s;
13808           //     struct s { int a; };
13809           // is accepted by gcc. Hence here we issue a warning instead of
13810           // an error and we do not invalidate the static declaration.
13811           // NOTE: to avoid multiple warnings, only check the first declaration.
13812           if (Var->isFirstDecl())
13813             RequireCompleteType(Var->getLocation(), Type,
13814                                 diag::ext_typecheck_decl_incomplete_type);
13815         }
13816       }
13817 
13818       // Record the tentative definition; we're done.
13819       if (!Var->isInvalidDecl())
13820         TentativeDefinitions.push_back(Var);
13821       return;
13822     }
13823 
13824     // Provide a specific diagnostic for uninitialized variable
13825     // definitions with incomplete array type.
13826     if (Type->isIncompleteArrayType()) {
13827       if (Var->isConstexpr())
13828         Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13829             << Var;
13830       else
13831         Diag(Var->getLocation(),
13832              diag::err_typecheck_incomplete_array_needs_initializer);
13833       Var->setInvalidDecl();
13834       return;
13835     }
13836 
13837     // Provide a specific diagnostic for uninitialized variable
13838     // definitions with reference type.
13839     if (Type->isReferenceType()) {
13840       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13841           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13842       return;
13843     }
13844 
13845     // Do not attempt to type-check the default initializer for a
13846     // variable with dependent type.
13847     if (Type->isDependentType())
13848       return;
13849 
13850     if (Var->isInvalidDecl())
13851       return;
13852 
13853     if (!Var->hasAttr<AliasAttr>()) {
13854       if (RequireCompleteType(Var->getLocation(),
13855                               Context.getBaseElementType(Type),
13856                               diag::err_typecheck_decl_incomplete_type)) {
13857         Var->setInvalidDecl();
13858         return;
13859       }
13860     } else {
13861       return;
13862     }
13863 
13864     // The variable can not have an abstract class type.
13865     if (RequireNonAbstractType(Var->getLocation(), Type,
13866                                diag::err_abstract_type_in_decl,
13867                                AbstractVariableType)) {
13868       Var->setInvalidDecl();
13869       return;
13870     }
13871 
13872     // Check for jumps past the implicit initializer.  C++0x
13873     // clarifies that this applies to a "variable with automatic
13874     // storage duration", not a "local variable".
13875     // C++11 [stmt.dcl]p3
13876     //   A program that jumps from a point where a variable with automatic
13877     //   storage duration is not in scope to a point where it is in scope is
13878     //   ill-formed unless the variable has scalar type, class type with a
13879     //   trivial default constructor and a trivial destructor, a cv-qualified
13880     //   version of one of these types, or an array of one of the preceding
13881     //   types and is declared without an initializer.
13882     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13883       if (const RecordType *Record
13884             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13885         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13886         // Mark the function (if we're in one) for further checking even if the
13887         // looser rules of C++11 do not require such checks, so that we can
13888         // diagnose incompatibilities with C++98.
13889         if (!CXXRecord->isPOD())
13890           setFunctionHasBranchProtectedScope();
13891       }
13892     }
13893     // In OpenCL, we can't initialize objects in the __local address space,
13894     // even implicitly, so don't synthesize an implicit initializer.
13895     if (getLangOpts().OpenCL &&
13896         Var->getType().getAddressSpace() == LangAS::opencl_local)
13897       return;
13898     // C++03 [dcl.init]p9:
13899     //   If no initializer is specified for an object, and the
13900     //   object is of (possibly cv-qualified) non-POD class type (or
13901     //   array thereof), the object shall be default-initialized; if
13902     //   the object is of const-qualified type, the underlying class
13903     //   type shall have a user-declared default
13904     //   constructor. Otherwise, if no initializer is specified for
13905     //   a non- static object, the object and its subobjects, if
13906     //   any, have an indeterminate initial value); if the object
13907     //   or any of its subobjects are of const-qualified type, the
13908     //   program is ill-formed.
13909     // C++0x [dcl.init]p11:
13910     //   If no initializer is specified for an object, the object is
13911     //   default-initialized; [...].
13912     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13913     InitializationKind Kind
13914       = InitializationKind::CreateDefault(Var->getLocation());
13915 
13916     InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13917     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13918 
13919     if (Init.get()) {
13920       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13921       // This is important for template substitution.
13922       Var->setInitStyle(VarDecl::CallInit);
13923     } else if (Init.isInvalid()) {
13924       // If default-init fails, attach a recovery-expr initializer to track
13925       // that initialization was attempted and failed.
13926       auto RecoveryExpr =
13927           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13928       if (RecoveryExpr.get())
13929         Var->setInit(RecoveryExpr.get());
13930     }
13931 
13932     CheckCompleteVariableDeclaration(Var);
13933   }
13934 }
13935 
13936 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13937   // If there is no declaration, there was an error parsing it. Ignore it.
13938   if (!D)
13939     return;
13940 
13941   VarDecl *VD = dyn_cast<VarDecl>(D);
13942   if (!VD) {
13943     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13944     D->setInvalidDecl();
13945     return;
13946   }
13947 
13948   VD->setCXXForRangeDecl(true);
13949 
13950   // for-range-declaration cannot be given a storage class specifier.
13951   int Error = -1;
13952   switch (VD->getStorageClass()) {
13953   case SC_None:
13954     break;
13955   case SC_Extern:
13956     Error = 0;
13957     break;
13958   case SC_Static:
13959     Error = 1;
13960     break;
13961   case SC_PrivateExtern:
13962     Error = 2;
13963     break;
13964   case SC_Auto:
13965     Error = 3;
13966     break;
13967   case SC_Register:
13968     Error = 4;
13969     break;
13970   }
13971 
13972   // for-range-declaration cannot be given a storage class specifier con't.
13973   switch (VD->getTSCSpec()) {
13974   case TSCS_thread_local:
13975     Error = 6;
13976     break;
13977   case TSCS___thread:
13978   case TSCS__Thread_local:
13979   case TSCS_unspecified:
13980     break;
13981   }
13982 
13983   if (Error != -1) {
13984     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13985         << VD << Error;
13986     D->setInvalidDecl();
13987   }
13988 }
13989 
13990 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13991                                             IdentifierInfo *Ident,
13992                                             ParsedAttributes &Attrs) {
13993   // C++1y [stmt.iter]p1:
13994   //   A range-based for statement of the form
13995   //      for ( for-range-identifier : for-range-initializer ) statement
13996   //   is equivalent to
13997   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13998   DeclSpec DS(Attrs.getPool().getFactory());
13999 
14000   const char *PrevSpec;
14001   unsigned DiagID;
14002   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14003                      getPrintingPolicy());
14004 
14005   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14006   D.SetIdentifier(Ident, IdentLoc);
14007   D.takeAttributes(Attrs);
14008 
14009   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14010                 IdentLoc);
14011   Decl *Var = ActOnDeclarator(S, D);
14012   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14013   FinalizeDeclaration(Var);
14014   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14015                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14016                                                       : IdentLoc);
14017 }
14018 
14019 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14020   if (var->isInvalidDecl()) return;
14021 
14022   MaybeAddCUDAConstantAttr(var);
14023 
14024   if (getLangOpts().OpenCL) {
14025     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14026     // initialiser
14027     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14028         !var->hasInit()) {
14029       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14030           << 1 /*Init*/;
14031       var->setInvalidDecl();
14032       return;
14033     }
14034   }
14035 
14036   // In Objective-C, don't allow jumps past the implicit initialization of a
14037   // local retaining variable.
14038   if (getLangOpts().ObjC &&
14039       var->hasLocalStorage()) {
14040     switch (var->getType().getObjCLifetime()) {
14041     case Qualifiers::OCL_None:
14042     case Qualifiers::OCL_ExplicitNone:
14043     case Qualifiers::OCL_Autoreleasing:
14044       break;
14045 
14046     case Qualifiers::OCL_Weak:
14047     case Qualifiers::OCL_Strong:
14048       setFunctionHasBranchProtectedScope();
14049       break;
14050     }
14051   }
14052 
14053   if (var->hasLocalStorage() &&
14054       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14055     setFunctionHasBranchProtectedScope();
14056 
14057   // Warn about externally-visible variables being defined without a
14058   // prior declaration.  We only want to do this for global
14059   // declarations, but we also specifically need to avoid doing it for
14060   // class members because the linkage of an anonymous class can
14061   // change if it's later given a typedef name.
14062   if (var->isThisDeclarationADefinition() &&
14063       var->getDeclContext()->getRedeclContext()->isFileContext() &&
14064       var->isExternallyVisible() && var->hasLinkage() &&
14065       !var->isInline() && !var->getDescribedVarTemplate() &&
14066       !isa<VarTemplatePartialSpecializationDecl>(var) &&
14067       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14068       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14069                                   var->getLocation())) {
14070     // Find a previous declaration that's not a definition.
14071     VarDecl *prev = var->getPreviousDecl();
14072     while (prev && prev->isThisDeclarationADefinition())
14073       prev = prev->getPreviousDecl();
14074 
14075     if (!prev) {
14076       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14077       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14078           << /* variable */ 0;
14079     }
14080   }
14081 
14082   // Cache the result of checking for constant initialization.
14083   std::optional<bool> CacheHasConstInit;
14084   const Expr *CacheCulprit = nullptr;
14085   auto checkConstInit = [&]() mutable {
14086     if (!CacheHasConstInit)
14087       CacheHasConstInit = var->getInit()->isConstantInitializer(
14088             Context, var->getType()->isReferenceType(), &CacheCulprit);
14089     return *CacheHasConstInit;
14090   };
14091 
14092   if (var->getTLSKind() == VarDecl::TLS_Static) {
14093     if (var->getType().isDestructedType()) {
14094       // GNU C++98 edits for __thread, [basic.start.term]p3:
14095       //   The type of an object with thread storage duration shall not
14096       //   have a non-trivial destructor.
14097       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14098       if (getLangOpts().CPlusPlus11)
14099         Diag(var->getLocation(), diag::note_use_thread_local);
14100     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14101       if (!checkConstInit()) {
14102         // GNU C++98 edits for __thread, [basic.start.init]p4:
14103         //   An object of thread storage duration shall not require dynamic
14104         //   initialization.
14105         // FIXME: Need strict checking here.
14106         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14107           << CacheCulprit->getSourceRange();
14108         if (getLangOpts().CPlusPlus11)
14109           Diag(var->getLocation(), diag::note_use_thread_local);
14110       }
14111     }
14112   }
14113 
14114 
14115   if (!var->getType()->isStructureType() && var->hasInit() &&
14116       isa<InitListExpr>(var->getInit())) {
14117     const auto *ILE = cast<InitListExpr>(var->getInit());
14118     unsigned NumInits = ILE->getNumInits();
14119     if (NumInits > 2)
14120       for (unsigned I = 0; I < NumInits; ++I) {
14121         const auto *Init = ILE->getInit(I);
14122         if (!Init)
14123           break;
14124         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14125         if (!SL)
14126           break;
14127 
14128         unsigned NumConcat = SL->getNumConcatenated();
14129         // Diagnose missing comma in string array initialization.
14130         // Do not warn when all the elements in the initializer are concatenated
14131         // together. Do not warn for macros too.
14132         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14133           bool OnlyOneMissingComma = true;
14134           for (unsigned J = I + 1; J < NumInits; ++J) {
14135             const auto *Init = ILE->getInit(J);
14136             if (!Init)
14137               break;
14138             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14139             if (!SLJ || SLJ->getNumConcatenated() > 1) {
14140               OnlyOneMissingComma = false;
14141               break;
14142             }
14143           }
14144 
14145           if (OnlyOneMissingComma) {
14146             SmallVector<FixItHint, 1> Hints;
14147             for (unsigned i = 0; i < NumConcat - 1; ++i)
14148               Hints.push_back(FixItHint::CreateInsertion(
14149                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14150 
14151             Diag(SL->getStrTokenLoc(1),
14152                  diag::warn_concatenated_literal_array_init)
14153                 << Hints;
14154             Diag(SL->getBeginLoc(),
14155                  diag::note_concatenated_string_literal_silence);
14156           }
14157           // In any case, stop now.
14158           break;
14159         }
14160       }
14161   }
14162 
14163 
14164   QualType type = var->getType();
14165 
14166   if (var->hasAttr<BlocksAttr>())
14167     getCurFunction()->addByrefBlockVar(var);
14168 
14169   Expr *Init = var->getInit();
14170   bool GlobalStorage = var->hasGlobalStorage();
14171   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14172   QualType baseType = Context.getBaseElementType(type);
14173   bool HasConstInit = true;
14174 
14175   // Check whether the initializer is sufficiently constant.
14176   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14177       !Init->isValueDependent() &&
14178       (GlobalStorage || var->isConstexpr() ||
14179        var->mightBeUsableInConstantExpressions(Context))) {
14180     // If this variable might have a constant initializer or might be usable in
14181     // constant expressions, check whether or not it actually is now.  We can't
14182     // do this lazily, because the result might depend on things that change
14183     // later, such as which constexpr functions happen to be defined.
14184     SmallVector<PartialDiagnosticAt, 8> Notes;
14185     if (!getLangOpts().CPlusPlus11) {
14186       // Prior to C++11, in contexts where a constant initializer is required,
14187       // the set of valid constant initializers is described by syntactic rules
14188       // in [expr.const]p2-6.
14189       // FIXME: Stricter checking for these rules would be useful for constinit /
14190       // -Wglobal-constructors.
14191       HasConstInit = checkConstInit();
14192 
14193       // Compute and cache the constant value, and remember that we have a
14194       // constant initializer.
14195       if (HasConstInit) {
14196         (void)var->checkForConstantInitialization(Notes);
14197         Notes.clear();
14198       } else if (CacheCulprit) {
14199         Notes.emplace_back(CacheCulprit->getExprLoc(),
14200                            PDiag(diag::note_invalid_subexpr_in_const_expr));
14201         Notes.back().second << CacheCulprit->getSourceRange();
14202       }
14203     } else {
14204       // Evaluate the initializer to see if it's a constant initializer.
14205       HasConstInit = var->checkForConstantInitialization(Notes);
14206     }
14207 
14208     if (HasConstInit) {
14209       // FIXME: Consider replacing the initializer with a ConstantExpr.
14210     } else if (var->isConstexpr()) {
14211       SourceLocation DiagLoc = var->getLocation();
14212       // If the note doesn't add any useful information other than a source
14213       // location, fold it into the primary diagnostic.
14214       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14215                                    diag::note_invalid_subexpr_in_const_expr) {
14216         DiagLoc = Notes[0].first;
14217         Notes.clear();
14218       }
14219       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14220           << var << Init->getSourceRange();
14221       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14222         Diag(Notes[I].first, Notes[I].second);
14223     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14224       auto *Attr = var->getAttr<ConstInitAttr>();
14225       Diag(var->getLocation(), diag::err_require_constant_init_failed)
14226           << Init->getSourceRange();
14227       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14228           << Attr->getRange() << Attr->isConstinit();
14229       for (auto &it : Notes)
14230         Diag(it.first, it.second);
14231     } else if (IsGlobal &&
14232                !getDiagnostics().isIgnored(diag::warn_global_constructor,
14233                                            var->getLocation())) {
14234       // Warn about globals which don't have a constant initializer.  Don't
14235       // warn about globals with a non-trivial destructor because we already
14236       // warned about them.
14237       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14238       if (!(RD && !RD->hasTrivialDestructor())) {
14239         // checkConstInit() here permits trivial default initialization even in
14240         // C++11 onwards, where such an initializer is not a constant initializer
14241         // but nonetheless doesn't require a global constructor.
14242         if (!checkConstInit())
14243           Diag(var->getLocation(), diag::warn_global_constructor)
14244               << Init->getSourceRange();
14245       }
14246     }
14247   }
14248 
14249   // Apply section attributes and pragmas to global variables.
14250   if (GlobalStorage && var->isThisDeclarationADefinition() &&
14251       !inTemplateInstantiation()) {
14252     PragmaStack<StringLiteral *> *Stack = nullptr;
14253     int SectionFlags = ASTContext::PSF_Read;
14254     if (var->getType().isConstQualified()) {
14255       if (HasConstInit)
14256         Stack = &ConstSegStack;
14257       else {
14258         Stack = &BSSSegStack;
14259         SectionFlags |= ASTContext::PSF_Write;
14260       }
14261     } else if (var->hasInit() && HasConstInit) {
14262       Stack = &DataSegStack;
14263       SectionFlags |= ASTContext::PSF_Write;
14264     } else {
14265       Stack = &BSSSegStack;
14266       SectionFlags |= ASTContext::PSF_Write;
14267     }
14268     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14269       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14270         SectionFlags |= ASTContext::PSF_Implicit;
14271       UnifySection(SA->getName(), SectionFlags, var);
14272     } else if (Stack->CurrentValue) {
14273       SectionFlags |= ASTContext::PSF_Implicit;
14274       auto SectionName = Stack->CurrentValue->getString();
14275       var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14276                                                Stack->CurrentPragmaLocation,
14277                                                SectionAttr::Declspec_allocate));
14278       if (UnifySection(SectionName, SectionFlags, var))
14279         var->dropAttr<SectionAttr>();
14280     }
14281 
14282     // Apply the init_seg attribute if this has an initializer.  If the
14283     // initializer turns out to not be dynamic, we'll end up ignoring this
14284     // attribute.
14285     if (CurInitSeg && var->getInit())
14286       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14287                                                CurInitSegLoc));
14288   }
14289 
14290   // All the following checks are C++ only.
14291   if (!getLangOpts().CPlusPlus) {
14292     // If this variable must be emitted, add it as an initializer for the
14293     // current module.
14294     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14295       Context.addModuleInitializer(ModuleScopes.back().Module, var);
14296     return;
14297   }
14298 
14299   // Require the destructor.
14300   if (!type->isDependentType())
14301     if (const RecordType *recordType = baseType->getAs<RecordType>())
14302       FinalizeVarWithDestructor(var, recordType);
14303 
14304   // If this variable must be emitted, add it as an initializer for the current
14305   // module.
14306   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14307     Context.addModuleInitializer(ModuleScopes.back().Module, var);
14308 
14309   // Build the bindings if this is a structured binding declaration.
14310   if (auto *DD = dyn_cast<DecompositionDecl>(var))
14311     CheckCompleteDecompositionDeclaration(DD);
14312 }
14313 
14314 /// Check if VD needs to be dllexport/dllimport due to being in a
14315 /// dllexport/import function.
14316 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14317   assert(VD->isStaticLocal());
14318 
14319   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14320 
14321   // Find outermost function when VD is in lambda function.
14322   while (FD && !getDLLAttr(FD) &&
14323          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14324          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14325     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14326   }
14327 
14328   if (!FD)
14329     return;
14330 
14331   // Static locals inherit dll attributes from their function.
14332   if (Attr *A = getDLLAttr(FD)) {
14333     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14334     NewAttr->setInherited(true);
14335     VD->addAttr(NewAttr);
14336   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14337     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14338     NewAttr->setInherited(true);
14339     VD->addAttr(NewAttr);
14340 
14341     // Export this function to enforce exporting this static variable even
14342     // if it is not used in this compilation unit.
14343     if (!FD->hasAttr<DLLExportAttr>())
14344       FD->addAttr(NewAttr);
14345 
14346   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14347     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14348     NewAttr->setInherited(true);
14349     VD->addAttr(NewAttr);
14350   }
14351 }
14352 
14353 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14354   assert(VD->getTLSKind());
14355 
14356   // Perform TLS alignment check here after attributes attached to the variable
14357   // which may affect the alignment have been processed. Only perform the check
14358   // if the target has a maximum TLS alignment (zero means no constraints).
14359   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14360     // Protect the check so that it's not performed on dependent types and
14361     // dependent alignments (we can't determine the alignment in that case).
14362     if (!VD->hasDependentAlignment()) {
14363       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14364       if (Context.getDeclAlign(VD) > MaxAlignChars) {
14365         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14366             << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14367             << (unsigned)MaxAlignChars.getQuantity();
14368       }
14369     }
14370   }
14371 }
14372 
14373 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14374 /// any semantic actions necessary after any initializer has been attached.
14375 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14376   // Note that we are no longer parsing the initializer for this declaration.
14377   ParsingInitForAutoVars.erase(ThisDecl);
14378 
14379   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14380   if (!VD)
14381     return;
14382 
14383   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14384   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14385       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14386     if (PragmaClangBSSSection.Valid)
14387       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14388           Context, PragmaClangBSSSection.SectionName,
14389           PragmaClangBSSSection.PragmaLocation));
14390     if (PragmaClangDataSection.Valid)
14391       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14392           Context, PragmaClangDataSection.SectionName,
14393           PragmaClangDataSection.PragmaLocation));
14394     if (PragmaClangRodataSection.Valid)
14395       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14396           Context, PragmaClangRodataSection.SectionName,
14397           PragmaClangRodataSection.PragmaLocation));
14398     if (PragmaClangRelroSection.Valid)
14399       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14400           Context, PragmaClangRelroSection.SectionName,
14401           PragmaClangRelroSection.PragmaLocation));
14402   }
14403 
14404   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14405     for (auto *BD : DD->bindings()) {
14406       FinalizeDeclaration(BD);
14407     }
14408   }
14409 
14410   checkAttributesAfterMerging(*this, *VD);
14411 
14412   if (VD->isStaticLocal())
14413     CheckStaticLocalForDllExport(VD);
14414 
14415   if (VD->getTLSKind())
14416     CheckThreadLocalForLargeAlignment(VD);
14417 
14418   // Perform check for initializers of device-side global variables.
14419   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14420   // 7.5). We must also apply the same checks to all __shared__
14421   // variables whether they are local or not. CUDA also allows
14422   // constant initializers for __constant__ and __device__ variables.
14423   if (getLangOpts().CUDA)
14424     checkAllowedCUDAInitializer(VD);
14425 
14426   // Grab the dllimport or dllexport attribute off of the VarDecl.
14427   const InheritableAttr *DLLAttr = getDLLAttr(VD);
14428 
14429   // Imported static data members cannot be defined out-of-line.
14430   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14431     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14432         VD->isThisDeclarationADefinition()) {
14433       // We allow definitions of dllimport class template static data members
14434       // with a warning.
14435       CXXRecordDecl *Context =
14436         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14437       bool IsClassTemplateMember =
14438           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14439           Context->getDescribedClassTemplate();
14440 
14441       Diag(VD->getLocation(),
14442            IsClassTemplateMember
14443                ? diag::warn_attribute_dllimport_static_field_definition
14444                : diag::err_attribute_dllimport_static_field_definition);
14445       Diag(IA->getLocation(), diag::note_attribute);
14446       if (!IsClassTemplateMember)
14447         VD->setInvalidDecl();
14448     }
14449   }
14450 
14451   // dllimport/dllexport variables cannot be thread local, their TLS index
14452   // isn't exported with the variable.
14453   if (DLLAttr && VD->getTLSKind()) {
14454     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14455     if (F && getDLLAttr(F)) {
14456       assert(VD->isStaticLocal());
14457       // But if this is a static local in a dlimport/dllexport function, the
14458       // function will never be inlined, which means the var would never be
14459       // imported, so having it marked import/export is safe.
14460     } else {
14461       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14462                                                                     << DLLAttr;
14463       VD->setInvalidDecl();
14464     }
14465   }
14466 
14467   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14468     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14469       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14470           << Attr;
14471       VD->dropAttr<UsedAttr>();
14472     }
14473   }
14474   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14475     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14476       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14477           << Attr;
14478       VD->dropAttr<RetainAttr>();
14479     }
14480   }
14481 
14482   const DeclContext *DC = VD->getDeclContext();
14483   // If there's a #pragma GCC visibility in scope, and this isn't a class
14484   // member, set the visibility of this variable.
14485   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14486     AddPushedVisibilityAttribute(VD);
14487 
14488   // FIXME: Warn on unused var template partial specializations.
14489   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14490     MarkUnusedFileScopedDecl(VD);
14491 
14492   // Now we have parsed the initializer and can update the table of magic
14493   // tag values.
14494   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14495       !VD->getType()->isIntegralOrEnumerationType())
14496     return;
14497 
14498   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14499     const Expr *MagicValueExpr = VD->getInit();
14500     if (!MagicValueExpr) {
14501       continue;
14502     }
14503     std::optional<llvm::APSInt> MagicValueInt;
14504     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14505       Diag(I->getRange().getBegin(),
14506            diag::err_type_tag_for_datatype_not_ice)
14507         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14508       continue;
14509     }
14510     if (MagicValueInt->getActiveBits() > 64) {
14511       Diag(I->getRange().getBegin(),
14512            diag::err_type_tag_for_datatype_too_large)
14513         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14514       continue;
14515     }
14516     uint64_t MagicValue = MagicValueInt->getZExtValue();
14517     RegisterTypeTagForDatatype(I->getArgumentKind(),
14518                                MagicValue,
14519                                I->getMatchingCType(),
14520                                I->getLayoutCompatible(),
14521                                I->getMustBeNull());
14522   }
14523 }
14524 
14525 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14526   auto *VD = dyn_cast<VarDecl>(DD);
14527   return VD && !VD->getType()->hasAutoForTrailingReturnType();
14528 }
14529 
14530 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14531                                                    ArrayRef<Decl *> Group) {
14532   SmallVector<Decl*, 8> Decls;
14533 
14534   if (DS.isTypeSpecOwned())
14535     Decls.push_back(DS.getRepAsDecl());
14536 
14537   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14538   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14539   bool DiagnosedMultipleDecomps = false;
14540   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14541   bool DiagnosedNonDeducedAuto = false;
14542 
14543   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14544     if (Decl *D = Group[i]) {
14545       // Check if the Decl has been declared in '#pragma omp declare target'
14546       // directive and has static storage duration.
14547       if (auto *VD = dyn_cast<VarDecl>(D);
14548           LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14549           VD->hasGlobalStorage())
14550         ActOnOpenMPDeclareTargetInitializer(D);
14551       // For declarators, there are some additional syntactic-ish checks we need
14552       // to perform.
14553       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14554         if (!FirstDeclaratorInGroup)
14555           FirstDeclaratorInGroup = DD;
14556         if (!FirstDecompDeclaratorInGroup)
14557           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14558         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14559             !hasDeducedAuto(DD))
14560           FirstNonDeducedAutoInGroup = DD;
14561 
14562         if (FirstDeclaratorInGroup != DD) {
14563           // A decomposition declaration cannot be combined with any other
14564           // declaration in the same group.
14565           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14566             Diag(FirstDecompDeclaratorInGroup->getLocation(),
14567                  diag::err_decomp_decl_not_alone)
14568                 << FirstDeclaratorInGroup->getSourceRange()
14569                 << DD->getSourceRange();
14570             DiagnosedMultipleDecomps = true;
14571           }
14572 
14573           // A declarator that uses 'auto' in any way other than to declare a
14574           // variable with a deduced type cannot be combined with any other
14575           // declarator in the same group.
14576           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14577             Diag(FirstNonDeducedAutoInGroup->getLocation(),
14578                  diag::err_auto_non_deduced_not_alone)
14579                 << FirstNonDeducedAutoInGroup->getType()
14580                        ->hasAutoForTrailingReturnType()
14581                 << FirstDeclaratorInGroup->getSourceRange()
14582                 << DD->getSourceRange();
14583             DiagnosedNonDeducedAuto = true;
14584           }
14585         }
14586       }
14587 
14588       Decls.push_back(D);
14589     }
14590   }
14591 
14592   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14593     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14594       handleTagNumbering(Tag, S);
14595       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14596           getLangOpts().CPlusPlus)
14597         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14598     }
14599   }
14600 
14601   return BuildDeclaratorGroup(Decls);
14602 }
14603 
14604 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14605 /// group, performing any necessary semantic checking.
14606 Sema::DeclGroupPtrTy
14607 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14608   // C++14 [dcl.spec.auto]p7: (DR1347)
14609   //   If the type that replaces the placeholder type is not the same in each
14610   //   deduction, the program is ill-formed.
14611   if (Group.size() > 1) {
14612     QualType Deduced;
14613     VarDecl *DeducedDecl = nullptr;
14614     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14615       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14616       if (!D || D->isInvalidDecl())
14617         break;
14618       DeducedType *DT = D->getType()->getContainedDeducedType();
14619       if (!DT || DT->getDeducedType().isNull())
14620         continue;
14621       if (Deduced.isNull()) {
14622         Deduced = DT->getDeducedType();
14623         DeducedDecl = D;
14624       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14625         auto *AT = dyn_cast<AutoType>(DT);
14626         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14627                         diag::err_auto_different_deductions)
14628                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14629                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14630                    << D->getDeclName();
14631         if (DeducedDecl->hasInit())
14632           Dia << DeducedDecl->getInit()->getSourceRange();
14633         if (D->getInit())
14634           Dia << D->getInit()->getSourceRange();
14635         D->setInvalidDecl();
14636         break;
14637       }
14638     }
14639   }
14640 
14641   ActOnDocumentableDecls(Group);
14642 
14643   return DeclGroupPtrTy::make(
14644       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14645 }
14646 
14647 void Sema::ActOnDocumentableDecl(Decl *D) {
14648   ActOnDocumentableDecls(D);
14649 }
14650 
14651 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14652   // Don't parse the comment if Doxygen diagnostics are ignored.
14653   if (Group.empty() || !Group[0])
14654     return;
14655 
14656   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14657                       Group[0]->getLocation()) &&
14658       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14659                       Group[0]->getLocation()))
14660     return;
14661 
14662   if (Group.size() >= 2) {
14663     // This is a decl group.  Normally it will contain only declarations
14664     // produced from declarator list.  But in case we have any definitions or
14665     // additional declaration references:
14666     //   'typedef struct S {} S;'
14667     //   'typedef struct S *S;'
14668     //   'struct S *pS;'
14669     // FinalizeDeclaratorGroup adds these as separate declarations.
14670     Decl *MaybeTagDecl = Group[0];
14671     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14672       Group = Group.slice(1);
14673     }
14674   }
14675 
14676   // FIMXE: We assume every Decl in the group is in the same file.
14677   // This is false when preprocessor constructs the group from decls in
14678   // different files (e. g. macros or #include).
14679   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14680 }
14681 
14682 /// Common checks for a parameter-declaration that should apply to both function
14683 /// parameters and non-type template parameters.
14684 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14685   // Check that there are no default arguments inside the type of this
14686   // parameter.
14687   if (getLangOpts().CPlusPlus)
14688     CheckExtraCXXDefaultArguments(D);
14689 
14690   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14691   if (D.getCXXScopeSpec().isSet()) {
14692     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14693       << D.getCXXScopeSpec().getRange();
14694   }
14695 
14696   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14697   // simple identifier except [...irrelevant cases...].
14698   switch (D.getName().getKind()) {
14699   case UnqualifiedIdKind::IK_Identifier:
14700     break;
14701 
14702   case UnqualifiedIdKind::IK_OperatorFunctionId:
14703   case UnqualifiedIdKind::IK_ConversionFunctionId:
14704   case UnqualifiedIdKind::IK_LiteralOperatorId:
14705   case UnqualifiedIdKind::IK_ConstructorName:
14706   case UnqualifiedIdKind::IK_DestructorName:
14707   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14708   case UnqualifiedIdKind::IK_DeductionGuideName:
14709     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14710       << GetNameForDeclarator(D).getName();
14711     break;
14712 
14713   case UnqualifiedIdKind::IK_TemplateId:
14714   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14715     // GetNameForDeclarator would not produce a useful name in this case.
14716     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14717     break;
14718   }
14719 }
14720 
14721 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14722 /// to introduce parameters into function prototype scope.
14723 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14724   const DeclSpec &DS = D.getDeclSpec();
14725 
14726   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14727 
14728   // C++03 [dcl.stc]p2 also permits 'auto'.
14729   StorageClass SC = SC_None;
14730   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14731     SC = SC_Register;
14732     // In C++11, the 'register' storage class specifier is deprecated.
14733     // In C++17, it is not allowed, but we tolerate it as an extension.
14734     if (getLangOpts().CPlusPlus11) {
14735       Diag(DS.getStorageClassSpecLoc(),
14736            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14737                                      : diag::warn_deprecated_register)
14738         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14739     }
14740   } else if (getLangOpts().CPlusPlus &&
14741              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14742     SC = SC_Auto;
14743   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14744     Diag(DS.getStorageClassSpecLoc(),
14745          diag::err_invalid_storage_class_in_func_decl);
14746     D.getMutableDeclSpec().ClearStorageClassSpecs();
14747   }
14748 
14749   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14750     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14751       << DeclSpec::getSpecifierName(TSCS);
14752   if (DS.isInlineSpecified())
14753     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14754         << getLangOpts().CPlusPlus17;
14755   if (DS.hasConstexprSpecifier())
14756     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14757         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14758 
14759   DiagnoseFunctionSpecifiers(DS);
14760 
14761   CheckFunctionOrTemplateParamDeclarator(S, D);
14762 
14763   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14764   QualType parmDeclType = TInfo->getType();
14765 
14766   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14767   IdentifierInfo *II = D.getIdentifier();
14768   if (II) {
14769     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14770                    ForVisibleRedeclaration);
14771     LookupName(R, S);
14772     if (R.isSingleResult()) {
14773       NamedDecl *PrevDecl = R.getFoundDecl();
14774       if (PrevDecl->isTemplateParameter()) {
14775         // Maybe we will complain about the shadowed template parameter.
14776         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14777         // Just pretend that we didn't see the previous declaration.
14778         PrevDecl = nullptr;
14779       } else if (S->isDeclScope(PrevDecl)) {
14780         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14781         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14782 
14783         // Recover by removing the name
14784         II = nullptr;
14785         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14786         D.setInvalidType(true);
14787       }
14788     }
14789   }
14790 
14791   // Temporarily put parameter variables in the translation unit, not
14792   // the enclosing context.  This prevents them from accidentally
14793   // looking like class members in C++.
14794   ParmVarDecl *New =
14795       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14796                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14797 
14798   if (D.isInvalidType())
14799     New->setInvalidDecl();
14800 
14801   assert(S->isFunctionPrototypeScope());
14802   assert(S->getFunctionPrototypeDepth() >= 1);
14803   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14804                     S->getNextFunctionPrototypeIndex());
14805 
14806   // Add the parameter declaration into this scope.
14807   S->AddDecl(New);
14808   if (II)
14809     IdResolver.AddDecl(New);
14810 
14811   ProcessDeclAttributes(S, New, D);
14812 
14813   if (D.getDeclSpec().isModulePrivateSpecified())
14814     Diag(New->getLocation(), diag::err_module_private_local)
14815         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14816         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14817 
14818   if (New->hasAttr<BlocksAttr>()) {
14819     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14820   }
14821 
14822   if (getLangOpts().OpenCL)
14823     deduceOpenCLAddressSpace(New);
14824 
14825   return New;
14826 }
14827 
14828 /// Synthesizes a variable for a parameter arising from a
14829 /// typedef.
14830 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14831                                               SourceLocation Loc,
14832                                               QualType T) {
14833   /* FIXME: setting StartLoc == Loc.
14834      Would it be worth to modify callers so as to provide proper source
14835      location for the unnamed parameters, embedding the parameter's type? */
14836   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14837                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14838                                            SC_None, nullptr);
14839   Param->setImplicit();
14840   return Param;
14841 }
14842 
14843 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14844   // Don't diagnose unused-parameter errors in template instantiations; we
14845   // will already have done so in the template itself.
14846   if (inTemplateInstantiation())
14847     return;
14848 
14849   for (const ParmVarDecl *Parameter : Parameters) {
14850     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14851         !Parameter->hasAttr<UnusedAttr>()) {
14852       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14853         << Parameter->getDeclName();
14854     }
14855   }
14856 }
14857 
14858 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14859     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14860   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14861     return;
14862 
14863   // Warn if the return value is pass-by-value and larger than the specified
14864   // threshold.
14865   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14866     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14867     if (Size > LangOpts.NumLargeByValueCopy)
14868       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14869   }
14870 
14871   // Warn if any parameter is pass-by-value and larger than the specified
14872   // threshold.
14873   for (const ParmVarDecl *Parameter : Parameters) {
14874     QualType T = Parameter->getType();
14875     if (T->isDependentType() || !T.isPODType(Context))
14876       continue;
14877     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14878     if (Size > LangOpts.NumLargeByValueCopy)
14879       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14880           << Parameter << Size;
14881   }
14882 }
14883 
14884 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14885                                   SourceLocation NameLoc, IdentifierInfo *Name,
14886                                   QualType T, TypeSourceInfo *TSInfo,
14887                                   StorageClass SC) {
14888   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14889   if (getLangOpts().ObjCAutoRefCount &&
14890       T.getObjCLifetime() == Qualifiers::OCL_None &&
14891       T->isObjCLifetimeType()) {
14892 
14893     Qualifiers::ObjCLifetime lifetime;
14894 
14895     // Special cases for arrays:
14896     //   - if it's const, use __unsafe_unretained
14897     //   - otherwise, it's an error
14898     if (T->isArrayType()) {
14899       if (!T.isConstQualified()) {
14900         if (DelayedDiagnostics.shouldDelayDiagnostics())
14901           DelayedDiagnostics.add(
14902               sema::DelayedDiagnostic::makeForbiddenType(
14903               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14904         else
14905           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14906               << TSInfo->getTypeLoc().getSourceRange();
14907       }
14908       lifetime = Qualifiers::OCL_ExplicitNone;
14909     } else {
14910       lifetime = T->getObjCARCImplicitLifetime();
14911     }
14912     T = Context.getLifetimeQualifiedType(T, lifetime);
14913   }
14914 
14915   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14916                                          Context.getAdjustedParameterType(T),
14917                                          TSInfo, SC, nullptr);
14918 
14919   // Make a note if we created a new pack in the scope of a lambda, so that
14920   // we know that references to that pack must also be expanded within the
14921   // lambda scope.
14922   if (New->isParameterPack())
14923     if (auto *LSI = getEnclosingLambda())
14924       LSI->LocalPacks.push_back(New);
14925 
14926   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14927       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14928     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14929                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14930 
14931   // Parameter declarators cannot be interface types. All ObjC objects are
14932   // passed by reference.
14933   if (T->isObjCObjectType()) {
14934     SourceLocation TypeEndLoc =
14935         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14936     Diag(NameLoc,
14937          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14938       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14939     T = Context.getObjCObjectPointerType(T);
14940     New->setType(T);
14941   }
14942 
14943   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14944   // duration shall not be qualified by an address-space qualifier."
14945   // Since all parameters have automatic store duration, they can not have
14946   // an address space.
14947   if (T.getAddressSpace() != LangAS::Default &&
14948       // OpenCL allows function arguments declared to be an array of a type
14949       // to be qualified with an address space.
14950       !(getLangOpts().OpenCL &&
14951         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
14952       // WebAssembly allows reference types as parameters. Funcref in particular
14953       // lives in a different address space.
14954       !(T->isFunctionPointerType() &&
14955         T.getAddressSpace() == LangAS::wasm_funcref)) {
14956     Diag(NameLoc, diag::err_arg_with_address_space);
14957     New->setInvalidDecl();
14958   }
14959 
14960   // PPC MMA non-pointer types are not allowed as function argument types.
14961   if (Context.getTargetInfo().getTriple().isPPC64() &&
14962       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14963     New->setInvalidDecl();
14964   }
14965 
14966   return New;
14967 }
14968 
14969 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14970                                            SourceLocation LocAfterDecls) {
14971   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14972 
14973   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14974   // in the declaration list shall have at least one declarator, those
14975   // declarators shall only declare identifiers from the identifier list, and
14976   // every identifier in the identifier list shall be declared.
14977   //
14978   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14979   // identifiers it names shall be declared in the declaration list."
14980   //
14981   // This is why we only diagnose in C99 and later. Note, the other conditions
14982   // listed are checked elsewhere.
14983   if (!FTI.hasPrototype) {
14984     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14985       --i;
14986       if (FTI.Params[i].Param == nullptr) {
14987         if (getLangOpts().C99) {
14988           SmallString<256> Code;
14989           llvm::raw_svector_ostream(Code)
14990               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14991           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14992               << FTI.Params[i].Ident
14993               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14994         }
14995 
14996         // Implicitly declare the argument as type 'int' for lack of a better
14997         // type.
14998         AttributeFactory attrs;
14999         DeclSpec DS(attrs);
15000         const char* PrevSpec; // unused
15001         unsigned DiagID; // unused
15002         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15003                            DiagID, Context.getPrintingPolicy());
15004         // Use the identifier location for the type source range.
15005         DS.SetRangeStart(FTI.Params[i].IdentLoc);
15006         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15007         Declarator ParamD(DS, ParsedAttributesView::none(),
15008                           DeclaratorContext::KNRTypeList);
15009         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15010         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15011       }
15012     }
15013   }
15014 }
15015 
15016 Decl *
15017 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15018                               MultiTemplateParamsArg TemplateParameterLists,
15019                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15020   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15021   assert(D.isFunctionDeclarator() && "Not a function declarator!");
15022   Scope *ParentScope = FnBodyScope->getParent();
15023 
15024   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15025   // we define a non-templated function definition, we will create a declaration
15026   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15027   // The base function declaration will have the equivalent of an `omp declare
15028   // variant` annotation which specifies the mangled definition as a
15029   // specialization function under the OpenMP context defined as part of the
15030   // `omp begin declare variant`.
15031   SmallVector<FunctionDecl *, 4> Bases;
15032   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15033     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15034         ParentScope, D, TemplateParameterLists, Bases);
15035 
15036   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15037   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15038   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15039 
15040   if (!Bases.empty())
15041     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15042 
15043   return Dcl;
15044 }
15045 
15046 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15047   Consumer.HandleInlineFunctionDefinition(D);
15048 }
15049 
15050 static bool FindPossiblePrototype(const FunctionDecl *FD,
15051                                   const FunctionDecl *&PossiblePrototype) {
15052   for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15053        Prev = Prev->getPreviousDecl()) {
15054     // Ignore any declarations that occur in function or method
15055     // scope, because they aren't visible from the header.
15056     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15057       continue;
15058 
15059     PossiblePrototype = Prev;
15060     return Prev->getType()->isFunctionProtoType();
15061   }
15062   return false;
15063 }
15064 
15065 static bool
15066 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15067                                 const FunctionDecl *&PossiblePrototype) {
15068   // Don't warn about invalid declarations.
15069   if (FD->isInvalidDecl())
15070     return false;
15071 
15072   // Or declarations that aren't global.
15073   if (!FD->isGlobal())
15074     return false;
15075 
15076   // Don't warn about C++ member functions.
15077   if (isa<CXXMethodDecl>(FD))
15078     return false;
15079 
15080   // Don't warn about 'main'.
15081   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15082     if (IdentifierInfo *II = FD->getIdentifier())
15083       if (II->isStr("main") || II->isStr("efi_main"))
15084         return false;
15085 
15086   // Don't warn about inline functions.
15087   if (FD->isInlined())
15088     return false;
15089 
15090   // Don't warn about function templates.
15091   if (FD->getDescribedFunctionTemplate())
15092     return false;
15093 
15094   // Don't warn about function template specializations.
15095   if (FD->isFunctionTemplateSpecialization())
15096     return false;
15097 
15098   // Don't warn for OpenCL kernels.
15099   if (FD->hasAttr<OpenCLKernelAttr>())
15100     return false;
15101 
15102   // Don't warn on explicitly deleted functions.
15103   if (FD->isDeleted())
15104     return false;
15105 
15106   // Don't warn on implicitly local functions (such as having local-typed
15107   // parameters).
15108   if (!FD->isExternallyVisible())
15109     return false;
15110 
15111   // If we were able to find a potential prototype, don't warn.
15112   if (FindPossiblePrototype(FD, PossiblePrototype))
15113     return false;
15114 
15115   return true;
15116 }
15117 
15118 void
15119 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15120                                    const FunctionDecl *EffectiveDefinition,
15121                                    SkipBodyInfo *SkipBody) {
15122   const FunctionDecl *Definition = EffectiveDefinition;
15123   if (!Definition &&
15124       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15125     return;
15126 
15127   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15128     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15129       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15130         // A merged copy of the same function, instantiated as a member of
15131         // the same class, is OK.
15132         if (declaresSameEntity(OrigFD, OrigDef) &&
15133             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15134                                cast<Decl>(FD->getLexicalDeclContext())))
15135           return;
15136       }
15137     }
15138   }
15139 
15140   if (canRedefineFunction(Definition, getLangOpts()))
15141     return;
15142 
15143   // Don't emit an error when this is redefinition of a typo-corrected
15144   // definition.
15145   if (TypoCorrectedFunctionDefinitions.count(Definition))
15146     return;
15147 
15148   // If we don't have a visible definition of the function, and it's inline or
15149   // a template, skip the new definition.
15150   if (SkipBody && !hasVisibleDefinition(Definition) &&
15151       (Definition->getFormalLinkage() == InternalLinkage ||
15152        Definition->isInlined() ||
15153        Definition->getDescribedFunctionTemplate() ||
15154        Definition->getNumTemplateParameterLists())) {
15155     SkipBody->ShouldSkip = true;
15156     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15157     if (auto *TD = Definition->getDescribedFunctionTemplate())
15158       makeMergedDefinitionVisible(TD);
15159     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15160     return;
15161   }
15162 
15163   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15164       Definition->getStorageClass() == SC_Extern)
15165     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15166         << FD << getLangOpts().CPlusPlus;
15167   else
15168     Diag(FD->getLocation(), diag::err_redefinition) << FD;
15169 
15170   Diag(Definition->getLocation(), diag::note_previous_definition);
15171   FD->setInvalidDecl();
15172 }
15173 
15174 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
15175                                    Sema &S) {
15176   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
15177 
15178   LambdaScopeInfo *LSI = S.PushLambdaScope();
15179   LSI->CallOperator = CallOperator;
15180   LSI->Lambda = LambdaClass;
15181   LSI->ReturnType = CallOperator->getReturnType();
15182   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15183 
15184   if (LCD == LCD_None)
15185     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15186   else if (LCD == LCD_ByCopy)
15187     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15188   else if (LCD == LCD_ByRef)
15189     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15190   DeclarationNameInfo DNI = CallOperator->getNameInfo();
15191 
15192   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15193   LSI->Mutable = !CallOperator->isConst();
15194 
15195   // Add the captures to the LSI so they can be noted as already
15196   // captured within tryCaptureVar.
15197   auto I = LambdaClass->field_begin();
15198   for (const auto &C : LambdaClass->captures()) {
15199     if (C.capturesVariable()) {
15200       ValueDecl *VD = C.getCapturedVar();
15201       if (VD->isInitCapture())
15202         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15203       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15204       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15205           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15206           /*EllipsisLoc*/C.isPackExpansion()
15207                          ? C.getEllipsisLoc() : SourceLocation(),
15208           I->getType(), /*Invalid*/false);
15209 
15210     } else if (C.capturesThis()) {
15211       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15212                           C.getCaptureKind() == LCK_StarThis);
15213     } else {
15214       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15215                              I->getType());
15216     }
15217     ++I;
15218   }
15219 }
15220 
15221 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15222                                     SkipBodyInfo *SkipBody,
15223                                     FnBodyKind BodyKind) {
15224   if (!D) {
15225     // Parsing the function declaration failed in some way. Push on a fake scope
15226     // anyway so we can try to parse the function body.
15227     PushFunctionScope();
15228     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15229     return D;
15230   }
15231 
15232   FunctionDecl *FD = nullptr;
15233 
15234   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15235     FD = FunTmpl->getTemplatedDecl();
15236   else
15237     FD = cast<FunctionDecl>(D);
15238 
15239   // Do not push if it is a lambda because one is already pushed when building
15240   // the lambda in ActOnStartOfLambdaDefinition().
15241   if (!isLambdaCallOperator(FD))
15242     // [expr.const]/p14.1
15243     // An expression or conversion is in an immediate function context if it is
15244     // potentially evaluated and either: its innermost enclosing non-block scope
15245     // is a function parameter scope of an immediate function.
15246     PushExpressionEvaluationContext(
15247         FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15248                           : ExprEvalContexts.back().Context);
15249 
15250   // Each ExpressionEvaluationContextRecord also keeps track of whether the
15251   // context is nested in an immediate function context, so smaller contexts
15252   // that appear inside immediate functions (like variable initializers) are
15253   // considered to be inside an immediate function context even though by
15254   // themselves they are not immediate function contexts. But when a new
15255   // function is entered, we need to reset this tracking, since the entered
15256   // function might be not an immediate function.
15257   ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15258   ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15259       getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15260 
15261   // Check for defining attributes before the check for redefinition.
15262   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15263     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15264     FD->dropAttr<AliasAttr>();
15265     FD->setInvalidDecl();
15266   }
15267   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15268     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15269     FD->dropAttr<IFuncAttr>();
15270     FD->setInvalidDecl();
15271   }
15272   if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15273     if (!Context.getTargetInfo().hasFeature("fmv") &&
15274         !Attr->isDefaultVersion()) {
15275       // If function multi versioning disabled skip parsing function body
15276       // defined with non-default target_version attribute
15277       if (SkipBody)
15278         SkipBody->ShouldSkip = true;
15279       return nullptr;
15280     }
15281   }
15282 
15283   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15284     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15285         Ctor->isDefaultConstructor() &&
15286         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15287       // If this is an MS ABI dllexport default constructor, instantiate any
15288       // default arguments.
15289       InstantiateDefaultCtorDefaultArgs(Ctor);
15290     }
15291   }
15292 
15293   // See if this is a redefinition. If 'will have body' (or similar) is already
15294   // set, then these checks were already performed when it was set.
15295   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15296       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15297     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15298 
15299     // If we're skipping the body, we're done. Don't enter the scope.
15300     if (SkipBody && SkipBody->ShouldSkip)
15301       return D;
15302   }
15303 
15304   // Mark this function as "will have a body eventually".  This lets users to
15305   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15306   // this function.
15307   FD->setWillHaveBody();
15308 
15309   // If we are instantiating a generic lambda call operator, push
15310   // a LambdaScopeInfo onto the function stack.  But use the information
15311   // that's already been calculated (ActOnLambdaExpr) to prime the current
15312   // LambdaScopeInfo.
15313   // When the template operator is being specialized, the LambdaScopeInfo,
15314   // has to be properly restored so that tryCaptureVariable doesn't try
15315   // and capture any new variables. In addition when calculating potential
15316   // captures during transformation of nested lambdas, it is necessary to
15317   // have the LSI properly restored.
15318   if (isGenericLambdaCallOperatorSpecialization(FD)) {
15319     assert(inTemplateInstantiation() &&
15320            "There should be an active template instantiation on the stack "
15321            "when instantiating a generic lambda!");
15322     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
15323   } else {
15324     // Enter a new function scope
15325     PushFunctionScope();
15326   }
15327 
15328   // Builtin functions cannot be defined.
15329   if (unsigned BuiltinID = FD->getBuiltinID()) {
15330     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15331         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15332       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15333       FD->setInvalidDecl();
15334     }
15335   }
15336 
15337   // The return type of a function definition must be complete (C99 6.9.1p3).
15338   // C++23 [dcl.fct.def.general]/p2
15339   // The type of [...] the return for a function definition
15340   // shall not be a (possibly cv-qualified) class type that is incomplete
15341   // or abstract within the function body unless the function is deleted.
15342   QualType ResultType = FD->getReturnType();
15343   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15344       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15345       (RequireCompleteType(FD->getLocation(), ResultType,
15346                            diag::err_func_def_incomplete_result) ||
15347        RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15348                               diag::err_abstract_type_in_decl,
15349                               AbstractReturnType)))
15350     FD->setInvalidDecl();
15351 
15352   if (FnBodyScope)
15353     PushDeclContext(FnBodyScope, FD);
15354 
15355   // Check the validity of our function parameters
15356   if (BodyKind != FnBodyKind::Delete)
15357     CheckParmsForFunctionDef(FD->parameters(),
15358                              /*CheckParameterNames=*/true);
15359 
15360   // Add non-parameter declarations already in the function to the current
15361   // scope.
15362   if (FnBodyScope) {
15363     for (Decl *NPD : FD->decls()) {
15364       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15365       if (!NonParmDecl)
15366         continue;
15367       assert(!isa<ParmVarDecl>(NonParmDecl) &&
15368              "parameters should not be in newly created FD yet");
15369 
15370       // If the decl has a name, make it accessible in the current scope.
15371       if (NonParmDecl->getDeclName())
15372         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15373 
15374       // Similarly, dive into enums and fish their constants out, making them
15375       // accessible in this scope.
15376       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15377         for (auto *EI : ED->enumerators())
15378           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15379       }
15380     }
15381   }
15382 
15383   // Introduce our parameters into the function scope
15384   for (auto *Param : FD->parameters()) {
15385     Param->setOwningFunction(FD);
15386 
15387     // If this has an identifier, add it to the scope stack.
15388     if (Param->getIdentifier() && FnBodyScope) {
15389       CheckShadow(FnBodyScope, Param);
15390 
15391       PushOnScopeChains(Param, FnBodyScope);
15392     }
15393   }
15394 
15395   // C++ [module.import/6] external definitions are not permitted in header
15396   // units.  Deleted and Defaulted functions are implicitly inline (but the
15397   // inline state is not set at this point, so check the BodyKind explicitly).
15398   // FIXME: Consider an alternate location for the test where the inlined()
15399   // state is complete.
15400   if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15401       !FD->isInvalidDecl() && !FD->isInlined() &&
15402       BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15403       FD->getFormalLinkage() == Linkage::ExternalLinkage &&
15404       !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15405     assert(FD->isThisDeclarationADefinition());
15406     Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15407     FD->setInvalidDecl();
15408   }
15409 
15410   // Ensure that the function's exception specification is instantiated.
15411   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15412     ResolveExceptionSpec(D->getLocation(), FPT);
15413 
15414   // dllimport cannot be applied to non-inline function definitions.
15415   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15416       !FD->isTemplateInstantiation()) {
15417     assert(!FD->hasAttr<DLLExportAttr>());
15418     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15419     FD->setInvalidDecl();
15420     return D;
15421   }
15422   // We want to attach documentation to original Decl (which might be
15423   // a function template).
15424   ActOnDocumentableDecl(D);
15425   if (getCurLexicalContext()->isObjCContainer() &&
15426       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15427       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15428     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15429 
15430   return D;
15431 }
15432 
15433 /// Given the set of return statements within a function body,
15434 /// compute the variables that are subject to the named return value
15435 /// optimization.
15436 ///
15437 /// Each of the variables that is subject to the named return value
15438 /// optimization will be marked as NRVO variables in the AST, and any
15439 /// return statement that has a marked NRVO variable as its NRVO candidate can
15440 /// use the named return value optimization.
15441 ///
15442 /// This function applies a very simplistic algorithm for NRVO: if every return
15443 /// statement in the scope of a variable has the same NRVO candidate, that
15444 /// candidate is an NRVO variable.
15445 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15446   ReturnStmt **Returns = Scope->Returns.data();
15447 
15448   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15449     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15450       if (!NRVOCandidate->isNRVOVariable())
15451         Returns[I]->setNRVOCandidate(nullptr);
15452     }
15453   }
15454 }
15455 
15456 bool Sema::canDelayFunctionBody(const Declarator &D) {
15457   // We can't delay parsing the body of a constexpr function template (yet).
15458   if (D.getDeclSpec().hasConstexprSpecifier())
15459     return false;
15460 
15461   // We can't delay parsing the body of a function template with a deduced
15462   // return type (yet).
15463   if (D.getDeclSpec().hasAutoTypeSpec()) {
15464     // If the placeholder introduces a non-deduced trailing return type,
15465     // we can still delay parsing it.
15466     if (D.getNumTypeObjects()) {
15467       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15468       if (Outer.Kind == DeclaratorChunk::Function &&
15469           Outer.Fun.hasTrailingReturnType()) {
15470         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15471         return Ty.isNull() || !Ty->isUndeducedType();
15472       }
15473     }
15474     return false;
15475   }
15476 
15477   return true;
15478 }
15479 
15480 bool Sema::canSkipFunctionBody(Decl *D) {
15481   // We cannot skip the body of a function (or function template) which is
15482   // constexpr, since we may need to evaluate its body in order to parse the
15483   // rest of the file.
15484   // We cannot skip the body of a function with an undeduced return type,
15485   // because any callers of that function need to know the type.
15486   if (const FunctionDecl *FD = D->getAsFunction()) {
15487     if (FD->isConstexpr())
15488       return false;
15489     // We can't simply call Type::isUndeducedType here, because inside template
15490     // auto can be deduced to a dependent type, which is not considered
15491     // "undeduced".
15492     if (FD->getReturnType()->getContainedDeducedType())
15493       return false;
15494   }
15495   return Consumer.shouldSkipFunctionBody(D);
15496 }
15497 
15498 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15499   if (!Decl)
15500     return nullptr;
15501   if (FunctionDecl *FD = Decl->getAsFunction())
15502     FD->setHasSkippedBody();
15503   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15504     MD->setHasSkippedBody();
15505   return Decl;
15506 }
15507 
15508 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15509   return ActOnFinishFunctionBody(D, BodyArg, false);
15510 }
15511 
15512 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15513 /// body.
15514 class ExitFunctionBodyRAII {
15515 public:
15516   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15517   ~ExitFunctionBodyRAII() {
15518     if (!IsLambda)
15519       S.PopExpressionEvaluationContext();
15520   }
15521 
15522 private:
15523   Sema &S;
15524   bool IsLambda = false;
15525 };
15526 
15527 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15528   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15529 
15530   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15531     if (EscapeInfo.count(BD))
15532       return EscapeInfo[BD];
15533 
15534     bool R = false;
15535     const BlockDecl *CurBD = BD;
15536 
15537     do {
15538       R = !CurBD->doesNotEscape();
15539       if (R)
15540         break;
15541       CurBD = CurBD->getParent()->getInnermostBlockDecl();
15542     } while (CurBD);
15543 
15544     return EscapeInfo[BD] = R;
15545   };
15546 
15547   // If the location where 'self' is implicitly retained is inside a escaping
15548   // block, emit a diagnostic.
15549   for (const std::pair<SourceLocation, const BlockDecl *> &P :
15550        S.ImplicitlyRetainedSelfLocs)
15551     if (IsOrNestedInEscapingBlock(P.second))
15552       S.Diag(P.first, diag::warn_implicitly_retains_self)
15553           << FixItHint::CreateInsertion(P.first, "self->");
15554 }
15555 
15556 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15557                                     bool IsInstantiation) {
15558   FunctionScopeInfo *FSI = getCurFunction();
15559   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15560 
15561   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15562     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15563 
15564   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15565   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15566 
15567   if (getLangOpts().Coroutines && FSI->isCoroutine())
15568     CheckCompletedCoroutineBody(FD, Body);
15569 
15570   {
15571     // Do not call PopExpressionEvaluationContext() if it is a lambda because
15572     // one is already popped when finishing the lambda in BuildLambdaExpr().
15573     // This is meant to pop the context added in ActOnStartOfFunctionDef().
15574     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15575     if (FD) {
15576       FD->setBody(Body);
15577       FD->setWillHaveBody(false);
15578       CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15579 
15580       if (getLangOpts().CPlusPlus14) {
15581         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15582             FD->getReturnType()->isUndeducedType()) {
15583           // For a function with a deduced result type to return void,
15584           // the result type as written must be 'auto' or 'decltype(auto)',
15585           // possibly cv-qualified or constrained, but not ref-qualified.
15586           if (!FD->getReturnType()->getAs<AutoType>()) {
15587             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15588                 << FD->getReturnType();
15589             FD->setInvalidDecl();
15590           } else {
15591             // Falling off the end of the function is the same as 'return;'.
15592             Expr *Dummy = nullptr;
15593             if (DeduceFunctionTypeFromReturnExpr(
15594                     FD, dcl->getLocation(), Dummy,
15595                     FD->getReturnType()->getAs<AutoType>()))
15596               FD->setInvalidDecl();
15597           }
15598         }
15599       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15600         // In C++11, we don't use 'auto' deduction rules for lambda call
15601         // operators because we don't support return type deduction.
15602         auto *LSI = getCurLambda();
15603         if (LSI->HasImplicitReturnType) {
15604           deduceClosureReturnType(*LSI);
15605 
15606           // C++11 [expr.prim.lambda]p4:
15607           //   [...] if there are no return statements in the compound-statement
15608           //   [the deduced type is] the type void
15609           QualType RetType =
15610               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15611 
15612           // Update the return type to the deduced type.
15613           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15614           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15615                                               Proto->getExtProtoInfo()));
15616         }
15617       }
15618 
15619       // If the function implicitly returns zero (like 'main') or is naked,
15620       // don't complain about missing return statements.
15621       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15622         WP.disableCheckFallThrough();
15623 
15624       // MSVC permits the use of pure specifier (=0) on function definition,
15625       // defined at class scope, warn about this non-standard construct.
15626       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15627         Diag(FD->getLocation(), diag::ext_pure_function_definition);
15628 
15629       if (!FD->isInvalidDecl()) {
15630         // Don't diagnose unused parameters of defaulted, deleted or naked
15631         // functions.
15632         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15633             !FD->hasAttr<NakedAttr>())
15634           DiagnoseUnusedParameters(FD->parameters());
15635         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15636                                                FD->getReturnType(), FD);
15637 
15638         // If this is a structor, we need a vtable.
15639         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15640           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15641         else if (CXXDestructorDecl *Destructor =
15642                      dyn_cast<CXXDestructorDecl>(FD))
15643           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15644 
15645         // Try to apply the named return value optimization. We have to check
15646         // if we can do this here because lambdas keep return statements around
15647         // to deduce an implicit return type.
15648         if (FD->getReturnType()->isRecordType() &&
15649             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15650           computeNRVO(Body, FSI);
15651       }
15652 
15653       // GNU warning -Wmissing-prototypes:
15654       //   Warn if a global function is defined without a previous
15655       //   prototype declaration. This warning is issued even if the
15656       //   definition itself provides a prototype. The aim is to detect
15657       //   global functions that fail to be declared in header files.
15658       const FunctionDecl *PossiblePrototype = nullptr;
15659       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15660         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15661 
15662         if (PossiblePrototype) {
15663           // We found a declaration that is not a prototype,
15664           // but that could be a zero-parameter prototype
15665           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15666             TypeLoc TL = TI->getTypeLoc();
15667             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15668               Diag(PossiblePrototype->getLocation(),
15669                    diag::note_declaration_not_a_prototype)
15670                   << (FD->getNumParams() != 0)
15671                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15672                                                     FTL.getRParenLoc(), "void")
15673                                               : FixItHint{});
15674           }
15675         } else {
15676           // Returns true if the token beginning at this Loc is `const`.
15677           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15678                                   const LangOptions &LangOpts) {
15679             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15680             if (LocInfo.first.isInvalid())
15681               return false;
15682 
15683             bool Invalid = false;
15684             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15685             if (Invalid)
15686               return false;
15687 
15688             if (LocInfo.second > Buffer.size())
15689               return false;
15690 
15691             const char *LexStart = Buffer.data() + LocInfo.second;
15692             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15693 
15694             return StartTok.consume_front("const") &&
15695                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15696                     StartTok.startswith("/*") || StartTok.startswith("//"));
15697           };
15698 
15699           auto findBeginLoc = [&]() {
15700             // If the return type has `const` qualifier, we want to insert
15701             // `static` before `const` (and not before the typename).
15702             if ((FD->getReturnType()->isAnyPointerType() &&
15703                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15704                 FD->getReturnType().isConstQualified()) {
15705               // But only do this if we can determine where the `const` is.
15706 
15707               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15708                                getLangOpts()))
15709 
15710                 return FD->getBeginLoc();
15711             }
15712             return FD->getTypeSpecStartLoc();
15713           };
15714           Diag(FD->getTypeSpecStartLoc(),
15715                diag::note_static_for_internal_linkage)
15716               << /* function */ 1
15717               << (FD->getStorageClass() == SC_None
15718                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15719                       : FixItHint{});
15720         }
15721       }
15722 
15723       // We might not have found a prototype because we didn't wish to warn on
15724       // the lack of a missing prototype. Try again without the checks for
15725       // whether we want to warn on the missing prototype.
15726       if (!PossiblePrototype)
15727         (void)FindPossiblePrototype(FD, PossiblePrototype);
15728 
15729       // If the function being defined does not have a prototype, then we may
15730       // need to diagnose it as changing behavior in C2x because we now know
15731       // whether the function accepts arguments or not. This only handles the
15732       // case where the definition has no prototype but does have parameters
15733       // and either there is no previous potential prototype, or the previous
15734       // potential prototype also has no actual prototype. This handles cases
15735       // like:
15736       //   void f(); void f(a) int a; {}
15737       //   void g(a) int a; {}
15738       // See MergeFunctionDecl() for other cases of the behavior change
15739       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15740       // type without a prototype.
15741       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15742           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15743                                   !PossiblePrototype->isImplicit()))) {
15744         // The function definition has parameters, so this will change behavior
15745         // in C2x. If there is a possible prototype, it comes before the
15746         // function definition.
15747         // FIXME: The declaration may have already been diagnosed as being
15748         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15749         // there's no way to test for the "changes behavior" condition in
15750         // SemaType.cpp when forming the declaration's function type. So, we do
15751         // this awkward dance instead.
15752         //
15753         // If we have a possible prototype and it declares a function with a
15754         // prototype, we don't want to diagnose it; if we have a possible
15755         // prototype and it has no prototype, it may have already been
15756         // diagnosed in SemaType.cpp as deprecated depending on whether
15757         // -Wstrict-prototypes is enabled. If we already warned about it being
15758         // deprecated, add a note that it also changes behavior. If we didn't
15759         // warn about it being deprecated (because the diagnostic is not
15760         // enabled), warn now that it is deprecated and changes behavior.
15761 
15762         // This K&R C function definition definitely changes behavior in C2x,
15763         // so diagnose it.
15764         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15765             << /*definition*/ 1 << /* not supported in C2x */ 0;
15766 
15767         // If we have a possible prototype for the function which is a user-
15768         // visible declaration, we already tested that it has no prototype.
15769         // This will change behavior in C2x. This gets a warning rather than a
15770         // note because it's the same behavior-changing problem as with the
15771         // definition.
15772         if (PossiblePrototype)
15773           Diag(PossiblePrototype->getLocation(),
15774                diag::warn_non_prototype_changes_behavior)
15775               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15776               << /*definition*/ 1;
15777       }
15778 
15779       // Warn on CPUDispatch with an actual body.
15780       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15781         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15782           if (!CmpndBody->body_empty())
15783             Diag(CmpndBody->body_front()->getBeginLoc(),
15784                  diag::warn_dispatch_body_ignored);
15785 
15786       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15787         const CXXMethodDecl *KeyFunction;
15788         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15789             MD->isVirtual() &&
15790             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15791             MD == KeyFunction->getCanonicalDecl()) {
15792           // Update the key-function state if necessary for this ABI.
15793           if (FD->isInlined() &&
15794               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15795             Context.setNonKeyFunction(MD);
15796 
15797             // If the newly-chosen key function is already defined, then we
15798             // need to mark the vtable as used retroactively.
15799             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15800             const FunctionDecl *Definition;
15801             if (KeyFunction && KeyFunction->isDefined(Definition))
15802               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15803           } else {
15804             // We just defined they key function; mark the vtable as used.
15805             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15806           }
15807         }
15808       }
15809 
15810       assert(
15811           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15812           "Function parsing confused");
15813     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15814       assert(MD == getCurMethodDecl() && "Method parsing confused");
15815       MD->setBody(Body);
15816       if (!MD->isInvalidDecl()) {
15817         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15818                                                MD->getReturnType(), MD);
15819 
15820         if (Body)
15821           computeNRVO(Body, FSI);
15822       }
15823       if (FSI->ObjCShouldCallSuper) {
15824         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15825             << MD->getSelector().getAsString();
15826         FSI->ObjCShouldCallSuper = false;
15827       }
15828       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15829         const ObjCMethodDecl *InitMethod = nullptr;
15830         bool isDesignated =
15831             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15832         assert(isDesignated && InitMethod);
15833         (void)isDesignated;
15834 
15835         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15836           auto IFace = MD->getClassInterface();
15837           if (!IFace)
15838             return false;
15839           auto SuperD = IFace->getSuperClass();
15840           if (!SuperD)
15841             return false;
15842           return SuperD->getIdentifier() ==
15843                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15844         };
15845         // Don't issue this warning for unavailable inits or direct subclasses
15846         // of NSObject.
15847         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15848           Diag(MD->getLocation(),
15849                diag::warn_objc_designated_init_missing_super_call);
15850           Diag(InitMethod->getLocation(),
15851                diag::note_objc_designated_init_marked_here);
15852         }
15853         FSI->ObjCWarnForNoDesignatedInitChain = false;
15854       }
15855       if (FSI->ObjCWarnForNoInitDelegation) {
15856         // Don't issue this warning for unavaialable inits.
15857         if (!MD->isUnavailable())
15858           Diag(MD->getLocation(),
15859                diag::warn_objc_secondary_init_missing_init_call);
15860         FSI->ObjCWarnForNoInitDelegation = false;
15861       }
15862 
15863       diagnoseImplicitlyRetainedSelf(*this);
15864     } else {
15865       // Parsing the function declaration failed in some way. Pop the fake scope
15866       // we pushed on.
15867       PopFunctionScopeInfo(ActivePolicy, dcl);
15868       return nullptr;
15869     }
15870 
15871     if (Body && FSI->HasPotentialAvailabilityViolations)
15872       DiagnoseUnguardedAvailabilityViolations(dcl);
15873 
15874     assert(!FSI->ObjCShouldCallSuper &&
15875            "This should only be set for ObjC methods, which should have been "
15876            "handled in the block above.");
15877 
15878     // Verify and clean out per-function state.
15879     if (Body && (!FD || !FD->isDefaulted())) {
15880       // C++ constructors that have function-try-blocks can't have return
15881       // statements in the handlers of that block. (C++ [except.handle]p14)
15882       // Verify this.
15883       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15884         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15885 
15886       // Verify that gotos and switch cases don't jump into scopes illegally.
15887       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15888         DiagnoseInvalidJumps(Body);
15889 
15890       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15891         if (!Destructor->getParent()->isDependentType())
15892           CheckDestructor(Destructor);
15893 
15894         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15895                                                Destructor->getParent());
15896       }
15897 
15898       // If any errors have occurred, clear out any temporaries that may have
15899       // been leftover. This ensures that these temporaries won't be picked up
15900       // for deletion in some later function.
15901       if (hasUncompilableErrorOccurred() ||
15902           getDiagnostics().getSuppressAllDiagnostics()) {
15903         DiscardCleanupsInEvaluationContext();
15904       }
15905       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15906         // Since the body is valid, issue any analysis-based warnings that are
15907         // enabled.
15908         ActivePolicy = &WP;
15909       }
15910 
15911       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15912           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15913         FD->setInvalidDecl();
15914 
15915       if (FD && FD->hasAttr<NakedAttr>()) {
15916         for (const Stmt *S : Body->children()) {
15917           // Allow local register variables without initializer as they don't
15918           // require prologue.
15919           bool RegisterVariables = false;
15920           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15921             for (const auto *Decl : DS->decls()) {
15922               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15923                 RegisterVariables =
15924                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15925                 if (!RegisterVariables)
15926                   break;
15927               }
15928             }
15929           }
15930           if (RegisterVariables)
15931             continue;
15932           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15933             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15934             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15935             FD->setInvalidDecl();
15936             break;
15937           }
15938         }
15939       }
15940 
15941       assert(ExprCleanupObjects.size() ==
15942                  ExprEvalContexts.back().NumCleanupObjects &&
15943              "Leftover temporaries in function");
15944       assert(!Cleanup.exprNeedsCleanups() &&
15945              "Unaccounted cleanups in function");
15946       assert(MaybeODRUseExprs.empty() &&
15947              "Leftover expressions for odr-use checking");
15948     }
15949   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15950     // the declaration context below. Otherwise, we're unable to transform
15951     // 'this' expressions when transforming immediate context functions.
15952 
15953   if (!IsInstantiation)
15954     PopDeclContext();
15955 
15956   PopFunctionScopeInfo(ActivePolicy, dcl);
15957   // If any errors have occurred, clear out any temporaries that may have
15958   // been leftover. This ensures that these temporaries won't be picked up for
15959   // deletion in some later function.
15960   if (hasUncompilableErrorOccurred()) {
15961     DiscardCleanupsInEvaluationContext();
15962   }
15963 
15964   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
15965                                   !LangOpts.OMPTargetTriples.empty())) ||
15966              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15967     auto ES = getEmissionStatus(FD);
15968     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15969         ES == Sema::FunctionEmissionStatus::Unknown)
15970       DeclsToCheckForDeferredDiags.insert(FD);
15971   }
15972 
15973   if (FD && !FD->isDeleted())
15974     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15975 
15976   return dcl;
15977 }
15978 
15979 /// When we finish delayed parsing of an attribute, we must attach it to the
15980 /// relevant Decl.
15981 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15982                                        ParsedAttributes &Attrs) {
15983   // Always attach attributes to the underlying decl.
15984   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15985     D = TD->getTemplatedDecl();
15986   ProcessDeclAttributeList(S, D, Attrs);
15987 
15988   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15989     if (Method->isStatic())
15990       checkThisInStaticMemberFunctionAttributes(Method);
15991 }
15992 
15993 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15994 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15995 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15996                                           IdentifierInfo &II, Scope *S) {
15997   // It is not valid to implicitly define a function in C2x.
15998   assert(LangOpts.implicitFunctionsAllowed() &&
15999          "Implicit function declarations aren't allowed in this language mode");
16000 
16001   // Find the scope in which the identifier is injected and the corresponding
16002   // DeclContext.
16003   // FIXME: C89 does not say what happens if there is no enclosing block scope.
16004   // In that case, we inject the declaration into the translation unit scope
16005   // instead.
16006   Scope *BlockScope = S;
16007   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16008     BlockScope = BlockScope->getParent();
16009 
16010   // Loop until we find a DeclContext that is either a function/method or the
16011   // translation unit, which are the only two valid places to implicitly define
16012   // a function. This avoids accidentally defining the function within a tag
16013   // declaration, for example.
16014   Scope *ContextScope = BlockScope;
16015   while (!ContextScope->getEntity() ||
16016          (!ContextScope->getEntity()->isFunctionOrMethod() &&
16017           !ContextScope->getEntity()->isTranslationUnit()))
16018     ContextScope = ContextScope->getParent();
16019   ContextRAII SavedContext(*this, ContextScope->getEntity());
16020 
16021   // Before we produce a declaration for an implicitly defined
16022   // function, see whether there was a locally-scoped declaration of
16023   // this name as a function or variable. If so, use that
16024   // (non-visible) declaration, and complain about it.
16025   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16026   if (ExternCPrev) {
16027     // We still need to inject the function into the enclosing block scope so
16028     // that later (non-call) uses can see it.
16029     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16030 
16031     // C89 footnote 38:
16032     //   If in fact it is not defined as having type "function returning int",
16033     //   the behavior is undefined.
16034     if (!isa<FunctionDecl>(ExternCPrev) ||
16035         !Context.typesAreCompatible(
16036             cast<FunctionDecl>(ExternCPrev)->getType(),
16037             Context.getFunctionNoProtoType(Context.IntTy))) {
16038       Diag(Loc, diag::ext_use_out_of_scope_declaration)
16039           << ExternCPrev << !getLangOpts().C99;
16040       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16041       return ExternCPrev;
16042     }
16043   }
16044 
16045   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16046   unsigned diag_id;
16047   if (II.getName().startswith("__builtin_"))
16048     diag_id = diag::warn_builtin_unknown;
16049   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16050   else if (getLangOpts().C99)
16051     diag_id = diag::ext_implicit_function_decl_c99;
16052   else
16053     diag_id = diag::warn_implicit_function_decl;
16054 
16055   TypoCorrection Corrected;
16056   // Because typo correction is expensive, only do it if the implicit
16057   // function declaration is going to be treated as an error.
16058   //
16059   // Perform the correction before issuing the main diagnostic, as some
16060   // consumers use typo-correction callbacks to enhance the main diagnostic.
16061   if (S && !ExternCPrev &&
16062       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16063     DeclFilterCCC<FunctionDecl> CCC{};
16064     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16065                             S, nullptr, CCC, CTK_NonError);
16066   }
16067 
16068   Diag(Loc, diag_id) << &II;
16069   if (Corrected) {
16070     // If the correction is going to suggest an implicitly defined function,
16071     // skip the correction as not being a particularly good idea.
16072     bool Diagnose = true;
16073     if (const auto *D = Corrected.getCorrectionDecl())
16074       Diagnose = !D->isImplicit();
16075     if (Diagnose)
16076       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16077                    /*ErrorRecovery*/ false);
16078   }
16079 
16080   // If we found a prior declaration of this function, don't bother building
16081   // another one. We've already pushed that one into scope, so there's nothing
16082   // more to do.
16083   if (ExternCPrev)
16084     return ExternCPrev;
16085 
16086   // Set a Declarator for the implicit definition: int foo();
16087   const char *Dummy;
16088   AttributeFactory attrFactory;
16089   DeclSpec DS(attrFactory);
16090   unsigned DiagID;
16091   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16092                                   Context.getPrintingPolicy());
16093   (void)Error; // Silence warning.
16094   assert(!Error && "Error setting up implicit decl!");
16095   SourceLocation NoLoc;
16096   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16097   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16098                                              /*IsAmbiguous=*/false,
16099                                              /*LParenLoc=*/NoLoc,
16100                                              /*Params=*/nullptr,
16101                                              /*NumParams=*/0,
16102                                              /*EllipsisLoc=*/NoLoc,
16103                                              /*RParenLoc=*/NoLoc,
16104                                              /*RefQualifierIsLvalueRef=*/true,
16105                                              /*RefQualifierLoc=*/NoLoc,
16106                                              /*MutableLoc=*/NoLoc, EST_None,
16107                                              /*ESpecRange=*/SourceRange(),
16108                                              /*Exceptions=*/nullptr,
16109                                              /*ExceptionRanges=*/nullptr,
16110                                              /*NumExceptions=*/0,
16111                                              /*NoexceptExpr=*/nullptr,
16112                                              /*ExceptionSpecTokens=*/nullptr,
16113                                              /*DeclsInPrototype=*/std::nullopt,
16114                                              Loc, Loc, D),
16115                 std::move(DS.getAttributes()), SourceLocation());
16116   D.SetIdentifier(&II, Loc);
16117 
16118   // Insert this function into the enclosing block scope.
16119   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16120   FD->setImplicit();
16121 
16122   AddKnownFunctionAttributes(FD);
16123 
16124   return FD;
16125 }
16126 
16127 /// If this function is a C++ replaceable global allocation function
16128 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16129 /// adds any function attributes that we know a priori based on the standard.
16130 ///
16131 /// We need to check for duplicate attributes both here and where user-written
16132 /// attributes are applied to declarations.
16133 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16134     FunctionDecl *FD) {
16135   if (FD->isInvalidDecl())
16136     return;
16137 
16138   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16139       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16140     return;
16141 
16142   std::optional<unsigned> AlignmentParam;
16143   bool IsNothrow = false;
16144   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16145     return;
16146 
16147   // C++2a [basic.stc.dynamic.allocation]p4:
16148   //   An allocation function that has a non-throwing exception specification
16149   //   indicates failure by returning a null pointer value. Any other allocation
16150   //   function never returns a null pointer value and indicates failure only by
16151   //   throwing an exception [...]
16152   //
16153   // However, -fcheck-new invalidates this possible assumption, so don't add
16154   // NonNull when that is enabled.
16155   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16156       !getLangOpts().CheckNew)
16157     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16158 
16159   // C++2a [basic.stc.dynamic.allocation]p2:
16160   //   An allocation function attempts to allocate the requested amount of
16161   //   storage. [...] If the request succeeds, the value returned by a
16162   //   replaceable allocation function is a [...] pointer value p0 different
16163   //   from any previously returned value p1 [...]
16164   //
16165   // However, this particular information is being added in codegen,
16166   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16167 
16168   // C++2a [basic.stc.dynamic.allocation]p2:
16169   //   An allocation function attempts to allocate the requested amount of
16170   //   storage. If it is successful, it returns the address of the start of a
16171   //   block of storage whose length in bytes is at least as large as the
16172   //   requested size.
16173   if (!FD->hasAttr<AllocSizeAttr>()) {
16174     FD->addAttr(AllocSizeAttr::CreateImplicit(
16175         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16176         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16177   }
16178 
16179   // C++2a [basic.stc.dynamic.allocation]p3:
16180   //   For an allocation function [...], the pointer returned on a successful
16181   //   call shall represent the address of storage that is aligned as follows:
16182   //   (3.1) If the allocation function takes an argument of type
16183   //         std​::​align_­val_­t, the storage will have the alignment
16184   //         specified by the value of this argument.
16185   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16186     FD->addAttr(AllocAlignAttr::CreateImplicit(
16187         Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16188   }
16189 
16190   // FIXME:
16191   // C++2a [basic.stc.dynamic.allocation]p3:
16192   //   For an allocation function [...], the pointer returned on a successful
16193   //   call shall represent the address of storage that is aligned as follows:
16194   //   (3.2) Otherwise, if the allocation function is named operator new[],
16195   //         the storage is aligned for any object that does not have
16196   //         new-extended alignment ([basic.align]) and is no larger than the
16197   //         requested size.
16198   //   (3.3) Otherwise, the storage is aligned for any object that does not
16199   //         have new-extended alignment and is of the requested size.
16200 }
16201 
16202 /// Adds any function attributes that we know a priori based on
16203 /// the declaration of this function.
16204 ///
16205 /// These attributes can apply both to implicitly-declared builtins
16206 /// (like __builtin___printf_chk) or to library-declared functions
16207 /// like NSLog or printf.
16208 ///
16209 /// We need to check for duplicate attributes both here and where user-written
16210 /// attributes are applied to declarations.
16211 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16212   if (FD->isInvalidDecl())
16213     return;
16214 
16215   // If this is a built-in function, map its builtin attributes to
16216   // actual attributes.
16217   if (unsigned BuiltinID = FD->getBuiltinID()) {
16218     // Handle printf-formatting attributes.
16219     unsigned FormatIdx;
16220     bool HasVAListArg;
16221     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16222       if (!FD->hasAttr<FormatAttr>()) {
16223         const char *fmt = "printf";
16224         unsigned int NumParams = FD->getNumParams();
16225         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16226             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16227           fmt = "NSString";
16228         FD->addAttr(FormatAttr::CreateImplicit(Context,
16229                                                &Context.Idents.get(fmt),
16230                                                FormatIdx+1,
16231                                                HasVAListArg ? 0 : FormatIdx+2,
16232                                                FD->getLocation()));
16233       }
16234     }
16235     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16236                                              HasVAListArg)) {
16237      if (!FD->hasAttr<FormatAttr>())
16238        FD->addAttr(FormatAttr::CreateImplicit(Context,
16239                                               &Context.Idents.get("scanf"),
16240                                               FormatIdx+1,
16241                                               HasVAListArg ? 0 : FormatIdx+2,
16242                                               FD->getLocation()));
16243     }
16244 
16245     // Handle automatically recognized callbacks.
16246     SmallVector<int, 4> Encoding;
16247     if (!FD->hasAttr<CallbackAttr>() &&
16248         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16249       FD->addAttr(CallbackAttr::CreateImplicit(
16250           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16251 
16252     // Mark const if we don't care about errno and/or floating point exceptions
16253     // that are the only thing preventing the function from being const. This
16254     // allows IRgen to use LLVM intrinsics for such functions.
16255     bool NoExceptions =
16256         getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16257     bool ConstWithoutErrnoAndExceptions =
16258         Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16259     bool ConstWithoutExceptions =
16260         Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16261     if (!FD->hasAttr<ConstAttr>() &&
16262         (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16263         (!ConstWithoutErrnoAndExceptions ||
16264          (!getLangOpts().MathErrno && NoExceptions)) &&
16265         (!ConstWithoutExceptions || NoExceptions))
16266       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16267 
16268     // We make "fma" on GNU or Windows const because we know it does not set
16269     // errno in those environments even though it could set errno based on the
16270     // C standard.
16271     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16272     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16273         !FD->hasAttr<ConstAttr>()) {
16274       switch (BuiltinID) {
16275       case Builtin::BI__builtin_fma:
16276       case Builtin::BI__builtin_fmaf:
16277       case Builtin::BI__builtin_fmal:
16278       case Builtin::BIfma:
16279       case Builtin::BIfmaf:
16280       case Builtin::BIfmal:
16281         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16282         break;
16283       default:
16284         break;
16285       }
16286     }
16287 
16288     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16289         !FD->hasAttr<ReturnsTwiceAttr>())
16290       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16291                                          FD->getLocation()));
16292     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16293       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16294     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16295       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16296     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16297       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16298     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16299         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16300       // Add the appropriate attribute, depending on the CUDA compilation mode
16301       // and which target the builtin belongs to. For example, during host
16302       // compilation, aux builtins are __device__, while the rest are __host__.
16303       if (getLangOpts().CUDAIsDevice !=
16304           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16305         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16306       else
16307         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16308     }
16309 
16310     // Add known guaranteed alignment for allocation functions.
16311     switch (BuiltinID) {
16312     case Builtin::BImemalign:
16313     case Builtin::BIaligned_alloc:
16314       if (!FD->hasAttr<AllocAlignAttr>())
16315         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16316                                                    FD->getLocation()));
16317       break;
16318     default:
16319       break;
16320     }
16321 
16322     // Add allocsize attribute for allocation functions.
16323     switch (BuiltinID) {
16324     case Builtin::BIcalloc:
16325       FD->addAttr(AllocSizeAttr::CreateImplicit(
16326           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16327       break;
16328     case Builtin::BImemalign:
16329     case Builtin::BIaligned_alloc:
16330     case Builtin::BIrealloc:
16331       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16332                                                 ParamIdx(), FD->getLocation()));
16333       break;
16334     case Builtin::BImalloc:
16335       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16336                                                 ParamIdx(), FD->getLocation()));
16337       break;
16338     default:
16339       break;
16340     }
16341 
16342     // Add lifetime attribute to std::move, std::fowrard et al.
16343     switch (BuiltinID) {
16344     case Builtin::BIaddressof:
16345     case Builtin::BI__addressof:
16346     case Builtin::BI__builtin_addressof:
16347     case Builtin::BIas_const:
16348     case Builtin::BIforward:
16349     case Builtin::BIforward_like:
16350     case Builtin::BImove:
16351     case Builtin::BImove_if_noexcept:
16352       if (ParmVarDecl *P = FD->getParamDecl(0u);
16353           !P->hasAttr<LifetimeBoundAttr>())
16354         P->addAttr(
16355             LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16356       break;
16357     default:
16358       break;
16359     }
16360   }
16361 
16362   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16363 
16364   // If C++ exceptions are enabled but we are told extern "C" functions cannot
16365   // throw, add an implicit nothrow attribute to any extern "C" function we come
16366   // across.
16367   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16368       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16369     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16370     if (!FPT || FPT->getExceptionSpecType() == EST_None)
16371       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16372   }
16373 
16374   IdentifierInfo *Name = FD->getIdentifier();
16375   if (!Name)
16376     return;
16377   if ((!getLangOpts().CPlusPlus &&
16378        FD->getDeclContext()->isTranslationUnit()) ||
16379       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16380        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16381        LinkageSpecDecl::lang_c)) {
16382     // Okay: this could be a libc/libm/Objective-C function we know
16383     // about.
16384   } else
16385     return;
16386 
16387   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16388     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16389     // target-specific builtins, perhaps?
16390     if (!FD->hasAttr<FormatAttr>())
16391       FD->addAttr(FormatAttr::CreateImplicit(Context,
16392                                              &Context.Idents.get("printf"), 2,
16393                                              Name->isStr("vasprintf") ? 0 : 3,
16394                                              FD->getLocation()));
16395   }
16396 
16397   if (Name->isStr("__CFStringMakeConstantString")) {
16398     // We already have a __builtin___CFStringMakeConstantString,
16399     // but builds that use -fno-constant-cfstrings don't go through that.
16400     if (!FD->hasAttr<FormatArgAttr>())
16401       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16402                                                 FD->getLocation()));
16403   }
16404 }
16405 
16406 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16407                                     TypeSourceInfo *TInfo) {
16408   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16409   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16410 
16411   if (!TInfo) {
16412     assert(D.isInvalidType() && "no declarator info for valid type");
16413     TInfo = Context.getTrivialTypeSourceInfo(T);
16414   }
16415 
16416   // Scope manipulation handled by caller.
16417   TypedefDecl *NewTD =
16418       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16419                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16420 
16421   // Bail out immediately if we have an invalid declaration.
16422   if (D.isInvalidType()) {
16423     NewTD->setInvalidDecl();
16424     return NewTD;
16425   }
16426 
16427   if (D.getDeclSpec().isModulePrivateSpecified()) {
16428     if (CurContext->isFunctionOrMethod())
16429       Diag(NewTD->getLocation(), diag::err_module_private_local)
16430           << 2 << NewTD
16431           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16432           << FixItHint::CreateRemoval(
16433                  D.getDeclSpec().getModulePrivateSpecLoc());
16434     else
16435       NewTD->setModulePrivate();
16436   }
16437 
16438   // C++ [dcl.typedef]p8:
16439   //   If the typedef declaration defines an unnamed class (or
16440   //   enum), the first typedef-name declared by the declaration
16441   //   to be that class type (or enum type) is used to denote the
16442   //   class type (or enum type) for linkage purposes only.
16443   // We need to check whether the type was declared in the declaration.
16444   switch (D.getDeclSpec().getTypeSpecType()) {
16445   case TST_enum:
16446   case TST_struct:
16447   case TST_interface:
16448   case TST_union:
16449   case TST_class: {
16450     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16451     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16452     break;
16453   }
16454 
16455   default:
16456     break;
16457   }
16458 
16459   return NewTD;
16460 }
16461 
16462 /// Check that this is a valid underlying type for an enum declaration.
16463 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16464   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16465   QualType T = TI->getType();
16466 
16467   if (T->isDependentType())
16468     return false;
16469 
16470   // This doesn't use 'isIntegralType' despite the error message mentioning
16471   // integral type because isIntegralType would also allow enum types in C.
16472   if (const BuiltinType *BT = T->getAs<BuiltinType>())
16473     if (BT->isInteger())
16474       return false;
16475 
16476   if (T->isBitIntType())
16477     return false;
16478 
16479   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16480 }
16481 
16482 /// Check whether this is a valid redeclaration of a previous enumeration.
16483 /// \return true if the redeclaration was invalid.
16484 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16485                                   QualType EnumUnderlyingTy, bool IsFixed,
16486                                   const EnumDecl *Prev) {
16487   if (IsScoped != Prev->isScoped()) {
16488     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16489       << Prev->isScoped();
16490     Diag(Prev->getLocation(), diag::note_previous_declaration);
16491     return true;
16492   }
16493 
16494   if (IsFixed && Prev->isFixed()) {
16495     if (!EnumUnderlyingTy->isDependentType() &&
16496         !Prev->getIntegerType()->isDependentType() &&
16497         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16498                                         Prev->getIntegerType())) {
16499       // TODO: Highlight the underlying type of the redeclaration.
16500       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16501         << EnumUnderlyingTy << Prev->getIntegerType();
16502       Diag(Prev->getLocation(), diag::note_previous_declaration)
16503           << Prev->getIntegerTypeRange();
16504       return true;
16505     }
16506   } else if (IsFixed != Prev->isFixed()) {
16507     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16508       << Prev->isFixed();
16509     Diag(Prev->getLocation(), diag::note_previous_declaration);
16510     return true;
16511   }
16512 
16513   return false;
16514 }
16515 
16516 /// Get diagnostic %select index for tag kind for
16517 /// redeclaration diagnostic message.
16518 /// WARNING: Indexes apply to particular diagnostics only!
16519 ///
16520 /// \returns diagnostic %select index.
16521 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16522   switch (Tag) {
16523   case TTK_Struct: return 0;
16524   case TTK_Interface: return 1;
16525   case TTK_Class:  return 2;
16526   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16527   }
16528 }
16529 
16530 /// Determine if tag kind is a class-key compatible with
16531 /// class for redeclaration (class, struct, or __interface).
16532 ///
16533 /// \returns true iff the tag kind is compatible.
16534 static bool isClassCompatTagKind(TagTypeKind Tag)
16535 {
16536   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16537 }
16538 
16539 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16540                                              TagTypeKind TTK) {
16541   if (isa<TypedefDecl>(PrevDecl))
16542     return NTK_Typedef;
16543   else if (isa<TypeAliasDecl>(PrevDecl))
16544     return NTK_TypeAlias;
16545   else if (isa<ClassTemplateDecl>(PrevDecl))
16546     return NTK_Template;
16547   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16548     return NTK_TypeAliasTemplate;
16549   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16550     return NTK_TemplateTemplateArgument;
16551   switch (TTK) {
16552   case TTK_Struct:
16553   case TTK_Interface:
16554   case TTK_Class:
16555     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16556   case TTK_Union:
16557     return NTK_NonUnion;
16558   case TTK_Enum:
16559     return NTK_NonEnum;
16560   }
16561   llvm_unreachable("invalid TTK");
16562 }
16563 
16564 /// Determine whether a tag with a given kind is acceptable
16565 /// as a redeclaration of the given tag declaration.
16566 ///
16567 /// \returns true if the new tag kind is acceptable, false otherwise.
16568 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16569                                         TagTypeKind NewTag, bool isDefinition,
16570                                         SourceLocation NewTagLoc,
16571                                         const IdentifierInfo *Name) {
16572   // C++ [dcl.type.elab]p3:
16573   //   The class-key or enum keyword present in the
16574   //   elaborated-type-specifier shall agree in kind with the
16575   //   declaration to which the name in the elaborated-type-specifier
16576   //   refers. This rule also applies to the form of
16577   //   elaborated-type-specifier that declares a class-name or
16578   //   friend class since it can be construed as referring to the
16579   //   definition of the class. Thus, in any
16580   //   elaborated-type-specifier, the enum keyword shall be used to
16581   //   refer to an enumeration (7.2), the union class-key shall be
16582   //   used to refer to a union (clause 9), and either the class or
16583   //   struct class-key shall be used to refer to a class (clause 9)
16584   //   declared using the class or struct class-key.
16585   TagTypeKind OldTag = Previous->getTagKind();
16586   if (OldTag != NewTag &&
16587       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16588     return false;
16589 
16590   // Tags are compatible, but we might still want to warn on mismatched tags.
16591   // Non-class tags can't be mismatched at this point.
16592   if (!isClassCompatTagKind(NewTag))
16593     return true;
16594 
16595   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16596   // by our warning analysis. We don't want to warn about mismatches with (eg)
16597   // declarations in system headers that are designed to be specialized, but if
16598   // a user asks us to warn, we should warn if their code contains mismatched
16599   // declarations.
16600   auto IsIgnoredLoc = [&](SourceLocation Loc) {
16601     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16602                                       Loc);
16603   };
16604   if (IsIgnoredLoc(NewTagLoc))
16605     return true;
16606 
16607   auto IsIgnored = [&](const TagDecl *Tag) {
16608     return IsIgnoredLoc(Tag->getLocation());
16609   };
16610   while (IsIgnored(Previous)) {
16611     Previous = Previous->getPreviousDecl();
16612     if (!Previous)
16613       return true;
16614     OldTag = Previous->getTagKind();
16615   }
16616 
16617   bool isTemplate = false;
16618   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16619     isTemplate = Record->getDescribedClassTemplate();
16620 
16621   if (inTemplateInstantiation()) {
16622     if (OldTag != NewTag) {
16623       // In a template instantiation, do not offer fix-its for tag mismatches
16624       // since they usually mess up the template instead of fixing the problem.
16625       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16626         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16627         << getRedeclDiagFromTagKind(OldTag);
16628       // FIXME: Note previous location?
16629     }
16630     return true;
16631   }
16632 
16633   if (isDefinition) {
16634     // On definitions, check all previous tags and issue a fix-it for each
16635     // one that doesn't match the current tag.
16636     if (Previous->getDefinition()) {
16637       // Don't suggest fix-its for redefinitions.
16638       return true;
16639     }
16640 
16641     bool previousMismatch = false;
16642     for (const TagDecl *I : Previous->redecls()) {
16643       if (I->getTagKind() != NewTag) {
16644         // Ignore previous declarations for which the warning was disabled.
16645         if (IsIgnored(I))
16646           continue;
16647 
16648         if (!previousMismatch) {
16649           previousMismatch = true;
16650           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16651             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16652             << getRedeclDiagFromTagKind(I->getTagKind());
16653         }
16654         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16655           << getRedeclDiagFromTagKind(NewTag)
16656           << FixItHint::CreateReplacement(I->getInnerLocStart(),
16657                TypeWithKeyword::getTagTypeKindName(NewTag));
16658       }
16659     }
16660     return true;
16661   }
16662 
16663   // Identify the prevailing tag kind: this is the kind of the definition (if
16664   // there is a non-ignored definition), or otherwise the kind of the prior
16665   // (non-ignored) declaration.
16666   const TagDecl *PrevDef = Previous->getDefinition();
16667   if (PrevDef && IsIgnored(PrevDef))
16668     PrevDef = nullptr;
16669   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16670   if (Redecl->getTagKind() != NewTag) {
16671     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16672       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16673       << getRedeclDiagFromTagKind(OldTag);
16674     Diag(Redecl->getLocation(), diag::note_previous_use);
16675 
16676     // If there is a previous definition, suggest a fix-it.
16677     if (PrevDef) {
16678       Diag(NewTagLoc, diag::note_struct_class_suggestion)
16679         << getRedeclDiagFromTagKind(Redecl->getTagKind())
16680         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16681              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16682     }
16683   }
16684 
16685   return true;
16686 }
16687 
16688 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16689 /// from an outer enclosing namespace or file scope inside a friend declaration.
16690 /// This should provide the commented out code in the following snippet:
16691 ///   namespace N {
16692 ///     struct X;
16693 ///     namespace M {
16694 ///       struct Y { friend struct /*N::*/ X; };
16695 ///     }
16696 ///   }
16697 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16698                                          SourceLocation NameLoc) {
16699   // While the decl is in a namespace, do repeated lookup of that name and see
16700   // if we get the same namespace back.  If we do not, continue until
16701   // translation unit scope, at which point we have a fully qualified NNS.
16702   SmallVector<IdentifierInfo *, 4> Namespaces;
16703   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16704   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16705     // This tag should be declared in a namespace, which can only be enclosed by
16706     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16707     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16708     if (!Namespace || Namespace->isAnonymousNamespace())
16709       return FixItHint();
16710     IdentifierInfo *II = Namespace->getIdentifier();
16711     Namespaces.push_back(II);
16712     NamedDecl *Lookup = SemaRef.LookupSingleName(
16713         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16714     if (Lookup == Namespace)
16715       break;
16716   }
16717 
16718   // Once we have all the namespaces, reverse them to go outermost first, and
16719   // build an NNS.
16720   SmallString<64> Insertion;
16721   llvm::raw_svector_ostream OS(Insertion);
16722   if (DC->isTranslationUnit())
16723     OS << "::";
16724   std::reverse(Namespaces.begin(), Namespaces.end());
16725   for (auto *II : Namespaces)
16726     OS << II->getName() << "::";
16727   return FixItHint::CreateInsertion(NameLoc, Insertion);
16728 }
16729 
16730 /// Determine whether a tag originally declared in context \p OldDC can
16731 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16732 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16733 /// using-declaration).
16734 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16735                                          DeclContext *NewDC) {
16736   OldDC = OldDC->getRedeclContext();
16737   NewDC = NewDC->getRedeclContext();
16738 
16739   if (OldDC->Equals(NewDC))
16740     return true;
16741 
16742   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16743   // encloses the other).
16744   if (S.getLangOpts().MSVCCompat &&
16745       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16746     return true;
16747 
16748   return false;
16749 }
16750 
16751 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16752 /// former case, Name will be non-null.  In the later case, Name will be null.
16753 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16754 /// reference/declaration/definition of a tag.
16755 ///
16756 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16757 /// trailing-type-specifier) other than one in an alias-declaration.
16758 ///
16759 /// \param SkipBody If non-null, will be set to indicate if the caller should
16760 /// skip the definition of this tag and treat it as if it were a declaration.
16761 DeclResult
16762 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16763                CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16764                const ParsedAttributesView &Attrs, AccessSpecifier AS,
16765                SourceLocation ModulePrivateLoc,
16766                MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16767                bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16768                bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16769                bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16770                OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16771   // If this is not a definition, it must have a name.
16772   IdentifierInfo *OrigName = Name;
16773   assert((Name != nullptr || TUK == TUK_Definition) &&
16774          "Nameless record must be a definition!");
16775   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16776 
16777   OwnedDecl = false;
16778   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16779   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16780 
16781   // FIXME: Check member specializations more carefully.
16782   bool isMemberSpecialization = false;
16783   bool Invalid = false;
16784 
16785   // We only need to do this matching if we have template parameters
16786   // or a scope specifier, which also conveniently avoids this work
16787   // for non-C++ cases.
16788   if (TemplateParameterLists.size() > 0 ||
16789       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16790     if (TemplateParameterList *TemplateParams =
16791             MatchTemplateParametersToScopeSpecifier(
16792                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16793                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16794       if (Kind == TTK_Enum) {
16795         Diag(KWLoc, diag::err_enum_template);
16796         return true;
16797       }
16798 
16799       if (TemplateParams->size() > 0) {
16800         // This is a declaration or definition of a class template (which may
16801         // be a member of another template).
16802 
16803         if (Invalid)
16804           return true;
16805 
16806         OwnedDecl = false;
16807         DeclResult Result = CheckClassTemplate(
16808             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16809             AS, ModulePrivateLoc,
16810             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16811             TemplateParameterLists.data(), SkipBody);
16812         return Result.get();
16813       } else {
16814         // The "template<>" header is extraneous.
16815         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16816           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16817         isMemberSpecialization = true;
16818       }
16819     }
16820 
16821     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16822         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16823       return true;
16824   }
16825 
16826   // Figure out the underlying type if this a enum declaration. We need to do
16827   // this early, because it's needed to detect if this is an incompatible
16828   // redeclaration.
16829   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16830   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16831 
16832   if (Kind == TTK_Enum) {
16833     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16834       // No underlying type explicitly specified, or we failed to parse the
16835       // type, default to int.
16836       EnumUnderlying = Context.IntTy.getTypePtr();
16837     } else if (UnderlyingType.get()) {
16838       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16839       // integral type; any cv-qualification is ignored.
16840       TypeSourceInfo *TI = nullptr;
16841       GetTypeFromParser(UnderlyingType.get(), &TI);
16842       EnumUnderlying = TI;
16843 
16844       if (CheckEnumUnderlyingType(TI))
16845         // Recover by falling back to int.
16846         EnumUnderlying = Context.IntTy.getTypePtr();
16847 
16848       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16849                                           UPPC_FixedUnderlyingType))
16850         EnumUnderlying = Context.IntTy.getTypePtr();
16851 
16852     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16853       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16854       // of 'int'. However, if this is an unfixed forward declaration, don't set
16855       // the underlying type unless the user enables -fms-compatibility. This
16856       // makes unfixed forward declared enums incomplete and is more conforming.
16857       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16858         EnumUnderlying = Context.IntTy.getTypePtr();
16859     }
16860   }
16861 
16862   DeclContext *SearchDC = CurContext;
16863   DeclContext *DC = CurContext;
16864   bool isStdBadAlloc = false;
16865   bool isStdAlignValT = false;
16866 
16867   RedeclarationKind Redecl = forRedeclarationInCurContext();
16868   if (TUK == TUK_Friend || TUK == TUK_Reference)
16869     Redecl = NotForRedeclaration;
16870 
16871   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16872   /// implemented asks for structural equivalence checking, the returned decl
16873   /// here is passed back to the parser, allowing the tag body to be parsed.
16874   auto createTagFromNewDecl = [&]() -> TagDecl * {
16875     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16876     // If there is an identifier, use the location of the identifier as the
16877     // location of the decl, otherwise use the location of the struct/union
16878     // keyword.
16879     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16880     TagDecl *New = nullptr;
16881 
16882     if (Kind == TTK_Enum) {
16883       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16884                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16885       // If this is an undefined enum, bail.
16886       if (TUK != TUK_Definition && !Invalid)
16887         return nullptr;
16888       if (EnumUnderlying) {
16889         EnumDecl *ED = cast<EnumDecl>(New);
16890         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16891           ED->setIntegerTypeSourceInfo(TI);
16892         else
16893           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16894         QualType EnumTy = ED->getIntegerType();
16895         ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
16896                                  ? Context.getPromotedIntegerType(EnumTy)
16897                                  : EnumTy);
16898       }
16899     } else { // struct/union
16900       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16901                                nullptr);
16902     }
16903 
16904     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16905       // Add alignment attributes if necessary; these attributes are checked
16906       // when the ASTContext lays out the structure.
16907       //
16908       // It is important for implementing the correct semantics that this
16909       // happen here (in ActOnTag). The #pragma pack stack is
16910       // maintained as a result of parser callbacks which can occur at
16911       // many points during the parsing of a struct declaration (because
16912       // the #pragma tokens are effectively skipped over during the
16913       // parsing of the struct).
16914       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16915         AddAlignmentAttributesForRecord(RD);
16916         AddMsStructLayoutForRecord(RD);
16917       }
16918     }
16919     New->setLexicalDeclContext(CurContext);
16920     return New;
16921   };
16922 
16923   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16924   if (Name && SS.isNotEmpty()) {
16925     // We have a nested-name tag ('struct foo::bar').
16926 
16927     // Check for invalid 'foo::'.
16928     if (SS.isInvalid()) {
16929       Name = nullptr;
16930       goto CreateNewDecl;
16931     }
16932 
16933     // If this is a friend or a reference to a class in a dependent
16934     // context, don't try to make a decl for it.
16935     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16936       DC = computeDeclContext(SS, false);
16937       if (!DC) {
16938         IsDependent = true;
16939         return true;
16940       }
16941     } else {
16942       DC = computeDeclContext(SS, true);
16943       if (!DC) {
16944         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16945           << SS.getRange();
16946         return true;
16947       }
16948     }
16949 
16950     if (RequireCompleteDeclContext(SS, DC))
16951       return true;
16952 
16953     SearchDC = DC;
16954     // Look-up name inside 'foo::'.
16955     LookupQualifiedName(Previous, DC);
16956 
16957     if (Previous.isAmbiguous())
16958       return true;
16959 
16960     if (Previous.empty()) {
16961       // Name lookup did not find anything. However, if the
16962       // nested-name-specifier refers to the current instantiation,
16963       // and that current instantiation has any dependent base
16964       // classes, we might find something at instantiation time: treat
16965       // this as a dependent elaborated-type-specifier.
16966       // But this only makes any sense for reference-like lookups.
16967       if (Previous.wasNotFoundInCurrentInstantiation() &&
16968           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16969         IsDependent = true;
16970         return true;
16971       }
16972 
16973       // A tag 'foo::bar' must already exist.
16974       Diag(NameLoc, diag::err_not_tag_in_scope)
16975         << Kind << Name << DC << SS.getRange();
16976       Name = nullptr;
16977       Invalid = true;
16978       goto CreateNewDecl;
16979     }
16980   } else if (Name) {
16981     // C++14 [class.mem]p14:
16982     //   If T is the name of a class, then each of the following shall have a
16983     //   name different from T:
16984     //    -- every member of class T that is itself a type
16985     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16986         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16987       return true;
16988 
16989     // If this is a named struct, check to see if there was a previous forward
16990     // declaration or definition.
16991     // FIXME: We're looking into outer scopes here, even when we
16992     // shouldn't be. Doing so can result in ambiguities that we
16993     // shouldn't be diagnosing.
16994     LookupName(Previous, S);
16995 
16996     // When declaring or defining a tag, ignore ambiguities introduced
16997     // by types using'ed into this scope.
16998     if (Previous.isAmbiguous() &&
16999         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17000       LookupResult::Filter F = Previous.makeFilter();
17001       while (F.hasNext()) {
17002         NamedDecl *ND = F.next();
17003         if (!ND->getDeclContext()->getRedeclContext()->Equals(
17004                 SearchDC->getRedeclContext()))
17005           F.erase();
17006       }
17007       F.done();
17008     }
17009 
17010     // C++11 [namespace.memdef]p3:
17011     //   If the name in a friend declaration is neither qualified nor
17012     //   a template-id and the declaration is a function or an
17013     //   elaborated-type-specifier, the lookup to determine whether
17014     //   the entity has been previously declared shall not consider
17015     //   any scopes outside the innermost enclosing namespace.
17016     //
17017     // MSVC doesn't implement the above rule for types, so a friend tag
17018     // declaration may be a redeclaration of a type declared in an enclosing
17019     // scope.  They do implement this rule for friend functions.
17020     //
17021     // Does it matter that this should be by scope instead of by
17022     // semantic context?
17023     if (!Previous.empty() && TUK == TUK_Friend) {
17024       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17025       LookupResult::Filter F = Previous.makeFilter();
17026       bool FriendSawTagOutsideEnclosingNamespace = false;
17027       while (F.hasNext()) {
17028         NamedDecl *ND = F.next();
17029         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17030         if (DC->isFileContext() &&
17031             !EnclosingNS->Encloses(ND->getDeclContext())) {
17032           if (getLangOpts().MSVCCompat)
17033             FriendSawTagOutsideEnclosingNamespace = true;
17034           else
17035             F.erase();
17036         }
17037       }
17038       F.done();
17039 
17040       // Diagnose this MSVC extension in the easy case where lookup would have
17041       // unambiguously found something outside the enclosing namespace.
17042       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17043         NamedDecl *ND = Previous.getFoundDecl();
17044         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17045             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17046       }
17047     }
17048 
17049     // Note:  there used to be some attempt at recovery here.
17050     if (Previous.isAmbiguous())
17051       return true;
17052 
17053     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17054       // FIXME: This makes sure that we ignore the contexts associated
17055       // with C structs, unions, and enums when looking for a matching
17056       // tag declaration or definition. See the similar lookup tweak
17057       // in Sema::LookupName; is there a better way to deal with this?
17058       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17059         SearchDC = SearchDC->getParent();
17060     } else if (getLangOpts().CPlusPlus) {
17061       // Inside ObjCContainer want to keep it as a lexical decl context but go
17062       // past it (most often to TranslationUnit) to find the semantic decl
17063       // context.
17064       while (isa<ObjCContainerDecl>(SearchDC))
17065         SearchDC = SearchDC->getParent();
17066     }
17067   } else if (getLangOpts().CPlusPlus) {
17068     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17069     // TagDecl the same way as we skip it for named TagDecl.
17070     while (isa<ObjCContainerDecl>(SearchDC))
17071       SearchDC = SearchDC->getParent();
17072   }
17073 
17074   if (Previous.isSingleResult() &&
17075       Previous.getFoundDecl()->isTemplateParameter()) {
17076     // Maybe we will complain about the shadowed template parameter.
17077     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17078     // Just pretend that we didn't see the previous declaration.
17079     Previous.clear();
17080   }
17081 
17082   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17083       DC->Equals(getStdNamespace())) {
17084     if (Name->isStr("bad_alloc")) {
17085       // This is a declaration of or a reference to "std::bad_alloc".
17086       isStdBadAlloc = true;
17087 
17088       // If std::bad_alloc has been implicitly declared (but made invisible to
17089       // name lookup), fill in this implicit declaration as the previous
17090       // declaration, so that the declarations get chained appropriately.
17091       if (Previous.empty() && StdBadAlloc)
17092         Previous.addDecl(getStdBadAlloc());
17093     } else if (Name->isStr("align_val_t")) {
17094       isStdAlignValT = true;
17095       if (Previous.empty() && StdAlignValT)
17096         Previous.addDecl(getStdAlignValT());
17097     }
17098   }
17099 
17100   // If we didn't find a previous declaration, and this is a reference
17101   // (or friend reference), move to the correct scope.  In C++, we
17102   // also need to do a redeclaration lookup there, just in case
17103   // there's a shadow friend decl.
17104   if (Name && Previous.empty() &&
17105       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17106     if (Invalid) goto CreateNewDecl;
17107     assert(SS.isEmpty());
17108 
17109     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17110       // C++ [basic.scope.pdecl]p5:
17111       //   -- for an elaborated-type-specifier of the form
17112       //
17113       //          class-key identifier
17114       //
17115       //      if the elaborated-type-specifier is used in the
17116       //      decl-specifier-seq or parameter-declaration-clause of a
17117       //      function defined in namespace scope, the identifier is
17118       //      declared as a class-name in the namespace that contains
17119       //      the declaration; otherwise, except as a friend
17120       //      declaration, the identifier is declared in the smallest
17121       //      non-class, non-function-prototype scope that contains the
17122       //      declaration.
17123       //
17124       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17125       // C structs and unions.
17126       //
17127       // It is an error in C++ to declare (rather than define) an enum
17128       // type, including via an elaborated type specifier.  We'll
17129       // diagnose that later; for now, declare the enum in the same
17130       // scope as we would have picked for any other tag type.
17131       //
17132       // GNU C also supports this behavior as part of its incomplete
17133       // enum types extension, while GNU C++ does not.
17134       //
17135       // Find the context where we'll be declaring the tag.
17136       // FIXME: We would like to maintain the current DeclContext as the
17137       // lexical context,
17138       SearchDC = getTagInjectionContext(SearchDC);
17139 
17140       // Find the scope where we'll be declaring the tag.
17141       S = getTagInjectionScope(S, getLangOpts());
17142     } else {
17143       assert(TUK == TUK_Friend);
17144       CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17145 
17146       // C++ [namespace.memdef]p3:
17147       //   If a friend declaration in a non-local class first declares a
17148       //   class or function, the friend class or function is a member of
17149       //   the innermost enclosing namespace.
17150       SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17151                                     : SearchDC->getEnclosingNamespaceContext();
17152     }
17153 
17154     // In C++, we need to do a redeclaration lookup to properly
17155     // diagnose some problems.
17156     // FIXME: redeclaration lookup is also used (with and without C++) to find a
17157     // hidden declaration so that we don't get ambiguity errors when using a
17158     // type declared by an elaborated-type-specifier.  In C that is not correct
17159     // and we should instead merge compatible types found by lookup.
17160     if (getLangOpts().CPlusPlus) {
17161       // FIXME: This can perform qualified lookups into function contexts,
17162       // which are meaningless.
17163       Previous.setRedeclarationKind(forRedeclarationInCurContext());
17164       LookupQualifiedName(Previous, SearchDC);
17165     } else {
17166       Previous.setRedeclarationKind(forRedeclarationInCurContext());
17167       LookupName(Previous, S);
17168     }
17169   }
17170 
17171   // If we have a known previous declaration to use, then use it.
17172   if (Previous.empty() && SkipBody && SkipBody->Previous)
17173     Previous.addDecl(SkipBody->Previous);
17174 
17175   if (!Previous.empty()) {
17176     NamedDecl *PrevDecl = Previous.getFoundDecl();
17177     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17178 
17179     // It's okay to have a tag decl in the same scope as a typedef
17180     // which hides a tag decl in the same scope.  Finding this
17181     // with a redeclaration lookup can only actually happen in C++.
17182     //
17183     // This is also okay for elaborated-type-specifiers, which is
17184     // technically forbidden by the current standard but which is
17185     // okay according to the likely resolution of an open issue;
17186     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17187     if (getLangOpts().CPlusPlus) {
17188       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17189         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17190           TagDecl *Tag = TT->getDecl();
17191           if (Tag->getDeclName() == Name &&
17192               Tag->getDeclContext()->getRedeclContext()
17193                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
17194             PrevDecl = Tag;
17195             Previous.clear();
17196             Previous.addDecl(Tag);
17197             Previous.resolveKind();
17198           }
17199         }
17200       }
17201     }
17202 
17203     // If this is a redeclaration of a using shadow declaration, it must
17204     // declare a tag in the same context. In MSVC mode, we allow a
17205     // redefinition if either context is within the other.
17206     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17207       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17208       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17209           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17210           !(OldTag && isAcceptableTagRedeclContext(
17211                           *this, OldTag->getDeclContext(), SearchDC))) {
17212         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17213         Diag(Shadow->getTargetDecl()->getLocation(),
17214              diag::note_using_decl_target);
17215         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17216             << 0;
17217         // Recover by ignoring the old declaration.
17218         Previous.clear();
17219         goto CreateNewDecl;
17220       }
17221     }
17222 
17223     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17224       // If this is a use of a previous tag, or if the tag is already declared
17225       // in the same scope (so that the definition/declaration completes or
17226       // rementions the tag), reuse the decl.
17227       if (TUK == TUK_Reference || TUK == TUK_Friend ||
17228           isDeclInScope(DirectPrevDecl, SearchDC, S,
17229                         SS.isNotEmpty() || isMemberSpecialization)) {
17230         // Make sure that this wasn't declared as an enum and now used as a
17231         // struct or something similar.
17232         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17233                                           TUK == TUK_Definition, KWLoc,
17234                                           Name)) {
17235           bool SafeToContinue
17236             = (PrevTagDecl->getTagKind() != TTK_Enum &&
17237                Kind != TTK_Enum);
17238           if (SafeToContinue)
17239             Diag(KWLoc, diag::err_use_with_wrong_tag)
17240               << Name
17241               << FixItHint::CreateReplacement(SourceRange(KWLoc),
17242                                               PrevTagDecl->getKindName());
17243           else
17244             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17245           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17246 
17247           if (SafeToContinue)
17248             Kind = PrevTagDecl->getTagKind();
17249           else {
17250             // Recover by making this an anonymous redefinition.
17251             Name = nullptr;
17252             Previous.clear();
17253             Invalid = true;
17254           }
17255         }
17256 
17257         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17258           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17259           if (TUK == TUK_Reference || TUK == TUK_Friend)
17260             return PrevTagDecl;
17261 
17262           QualType EnumUnderlyingTy;
17263           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17264             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17265           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17266             EnumUnderlyingTy = QualType(T, 0);
17267 
17268           // All conflicts with previous declarations are recovered by
17269           // returning the previous declaration, unless this is a definition,
17270           // in which case we want the caller to bail out.
17271           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17272                                      ScopedEnum, EnumUnderlyingTy,
17273                                      IsFixed, PrevEnum))
17274             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17275         }
17276 
17277         // C++11 [class.mem]p1:
17278         //   A member shall not be declared twice in the member-specification,
17279         //   except that a nested class or member class template can be declared
17280         //   and then later defined.
17281         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17282             S->isDeclScope(PrevDecl)) {
17283           Diag(NameLoc, diag::ext_member_redeclared);
17284           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17285         }
17286 
17287         if (!Invalid) {
17288           // If this is a use, just return the declaration we found, unless
17289           // we have attributes.
17290           if (TUK == TUK_Reference || TUK == TUK_Friend) {
17291             if (!Attrs.empty()) {
17292               // FIXME: Diagnose these attributes. For now, we create a new
17293               // declaration to hold them.
17294             } else if (TUK == TUK_Reference &&
17295                        (PrevTagDecl->getFriendObjectKind() ==
17296                             Decl::FOK_Undeclared ||
17297                         PrevDecl->getOwningModule() != getCurrentModule()) &&
17298                        SS.isEmpty()) {
17299               // This declaration is a reference to an existing entity, but
17300               // has different visibility from that entity: it either makes
17301               // a friend visible or it makes a type visible in a new module.
17302               // In either case, create a new declaration. We only do this if
17303               // the declaration would have meant the same thing if no prior
17304               // declaration were found, that is, if it was found in the same
17305               // scope where we would have injected a declaration.
17306               if (!getTagInjectionContext(CurContext)->getRedeclContext()
17307                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17308                 return PrevTagDecl;
17309               // This is in the injected scope, create a new declaration in
17310               // that scope.
17311               S = getTagInjectionScope(S, getLangOpts());
17312             } else {
17313               return PrevTagDecl;
17314             }
17315           }
17316 
17317           // Diagnose attempts to redefine a tag.
17318           if (TUK == TUK_Definition) {
17319             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17320               // If we're defining a specialization and the previous definition
17321               // is from an implicit instantiation, don't emit an error
17322               // here; we'll catch this in the general case below.
17323               bool IsExplicitSpecializationAfterInstantiation = false;
17324               if (isMemberSpecialization) {
17325                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17326                   IsExplicitSpecializationAfterInstantiation =
17327                     RD->getTemplateSpecializationKind() !=
17328                     TSK_ExplicitSpecialization;
17329                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17330                   IsExplicitSpecializationAfterInstantiation =
17331                     ED->getTemplateSpecializationKind() !=
17332                     TSK_ExplicitSpecialization;
17333               }
17334 
17335               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17336               // not keep more that one definition around (merge them). However,
17337               // ensure the decl passes the structural compatibility check in
17338               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17339               NamedDecl *Hidden = nullptr;
17340               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17341                 // There is a definition of this tag, but it is not visible. We
17342                 // explicitly make use of C++'s one definition rule here, and
17343                 // assume that this definition is identical to the hidden one
17344                 // we already have. Make the existing definition visible and
17345                 // use it in place of this one.
17346                 if (!getLangOpts().CPlusPlus) {
17347                   // Postpone making the old definition visible until after we
17348                   // complete parsing the new one and do the structural
17349                   // comparison.
17350                   SkipBody->CheckSameAsPrevious = true;
17351                   SkipBody->New = createTagFromNewDecl();
17352                   SkipBody->Previous = Def;
17353                   return Def;
17354                 } else {
17355                   SkipBody->ShouldSkip = true;
17356                   SkipBody->Previous = Def;
17357                   makeMergedDefinitionVisible(Hidden);
17358                   // Carry on and handle it like a normal definition. We'll
17359                   // skip starting the definitiion later.
17360                 }
17361               } else if (!IsExplicitSpecializationAfterInstantiation) {
17362                 // A redeclaration in function prototype scope in C isn't
17363                 // visible elsewhere, so merely issue a warning.
17364                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17365                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17366                 else
17367                   Diag(NameLoc, diag::err_redefinition) << Name;
17368                 notePreviousDefinition(Def,
17369                                        NameLoc.isValid() ? NameLoc : KWLoc);
17370                 // If this is a redefinition, recover by making this
17371                 // struct be anonymous, which will make any later
17372                 // references get the previous definition.
17373                 Name = nullptr;
17374                 Previous.clear();
17375                 Invalid = true;
17376               }
17377             } else {
17378               // If the type is currently being defined, complain
17379               // about a nested redefinition.
17380               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17381               if (TD->isBeingDefined()) {
17382                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17383                 Diag(PrevTagDecl->getLocation(),
17384                      diag::note_previous_definition);
17385                 Name = nullptr;
17386                 Previous.clear();
17387                 Invalid = true;
17388               }
17389             }
17390 
17391             // Okay, this is definition of a previously declared or referenced
17392             // tag. We're going to create a new Decl for it.
17393           }
17394 
17395           // Okay, we're going to make a redeclaration.  If this is some kind
17396           // of reference, make sure we build the redeclaration in the same DC
17397           // as the original, and ignore the current access specifier.
17398           if (TUK == TUK_Friend || TUK == TUK_Reference) {
17399             SearchDC = PrevTagDecl->getDeclContext();
17400             AS = AS_none;
17401           }
17402         }
17403         // If we get here we have (another) forward declaration or we
17404         // have a definition.  Just create a new decl.
17405 
17406       } else {
17407         // If we get here, this is a definition of a new tag type in a nested
17408         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17409         // new decl/type.  We set PrevDecl to NULL so that the entities
17410         // have distinct types.
17411         Previous.clear();
17412       }
17413       // If we get here, we're going to create a new Decl. If PrevDecl
17414       // is non-NULL, it's a definition of the tag declared by
17415       // PrevDecl. If it's NULL, we have a new definition.
17416 
17417     // Otherwise, PrevDecl is not a tag, but was found with tag
17418     // lookup.  This is only actually possible in C++, where a few
17419     // things like templates still live in the tag namespace.
17420     } else {
17421       // Use a better diagnostic if an elaborated-type-specifier
17422       // found the wrong kind of type on the first
17423       // (non-redeclaration) lookup.
17424       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17425           !Previous.isForRedeclaration()) {
17426         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17427         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17428                                                        << Kind;
17429         Diag(PrevDecl->getLocation(), diag::note_declared_at);
17430         Invalid = true;
17431 
17432       // Otherwise, only diagnose if the declaration is in scope.
17433       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17434                                 SS.isNotEmpty() || isMemberSpecialization)) {
17435         // do nothing
17436 
17437       // Diagnose implicit declarations introduced by elaborated types.
17438       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17439         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17440         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17441         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17442         Invalid = true;
17443 
17444       // Otherwise it's a declaration.  Call out a particularly common
17445       // case here.
17446       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17447         unsigned Kind = 0;
17448         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17449         Diag(NameLoc, diag::err_tag_definition_of_typedef)
17450           << Name << Kind << TND->getUnderlyingType();
17451         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17452         Invalid = true;
17453 
17454       // Otherwise, diagnose.
17455       } else {
17456         // The tag name clashes with something else in the target scope,
17457         // issue an error and recover by making this tag be anonymous.
17458         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17459         notePreviousDefinition(PrevDecl, NameLoc);
17460         Name = nullptr;
17461         Invalid = true;
17462       }
17463 
17464       // The existing declaration isn't relevant to us; we're in a
17465       // new scope, so clear out the previous declaration.
17466       Previous.clear();
17467     }
17468   }
17469 
17470 CreateNewDecl:
17471 
17472   TagDecl *PrevDecl = nullptr;
17473   if (Previous.isSingleResult())
17474     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17475 
17476   // If there is an identifier, use the location of the identifier as the
17477   // location of the decl, otherwise use the location of the struct/union
17478   // keyword.
17479   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17480 
17481   // Otherwise, create a new declaration. If there is a previous
17482   // declaration of the same entity, the two will be linked via
17483   // PrevDecl.
17484   TagDecl *New;
17485 
17486   if (Kind == TTK_Enum) {
17487     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17488     // enum X { A, B, C } D;    D should chain to X.
17489     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17490                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17491                            ScopedEnumUsesClassTag, IsFixed);
17492 
17493     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17494       StdAlignValT = cast<EnumDecl>(New);
17495 
17496     // If this is an undefined enum, warn.
17497     if (TUK != TUK_Definition && !Invalid) {
17498       TagDecl *Def;
17499       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17500         // C++0x: 7.2p2: opaque-enum-declaration.
17501         // Conflicts are diagnosed above. Do nothing.
17502       }
17503       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17504         Diag(Loc, diag::ext_forward_ref_enum_def)
17505           << New;
17506         Diag(Def->getLocation(), diag::note_previous_definition);
17507       } else {
17508         unsigned DiagID = diag::ext_forward_ref_enum;
17509         if (getLangOpts().MSVCCompat)
17510           DiagID = diag::ext_ms_forward_ref_enum;
17511         else if (getLangOpts().CPlusPlus)
17512           DiagID = diag::err_forward_ref_enum;
17513         Diag(Loc, DiagID);
17514       }
17515     }
17516 
17517     if (EnumUnderlying) {
17518       EnumDecl *ED = cast<EnumDecl>(New);
17519       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17520         ED->setIntegerTypeSourceInfo(TI);
17521       else
17522         ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17523       QualType EnumTy = ED->getIntegerType();
17524       ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17525                                ? Context.getPromotedIntegerType(EnumTy)
17526                                : EnumTy);
17527       assert(ED->isComplete() && "enum with type should be complete");
17528     }
17529   } else {
17530     // struct/union/class
17531 
17532     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17533     // struct X { int A; } D;    D should chain to X.
17534     if (getLangOpts().CPlusPlus) {
17535       // FIXME: Look for a way to use RecordDecl for simple structs.
17536       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17537                                   cast_or_null<CXXRecordDecl>(PrevDecl));
17538 
17539       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17540         StdBadAlloc = cast<CXXRecordDecl>(New);
17541     } else
17542       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17543                                cast_or_null<RecordDecl>(PrevDecl));
17544   }
17545 
17546   if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17547     Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17548         << (OOK == OOK_Macro) << New->getSourceRange();
17549 
17550   // C++11 [dcl.type]p3:
17551   //   A type-specifier-seq shall not define a class or enumeration [...].
17552   if (!Invalid && getLangOpts().CPlusPlus &&
17553       (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17554     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17555       << Context.getTagDeclType(New);
17556     Invalid = true;
17557   }
17558 
17559   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17560       DC->getDeclKind() == Decl::Enum) {
17561     Diag(New->getLocation(), diag::err_type_defined_in_enum)
17562       << Context.getTagDeclType(New);
17563     Invalid = true;
17564   }
17565 
17566   // Maybe add qualifier info.
17567   if (SS.isNotEmpty()) {
17568     if (SS.isSet()) {
17569       // If this is either a declaration or a definition, check the
17570       // nested-name-specifier against the current context.
17571       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17572           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17573                                        isMemberSpecialization))
17574         Invalid = true;
17575 
17576       New->setQualifierInfo(SS.getWithLocInContext(Context));
17577       if (TemplateParameterLists.size() > 0) {
17578         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17579       }
17580     }
17581     else
17582       Invalid = true;
17583   }
17584 
17585   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17586     // Add alignment attributes if necessary; these attributes are checked when
17587     // the ASTContext lays out the structure.
17588     //
17589     // It is important for implementing the correct semantics that this
17590     // happen here (in ActOnTag). The #pragma pack stack is
17591     // maintained as a result of parser callbacks which can occur at
17592     // many points during the parsing of a struct declaration (because
17593     // the #pragma tokens are effectively skipped over during the
17594     // parsing of the struct).
17595     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17596       AddAlignmentAttributesForRecord(RD);
17597       AddMsStructLayoutForRecord(RD);
17598     }
17599   }
17600 
17601   if (ModulePrivateLoc.isValid()) {
17602     if (isMemberSpecialization)
17603       Diag(New->getLocation(), diag::err_module_private_specialization)
17604         << 2
17605         << FixItHint::CreateRemoval(ModulePrivateLoc);
17606     // __module_private__ does not apply to local classes. However, we only
17607     // diagnose this as an error when the declaration specifiers are
17608     // freestanding. Here, we just ignore the __module_private__.
17609     else if (!SearchDC->isFunctionOrMethod())
17610       New->setModulePrivate();
17611   }
17612 
17613   // If this is a specialization of a member class (of a class template),
17614   // check the specialization.
17615   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17616     Invalid = true;
17617 
17618   // If we're declaring or defining a tag in function prototype scope in C,
17619   // note that this type can only be used within the function and add it to
17620   // the list of decls to inject into the function definition scope.
17621   if ((Name || Kind == TTK_Enum) &&
17622       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17623     if (getLangOpts().CPlusPlus) {
17624       // C++ [dcl.fct]p6:
17625       //   Types shall not be defined in return or parameter types.
17626       if (TUK == TUK_Definition && !IsTypeSpecifier) {
17627         Diag(Loc, diag::err_type_defined_in_param_type)
17628             << Name;
17629         Invalid = true;
17630       }
17631     } else if (!PrevDecl) {
17632       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17633     }
17634   }
17635 
17636   if (Invalid)
17637     New->setInvalidDecl();
17638 
17639   // Set the lexical context. If the tag has a C++ scope specifier, the
17640   // lexical context will be different from the semantic context.
17641   New->setLexicalDeclContext(CurContext);
17642 
17643   // Mark this as a friend decl if applicable.
17644   // In Microsoft mode, a friend declaration also acts as a forward
17645   // declaration so we always pass true to setObjectOfFriendDecl to make
17646   // the tag name visible.
17647   if (TUK == TUK_Friend)
17648     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17649 
17650   // Set the access specifier.
17651   if (!Invalid && SearchDC->isRecord())
17652     SetMemberAccessSpecifier(New, PrevDecl, AS);
17653 
17654   if (PrevDecl)
17655     CheckRedeclarationInModule(New, PrevDecl);
17656 
17657   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17658     New->startDefinition();
17659 
17660   ProcessDeclAttributeList(S, New, Attrs);
17661   AddPragmaAttributes(S, New);
17662 
17663   // If this has an identifier, add it to the scope stack.
17664   if (TUK == TUK_Friend) {
17665     // We might be replacing an existing declaration in the lookup tables;
17666     // if so, borrow its access specifier.
17667     if (PrevDecl)
17668       New->setAccess(PrevDecl->getAccess());
17669 
17670     DeclContext *DC = New->getDeclContext()->getRedeclContext();
17671     DC->makeDeclVisibleInContext(New);
17672     if (Name) // can be null along some error paths
17673       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17674         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17675   } else if (Name) {
17676     S = getNonFieldDeclScope(S);
17677     PushOnScopeChains(New, S, true);
17678   } else {
17679     CurContext->addDecl(New);
17680   }
17681 
17682   // If this is the C FILE type, notify the AST context.
17683   if (IdentifierInfo *II = New->getIdentifier())
17684     if (!New->isInvalidDecl() &&
17685         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17686         II->isStr("FILE"))
17687       Context.setFILEDecl(New);
17688 
17689   if (PrevDecl)
17690     mergeDeclAttributes(New, PrevDecl);
17691 
17692   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17693     inferGslOwnerPointerAttribute(CXXRD);
17694 
17695   // If there's a #pragma GCC visibility in scope, set the visibility of this
17696   // record.
17697   AddPushedVisibilityAttribute(New);
17698 
17699   if (isMemberSpecialization && !New->isInvalidDecl())
17700     CompleteMemberSpecialization(New, Previous);
17701 
17702   OwnedDecl = true;
17703   // In C++, don't return an invalid declaration. We can't recover well from
17704   // the cases where we make the type anonymous.
17705   if (Invalid && getLangOpts().CPlusPlus) {
17706     if (New->isBeingDefined())
17707       if (auto RD = dyn_cast<RecordDecl>(New))
17708         RD->completeDefinition();
17709     return true;
17710   } else if (SkipBody && SkipBody->ShouldSkip) {
17711     return SkipBody->Previous;
17712   } else {
17713     return New;
17714   }
17715 }
17716 
17717 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17718   AdjustDeclIfTemplate(TagD);
17719   TagDecl *Tag = cast<TagDecl>(TagD);
17720 
17721   // Enter the tag context.
17722   PushDeclContext(S, Tag);
17723 
17724   ActOnDocumentableDecl(TagD);
17725 
17726   // If there's a #pragma GCC visibility in scope, set the visibility of this
17727   // record.
17728   AddPushedVisibilityAttribute(Tag);
17729 }
17730 
17731 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17732   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17733     return false;
17734 
17735   // Make the previous decl visible.
17736   makeMergedDefinitionVisible(SkipBody.Previous);
17737   return true;
17738 }
17739 
17740 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17741   assert(IDecl->getLexicalParent() == CurContext &&
17742       "The next DeclContext should be lexically contained in the current one.");
17743   CurContext = IDecl;
17744 }
17745 
17746 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17747                                            SourceLocation FinalLoc,
17748                                            bool IsFinalSpelledSealed,
17749                                            bool IsAbstract,
17750                                            SourceLocation LBraceLoc) {
17751   AdjustDeclIfTemplate(TagD);
17752   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17753 
17754   FieldCollector->StartClass();
17755 
17756   if (!Record->getIdentifier())
17757     return;
17758 
17759   if (IsAbstract)
17760     Record->markAbstract();
17761 
17762   if (FinalLoc.isValid()) {
17763     Record->addAttr(FinalAttr::Create(Context, FinalLoc,
17764                                       IsFinalSpelledSealed
17765                                           ? FinalAttr::Keyword_sealed
17766                                           : FinalAttr::Keyword_final));
17767   }
17768   // C++ [class]p2:
17769   //   [...] The class-name is also inserted into the scope of the
17770   //   class itself; this is known as the injected-class-name. For
17771   //   purposes of access checking, the injected-class-name is treated
17772   //   as if it were a public member name.
17773   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17774       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17775       Record->getLocation(), Record->getIdentifier(),
17776       /*PrevDecl=*/nullptr,
17777       /*DelayTypeCreation=*/true);
17778   Context.getTypeDeclType(InjectedClassName, Record);
17779   InjectedClassName->setImplicit();
17780   InjectedClassName->setAccess(AS_public);
17781   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17782       InjectedClassName->setDescribedClassTemplate(Template);
17783   PushOnScopeChains(InjectedClassName, S);
17784   assert(InjectedClassName->isInjectedClassName() &&
17785          "Broken injected-class-name");
17786 }
17787 
17788 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17789                                     SourceRange BraceRange) {
17790   AdjustDeclIfTemplate(TagD);
17791   TagDecl *Tag = cast<TagDecl>(TagD);
17792   Tag->setBraceRange(BraceRange);
17793 
17794   // Make sure we "complete" the definition even it is invalid.
17795   if (Tag->isBeingDefined()) {
17796     assert(Tag->isInvalidDecl() && "We should already have completed it");
17797     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17798       RD->completeDefinition();
17799   }
17800 
17801   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17802     FieldCollector->FinishClass();
17803     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17804       auto *Def = RD->getDefinition();
17805       assert(Def && "The record is expected to have a completed definition");
17806       unsigned NumInitMethods = 0;
17807       for (auto *Method : Def->methods()) {
17808         if (!Method->getIdentifier())
17809             continue;
17810         if (Method->getName() == "__init")
17811           NumInitMethods++;
17812       }
17813       if (NumInitMethods > 1 || !Def->hasInitMethod())
17814         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17815     }
17816   }
17817 
17818   // Exit this scope of this tag's definition.
17819   PopDeclContext();
17820 
17821   if (getCurLexicalContext()->isObjCContainer() &&
17822       Tag->getDeclContext()->isFileContext())
17823     Tag->setTopLevelDeclInObjCContainer();
17824 
17825   // Notify the consumer that we've defined a tag.
17826   if (!Tag->isInvalidDecl())
17827     Consumer.HandleTagDeclDefinition(Tag);
17828 
17829   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17830   // from XLs and instead matches the XL #pragma pack(1) behavior.
17831   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17832       AlignPackStack.hasValue()) {
17833     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17834     // Only diagnose #pragma align(packed).
17835     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17836       return;
17837     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17838     if (!RD)
17839       return;
17840     // Only warn if there is at least 1 bitfield member.
17841     if (llvm::any_of(RD->fields(),
17842                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17843       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17844   }
17845 }
17846 
17847 void Sema::ActOnObjCContainerFinishDefinition() {
17848   // Exit this scope of this interface definition.
17849   PopDeclContext();
17850 }
17851 
17852 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17853   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17854   OriginalLexicalContext = ObjCCtx;
17855   ActOnObjCContainerFinishDefinition();
17856 }
17857 
17858 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17859   ActOnObjCContainerStartDefinition(ObjCCtx);
17860   OriginalLexicalContext = nullptr;
17861 }
17862 
17863 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17864   AdjustDeclIfTemplate(TagD);
17865   TagDecl *Tag = cast<TagDecl>(TagD);
17866   Tag->setInvalidDecl();
17867 
17868   // Make sure we "complete" the definition even it is invalid.
17869   if (Tag->isBeingDefined()) {
17870     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17871       RD->completeDefinition();
17872   }
17873 
17874   // We're undoing ActOnTagStartDefinition here, not
17875   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17876   // the FieldCollector.
17877 
17878   PopDeclContext();
17879 }
17880 
17881 // Note that FieldName may be null for anonymous bitfields.
17882 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17883                                 IdentifierInfo *FieldName, QualType FieldTy,
17884                                 bool IsMsStruct, Expr *BitWidth) {
17885   assert(BitWidth);
17886   if (BitWidth->containsErrors())
17887     return ExprError();
17888 
17889   // C99 6.7.2.1p4 - verify the field type.
17890   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17891   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17892     // Handle incomplete and sizeless types with a specific error.
17893     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17894                                  diag::err_field_incomplete_or_sizeless))
17895       return ExprError();
17896     if (FieldName)
17897       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17898         << FieldName << FieldTy << BitWidth->getSourceRange();
17899     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17900       << FieldTy << BitWidth->getSourceRange();
17901   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17902                                              UPPC_BitFieldWidth))
17903     return ExprError();
17904 
17905   // If the bit-width is type- or value-dependent, don't try to check
17906   // it now.
17907   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17908     return BitWidth;
17909 
17910   llvm::APSInt Value;
17911   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17912   if (ICE.isInvalid())
17913     return ICE;
17914   BitWidth = ICE.get();
17915 
17916   // Zero-width bitfield is ok for anonymous field.
17917   if (Value == 0 && FieldName)
17918     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17919 
17920   if (Value.isSigned() && Value.isNegative()) {
17921     if (FieldName)
17922       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17923                << FieldName << toString(Value, 10);
17924     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17925       << toString(Value, 10);
17926   }
17927 
17928   // The size of the bit-field must not exceed our maximum permitted object
17929   // size.
17930   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17931     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17932            << !FieldName << FieldName << toString(Value, 10);
17933   }
17934 
17935   if (!FieldTy->isDependentType()) {
17936     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17937     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17938     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17939 
17940     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17941     // ABI.
17942     bool CStdConstraintViolation =
17943         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17944     bool MSBitfieldViolation =
17945         Value.ugt(TypeStorageSize) &&
17946         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17947     if (CStdConstraintViolation || MSBitfieldViolation) {
17948       unsigned DiagWidth =
17949           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17950       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17951              << (bool)FieldName << FieldName << toString(Value, 10)
17952              << !CStdConstraintViolation << DiagWidth;
17953     }
17954 
17955     // Warn on types where the user might conceivably expect to get all
17956     // specified bits as value bits: that's all integral types other than
17957     // 'bool'.
17958     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17959       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17960           << FieldName << toString(Value, 10)
17961           << (unsigned)TypeWidth;
17962     }
17963   }
17964 
17965   return BitWidth;
17966 }
17967 
17968 /// ActOnField - Each field of a C struct/union is passed into this in order
17969 /// to create a FieldDecl object for it.
17970 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17971                        Declarator &D, Expr *BitfieldWidth) {
17972   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17973                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17974                                /*InitStyle=*/ICIS_NoInit, AS_public);
17975   return Res;
17976 }
17977 
17978 /// HandleField - Analyze a field of a C struct or a C++ data member.
17979 ///
17980 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17981                              SourceLocation DeclStart,
17982                              Declarator &D, Expr *BitWidth,
17983                              InClassInitStyle InitStyle,
17984                              AccessSpecifier AS) {
17985   if (D.isDecompositionDeclarator()) {
17986     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17987     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17988       << Decomp.getSourceRange();
17989     return nullptr;
17990   }
17991 
17992   IdentifierInfo *II = D.getIdentifier();
17993   SourceLocation Loc = DeclStart;
17994   if (II) Loc = D.getIdentifierLoc();
17995 
17996   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17997   QualType T = TInfo->getType();
17998   if (getLangOpts().CPlusPlus) {
17999     CheckExtraCXXDefaultArguments(D);
18000 
18001     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18002                                         UPPC_DataMemberType)) {
18003       D.setInvalidType();
18004       T = Context.IntTy;
18005       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18006     }
18007   }
18008 
18009   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18010 
18011   if (D.getDeclSpec().isInlineSpecified())
18012     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18013         << getLangOpts().CPlusPlus17;
18014   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18015     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18016          diag::err_invalid_thread)
18017       << DeclSpec::getSpecifierName(TSCS);
18018 
18019   // Check to see if this name was declared as a member previously
18020   NamedDecl *PrevDecl = nullptr;
18021   LookupResult Previous(*this, II, Loc, LookupMemberName,
18022                         ForVisibleRedeclaration);
18023   LookupName(Previous, S);
18024   switch (Previous.getResultKind()) {
18025     case LookupResult::Found:
18026     case LookupResult::FoundUnresolvedValue:
18027       PrevDecl = Previous.getAsSingle<NamedDecl>();
18028       break;
18029 
18030     case LookupResult::FoundOverloaded:
18031       PrevDecl = Previous.getRepresentativeDecl();
18032       break;
18033 
18034     case LookupResult::NotFound:
18035     case LookupResult::NotFoundInCurrentInstantiation:
18036     case LookupResult::Ambiguous:
18037       break;
18038   }
18039   Previous.suppressDiagnostics();
18040 
18041   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18042     // Maybe we will complain about the shadowed template parameter.
18043     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18044     // Just pretend that we didn't see the previous declaration.
18045     PrevDecl = nullptr;
18046   }
18047 
18048   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18049     PrevDecl = nullptr;
18050 
18051   bool Mutable
18052     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18053   SourceLocation TSSL = D.getBeginLoc();
18054   FieldDecl *NewFD
18055     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18056                      TSSL, AS, PrevDecl, &D);
18057 
18058   if (NewFD->isInvalidDecl())
18059     Record->setInvalidDecl();
18060 
18061   if (D.getDeclSpec().isModulePrivateSpecified())
18062     NewFD->setModulePrivate();
18063 
18064   if (NewFD->isInvalidDecl() && PrevDecl) {
18065     // Don't introduce NewFD into scope; there's already something
18066     // with the same name in the same scope.
18067   } else if (II) {
18068     PushOnScopeChains(NewFD, S);
18069   } else
18070     Record->addDecl(NewFD);
18071 
18072   return NewFD;
18073 }
18074 
18075 /// Build a new FieldDecl and check its well-formedness.
18076 ///
18077 /// This routine builds a new FieldDecl given the fields name, type,
18078 /// record, etc. \p PrevDecl should refer to any previous declaration
18079 /// with the same name and in the same scope as the field to be
18080 /// created.
18081 ///
18082 /// \returns a new FieldDecl.
18083 ///
18084 /// \todo The Declarator argument is a hack. It will be removed once
18085 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18086                                 TypeSourceInfo *TInfo,
18087                                 RecordDecl *Record, SourceLocation Loc,
18088                                 bool Mutable, Expr *BitWidth,
18089                                 InClassInitStyle InitStyle,
18090                                 SourceLocation TSSL,
18091                                 AccessSpecifier AS, NamedDecl *PrevDecl,
18092                                 Declarator *D) {
18093   IdentifierInfo *II = Name.getAsIdentifierInfo();
18094   bool InvalidDecl = false;
18095   if (D) InvalidDecl = D->isInvalidType();
18096 
18097   // If we receive a broken type, recover by assuming 'int' and
18098   // marking this declaration as invalid.
18099   if (T.isNull() || T->containsErrors()) {
18100     InvalidDecl = true;
18101     T = Context.IntTy;
18102   }
18103 
18104   QualType EltTy = Context.getBaseElementType(T);
18105   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18106     if (RequireCompleteSizedType(Loc, EltTy,
18107                                  diag::err_field_incomplete_or_sizeless)) {
18108       // Fields of incomplete type force their record to be invalid.
18109       Record->setInvalidDecl();
18110       InvalidDecl = true;
18111     } else {
18112       NamedDecl *Def;
18113       EltTy->isIncompleteType(&Def);
18114       if (Def && Def->isInvalidDecl()) {
18115         Record->setInvalidDecl();
18116         InvalidDecl = true;
18117       }
18118     }
18119   }
18120 
18121   // TR 18037 does not allow fields to be declared with address space
18122   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18123       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18124     Diag(Loc, diag::err_field_with_address_space);
18125     Record->setInvalidDecl();
18126     InvalidDecl = true;
18127   }
18128 
18129   if (LangOpts.OpenCL) {
18130     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18131     // used as structure or union field: image, sampler, event or block types.
18132     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18133         T->isBlockPointerType()) {
18134       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18135       Record->setInvalidDecl();
18136       InvalidDecl = true;
18137     }
18138     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18139     // is enabled.
18140     if (BitWidth && !getOpenCLOptions().isAvailableOption(
18141                         "__cl_clang_bitfields", LangOpts)) {
18142       Diag(Loc, diag::err_opencl_bitfields);
18143       InvalidDecl = true;
18144     }
18145   }
18146 
18147   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18148   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18149       T.hasQualifiers()) {
18150     InvalidDecl = true;
18151     Diag(Loc, diag::err_anon_bitfield_qualifiers);
18152   }
18153 
18154   // C99 6.7.2.1p8: A member of a structure or union may have any type other
18155   // than a variably modified type.
18156   if (!InvalidDecl && T->isVariablyModifiedType()) {
18157     if (!tryToFixVariablyModifiedVarType(
18158             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18159       InvalidDecl = true;
18160   }
18161 
18162   // Fields can not have abstract class types
18163   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18164                                              diag::err_abstract_type_in_decl,
18165                                              AbstractFieldType))
18166     InvalidDecl = true;
18167 
18168   if (InvalidDecl)
18169     BitWidth = nullptr;
18170   // If this is declared as a bit-field, check the bit-field.
18171   if (BitWidth) {
18172     BitWidth =
18173         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18174     if (!BitWidth) {
18175       InvalidDecl = true;
18176       BitWidth = nullptr;
18177     }
18178   }
18179 
18180   // Check that 'mutable' is consistent with the type of the declaration.
18181   if (!InvalidDecl && Mutable) {
18182     unsigned DiagID = 0;
18183     if (T->isReferenceType())
18184       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18185                                         : diag::err_mutable_reference;
18186     else if (T.isConstQualified())
18187       DiagID = diag::err_mutable_const;
18188 
18189     if (DiagID) {
18190       SourceLocation ErrLoc = Loc;
18191       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18192         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18193       Diag(ErrLoc, DiagID);
18194       if (DiagID != diag::ext_mutable_reference) {
18195         Mutable = false;
18196         InvalidDecl = true;
18197       }
18198     }
18199   }
18200 
18201   // C++11 [class.union]p8 (DR1460):
18202   //   At most one variant member of a union may have a
18203   //   brace-or-equal-initializer.
18204   if (InitStyle != ICIS_NoInit)
18205     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18206 
18207   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18208                                        BitWidth, Mutable, InitStyle);
18209   if (InvalidDecl)
18210     NewFD->setInvalidDecl();
18211 
18212   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18213     Diag(Loc, diag::err_duplicate_member) << II;
18214     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18215     NewFD->setInvalidDecl();
18216   }
18217 
18218   if (!InvalidDecl && getLangOpts().CPlusPlus) {
18219     if (Record->isUnion()) {
18220       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18221         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18222         if (RDecl->getDefinition()) {
18223           // C++ [class.union]p1: An object of a class with a non-trivial
18224           // constructor, a non-trivial copy constructor, a non-trivial
18225           // destructor, or a non-trivial copy assignment operator
18226           // cannot be a member of a union, nor can an array of such
18227           // objects.
18228           if (CheckNontrivialField(NewFD))
18229             NewFD->setInvalidDecl();
18230         }
18231       }
18232 
18233       // C++ [class.union]p1: If a union contains a member of reference type,
18234       // the program is ill-formed, except when compiling with MSVC extensions
18235       // enabled.
18236       if (EltTy->isReferenceType()) {
18237         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18238                                     diag::ext_union_member_of_reference_type :
18239                                     diag::err_union_member_of_reference_type)
18240           << NewFD->getDeclName() << EltTy;
18241         if (!getLangOpts().MicrosoftExt)
18242           NewFD->setInvalidDecl();
18243       }
18244     }
18245   }
18246 
18247   // FIXME: We need to pass in the attributes given an AST
18248   // representation, not a parser representation.
18249   if (D) {
18250     // FIXME: The current scope is almost... but not entirely... correct here.
18251     ProcessDeclAttributes(getCurScope(), NewFD, *D);
18252 
18253     if (NewFD->hasAttrs())
18254       CheckAlignasUnderalignment(NewFD);
18255   }
18256 
18257   // In auto-retain/release, infer strong retension for fields of
18258   // retainable type.
18259   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18260     NewFD->setInvalidDecl();
18261 
18262   if (T.isObjCGCWeak())
18263     Diag(Loc, diag::warn_attribute_weak_on_field);
18264 
18265   // PPC MMA non-pointer types are not allowed as field types.
18266   if (Context.getTargetInfo().getTriple().isPPC64() &&
18267       CheckPPCMMAType(T, NewFD->getLocation()))
18268     NewFD->setInvalidDecl();
18269 
18270   NewFD->setAccess(AS);
18271   return NewFD;
18272 }
18273 
18274 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18275   assert(FD);
18276   assert(getLangOpts().CPlusPlus && "valid check only for C++");
18277 
18278   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18279     return false;
18280 
18281   QualType EltTy = Context.getBaseElementType(FD->getType());
18282   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18283     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18284     if (RDecl->getDefinition()) {
18285       // We check for copy constructors before constructors
18286       // because otherwise we'll never get complaints about
18287       // copy constructors.
18288 
18289       CXXSpecialMember member = CXXInvalid;
18290       // We're required to check for any non-trivial constructors. Since the
18291       // implicit default constructor is suppressed if there are any
18292       // user-declared constructors, we just need to check that there is a
18293       // trivial default constructor and a trivial copy constructor. (We don't
18294       // worry about move constructors here, since this is a C++98 check.)
18295       if (RDecl->hasNonTrivialCopyConstructor())
18296         member = CXXCopyConstructor;
18297       else if (!RDecl->hasTrivialDefaultConstructor())
18298         member = CXXDefaultConstructor;
18299       else if (RDecl->hasNonTrivialCopyAssignment())
18300         member = CXXCopyAssignment;
18301       else if (RDecl->hasNonTrivialDestructor())
18302         member = CXXDestructor;
18303 
18304       if (member != CXXInvalid) {
18305         if (!getLangOpts().CPlusPlus11 &&
18306             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18307           // Objective-C++ ARC: it is an error to have a non-trivial field of
18308           // a union. However, system headers in Objective-C programs
18309           // occasionally have Objective-C lifetime objects within unions,
18310           // and rather than cause the program to fail, we make those
18311           // members unavailable.
18312           SourceLocation Loc = FD->getLocation();
18313           if (getSourceManager().isInSystemHeader(Loc)) {
18314             if (!FD->hasAttr<UnavailableAttr>())
18315               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18316                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18317             return false;
18318           }
18319         }
18320 
18321         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18322                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18323                diag::err_illegal_union_or_anon_struct_member)
18324           << FD->getParent()->isUnion() << FD->getDeclName() << member;
18325         DiagnoseNontrivial(RDecl, member);
18326         return !getLangOpts().CPlusPlus11;
18327       }
18328     }
18329   }
18330 
18331   return false;
18332 }
18333 
18334 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18335 ///  AST enum value.
18336 static ObjCIvarDecl::AccessControl
18337 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18338   switch (ivarVisibility) {
18339   default: llvm_unreachable("Unknown visitibility kind");
18340   case tok::objc_private: return ObjCIvarDecl::Private;
18341   case tok::objc_public: return ObjCIvarDecl::Public;
18342   case tok::objc_protected: return ObjCIvarDecl::Protected;
18343   case tok::objc_package: return ObjCIvarDecl::Package;
18344   }
18345 }
18346 
18347 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18348 /// in order to create an IvarDecl object for it.
18349 Decl *Sema::ActOnIvar(Scope *S,
18350                                 SourceLocation DeclStart,
18351                                 Declarator &D, Expr *BitfieldWidth,
18352                                 tok::ObjCKeywordKind Visibility) {
18353 
18354   IdentifierInfo *II = D.getIdentifier();
18355   Expr *BitWidth = (Expr*)BitfieldWidth;
18356   SourceLocation Loc = DeclStart;
18357   if (II) Loc = D.getIdentifierLoc();
18358 
18359   // FIXME: Unnamed fields can be handled in various different ways, for
18360   // example, unnamed unions inject all members into the struct namespace!
18361 
18362   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18363   QualType T = TInfo->getType();
18364 
18365   if (BitWidth) {
18366     // 6.7.2.1p3, 6.7.2.1p4
18367     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18368     if (!BitWidth)
18369       D.setInvalidType();
18370   } else {
18371     // Not a bitfield.
18372 
18373     // validate II.
18374 
18375   }
18376   if (T->isReferenceType()) {
18377     Diag(Loc, diag::err_ivar_reference_type);
18378     D.setInvalidType();
18379   }
18380   // C99 6.7.2.1p8: A member of a structure or union may have any type other
18381   // than a variably modified type.
18382   else if (T->isVariablyModifiedType()) {
18383     if (!tryToFixVariablyModifiedVarType(
18384             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18385       D.setInvalidType();
18386   }
18387 
18388   // Get the visibility (access control) for this ivar.
18389   ObjCIvarDecl::AccessControl ac =
18390     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18391                                         : ObjCIvarDecl::None;
18392   // Must set ivar's DeclContext to its enclosing interface.
18393   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18394   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18395     return nullptr;
18396   ObjCContainerDecl *EnclosingContext;
18397   if (ObjCImplementationDecl *IMPDecl =
18398       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18399     if (LangOpts.ObjCRuntime.isFragile()) {
18400     // Case of ivar declared in an implementation. Context is that of its class.
18401       EnclosingContext = IMPDecl->getClassInterface();
18402       assert(EnclosingContext && "Implementation has no class interface!");
18403     }
18404     else
18405       EnclosingContext = EnclosingDecl;
18406   } else {
18407     if (ObjCCategoryDecl *CDecl =
18408         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18409       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18410         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18411         return nullptr;
18412       }
18413     }
18414     EnclosingContext = EnclosingDecl;
18415   }
18416 
18417   // Construct the decl.
18418   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18419                                              DeclStart, Loc, II, T,
18420                                              TInfo, ac, (Expr *)BitfieldWidth);
18421 
18422   if (II) {
18423     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18424                                            ForVisibleRedeclaration);
18425     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18426         && !isa<TagDecl>(PrevDecl)) {
18427       Diag(Loc, diag::err_duplicate_member) << II;
18428       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18429       NewID->setInvalidDecl();
18430     }
18431   }
18432 
18433   // Process attributes attached to the ivar.
18434   ProcessDeclAttributes(S, NewID, D);
18435 
18436   if (D.isInvalidType())
18437     NewID->setInvalidDecl();
18438 
18439   // In ARC, infer 'retaining' for ivars of retainable type.
18440   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18441     NewID->setInvalidDecl();
18442 
18443   if (D.getDeclSpec().isModulePrivateSpecified())
18444     NewID->setModulePrivate();
18445 
18446   if (II) {
18447     // FIXME: When interfaces are DeclContexts, we'll need to add
18448     // these to the interface.
18449     S->AddDecl(NewID);
18450     IdResolver.AddDecl(NewID);
18451   }
18452 
18453   if (LangOpts.ObjCRuntime.isNonFragile() &&
18454       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18455     Diag(Loc, diag::warn_ivars_in_interface);
18456 
18457   return NewID;
18458 }
18459 
18460 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18461 /// class and class extensions. For every class \@interface and class
18462 /// extension \@interface, if the last ivar is a bitfield of any type,
18463 /// then add an implicit `char :0` ivar to the end of that interface.
18464 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18465                              SmallVectorImpl<Decl *> &AllIvarDecls) {
18466   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18467     return;
18468 
18469   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18470   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18471 
18472   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18473     return;
18474   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18475   if (!ID) {
18476     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18477       if (!CD->IsClassExtension())
18478         return;
18479     }
18480     // No need to add this to end of @implementation.
18481     else
18482       return;
18483   }
18484   // All conditions are met. Add a new bitfield to the tail end of ivars.
18485   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18486   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18487 
18488   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18489                               DeclLoc, DeclLoc, nullptr,
18490                               Context.CharTy,
18491                               Context.getTrivialTypeSourceInfo(Context.CharTy,
18492                                                                DeclLoc),
18493                               ObjCIvarDecl::Private, BW,
18494                               true);
18495   AllIvarDecls.push_back(Ivar);
18496 }
18497 
18498 /// [class.dtor]p4:
18499 ///   At the end of the definition of a class, overload resolution is
18500 ///   performed among the prospective destructors declared in that class with
18501 ///   an empty argument list to select the destructor for the class, also
18502 ///   known as the selected destructor.
18503 ///
18504 /// We do the overload resolution here, then mark the selected constructor in the AST.
18505 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18506 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18507   if (!Record->hasUserDeclaredDestructor()) {
18508     return;
18509   }
18510 
18511   SourceLocation Loc = Record->getLocation();
18512   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18513 
18514   for (auto *Decl : Record->decls()) {
18515     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18516       if (DD->isInvalidDecl())
18517         continue;
18518       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18519                              OCS);
18520       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18521     }
18522   }
18523 
18524   if (OCS.empty()) {
18525     return;
18526   }
18527   OverloadCandidateSet::iterator Best;
18528   unsigned Msg = 0;
18529   OverloadCandidateDisplayKind DisplayKind;
18530 
18531   switch (OCS.BestViableFunction(S, Loc, Best)) {
18532   case OR_Success:
18533   case OR_Deleted:
18534     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18535     break;
18536 
18537   case OR_Ambiguous:
18538     Msg = diag::err_ambiguous_destructor;
18539     DisplayKind = OCD_AmbiguousCandidates;
18540     break;
18541 
18542   case OR_No_Viable_Function:
18543     Msg = diag::err_no_viable_destructor;
18544     DisplayKind = OCD_AllCandidates;
18545     break;
18546   }
18547 
18548   if (Msg) {
18549     // OpenCL have got their own thing going with destructors. It's slightly broken,
18550     // but we allow it.
18551     if (!S.LangOpts.OpenCL) {
18552       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18553       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18554       Record->setInvalidDecl();
18555     }
18556     // It's a bit hacky: At this point we've raised an error but we want the
18557     // rest of the compiler to continue somehow working. However almost
18558     // everything we'll try to do with the class will depend on there being a
18559     // destructor. So let's pretend the first one is selected and hope for the
18560     // best.
18561     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18562   }
18563 }
18564 
18565 /// [class.mem.special]p5
18566 /// Two special member functions are of the same kind if:
18567 /// - they are both default constructors,
18568 /// - they are both copy or move constructors with the same first parameter
18569 ///   type, or
18570 /// - they are both copy or move assignment operators with the same first
18571 ///   parameter type and the same cv-qualifiers and ref-qualifier, if any.
18572 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18573                                               CXXMethodDecl *M1,
18574                                               CXXMethodDecl *M2,
18575                                               Sema::CXXSpecialMember CSM) {
18576   // We don't want to compare templates to non-templates: See
18577   // https://github.com/llvm/llvm-project/issues/59206
18578   if (CSM == Sema::CXXDefaultConstructor)
18579     return bool(M1->getDescribedFunctionTemplate()) ==
18580            bool(M2->getDescribedFunctionTemplate());
18581   if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18582                            M2->getParamDecl(0)->getType()))
18583     return false;
18584   if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18585     return false;
18586 
18587   return true;
18588 }
18589 
18590 /// [class.mem.special]p6:
18591 /// An eligible special member function is a special member function for which:
18592 /// - the function is not deleted,
18593 /// - the associated constraints, if any, are satisfied, and
18594 /// - no special member function of the same kind whose associated constraints
18595 ///   [CWG2595], if any, are satisfied is more constrained.
18596 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18597                                ArrayRef<CXXMethodDecl *> Methods,
18598                                Sema::CXXSpecialMember CSM) {
18599   SmallVector<bool, 4> SatisfactionStatus;
18600 
18601   for (CXXMethodDecl *Method : Methods) {
18602     const Expr *Constraints = Method->getTrailingRequiresClause();
18603     if (!Constraints)
18604       SatisfactionStatus.push_back(true);
18605     else {
18606       ConstraintSatisfaction Satisfaction;
18607       if (S.CheckFunctionConstraints(Method, Satisfaction))
18608         SatisfactionStatus.push_back(false);
18609       else
18610         SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18611     }
18612   }
18613 
18614   for (size_t i = 0; i < Methods.size(); i++) {
18615     if (!SatisfactionStatus[i])
18616       continue;
18617     CXXMethodDecl *Method = Methods[i];
18618     CXXMethodDecl *OrigMethod = Method;
18619     if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18620       OrigMethod = cast<CXXMethodDecl>(MF);
18621 
18622     const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18623     bool AnotherMethodIsMoreConstrained = false;
18624     for (size_t j = 0; j < Methods.size(); j++) {
18625       if (i == j || !SatisfactionStatus[j])
18626         continue;
18627       CXXMethodDecl *OtherMethod = Methods[j];
18628       if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18629         OtherMethod = cast<CXXMethodDecl>(MF);
18630 
18631       if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18632                                              CSM))
18633         continue;
18634 
18635       const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18636       if (!OtherConstraints)
18637         continue;
18638       if (!Constraints) {
18639         AnotherMethodIsMoreConstrained = true;
18640         break;
18641       }
18642       if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18643                                    {Constraints},
18644                                    AnotherMethodIsMoreConstrained)) {
18645         // There was an error with the constraints comparison. Exit the loop
18646         // and don't consider this function eligible.
18647         AnotherMethodIsMoreConstrained = true;
18648       }
18649       if (AnotherMethodIsMoreConstrained)
18650         break;
18651     }
18652     // FIXME: Do not consider deleted methods as eligible after implementing
18653     // DR1734 and DR1496.
18654     if (!AnotherMethodIsMoreConstrained) {
18655       Method->setIneligibleOrNotSelected(false);
18656       Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18657     }
18658   }
18659 }
18660 
18661 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18662                                                     CXXRecordDecl *Record) {
18663   SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18664   SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18665   SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18666   SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18667   SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18668 
18669   for (auto *Decl : Record->decls()) {
18670     auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18671     if (!MD) {
18672       auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18673       if (FTD)
18674         MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18675     }
18676     if (!MD)
18677       continue;
18678     if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18679       if (CD->isInvalidDecl())
18680         continue;
18681       if (CD->isDefaultConstructor())
18682         DefaultConstructors.push_back(MD);
18683       else if (CD->isCopyConstructor())
18684         CopyConstructors.push_back(MD);
18685       else if (CD->isMoveConstructor())
18686         MoveConstructors.push_back(MD);
18687     } else if (MD->isCopyAssignmentOperator()) {
18688       CopyAssignmentOperators.push_back(MD);
18689     } else if (MD->isMoveAssignmentOperator()) {
18690       MoveAssignmentOperators.push_back(MD);
18691     }
18692   }
18693 
18694   SetEligibleMethods(S, Record, DefaultConstructors,
18695                      Sema::CXXDefaultConstructor);
18696   SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18697   SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18698   SetEligibleMethods(S, Record, CopyAssignmentOperators,
18699                      Sema::CXXCopyAssignment);
18700   SetEligibleMethods(S, Record, MoveAssignmentOperators,
18701                      Sema::CXXMoveAssignment);
18702 }
18703 
18704 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18705                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
18706                        SourceLocation RBrac,
18707                        const ParsedAttributesView &Attrs) {
18708   assert(EnclosingDecl && "missing record or interface decl");
18709 
18710   // If this is an Objective-C @implementation or category and we have
18711   // new fields here we should reset the layout of the interface since
18712   // it will now change.
18713   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18714     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18715     switch (DC->getKind()) {
18716     default: break;
18717     case Decl::ObjCCategory:
18718       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18719       break;
18720     case Decl::ObjCImplementation:
18721       Context.
18722         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18723       break;
18724     }
18725   }
18726 
18727   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18728   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18729 
18730   // Start counting up the number of named members; make sure to include
18731   // members of anonymous structs and unions in the total.
18732   unsigned NumNamedMembers = 0;
18733   if (Record) {
18734     for (const auto *I : Record->decls()) {
18735       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18736         if (IFD->getDeclName())
18737           ++NumNamedMembers;
18738     }
18739   }
18740 
18741   // Verify that all the fields are okay.
18742   SmallVector<FieldDecl*, 32> RecFields;
18743 
18744   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18745        i != end; ++i) {
18746     FieldDecl *FD = cast<FieldDecl>(*i);
18747 
18748     // Get the type for the field.
18749     const Type *FDTy = FD->getType().getTypePtr();
18750 
18751     if (!FD->isAnonymousStructOrUnion()) {
18752       // Remember all fields written by the user.
18753       RecFields.push_back(FD);
18754     }
18755 
18756     // If the field is already invalid for some reason, don't emit more
18757     // diagnostics about it.
18758     if (FD->isInvalidDecl()) {
18759       EnclosingDecl->setInvalidDecl();
18760       continue;
18761     }
18762 
18763     // C99 6.7.2.1p2:
18764     //   A structure or union shall not contain a member with
18765     //   incomplete or function type (hence, a structure shall not
18766     //   contain an instance of itself, but may contain a pointer to
18767     //   an instance of itself), except that the last member of a
18768     //   structure with more than one named member may have incomplete
18769     //   array type; such a structure (and any union containing,
18770     //   possibly recursively, a member that is such a structure)
18771     //   shall not be a member of a structure or an element of an
18772     //   array.
18773     bool IsLastField = (i + 1 == Fields.end());
18774     if (FDTy->isFunctionType()) {
18775       // Field declared as a function.
18776       Diag(FD->getLocation(), diag::err_field_declared_as_function)
18777         << FD->getDeclName();
18778       FD->setInvalidDecl();
18779       EnclosingDecl->setInvalidDecl();
18780       continue;
18781     } else if (FDTy->isIncompleteArrayType() &&
18782                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18783       if (Record) {
18784         // Flexible array member.
18785         // Microsoft and g++ is more permissive regarding flexible array.
18786         // It will accept flexible array in union and also
18787         // as the sole element of a struct/class.
18788         unsigned DiagID = 0;
18789         if (!Record->isUnion() && !IsLastField) {
18790           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18791             << FD->getDeclName() << FD->getType() << Record->getTagKind();
18792           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18793           FD->setInvalidDecl();
18794           EnclosingDecl->setInvalidDecl();
18795           continue;
18796         } else if (Record->isUnion())
18797           DiagID = getLangOpts().MicrosoftExt
18798                        ? diag::ext_flexible_array_union_ms
18799                        : getLangOpts().CPlusPlus
18800                              ? diag::ext_flexible_array_union_gnu
18801                              : diag::err_flexible_array_union;
18802         else if (NumNamedMembers < 1)
18803           DiagID = getLangOpts().MicrosoftExt
18804                        ? diag::ext_flexible_array_empty_aggregate_ms
18805                        : getLangOpts().CPlusPlus
18806                              ? diag::ext_flexible_array_empty_aggregate_gnu
18807                              : diag::err_flexible_array_empty_aggregate;
18808 
18809         if (DiagID)
18810           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18811                                           << Record->getTagKind();
18812         // While the layout of types that contain virtual bases is not specified
18813         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18814         // virtual bases after the derived members.  This would make a flexible
18815         // array member declared at the end of an object not adjacent to the end
18816         // of the type.
18817         if (CXXRecord && CXXRecord->getNumVBases() != 0)
18818           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18819               << FD->getDeclName() << Record->getTagKind();
18820         if (!getLangOpts().C99)
18821           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18822             << FD->getDeclName() << Record->getTagKind();
18823 
18824         // If the element type has a non-trivial destructor, we would not
18825         // implicitly destroy the elements, so disallow it for now.
18826         //
18827         // FIXME: GCC allows this. We should probably either implicitly delete
18828         // the destructor of the containing class, or just allow this.
18829         QualType BaseElem = Context.getBaseElementType(FD->getType());
18830         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18831           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18832             << FD->getDeclName() << FD->getType();
18833           FD->setInvalidDecl();
18834           EnclosingDecl->setInvalidDecl();
18835           continue;
18836         }
18837         // Okay, we have a legal flexible array member at the end of the struct.
18838         Record->setHasFlexibleArrayMember(true);
18839       } else {
18840         // In ObjCContainerDecl ivars with incomplete array type are accepted,
18841         // unless they are followed by another ivar. That check is done
18842         // elsewhere, after synthesized ivars are known.
18843       }
18844     } else if (!FDTy->isDependentType() &&
18845                RequireCompleteSizedType(
18846                    FD->getLocation(), FD->getType(),
18847                    diag::err_field_incomplete_or_sizeless)) {
18848       // Incomplete type
18849       FD->setInvalidDecl();
18850       EnclosingDecl->setInvalidDecl();
18851       continue;
18852     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18853       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18854         // A type which contains a flexible array member is considered to be a
18855         // flexible array member.
18856         Record->setHasFlexibleArrayMember(true);
18857         if (!Record->isUnion()) {
18858           // If this is a struct/class and this is not the last element, reject
18859           // it.  Note that GCC supports variable sized arrays in the middle of
18860           // structures.
18861           if (!IsLastField)
18862             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18863               << FD->getDeclName() << FD->getType();
18864           else {
18865             // We support flexible arrays at the end of structs in
18866             // other structs as an extension.
18867             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18868               << FD->getDeclName();
18869           }
18870         }
18871       }
18872       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18873           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18874                                  diag::err_abstract_type_in_decl,
18875                                  AbstractIvarType)) {
18876         // Ivars can not have abstract class types
18877         FD->setInvalidDecl();
18878       }
18879       if (Record && FDTTy->getDecl()->hasObjectMember())
18880         Record->setHasObjectMember(true);
18881       if (Record && FDTTy->getDecl()->hasVolatileMember())
18882         Record->setHasVolatileMember(true);
18883     } else if (FDTy->isObjCObjectType()) {
18884       /// A field cannot be an Objective-c object
18885       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18886         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18887       QualType T = Context.getObjCObjectPointerType(FD->getType());
18888       FD->setType(T);
18889     } else if (Record && Record->isUnion() &&
18890                FD->getType().hasNonTrivialObjCLifetime() &&
18891                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18892                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18893                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18894                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18895       // For backward compatibility, fields of C unions declared in system
18896       // headers that have non-trivial ObjC ownership qualifications are marked
18897       // as unavailable unless the qualifier is explicit and __strong. This can
18898       // break ABI compatibility between programs compiled with ARC and MRR, but
18899       // is a better option than rejecting programs using those unions under
18900       // ARC.
18901       FD->addAttr(UnavailableAttr::CreateImplicit(
18902           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18903           FD->getLocation()));
18904     } else if (getLangOpts().ObjC &&
18905                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18906                !Record->hasObjectMember()) {
18907       if (FD->getType()->isObjCObjectPointerType() ||
18908           FD->getType().isObjCGCStrong())
18909         Record->setHasObjectMember(true);
18910       else if (Context.getAsArrayType(FD->getType())) {
18911         QualType BaseType = Context.getBaseElementType(FD->getType());
18912         if (BaseType->isRecordType() &&
18913             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18914           Record->setHasObjectMember(true);
18915         else if (BaseType->isObjCObjectPointerType() ||
18916                  BaseType.isObjCGCStrong())
18917                Record->setHasObjectMember(true);
18918       }
18919     }
18920 
18921     if (Record && !getLangOpts().CPlusPlus &&
18922         !shouldIgnoreForRecordTriviality(FD)) {
18923       QualType FT = FD->getType();
18924       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18925         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18926         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18927             Record->isUnion())
18928           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18929       }
18930       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18931       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18932         Record->setNonTrivialToPrimitiveCopy(true);
18933         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18934           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18935       }
18936       if (FT.isDestructedType()) {
18937         Record->setNonTrivialToPrimitiveDestroy(true);
18938         Record->setParamDestroyedInCallee(true);
18939         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18940           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18941       }
18942 
18943       if (const auto *RT = FT->getAs<RecordType>()) {
18944         if (RT->getDecl()->getArgPassingRestrictions() ==
18945             RecordDecl::APK_CanNeverPassInRegs)
18946           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18947       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18948         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18949     }
18950 
18951     if (Record && FD->getType().isVolatileQualified())
18952       Record->setHasVolatileMember(true);
18953     // Keep track of the number of named members.
18954     if (FD->getIdentifier())
18955       ++NumNamedMembers;
18956   }
18957 
18958   // Okay, we successfully defined 'Record'.
18959   if (Record) {
18960     bool Completed = false;
18961     if (CXXRecord) {
18962       if (!CXXRecord->isInvalidDecl()) {
18963         // Set access bits correctly on the directly-declared conversions.
18964         for (CXXRecordDecl::conversion_iterator
18965                I = CXXRecord->conversion_begin(),
18966                E = CXXRecord->conversion_end(); I != E; ++I)
18967           I.setAccess((*I)->getAccess());
18968       }
18969 
18970       // Add any implicitly-declared members to this class.
18971       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18972 
18973       if (!CXXRecord->isDependentType()) {
18974         if (!CXXRecord->isInvalidDecl()) {
18975           // If we have virtual base classes, we may end up finding multiple
18976           // final overriders for a given virtual function. Check for this
18977           // problem now.
18978           if (CXXRecord->getNumVBases()) {
18979             CXXFinalOverriderMap FinalOverriders;
18980             CXXRecord->getFinalOverriders(FinalOverriders);
18981 
18982             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18983                                              MEnd = FinalOverriders.end();
18984                  M != MEnd; ++M) {
18985               for (OverridingMethods::iterator SO = M->second.begin(),
18986                                             SOEnd = M->second.end();
18987                    SO != SOEnd; ++SO) {
18988                 assert(SO->second.size() > 0 &&
18989                        "Virtual function without overriding functions?");
18990                 if (SO->second.size() == 1)
18991                   continue;
18992 
18993                 // C++ [class.virtual]p2:
18994                 //   In a derived class, if a virtual member function of a base
18995                 //   class subobject has more than one final overrider the
18996                 //   program is ill-formed.
18997                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18998                   << (const NamedDecl *)M->first << Record;
18999                 Diag(M->first->getLocation(),
19000                      diag::note_overridden_virtual_function);
19001                 for (OverridingMethods::overriding_iterator
19002                           OM = SO->second.begin(),
19003                        OMEnd = SO->second.end();
19004                      OM != OMEnd; ++OM)
19005                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
19006                     << (const NamedDecl *)M->first << OM->Method->getParent();
19007 
19008                 Record->setInvalidDecl();
19009               }
19010             }
19011             CXXRecord->completeDefinition(&FinalOverriders);
19012             Completed = true;
19013           }
19014         }
19015         ComputeSelectedDestructor(*this, CXXRecord);
19016         ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19017       }
19018     }
19019 
19020     if (!Completed)
19021       Record->completeDefinition();
19022 
19023     // Handle attributes before checking the layout.
19024     ProcessDeclAttributeList(S, Record, Attrs);
19025 
19026     // Check to see if a FieldDecl is a pointer to a function.
19027     auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19028       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19029       if (!FD) {
19030         // Check whether this is a forward declaration that was inserted by
19031         // Clang. This happens when a non-forward declared / defined type is
19032         // used, e.g.:
19033         //
19034         //   struct foo {
19035         //     struct bar *(*f)();
19036         //     struct bar *(*g)();
19037         //   };
19038         //
19039         // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19040         // incomplete definition.
19041         if (const auto *TD = dyn_cast<TagDecl>(D))
19042           return !TD->isCompleteDefinition();
19043         return false;
19044       }
19045       QualType FieldType = FD->getType().getDesugaredType(Context);
19046       if (isa<PointerType>(FieldType)) {
19047         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19048         return PointeeType.getDesugaredType(Context)->isFunctionType();
19049       }
19050       return false;
19051     };
19052 
19053     // Maybe randomize the record's decls. We automatically randomize a record
19054     // of function pointers, unless it has the "no_randomize_layout" attribute.
19055     if (!getLangOpts().CPlusPlus &&
19056         (Record->hasAttr<RandomizeLayoutAttr>() ||
19057          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19058           llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19059         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19060         !Record->isRandomized()) {
19061       SmallVector<Decl *, 32> NewDeclOrdering;
19062       if (randstruct::randomizeStructureLayout(Context, Record,
19063                                                NewDeclOrdering))
19064         Record->reorderDecls(NewDeclOrdering);
19065     }
19066 
19067     // We may have deferred checking for a deleted destructor. Check now.
19068     if (CXXRecord) {
19069       auto *Dtor = CXXRecord->getDestructor();
19070       if (Dtor && Dtor->isImplicit() &&
19071           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19072         CXXRecord->setImplicitDestructorIsDeleted();
19073         SetDeclDeleted(Dtor, CXXRecord->getLocation());
19074       }
19075     }
19076 
19077     if (Record->hasAttrs()) {
19078       CheckAlignasUnderalignment(Record);
19079 
19080       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19081         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19082                                            IA->getRange(), IA->getBestCase(),
19083                                            IA->getInheritanceModel());
19084     }
19085 
19086     // Check if the structure/union declaration is a type that can have zero
19087     // size in C. For C this is a language extension, for C++ it may cause
19088     // compatibility problems.
19089     bool CheckForZeroSize;
19090     if (!getLangOpts().CPlusPlus) {
19091       CheckForZeroSize = true;
19092     } else {
19093       // For C++ filter out types that cannot be referenced in C code.
19094       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19095       CheckForZeroSize =
19096           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19097           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19098           CXXRecord->isCLike();
19099     }
19100     if (CheckForZeroSize) {
19101       bool ZeroSize = true;
19102       bool IsEmpty = true;
19103       unsigned NonBitFields = 0;
19104       for (RecordDecl::field_iterator I = Record->field_begin(),
19105                                       E = Record->field_end();
19106            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19107         IsEmpty = false;
19108         if (I->isUnnamedBitfield()) {
19109           if (!I->isZeroLengthBitField(Context))
19110             ZeroSize = false;
19111         } else {
19112           ++NonBitFields;
19113           QualType FieldType = I->getType();
19114           if (FieldType->isIncompleteType() ||
19115               !Context.getTypeSizeInChars(FieldType).isZero())
19116             ZeroSize = false;
19117         }
19118       }
19119 
19120       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19121       // allowed in C++, but warn if its declaration is inside
19122       // extern "C" block.
19123       if (ZeroSize) {
19124         Diag(RecLoc, getLangOpts().CPlusPlus ?
19125                          diag::warn_zero_size_struct_union_in_extern_c :
19126                          diag::warn_zero_size_struct_union_compat)
19127           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19128       }
19129 
19130       // Structs without named members are extension in C (C99 6.7.2.1p7),
19131       // but are accepted by GCC.
19132       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19133         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19134                                diag::ext_no_named_members_in_struct_union)
19135           << Record->isUnion();
19136       }
19137     }
19138   } else {
19139     ObjCIvarDecl **ClsFields =
19140       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19141     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19142       ID->setEndOfDefinitionLoc(RBrac);
19143       // Add ivar's to class's DeclContext.
19144       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19145         ClsFields[i]->setLexicalDeclContext(ID);
19146         ID->addDecl(ClsFields[i]);
19147       }
19148       // Must enforce the rule that ivars in the base classes may not be
19149       // duplicates.
19150       if (ID->getSuperClass())
19151         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19152     } else if (ObjCImplementationDecl *IMPDecl =
19153                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19154       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19155       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19156         // Ivar declared in @implementation never belongs to the implementation.
19157         // Only it is in implementation's lexical context.
19158         ClsFields[I]->setLexicalDeclContext(IMPDecl);
19159       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19160       IMPDecl->setIvarLBraceLoc(LBrac);
19161       IMPDecl->setIvarRBraceLoc(RBrac);
19162     } else if (ObjCCategoryDecl *CDecl =
19163                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19164       // case of ivars in class extension; all other cases have been
19165       // reported as errors elsewhere.
19166       // FIXME. Class extension does not have a LocEnd field.
19167       // CDecl->setLocEnd(RBrac);
19168       // Add ivar's to class extension's DeclContext.
19169       // Diagnose redeclaration of private ivars.
19170       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19171       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19172         if (IDecl) {
19173           if (const ObjCIvarDecl *ClsIvar =
19174               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19175             Diag(ClsFields[i]->getLocation(),
19176                  diag::err_duplicate_ivar_declaration);
19177             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19178             continue;
19179           }
19180           for (const auto *Ext : IDecl->known_extensions()) {
19181             if (const ObjCIvarDecl *ClsExtIvar
19182                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19183               Diag(ClsFields[i]->getLocation(),
19184                    diag::err_duplicate_ivar_declaration);
19185               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19186               continue;
19187             }
19188           }
19189         }
19190         ClsFields[i]->setLexicalDeclContext(CDecl);
19191         CDecl->addDecl(ClsFields[i]);
19192       }
19193       CDecl->setIvarLBraceLoc(LBrac);
19194       CDecl->setIvarRBraceLoc(RBrac);
19195     }
19196   }
19197 }
19198 
19199 /// Determine whether the given integral value is representable within
19200 /// the given type T.
19201 static bool isRepresentableIntegerValue(ASTContext &Context,
19202                                         llvm::APSInt &Value,
19203                                         QualType T) {
19204   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19205          "Integral type required!");
19206   unsigned BitWidth = Context.getIntWidth(T);
19207 
19208   if (Value.isUnsigned() || Value.isNonNegative()) {
19209     if (T->isSignedIntegerOrEnumerationType())
19210       --BitWidth;
19211     return Value.getActiveBits() <= BitWidth;
19212   }
19213   return Value.getSignificantBits() <= BitWidth;
19214 }
19215 
19216 // Given an integral type, return the next larger integral type
19217 // (or a NULL type of no such type exists).
19218 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19219   // FIXME: Int128/UInt128 support, which also needs to be introduced into
19220   // enum checking below.
19221   assert((T->isIntegralType(Context) ||
19222          T->isEnumeralType()) && "Integral type required!");
19223   const unsigned NumTypes = 4;
19224   QualType SignedIntegralTypes[NumTypes] = {
19225     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19226   };
19227   QualType UnsignedIntegralTypes[NumTypes] = {
19228     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19229     Context.UnsignedLongLongTy
19230   };
19231 
19232   unsigned BitWidth = Context.getTypeSize(T);
19233   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19234                                                         : UnsignedIntegralTypes;
19235   for (unsigned I = 0; I != NumTypes; ++I)
19236     if (Context.getTypeSize(Types[I]) > BitWidth)
19237       return Types[I];
19238 
19239   return QualType();
19240 }
19241 
19242 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19243                                           EnumConstantDecl *LastEnumConst,
19244                                           SourceLocation IdLoc,
19245                                           IdentifierInfo *Id,
19246                                           Expr *Val) {
19247   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19248   llvm::APSInt EnumVal(IntWidth);
19249   QualType EltTy;
19250 
19251   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19252     Val = nullptr;
19253 
19254   if (Val)
19255     Val = DefaultLvalueConversion(Val).get();
19256 
19257   if (Val) {
19258     if (Enum->isDependentType() || Val->isTypeDependent() ||
19259         Val->containsErrors())
19260       EltTy = Context.DependentTy;
19261     else {
19262       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19263       // underlying type, but do allow it in all other contexts.
19264       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19265         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19266         // constant-expression in the enumerator-definition shall be a converted
19267         // constant expression of the underlying type.
19268         EltTy = Enum->getIntegerType();
19269         ExprResult Converted =
19270           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19271                                            CCEK_Enumerator);
19272         if (Converted.isInvalid())
19273           Val = nullptr;
19274         else
19275           Val = Converted.get();
19276       } else if (!Val->isValueDependent() &&
19277                  !(Val =
19278                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19279                            .get())) {
19280         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19281       } else {
19282         if (Enum->isComplete()) {
19283           EltTy = Enum->getIntegerType();
19284 
19285           // In Obj-C and Microsoft mode, require the enumeration value to be
19286           // representable in the underlying type of the enumeration. In C++11,
19287           // we perform a non-narrowing conversion as part of converted constant
19288           // expression checking.
19289           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19290             if (Context.getTargetInfo()
19291                     .getTriple()
19292                     .isWindowsMSVCEnvironment()) {
19293               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19294             } else {
19295               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19296             }
19297           }
19298 
19299           // Cast to the underlying type.
19300           Val = ImpCastExprToType(Val, EltTy,
19301                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
19302                                                          : CK_IntegralCast)
19303                     .get();
19304         } else if (getLangOpts().CPlusPlus) {
19305           // C++11 [dcl.enum]p5:
19306           //   If the underlying type is not fixed, the type of each enumerator
19307           //   is the type of its initializing value:
19308           //     - If an initializer is specified for an enumerator, the
19309           //       initializing value has the same type as the expression.
19310           EltTy = Val->getType();
19311         } else {
19312           // C99 6.7.2.2p2:
19313           //   The expression that defines the value of an enumeration constant
19314           //   shall be an integer constant expression that has a value
19315           //   representable as an int.
19316 
19317           // Complain if the value is not representable in an int.
19318           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19319             Diag(IdLoc, diag::ext_enum_value_not_int)
19320               << toString(EnumVal, 10) << Val->getSourceRange()
19321               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19322           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19323             // Force the type of the expression to 'int'.
19324             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19325           }
19326           EltTy = Val->getType();
19327         }
19328       }
19329     }
19330   }
19331 
19332   if (!Val) {
19333     if (Enum->isDependentType())
19334       EltTy = Context.DependentTy;
19335     else if (!LastEnumConst) {
19336       // C++0x [dcl.enum]p5:
19337       //   If the underlying type is not fixed, the type of each enumerator
19338       //   is the type of its initializing value:
19339       //     - If no initializer is specified for the first enumerator, the
19340       //       initializing value has an unspecified integral type.
19341       //
19342       // GCC uses 'int' for its unspecified integral type, as does
19343       // C99 6.7.2.2p3.
19344       if (Enum->isFixed()) {
19345         EltTy = Enum->getIntegerType();
19346       }
19347       else {
19348         EltTy = Context.IntTy;
19349       }
19350     } else {
19351       // Assign the last value + 1.
19352       EnumVal = LastEnumConst->getInitVal();
19353       ++EnumVal;
19354       EltTy = LastEnumConst->getType();
19355 
19356       // Check for overflow on increment.
19357       if (EnumVal < LastEnumConst->getInitVal()) {
19358         // C++0x [dcl.enum]p5:
19359         //   If the underlying type is not fixed, the type of each enumerator
19360         //   is the type of its initializing value:
19361         //
19362         //     - Otherwise the type of the initializing value is the same as
19363         //       the type of the initializing value of the preceding enumerator
19364         //       unless the incremented value is not representable in that type,
19365         //       in which case the type is an unspecified integral type
19366         //       sufficient to contain the incremented value. If no such type
19367         //       exists, the program is ill-formed.
19368         QualType T = getNextLargerIntegralType(Context, EltTy);
19369         if (T.isNull() || Enum->isFixed()) {
19370           // There is no integral type larger enough to represent this
19371           // value. Complain, then allow the value to wrap around.
19372           EnumVal = LastEnumConst->getInitVal();
19373           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19374           ++EnumVal;
19375           if (Enum->isFixed())
19376             // When the underlying type is fixed, this is ill-formed.
19377             Diag(IdLoc, diag::err_enumerator_wrapped)
19378               << toString(EnumVal, 10)
19379               << EltTy;
19380           else
19381             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19382               << toString(EnumVal, 10);
19383         } else {
19384           EltTy = T;
19385         }
19386 
19387         // Retrieve the last enumerator's value, extent that type to the
19388         // type that is supposed to be large enough to represent the incremented
19389         // value, then increment.
19390         EnumVal = LastEnumConst->getInitVal();
19391         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19392         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19393         ++EnumVal;
19394 
19395         // If we're not in C++, diagnose the overflow of enumerator values,
19396         // which in C99 means that the enumerator value is not representable in
19397         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19398         // permits enumerator values that are representable in some larger
19399         // integral type.
19400         if (!getLangOpts().CPlusPlus && !T.isNull())
19401           Diag(IdLoc, diag::warn_enum_value_overflow);
19402       } else if (!getLangOpts().CPlusPlus &&
19403                  !EltTy->isDependentType() &&
19404                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19405         // Enforce C99 6.7.2.2p2 even when we compute the next value.
19406         Diag(IdLoc, diag::ext_enum_value_not_int)
19407           << toString(EnumVal, 10) << 1;
19408       }
19409     }
19410   }
19411 
19412   if (!EltTy->isDependentType()) {
19413     // Make the enumerator value match the signedness and size of the
19414     // enumerator's type.
19415     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19416     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19417   }
19418 
19419   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19420                                   Val, EnumVal);
19421 }
19422 
19423 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19424                                                 SourceLocation IILoc) {
19425   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19426       !getLangOpts().CPlusPlus)
19427     return SkipBodyInfo();
19428 
19429   // We have an anonymous enum definition. Look up the first enumerator to
19430   // determine if we should merge the definition with an existing one and
19431   // skip the body.
19432   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19433                                          forRedeclarationInCurContext());
19434   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19435   if (!PrevECD)
19436     return SkipBodyInfo();
19437 
19438   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19439   NamedDecl *Hidden;
19440   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19441     SkipBodyInfo Skip;
19442     Skip.Previous = Hidden;
19443     return Skip;
19444   }
19445 
19446   return SkipBodyInfo();
19447 }
19448 
19449 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19450                               SourceLocation IdLoc, IdentifierInfo *Id,
19451                               const ParsedAttributesView &Attrs,
19452                               SourceLocation EqualLoc, Expr *Val) {
19453   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19454   EnumConstantDecl *LastEnumConst =
19455     cast_or_null<EnumConstantDecl>(lastEnumConst);
19456 
19457   // The scope passed in may not be a decl scope.  Zip up the scope tree until
19458   // we find one that is.
19459   S = getNonFieldDeclScope(S);
19460 
19461   // Verify that there isn't already something declared with this name in this
19462   // scope.
19463   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19464   LookupName(R, S);
19465   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19466 
19467   if (PrevDecl && PrevDecl->isTemplateParameter()) {
19468     // Maybe we will complain about the shadowed template parameter.
19469     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19470     // Just pretend that we didn't see the previous declaration.
19471     PrevDecl = nullptr;
19472   }
19473 
19474   // C++ [class.mem]p15:
19475   // If T is the name of a class, then each of the following shall have a name
19476   // different from T:
19477   // - every enumerator of every member of class T that is an unscoped
19478   // enumerated type
19479   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19480     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19481                             DeclarationNameInfo(Id, IdLoc));
19482 
19483   EnumConstantDecl *New =
19484     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19485   if (!New)
19486     return nullptr;
19487 
19488   if (PrevDecl) {
19489     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19490       // Check for other kinds of shadowing not already handled.
19491       CheckShadow(New, PrevDecl, R);
19492     }
19493 
19494     // When in C++, we may get a TagDecl with the same name; in this case the
19495     // enum constant will 'hide' the tag.
19496     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19497            "Received TagDecl when not in C++!");
19498     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19499       if (isa<EnumConstantDecl>(PrevDecl))
19500         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19501       else
19502         Diag(IdLoc, diag::err_redefinition) << Id;
19503       notePreviousDefinition(PrevDecl, IdLoc);
19504       return nullptr;
19505     }
19506   }
19507 
19508   // Process attributes.
19509   ProcessDeclAttributeList(S, New, Attrs);
19510   AddPragmaAttributes(S, New);
19511 
19512   // Register this decl in the current scope stack.
19513   New->setAccess(TheEnumDecl->getAccess());
19514   PushOnScopeChains(New, S);
19515 
19516   ActOnDocumentableDecl(New);
19517 
19518   return New;
19519 }
19520 
19521 // Returns true when the enum initial expression does not trigger the
19522 // duplicate enum warning.  A few common cases are exempted as follows:
19523 // Element2 = Element1
19524 // Element2 = Element1 + 1
19525 // Element2 = Element1 - 1
19526 // Where Element2 and Element1 are from the same enum.
19527 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19528   Expr *InitExpr = ECD->getInitExpr();
19529   if (!InitExpr)
19530     return true;
19531   InitExpr = InitExpr->IgnoreImpCasts();
19532 
19533   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19534     if (!BO->isAdditiveOp())
19535       return true;
19536     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19537     if (!IL)
19538       return true;
19539     if (IL->getValue() != 1)
19540       return true;
19541 
19542     InitExpr = BO->getLHS();
19543   }
19544 
19545   // This checks if the elements are from the same enum.
19546   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19547   if (!DRE)
19548     return true;
19549 
19550   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19551   if (!EnumConstant)
19552     return true;
19553 
19554   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19555       Enum)
19556     return true;
19557 
19558   return false;
19559 }
19560 
19561 // Emits a warning when an element is implicitly set a value that
19562 // a previous element has already been set to.
19563 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19564                                         EnumDecl *Enum, QualType EnumType) {
19565   // Avoid anonymous enums
19566   if (!Enum->getIdentifier())
19567     return;
19568 
19569   // Only check for small enums.
19570   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19571     return;
19572 
19573   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19574     return;
19575 
19576   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19577   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19578 
19579   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19580 
19581   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19582   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19583 
19584   // Use int64_t as a key to avoid needing special handling for map keys.
19585   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19586     llvm::APSInt Val = D->getInitVal();
19587     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19588   };
19589 
19590   DuplicatesVector DupVector;
19591   ValueToVectorMap EnumMap;
19592 
19593   // Populate the EnumMap with all values represented by enum constants without
19594   // an initializer.
19595   for (auto *Element : Elements) {
19596     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19597 
19598     // Null EnumConstantDecl means a previous diagnostic has been emitted for
19599     // this constant.  Skip this enum since it may be ill-formed.
19600     if (!ECD) {
19601       return;
19602     }
19603 
19604     // Constants with initializers are handled in the next loop.
19605     if (ECD->getInitExpr())
19606       continue;
19607 
19608     // Duplicate values are handled in the next loop.
19609     EnumMap.insert({EnumConstantToKey(ECD), ECD});
19610   }
19611 
19612   if (EnumMap.size() == 0)
19613     return;
19614 
19615   // Create vectors for any values that has duplicates.
19616   for (auto *Element : Elements) {
19617     // The last loop returned if any constant was null.
19618     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19619     if (!ValidDuplicateEnum(ECD, Enum))
19620       continue;
19621 
19622     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19623     if (Iter == EnumMap.end())
19624       continue;
19625 
19626     DeclOrVector& Entry = Iter->second;
19627     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19628       // Ensure constants are different.
19629       if (D == ECD)
19630         continue;
19631 
19632       // Create new vector and push values onto it.
19633       auto Vec = std::make_unique<ECDVector>();
19634       Vec->push_back(D);
19635       Vec->push_back(ECD);
19636 
19637       // Update entry to point to the duplicates vector.
19638       Entry = Vec.get();
19639 
19640       // Store the vector somewhere we can consult later for quick emission of
19641       // diagnostics.
19642       DupVector.emplace_back(std::move(Vec));
19643       continue;
19644     }
19645 
19646     ECDVector *Vec = Entry.get<ECDVector*>();
19647     // Make sure constants are not added more than once.
19648     if (*Vec->begin() == ECD)
19649       continue;
19650 
19651     Vec->push_back(ECD);
19652   }
19653 
19654   // Emit diagnostics.
19655   for (const auto &Vec : DupVector) {
19656     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19657 
19658     // Emit warning for one enum constant.
19659     auto *FirstECD = Vec->front();
19660     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19661       << FirstECD << toString(FirstECD->getInitVal(), 10)
19662       << FirstECD->getSourceRange();
19663 
19664     // Emit one note for each of the remaining enum constants with
19665     // the same value.
19666     for (auto *ECD : llvm::drop_begin(*Vec))
19667       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19668         << ECD << toString(ECD->getInitVal(), 10)
19669         << ECD->getSourceRange();
19670   }
19671 }
19672 
19673 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19674                              bool AllowMask) const {
19675   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19676   assert(ED->isCompleteDefinition() && "expected enum definition");
19677 
19678   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19679   llvm::APInt &FlagBits = R.first->second;
19680 
19681   if (R.second) {
19682     for (auto *E : ED->enumerators()) {
19683       const auto &EVal = E->getInitVal();
19684       // Only single-bit enumerators introduce new flag values.
19685       if (EVal.isPowerOf2())
19686         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19687     }
19688   }
19689 
19690   // A value is in a flag enum if either its bits are a subset of the enum's
19691   // flag bits (the first condition) or we are allowing masks and the same is
19692   // true of its complement (the second condition). When masks are allowed, we
19693   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19694   //
19695   // While it's true that any value could be used as a mask, the assumption is
19696   // that a mask will have all of the insignificant bits set. Anything else is
19697   // likely a logic error.
19698   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19699   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19700 }
19701 
19702 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19703                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19704                          const ParsedAttributesView &Attrs) {
19705   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19706   QualType EnumType = Context.getTypeDeclType(Enum);
19707 
19708   ProcessDeclAttributeList(S, Enum, Attrs);
19709 
19710   if (Enum->isDependentType()) {
19711     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19712       EnumConstantDecl *ECD =
19713         cast_or_null<EnumConstantDecl>(Elements[i]);
19714       if (!ECD) continue;
19715 
19716       ECD->setType(EnumType);
19717     }
19718 
19719     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19720     return;
19721   }
19722 
19723   // TODO: If the result value doesn't fit in an int, it must be a long or long
19724   // long value.  ISO C does not support this, but GCC does as an extension,
19725   // emit a warning.
19726   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19727   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19728   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19729 
19730   // Verify that all the values are okay, compute the size of the values, and
19731   // reverse the list.
19732   unsigned NumNegativeBits = 0;
19733   unsigned NumPositiveBits = 0;
19734 
19735   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19736     EnumConstantDecl *ECD =
19737       cast_or_null<EnumConstantDecl>(Elements[i]);
19738     if (!ECD) continue;  // Already issued a diagnostic.
19739 
19740     const llvm::APSInt &InitVal = ECD->getInitVal();
19741 
19742     // Keep track of the size of positive and negative values.
19743     if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19744       // If the enumerator is zero that should still be counted as a positive
19745       // bit since we need a bit to store the value zero.
19746       unsigned ActiveBits = InitVal.getActiveBits();
19747       NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19748     } else {
19749       NumNegativeBits =
19750           std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19751     }
19752   }
19753 
19754   // If we have an empty set of enumerators we still need one bit.
19755   // From [dcl.enum]p8
19756   // If the enumerator-list is empty, the values of the enumeration are as if
19757   // the enumeration had a single enumerator with value 0
19758   if (!NumPositiveBits && !NumNegativeBits)
19759     NumPositiveBits = 1;
19760 
19761   // Figure out the type that should be used for this enum.
19762   QualType BestType;
19763   unsigned BestWidth;
19764 
19765   // C++0x N3000 [conv.prom]p3:
19766   //   An rvalue of an unscoped enumeration type whose underlying
19767   //   type is not fixed can be converted to an rvalue of the first
19768   //   of the following types that can represent all the values of
19769   //   the enumeration: int, unsigned int, long int, unsigned long
19770   //   int, long long int, or unsigned long long int.
19771   // C99 6.4.4.3p2:
19772   //   An identifier declared as an enumeration constant has type int.
19773   // The C99 rule is modified by a gcc extension
19774   QualType BestPromotionType;
19775 
19776   bool Packed = Enum->hasAttr<PackedAttr>();
19777   // -fshort-enums is the equivalent to specifying the packed attribute on all
19778   // enum definitions.
19779   if (LangOpts.ShortEnums)
19780     Packed = true;
19781 
19782   // If the enum already has a type because it is fixed or dictated by the
19783   // target, promote that type instead of analyzing the enumerators.
19784   if (Enum->isComplete()) {
19785     BestType = Enum->getIntegerType();
19786     if (Context.isPromotableIntegerType(BestType))
19787       BestPromotionType = Context.getPromotedIntegerType(BestType);
19788     else
19789       BestPromotionType = BestType;
19790 
19791     BestWidth = Context.getIntWidth(BestType);
19792   }
19793   else if (NumNegativeBits) {
19794     // If there is a negative value, figure out the smallest integer type (of
19795     // int/long/longlong) that fits.
19796     // If it's packed, check also if it fits a char or a short.
19797     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19798       BestType = Context.SignedCharTy;
19799       BestWidth = CharWidth;
19800     } else if (Packed && NumNegativeBits <= ShortWidth &&
19801                NumPositiveBits < ShortWidth) {
19802       BestType = Context.ShortTy;
19803       BestWidth = ShortWidth;
19804     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19805       BestType = Context.IntTy;
19806       BestWidth = IntWidth;
19807     } else {
19808       BestWidth = Context.getTargetInfo().getLongWidth();
19809 
19810       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19811         BestType = Context.LongTy;
19812       } else {
19813         BestWidth = Context.getTargetInfo().getLongLongWidth();
19814 
19815         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19816           Diag(Enum->getLocation(), diag::ext_enum_too_large);
19817         BestType = Context.LongLongTy;
19818       }
19819     }
19820     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19821   } else {
19822     // If there is no negative value, figure out the smallest type that fits
19823     // all of the enumerator values.
19824     // If it's packed, check also if it fits a char or a short.
19825     if (Packed && NumPositiveBits <= CharWidth) {
19826       BestType = Context.UnsignedCharTy;
19827       BestPromotionType = Context.IntTy;
19828       BestWidth = CharWidth;
19829     } else if (Packed && NumPositiveBits <= ShortWidth) {
19830       BestType = Context.UnsignedShortTy;
19831       BestPromotionType = Context.IntTy;
19832       BestWidth = ShortWidth;
19833     } else if (NumPositiveBits <= IntWidth) {
19834       BestType = Context.UnsignedIntTy;
19835       BestWidth = IntWidth;
19836       BestPromotionType
19837         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19838                            ? Context.UnsignedIntTy : Context.IntTy;
19839     } else if (NumPositiveBits <=
19840                (BestWidth = Context.getTargetInfo().getLongWidth())) {
19841       BestType = Context.UnsignedLongTy;
19842       BestPromotionType
19843         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19844                            ? Context.UnsignedLongTy : Context.LongTy;
19845     } else {
19846       BestWidth = Context.getTargetInfo().getLongLongWidth();
19847       assert(NumPositiveBits <= BestWidth &&
19848              "How could an initializer get larger than ULL?");
19849       BestType = Context.UnsignedLongLongTy;
19850       BestPromotionType
19851         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19852                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
19853     }
19854   }
19855 
19856   // Loop over all of the enumerator constants, changing their types to match
19857   // the type of the enum if needed.
19858   for (auto *D : Elements) {
19859     auto *ECD = cast_or_null<EnumConstantDecl>(D);
19860     if (!ECD) continue;  // Already issued a diagnostic.
19861 
19862     // Standard C says the enumerators have int type, but we allow, as an
19863     // extension, the enumerators to be larger than int size.  If each
19864     // enumerator value fits in an int, type it as an int, otherwise type it the
19865     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
19866     // that X has type 'int', not 'unsigned'.
19867 
19868     // Determine whether the value fits into an int.
19869     llvm::APSInt InitVal = ECD->getInitVal();
19870 
19871     // If it fits into an integer type, force it.  Otherwise force it to match
19872     // the enum decl type.
19873     QualType NewTy;
19874     unsigned NewWidth;
19875     bool NewSign;
19876     if (!getLangOpts().CPlusPlus &&
19877         !Enum->isFixed() &&
19878         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19879       NewTy = Context.IntTy;
19880       NewWidth = IntWidth;
19881       NewSign = true;
19882     } else if (ECD->getType() == BestType) {
19883       // Already the right type!
19884       if (getLangOpts().CPlusPlus)
19885         // C++ [dcl.enum]p4: Following the closing brace of an
19886         // enum-specifier, each enumerator has the type of its
19887         // enumeration.
19888         ECD->setType(EnumType);
19889       continue;
19890     } else {
19891       NewTy = BestType;
19892       NewWidth = BestWidth;
19893       NewSign = BestType->isSignedIntegerOrEnumerationType();
19894     }
19895 
19896     // Adjust the APSInt value.
19897     InitVal = InitVal.extOrTrunc(NewWidth);
19898     InitVal.setIsSigned(NewSign);
19899     ECD->setInitVal(InitVal);
19900 
19901     // Adjust the Expr initializer and type.
19902     if (ECD->getInitExpr() &&
19903         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19904       ECD->setInitExpr(ImplicitCastExpr::Create(
19905           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19906           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19907     if (getLangOpts().CPlusPlus)
19908       // C++ [dcl.enum]p4: Following the closing brace of an
19909       // enum-specifier, each enumerator has the type of its
19910       // enumeration.
19911       ECD->setType(EnumType);
19912     else
19913       ECD->setType(NewTy);
19914   }
19915 
19916   Enum->completeDefinition(BestType, BestPromotionType,
19917                            NumPositiveBits, NumNegativeBits);
19918 
19919   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19920 
19921   if (Enum->isClosedFlag()) {
19922     for (Decl *D : Elements) {
19923       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19924       if (!ECD) continue;  // Already issued a diagnostic.
19925 
19926       llvm::APSInt InitVal = ECD->getInitVal();
19927       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19928           !IsValueInFlagEnum(Enum, InitVal, true))
19929         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19930           << ECD << Enum;
19931     }
19932   }
19933 
19934   // Now that the enum type is defined, ensure it's not been underaligned.
19935   if (Enum->hasAttrs())
19936     CheckAlignasUnderalignment(Enum);
19937 }
19938 
19939 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19940                                   SourceLocation StartLoc,
19941                                   SourceLocation EndLoc) {
19942   StringLiteral *AsmString = cast<StringLiteral>(expr);
19943 
19944   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19945                                                    AsmString, StartLoc,
19946                                                    EndLoc);
19947   CurContext->addDecl(New);
19948   return New;
19949 }
19950 
19951 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
19952   auto *New = TopLevelStmtDecl::Create(Context, Statement);
19953   Context.getTranslationUnitDecl()->addDecl(New);
19954   return New;
19955 }
19956 
19957 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19958                                       IdentifierInfo* AliasName,
19959                                       SourceLocation PragmaLoc,
19960                                       SourceLocation NameLoc,
19961                                       SourceLocation AliasNameLoc) {
19962   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19963                                          LookupOrdinaryName);
19964   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19965                            AttributeCommonInfo::Form::Pragma());
19966   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19967       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19968 
19969   // If a declaration that:
19970   // 1) declares a function or a variable
19971   // 2) has external linkage
19972   // already exists, add a label attribute to it.
19973   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19974     if (isDeclExternC(PrevDecl))
19975       PrevDecl->addAttr(Attr);
19976     else
19977       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19978           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19979     // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19980   } else
19981     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19982 }
19983 
19984 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19985                              SourceLocation PragmaLoc,
19986                              SourceLocation NameLoc) {
19987   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19988 
19989   if (PrevDecl) {
19990     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
19991   } else {
19992     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19993   }
19994 }
19995 
19996 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19997                                 IdentifierInfo* AliasName,
19998                                 SourceLocation PragmaLoc,
19999                                 SourceLocation NameLoc,
20000                                 SourceLocation AliasNameLoc) {
20001   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20002                                     LookupOrdinaryName);
20003   WeakInfo W = WeakInfo(Name, NameLoc);
20004 
20005   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20006     if (!PrevDecl->hasAttr<AliasAttr>())
20007       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20008         DeclApplyPragmaWeak(TUScope, ND, W);
20009   } else {
20010     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20011   }
20012 }
20013 
20014 ObjCContainerDecl *Sema::getObjCDeclContext() const {
20015   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20016 }
20017 
20018 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20019                                                      bool Final) {
20020   assert(FD && "Expected non-null FunctionDecl");
20021 
20022   // SYCL functions can be template, so we check if they have appropriate
20023   // attribute prior to checking if it is a template.
20024   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20025     return FunctionEmissionStatus::Emitted;
20026 
20027   // Templates are emitted when they're instantiated.
20028   if (FD->isDependentContext())
20029     return FunctionEmissionStatus::TemplateDiscarded;
20030 
20031   // Check whether this function is an externally visible definition.
20032   auto IsEmittedForExternalSymbol = [this, FD]() {
20033     // We have to check the GVA linkage of the function's *definition* -- if we
20034     // only have a declaration, we don't know whether or not the function will
20035     // be emitted, because (say) the definition could include "inline".
20036     const FunctionDecl *Def = FD->getDefinition();
20037 
20038     return Def && !isDiscardableGVALinkage(
20039                       getASTContext().GetGVALinkageForFunction(Def));
20040   };
20041 
20042   if (LangOpts.OpenMPIsTargetDevice) {
20043     // In OpenMP device mode we will not emit host only functions, or functions
20044     // we don't need due to their linkage.
20045     std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20046         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20047     // DevTy may be changed later by
20048     //  #pragma omp declare target to(*) device_type(*).
20049     // Therefore DevTy having no value does not imply host. The emission status
20050     // will be checked again at the end of compilation unit with Final = true.
20051     if (DevTy)
20052       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20053         return FunctionEmissionStatus::OMPDiscarded;
20054     // If we have an explicit value for the device type, or we are in a target
20055     // declare context, we need to emit all extern and used symbols.
20056     if (isInOpenMPDeclareTargetContext() || DevTy)
20057       if (IsEmittedForExternalSymbol())
20058         return FunctionEmissionStatus::Emitted;
20059     // Device mode only emits what it must, if it wasn't tagged yet and needed,
20060     // we'll omit it.
20061     if (Final)
20062       return FunctionEmissionStatus::OMPDiscarded;
20063   } else if (LangOpts.OpenMP > 45) {
20064     // In OpenMP host compilation prior to 5.0 everything was an emitted host
20065     // function. In 5.0, no_host was introduced which might cause a function to
20066     // be ommitted.
20067     std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20068         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20069     if (DevTy)
20070       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20071         return FunctionEmissionStatus::OMPDiscarded;
20072   }
20073 
20074   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20075     return FunctionEmissionStatus::Emitted;
20076 
20077   if (LangOpts.CUDA) {
20078     // When compiling for device, host functions are never emitted.  Similarly,
20079     // when compiling for host, device and global functions are never emitted.
20080     // (Technically, we do emit a host-side stub for global functions, but this
20081     // doesn't count for our purposes here.)
20082     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20083     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20084       return FunctionEmissionStatus::CUDADiscarded;
20085     if (!LangOpts.CUDAIsDevice &&
20086         (T == Sema::CFT_Device || T == Sema::CFT_Global))
20087       return FunctionEmissionStatus::CUDADiscarded;
20088 
20089     if (IsEmittedForExternalSymbol())
20090       return FunctionEmissionStatus::Emitted;
20091   }
20092 
20093   // Otherwise, the function is known-emitted if it's in our set of
20094   // known-emitted functions.
20095   return FunctionEmissionStatus::Unknown;
20096 }
20097 
20098 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20099   // Host-side references to a __global__ function refer to the stub, so the
20100   // function itself is never emitted and therefore should not be marked.
20101   // If we have host fn calls kernel fn calls host+device, the HD function
20102   // does not get instantiated on the host. We model this by omitting at the
20103   // call to the kernel from the callgraph. This ensures that, when compiling
20104   // for host, only HD functions actually called from the host get marked as
20105   // known-emitted.
20106   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20107          IdentifyCUDATarget(Callee) == CFT_Global;
20108 }
20109