1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw___ibm128:
146   case tok::kw_wchar_t:
147   case tok::kw_bool:
148   case tok::kw___underlying_type:
149   case tok::kw___auto_type:
150     return true;
151 
152   case tok::annot_typename:
153   case tok::kw_char16_t:
154   case tok::kw_char32_t:
155   case tok::kw_typeof:
156   case tok::annot_decltype:
157   case tok::kw_decltype:
158     return getLangOpts().CPlusPlus;
159 
160   case tok::kw_char8_t:
161     return getLangOpts().Char8;
162 
163   default:
164     break;
165   }
166 
167   return false;
168 }
169 
170 namespace {
171 enum class UnqualifiedTypeNameLookupResult {
172   NotFound,
173   FoundNonType,
174   FoundType
175 };
176 } // end anonymous namespace
177 
178 /// Tries to perform unqualified lookup of the type decls in bases for
179 /// dependent class.
180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181 /// type decl, \a FoundType if only type decls are found.
182 static UnqualifiedTypeNameLookupResult
183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184                                 SourceLocation NameLoc,
185                                 const CXXRecordDecl *RD) {
186   if (!RD->hasDefinition())
187     return UnqualifiedTypeNameLookupResult::NotFound;
188   // Look for type decls in base classes.
189   UnqualifiedTypeNameLookupResult FoundTypeDecl =
190       UnqualifiedTypeNameLookupResult::NotFound;
191   for (const auto &Base : RD->bases()) {
192     const CXXRecordDecl *BaseRD = nullptr;
193     if (auto *BaseTT = Base.getType()->getAs<TagType>())
194       BaseRD = BaseTT->getAsCXXRecordDecl();
195     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
196       // Look for type decls in dependent base classes that have known primary
197       // templates.
198       if (!TST || !TST->isDependentType())
199         continue;
200       auto *TD = TST->getTemplateName().getAsTemplateDecl();
201       if (!TD)
202         continue;
203       if (auto *BasePrimaryTemplate =
204           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206           BaseRD = BasePrimaryTemplate;
207         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208           if (const ClassTemplatePartialSpecializationDecl *PS =
209                   CTD->findPartialSpecialization(Base.getType()))
210             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211               BaseRD = PS;
212         }
213       }
214     }
215     if (BaseRD) {
216       for (NamedDecl *ND : BaseRD->lookup(&II)) {
217         if (!isa<TypeDecl>(ND))
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220       }
221       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
223         case UnqualifiedTypeNameLookupResult::FoundNonType:
224           return UnqualifiedTypeNameLookupResult::FoundNonType;
225         case UnqualifiedTypeNameLookupResult::FoundType:
226           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227           break;
228         case UnqualifiedTypeNameLookupResult::NotFound:
229           break;
230         }
231       }
232     }
233   }
234 
235   return FoundTypeDecl;
236 }
237 
238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239                                                       const IdentifierInfo &II,
240                                                       SourceLocation NameLoc) {
241   // Lookup in the parent class template context, if any.
242   const CXXRecordDecl *RD = nullptr;
243   UnqualifiedTypeNameLookupResult FoundTypeDecl =
244       UnqualifiedTypeNameLookupResult::NotFound;
245   for (DeclContext *DC = S.CurContext;
246        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247        DC = DC->getParent()) {
248     // Look for type decls in dependent base classes that have known primary
249     // templates.
250     RD = dyn_cast<CXXRecordDecl>(DC);
251     if (RD && RD->getDescribedClassTemplate())
252       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253   }
254   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255     return nullptr;
256 
257   // We found some types in dependent base classes.  Recover as if the user
258   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
259   // lookup during template instantiation.
260   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
261 
262   ASTContext &Context = S.Context;
263   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
264                                           cast<Type>(Context.getRecordType(RD)));
265   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
266 
267   CXXScopeSpec SS;
268   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
269 
270   TypeLocBuilder Builder;
271   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272   DepTL.setNameLoc(NameLoc);
273   DepTL.setElaboratedKeywordLoc(SourceLocation());
274   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
276 }
277 
278 /// If the identifier refers to a type name within this scope,
279 /// return the declaration of that type.
280 ///
281 /// This routine performs ordinary name lookup of the identifier II
282 /// within the given scope, with optional C++ scope specifier SS, to
283 /// determine whether the name refers to a type. If so, returns an
284 /// opaque pointer (actually a QualType) corresponding to that
285 /// type. Otherwise, returns NULL.
286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
287                              Scope *S, CXXScopeSpec *SS,
288                              bool isClassName, bool HasTrailingDot,
289                              ParsedType ObjectTypePtr,
290                              bool IsCtorOrDtorName,
291                              bool WantNontrivialTypeSourceInfo,
292                              bool IsClassTemplateDeductionContext,
293                              IdentifierInfo **CorrectedII) {
294   // FIXME: Consider allowing this outside C++1z mode as an extension.
295   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297                               !isClassName && !HasTrailingDot;
298 
299   // Determine where we will perform name lookup.
300   DeclContext *LookupCtx = nullptr;
301   if (ObjectTypePtr) {
302     QualType ObjectType = ObjectTypePtr.get();
303     if (ObjectType->isRecordType())
304       LookupCtx = computeDeclContext(ObjectType);
305   } else if (SS && SS->isNotEmpty()) {
306     LookupCtx = computeDeclContext(*SS, false);
307 
308     if (!LookupCtx) {
309       if (isDependentScopeSpecifier(*SS)) {
310         // C++ [temp.res]p3:
311         //   A qualified-id that refers to a type and in which the
312         //   nested-name-specifier depends on a template-parameter (14.6.2)
313         //   shall be prefixed by the keyword typename to indicate that the
314         //   qualified-id denotes a type, forming an
315         //   elaborated-type-specifier (7.1.5.3).
316         //
317         // We therefore do not perform any name lookup if the result would
318         // refer to a member of an unknown specialization.
319         if (!isClassName && !IsCtorOrDtorName)
320           return nullptr;
321 
322         // We know from the grammar that this name refers to a type,
323         // so build a dependent node to describe the type.
324         if (WantNontrivialTypeSourceInfo)
325           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
326 
327         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
328         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
329                                        II, NameLoc);
330         return ParsedType::make(T);
331       }
332 
333       return nullptr;
334     }
335 
336     if (!LookupCtx->isDependentContext() &&
337         RequireCompleteDeclContext(*SS, LookupCtx))
338       return nullptr;
339   }
340 
341   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
342   // lookup for class-names.
343   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
344                                       LookupOrdinaryName;
345   LookupResult Result(*this, &II, NameLoc, Kind);
346   if (LookupCtx) {
347     // Perform "qualified" name lookup into the declaration context we
348     // computed, which is either the type of the base of a member access
349     // expression or the declaration context associated with a prior
350     // nested-name-specifier.
351     LookupQualifiedName(Result, LookupCtx);
352 
353     if (ObjectTypePtr && Result.empty()) {
354       // C++ [basic.lookup.classref]p3:
355       //   If the unqualified-id is ~type-name, the type-name is looked up
356       //   in the context of the entire postfix-expression. If the type T of
357       //   the object expression is of a class type C, the type-name is also
358       //   looked up in the scope of class C. At least one of the lookups shall
359       //   find a name that refers to (possibly cv-qualified) T.
360       LookupName(Result, S);
361     }
362   } else {
363     // Perform unqualified name lookup.
364     LookupName(Result, S);
365 
366     // For unqualified lookup in a class template in MSVC mode, look into
367     // dependent base classes where the primary class template is known.
368     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
369       if (ParsedType TypeInBase =
370               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
371         return TypeInBase;
372     }
373   }
374 
375   NamedDecl *IIDecl = nullptr;
376   UsingShadowDecl *FoundUsingShadow = nullptr;
377   switch (Result.getResultKind()) {
378   case LookupResult::NotFound:
379   case LookupResult::NotFoundInCurrentInstantiation:
380     if (CorrectedII) {
381       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
382                                AllowDeducedTemplate);
383       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
384                                               S, SS, CCC, CTK_ErrorRecovery);
385       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
386       TemplateTy Template;
387       bool MemberOfUnknownSpecialization;
388       UnqualifiedId TemplateName;
389       TemplateName.setIdentifier(NewII, NameLoc);
390       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
391       CXXScopeSpec NewSS, *NewSSPtr = SS;
392       if (SS && NNS) {
393         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
394         NewSSPtr = &NewSS;
395       }
396       if (Correction && (NNS || NewII != &II) &&
397           // Ignore a correction to a template type as the to-be-corrected
398           // identifier is not a template (typo correction for template names
399           // is handled elsewhere).
400           !(getLangOpts().CPlusPlus && NewSSPtr &&
401             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
402                            Template, MemberOfUnknownSpecialization))) {
403         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
404                                     isClassName, HasTrailingDot, ObjectTypePtr,
405                                     IsCtorOrDtorName,
406                                     WantNontrivialTypeSourceInfo,
407                                     IsClassTemplateDeductionContext);
408         if (Ty) {
409           diagnoseTypo(Correction,
410                        PDiag(diag::err_unknown_type_or_class_name_suggest)
411                          << Result.getLookupName() << isClassName);
412           if (SS && NNS)
413             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
414           *CorrectedII = NewII;
415           return Ty;
416         }
417       }
418     }
419     // If typo correction failed or was not performed, fall through
420     LLVM_FALLTHROUGH;
421   case LookupResult::FoundOverloaded:
422   case LookupResult::FoundUnresolvedValue:
423     Result.suppressDiagnostics();
424     return nullptr;
425 
426   case LookupResult::Ambiguous:
427     // Recover from type-hiding ambiguities by hiding the type.  We'll
428     // do the lookup again when looking for an object, and we can
429     // diagnose the error then.  If we don't do this, then the error
430     // about hiding the type will be immediately followed by an error
431     // that only makes sense if the identifier was treated like a type.
432     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
433       Result.suppressDiagnostics();
434       return nullptr;
435     }
436 
437     // Look to see if we have a type anywhere in the list of results.
438     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
439          Res != ResEnd; ++Res) {
440       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
441       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
442               RealRes) ||
443           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
444         if (!IIDecl ||
445             // Make the selection of the recovery decl deterministic.
446             RealRes->getLocation() < IIDecl->getLocation()) {
447           IIDecl = RealRes;
448           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
449         }
450       }
451     }
452 
453     if (!IIDecl) {
454       // None of the entities we found is a type, so there is no way
455       // to even assume that the result is a type. In this case, don't
456       // complain about the ambiguity. The parser will either try to
457       // perform this lookup again (e.g., as an object name), which
458       // will produce the ambiguity, or will complain that it expected
459       // a type name.
460       Result.suppressDiagnostics();
461       return nullptr;
462     }
463 
464     // We found a type within the ambiguous lookup; diagnose the
465     // ambiguity and then return that type. This might be the right
466     // answer, or it might not be, but it suppresses any attempt to
467     // perform the name lookup again.
468     break;
469 
470   case LookupResult::Found:
471     IIDecl = Result.getFoundDecl();
472     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
473     break;
474   }
475 
476   assert(IIDecl && "Didn't find decl");
477 
478   QualType T;
479   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
480     // C++ [class.qual]p2: A lookup that would find the injected-class-name
481     // instead names the constructors of the class, except when naming a class.
482     // This is ill-formed when we're not actually forming a ctor or dtor name.
483     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
484     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
485     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
486         FoundRD->isInjectedClassName() &&
487         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
488       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
489           << &II << /*Type*/1;
490 
491     DiagnoseUseOfDecl(IIDecl, NameLoc);
492 
493     T = Context.getTypeDeclType(TD);
494     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
495   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
496     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
497     if (!HasTrailingDot)
498       T = Context.getObjCInterfaceType(IDecl);
499     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
500   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
501     (void)DiagnoseUseOfDecl(UD, NameLoc);
502     // Recover with 'int'
503     T = Context.IntTy;
504     FoundUsingShadow = nullptr;
505   } else if (AllowDeducedTemplate) {
506     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
507       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
508       TemplateName Template =
509           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
510       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
511                                                        false);
512       // Don't wrap in a further UsingType.
513       FoundUsingShadow = nullptr;
514     }
515   }
516 
517   if (T.isNull()) {
518     // If it's not plausibly a type, suppress diagnostics.
519     Result.suppressDiagnostics();
520     return nullptr;
521   }
522 
523   if (FoundUsingShadow)
524     T = Context.getUsingType(FoundUsingShadow, T);
525 
526   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
527   // constructor or destructor name (in such a case, the scope specifier
528   // will be attached to the enclosing Expr or Decl node).
529   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
530       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
531     if (WantNontrivialTypeSourceInfo) {
532       // Construct a type with type-source information.
533       TypeLocBuilder Builder;
534       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
535 
536       T = getElaboratedType(ETK_None, *SS, T);
537       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
538       ElabTL.setElaboratedKeywordLoc(SourceLocation());
539       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
540       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
541     } else {
542       T = getElaboratedType(ETK_None, *SS, T);
543     }
544   }
545 
546   return ParsedType::make(T);
547 }
548 
549 // Builds a fake NNS for the given decl context.
550 static NestedNameSpecifier *
551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
552   for (;; DC = DC->getLookupParent()) {
553     DC = DC->getPrimaryContext();
554     auto *ND = dyn_cast<NamespaceDecl>(DC);
555     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
556       return NestedNameSpecifier::Create(Context, nullptr, ND);
557     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
558       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
559                                          RD->getTypeForDecl());
560     else if (isa<TranslationUnitDecl>(DC))
561       return NestedNameSpecifier::GlobalSpecifier(Context);
562   }
563   llvm_unreachable("something isn't in TU scope?");
564 }
565 
566 /// Find the parent class with dependent bases of the innermost enclosing method
567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
568 /// up allowing unqualified dependent type names at class-level, which MSVC
569 /// correctly rejects.
570 static const CXXRecordDecl *
571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
572   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
573     DC = DC->getPrimaryContext();
574     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
575       if (MD->getParent()->hasAnyDependentBases())
576         return MD->getParent();
577   }
578   return nullptr;
579 }
580 
581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
582                                           SourceLocation NameLoc,
583                                           bool IsTemplateTypeArg) {
584   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
585 
586   NestedNameSpecifier *NNS = nullptr;
587   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
588     // If we weren't able to parse a default template argument, delay lookup
589     // until instantiation time by making a non-dependent DependentTypeName. We
590     // pretend we saw a NestedNameSpecifier referring to the current scope, and
591     // lookup is retried.
592     // FIXME: This hurts our diagnostic quality, since we get errors like "no
593     // type named 'Foo' in 'current_namespace'" when the user didn't write any
594     // name specifiers.
595     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
596     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
597   } else if (const CXXRecordDecl *RD =
598                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
599     // Build a DependentNameType that will perform lookup into RD at
600     // instantiation time.
601     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
602                                       RD->getTypeForDecl());
603 
604     // Diagnose that this identifier was undeclared, and retry the lookup during
605     // template instantiation.
606     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
607                                                                       << RD;
608   } else {
609     // This is not a situation that we should recover from.
610     return ParsedType();
611   }
612 
613   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
614 
615   // Build type location information.  We synthesized the qualifier, so we have
616   // to build a fake NestedNameSpecifierLoc.
617   NestedNameSpecifierLocBuilder NNSLocBuilder;
618   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
619   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
620 
621   TypeLocBuilder Builder;
622   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
623   DepTL.setNameLoc(NameLoc);
624   DepTL.setElaboratedKeywordLoc(SourceLocation());
625   DepTL.setQualifierLoc(QualifierLoc);
626   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
627 }
628 
629 /// isTagName() - This method is called *for error recovery purposes only*
630 /// to determine if the specified name is a valid tag name ("struct foo").  If
631 /// so, this returns the TST for the tag corresponding to it (TST_enum,
632 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
633 /// cases in C where the user forgot to specify the tag.
634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
635   // Do a tag name lookup in this scope.
636   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
637   LookupName(R, S, false);
638   R.suppressDiagnostics();
639   if (R.getResultKind() == LookupResult::Found)
640     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
641       switch (TD->getTagKind()) {
642       case TTK_Struct: return DeclSpec::TST_struct;
643       case TTK_Interface: return DeclSpec::TST_interface;
644       case TTK_Union:  return DeclSpec::TST_union;
645       case TTK_Class:  return DeclSpec::TST_class;
646       case TTK_Enum:   return DeclSpec::TST_enum;
647       }
648     }
649 
650   return DeclSpec::TST_unspecified;
651 }
652 
653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
655 /// then downgrade the missing typename error to a warning.
656 /// This is needed for MSVC compatibility; Example:
657 /// @code
658 /// template<class T> class A {
659 /// public:
660 ///   typedef int TYPE;
661 /// };
662 /// template<class T> class B : public A<T> {
663 /// public:
664 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
665 /// };
666 /// @endcode
667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
668   if (CurContext->isRecord()) {
669     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
670       return true;
671 
672     const Type *Ty = SS->getScopeRep()->getAsType();
673 
674     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675     for (const auto &Base : RD->bases())
676       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677         return true;
678     return S->isFunctionPrototypeScope();
679   }
680   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681 }
682 
683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
684                                    SourceLocation IILoc,
685                                    Scope *S,
686                                    CXXScopeSpec *SS,
687                                    ParsedType &SuggestedType,
688                                    bool IsTemplateName) {
689   // Don't report typename errors for editor placeholders.
690   if (II->isEditorPlaceholder())
691     return;
692   // We don't have anything to suggest (yet).
693   SuggestedType = nullptr;
694 
695   // There may have been a typo in the name of the type. Look up typo
696   // results, in case we have something that we can suggest.
697   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698                            /*AllowTemplates=*/IsTemplateName,
699                            /*AllowNonTemplates=*/!IsTemplateName);
700   if (TypoCorrection Corrected =
701           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
702                       CCC, CTK_ErrorRecovery)) {
703     // FIXME: Support error recovery for the template-name case.
704     bool CanRecover = !IsTemplateName;
705     if (Corrected.isKeyword()) {
706       // We corrected to a keyword.
707       diagnoseTypo(Corrected,
708                    PDiag(IsTemplateName ? diag::err_no_template_suggest
709                                         : diag::err_unknown_typename_suggest)
710                        << II);
711       II = Corrected.getCorrectionAsIdentifierInfo();
712     } else {
713       // We found a similarly-named type or interface; suggest that.
714       if (!SS || !SS->isSet()) {
715         diagnoseTypo(Corrected,
716                      PDiag(IsTemplateName ? diag::err_no_template_suggest
717                                           : diag::err_unknown_typename_suggest)
718                          << II, CanRecover);
719       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
722                                 II->getName().equals(CorrectedStr);
723         diagnoseTypo(Corrected,
724                      PDiag(IsTemplateName
725                                ? diag::err_no_member_template_suggest
726                                : diag::err_unknown_nested_typename_suggest)
727                          << II << DC << DroppedSpecifier << SS->getRange(),
728                      CanRecover);
729       } else {
730         llvm_unreachable("could not have corrected a typo here");
731       }
732 
733       if (!CanRecover)
734         return;
735 
736       CXXScopeSpec tmpSS;
737       if (Corrected.getCorrectionSpecifier())
738         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739                           SourceRange(IILoc));
740       // FIXME: Support class template argument deduction here.
741       SuggestedType =
742           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744                       /*IsCtorOrDtorName=*/false,
745                       /*WantNontrivialTypeSourceInfo=*/true);
746     }
747     return;
748   }
749 
750   if (getLangOpts().CPlusPlus && !IsTemplateName) {
751     // See if II is a class template that the user forgot to pass arguments to.
752     UnqualifiedId Name;
753     Name.setIdentifier(II, IILoc);
754     CXXScopeSpec EmptySS;
755     TemplateTy TemplateResult;
756     bool MemberOfUnknownSpecialization;
757     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758                        Name, nullptr, true, TemplateResult,
759                        MemberOfUnknownSpecialization) == TNK_Type_template) {
760       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761       return;
762     }
763   }
764 
765   // FIXME: Should we move the logic that tries to recover from a missing tag
766   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767 
768   if (!SS || (!SS->isSet() && !SS->isInvalid()))
769     Diag(IILoc, IsTemplateName ? diag::err_no_template
770                                : diag::err_unknown_typename)
771         << II;
772   else if (DeclContext *DC = computeDeclContext(*SS, false))
773     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774                                : diag::err_typename_nested_not_found)
775         << II << DC << SS->getRange();
776   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777     SuggestedType =
778         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779   } else if (isDependentScopeSpecifier(*SS)) {
780     unsigned DiagID = diag::err_typename_missing;
781     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782       DiagID = diag::ext_typename_missing;
783 
784     Diag(SS->getRange().getBegin(), DiagID)
785       << SS->getScopeRep() << II->getName()
786       << SourceRange(SS->getRange().getBegin(), IILoc)
787       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788     SuggestedType = ActOnTypenameType(S, SourceLocation(),
789                                       *SS, *II, IILoc).get();
790   } else {
791     assert(SS && SS->isInvalid() &&
792            "Invalid scope specifier has already been diagnosed");
793   }
794 }
795 
796 /// Determine whether the given result set contains either a type name
797 /// or
798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800                        NextToken.is(tok::less);
801 
802   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804       return true;
805 
806     if (CheckTemplate && isa<TemplateDecl>(*I))
807       return true;
808   }
809 
810   return false;
811 }
812 
813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
814                                     Scope *S, CXXScopeSpec &SS,
815                                     IdentifierInfo *&Name,
816                                     SourceLocation NameLoc) {
817   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818   SemaRef.LookupParsedName(R, S, &SS);
819   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820     StringRef FixItTagName;
821     switch (Tag->getTagKind()) {
822       case TTK_Class:
823         FixItTagName = "class ";
824         break;
825 
826       case TTK_Enum:
827         FixItTagName = "enum ";
828         break;
829 
830       case TTK_Struct:
831         FixItTagName = "struct ";
832         break;
833 
834       case TTK_Interface:
835         FixItTagName = "__interface ";
836         break;
837 
838       case TTK_Union:
839         FixItTagName = "union ";
840         break;
841     }
842 
843     StringRef TagName = FixItTagName.drop_back();
844     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847 
848     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849          I != IEnd; ++I)
850       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851         << Name << TagName;
852 
853     // Replace lookup results with just the tag decl.
854     Result.clear(Sema::LookupTagName);
855     SemaRef.LookupParsedName(Result, S, &SS);
856     return true;
857   }
858 
859   return false;
860 }
861 
862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
863                                             IdentifierInfo *&Name,
864                                             SourceLocation NameLoc,
865                                             const Token &NextToken,
866                                             CorrectionCandidateCallback *CCC) {
867   DeclarationNameInfo NameInfo(Name, NameLoc);
868   ObjCMethodDecl *CurMethod = getCurMethodDecl();
869 
870   assert(NextToken.isNot(tok::coloncolon) &&
871          "parse nested name specifiers before calling ClassifyName");
872   if (getLangOpts().CPlusPlus && SS.isSet() &&
873       isCurrentClassName(*Name, S, &SS)) {
874     // Per [class.qual]p2, this names the constructors of SS, not the
875     // injected-class-name. We don't have a classification for that.
876     // There's not much point caching this result, since the parser
877     // will reject it later.
878     return NameClassification::Unknown();
879   }
880 
881   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882   LookupParsedName(Result, S, &SS, !CurMethod);
883 
884   if (SS.isInvalid())
885     return NameClassification::Error();
886 
887   // For unqualified lookup in a class template in MSVC mode, look into
888   // dependent base classes where the primary class template is known.
889   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
890     if (ParsedType TypeInBase =
891             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
892       return TypeInBase;
893   }
894 
895   // Perform lookup for Objective-C instance variables (including automatically
896   // synthesized instance variables), if we're in an Objective-C method.
897   // FIXME: This lookup really, really needs to be folded in to the normal
898   // unqualified lookup mechanism.
899   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
900     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
901     if (Ivar.isInvalid())
902       return NameClassification::Error();
903     if (Ivar.isUsable())
904       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
905 
906     // We defer builtin creation until after ivar lookup inside ObjC methods.
907     if (Result.empty())
908       LookupBuiltin(Result);
909   }
910 
911   bool SecondTry = false;
912   bool IsFilteredTemplateName = false;
913 
914 Corrected:
915   switch (Result.getResultKind()) {
916   case LookupResult::NotFound:
917     // If an unqualified-id is followed by a '(', then we have a function
918     // call.
919     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
920       // In C++, this is an ADL-only call.
921       // FIXME: Reference?
922       if (getLangOpts().CPlusPlus)
923         return NameClassification::UndeclaredNonType();
924 
925       // C90 6.3.2.2:
926       //   If the expression that precedes the parenthesized argument list in a
927       //   function call consists solely of an identifier, and if no
928       //   declaration is visible for this identifier, the identifier is
929       //   implicitly declared exactly as if, in the innermost block containing
930       //   the function call, the declaration
931       //
932       //     extern int identifier ();
933       //
934       //   appeared.
935       //
936       // We also allow this in C99 as an extension. However, this is not
937       // allowed in all language modes as functions without prototypes may not
938       // be supported.
939       if (getLangOpts().implicitFunctionsAllowed()) {
940         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
941           return NameClassification::NonType(D);
942       }
943     }
944 
945     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
946       // In C++20 onwards, this could be an ADL-only call to a function
947       // template, and we're required to assume that this is a template name.
948       //
949       // FIXME: Find a way to still do typo correction in this case.
950       TemplateName Template =
951           Context.getAssumedTemplateName(NameInfo.getName());
952       return NameClassification::UndeclaredTemplate(Template);
953     }
954 
955     // In C, we first see whether there is a tag type by the same name, in
956     // which case it's likely that the user just forgot to write "enum",
957     // "struct", or "union".
958     if (!getLangOpts().CPlusPlus && !SecondTry &&
959         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
960       break;
961     }
962 
963     // Perform typo correction to determine if there is another name that is
964     // close to this name.
965     if (!SecondTry && CCC) {
966       SecondTry = true;
967       if (TypoCorrection Corrected =
968               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
969                           &SS, *CCC, CTK_ErrorRecovery)) {
970         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
971         unsigned QualifiedDiag = diag::err_no_member_suggest;
972 
973         NamedDecl *FirstDecl = Corrected.getFoundDecl();
974         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
975         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
976             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
977           UnqualifiedDiag = diag::err_no_template_suggest;
978           QualifiedDiag = diag::err_no_member_template_suggest;
979         } else if (UnderlyingFirstDecl &&
980                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
981                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
982                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
983           UnqualifiedDiag = diag::err_unknown_typename_suggest;
984           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
985         }
986 
987         if (SS.isEmpty()) {
988           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
989         } else {// FIXME: is this even reachable? Test it.
990           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
991           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
992                                   Name->getName().equals(CorrectedStr);
993           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
994                                     << Name << computeDeclContext(SS, false)
995                                     << DroppedSpecifier << SS.getRange());
996         }
997 
998         // Update the name, so that the caller has the new name.
999         Name = Corrected.getCorrectionAsIdentifierInfo();
1000 
1001         // Typo correction corrected to a keyword.
1002         if (Corrected.isKeyword())
1003           return Name;
1004 
1005         // Also update the LookupResult...
1006         // FIXME: This should probably go away at some point
1007         Result.clear();
1008         Result.setLookupName(Corrected.getCorrection());
1009         if (FirstDecl)
1010           Result.addDecl(FirstDecl);
1011 
1012         // If we found an Objective-C instance variable, let
1013         // LookupInObjCMethod build the appropriate expression to
1014         // reference the ivar.
1015         // FIXME: This is a gross hack.
1016         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1017           DeclResult R =
1018               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1019           if (R.isInvalid())
1020             return NameClassification::Error();
1021           if (R.isUsable())
1022             return NameClassification::NonType(Ivar);
1023         }
1024 
1025         goto Corrected;
1026       }
1027     }
1028 
1029     // We failed to correct; just fall through and let the parser deal with it.
1030     Result.suppressDiagnostics();
1031     return NameClassification::Unknown();
1032 
1033   case LookupResult::NotFoundInCurrentInstantiation: {
1034     // We performed name lookup into the current instantiation, and there were
1035     // dependent bases, so we treat this result the same way as any other
1036     // dependent nested-name-specifier.
1037 
1038     // C++ [temp.res]p2:
1039     //   A name used in a template declaration or definition and that is
1040     //   dependent on a template-parameter is assumed not to name a type
1041     //   unless the applicable name lookup finds a type name or the name is
1042     //   qualified by the keyword typename.
1043     //
1044     // FIXME: If the next token is '<', we might want to ask the parser to
1045     // perform some heroics to see if we actually have a
1046     // template-argument-list, which would indicate a missing 'template'
1047     // keyword here.
1048     return NameClassification::DependentNonType();
1049   }
1050 
1051   case LookupResult::Found:
1052   case LookupResult::FoundOverloaded:
1053   case LookupResult::FoundUnresolvedValue:
1054     break;
1055 
1056   case LookupResult::Ambiguous:
1057     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1059                                       /*AllowDependent=*/false)) {
1060       // C++ [temp.local]p3:
1061       //   A lookup that finds an injected-class-name (10.2) can result in an
1062       //   ambiguity in certain cases (for example, if it is found in more than
1063       //   one base class). If all of the injected-class-names that are found
1064       //   refer to specializations of the same class template, and if the name
1065       //   is followed by a template-argument-list, the reference refers to the
1066       //   class template itself and not a specialization thereof, and is not
1067       //   ambiguous.
1068       //
1069       // This filtering can make an ambiguous result into an unambiguous one,
1070       // so try again after filtering out template names.
1071       FilterAcceptableTemplateNames(Result);
1072       if (!Result.isAmbiguous()) {
1073         IsFilteredTemplateName = true;
1074         break;
1075       }
1076     }
1077 
1078     // Diagnose the ambiguity and return an error.
1079     return NameClassification::Error();
1080   }
1081 
1082   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1083       (IsFilteredTemplateName ||
1084        hasAnyAcceptableTemplateNames(
1085            Result, /*AllowFunctionTemplates=*/true,
1086            /*AllowDependent=*/false,
1087            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1088                getLangOpts().CPlusPlus20))) {
1089     // C++ [temp.names]p3:
1090     //   After name lookup (3.4) finds that a name is a template-name or that
1091     //   an operator-function-id or a literal- operator-id refers to a set of
1092     //   overloaded functions any member of which is a function template if
1093     //   this is followed by a <, the < is always taken as the delimiter of a
1094     //   template-argument-list and never as the less-than operator.
1095     // C++2a [temp.names]p2:
1096     //   A name is also considered to refer to a template if it is an
1097     //   unqualified-id followed by a < and name lookup finds either one
1098     //   or more functions or finds nothing.
1099     if (!IsFilteredTemplateName)
1100       FilterAcceptableTemplateNames(Result);
1101 
1102     bool IsFunctionTemplate;
1103     bool IsVarTemplate;
1104     TemplateName Template;
1105     if (Result.end() - Result.begin() > 1) {
1106       IsFunctionTemplate = true;
1107       Template = Context.getOverloadedTemplateName(Result.begin(),
1108                                                    Result.end());
1109     } else if (!Result.empty()) {
1110       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1111           *Result.begin(), /*AllowFunctionTemplates=*/true,
1112           /*AllowDependent=*/false));
1113       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1114       IsVarTemplate = isa<VarTemplateDecl>(TD);
1115 
1116       UsingShadowDecl *FoundUsingShadow =
1117           dyn_cast<UsingShadowDecl>(*Result.begin());
1118       assert(!FoundUsingShadow ||
1119              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1120       Template =
1121           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1122       if (SS.isNotEmpty())
1123         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1124                                                     /*TemplateKeyword=*/false,
1125                                                     Template);
1126     } else {
1127       // All results were non-template functions. This is a function template
1128       // name.
1129       IsFunctionTemplate = true;
1130       Template = Context.getAssumedTemplateName(NameInfo.getName());
1131     }
1132 
1133     if (IsFunctionTemplate) {
1134       // Function templates always go through overload resolution, at which
1135       // point we'll perform the various checks (e.g., accessibility) we need
1136       // to based on which function we selected.
1137       Result.suppressDiagnostics();
1138 
1139       return NameClassification::FunctionTemplate(Template);
1140     }
1141 
1142     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143                          : NameClassification::TypeTemplate(Template);
1144   }
1145 
1146   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147     QualType T = Context.getTypeDeclType(Type);
1148     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1149       T = Context.getUsingType(USD, T);
1150 
1151     if (SS.isEmpty()) // No elaborated type, trivial location info
1152       return ParsedType::make(T);
1153 
1154     TypeLocBuilder Builder;
1155     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1156     T = getElaboratedType(ETK_None, SS, T);
1157     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1158     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1159     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1160     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1161   };
1162 
1163   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1164   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1165     DiagnoseUseOfDecl(Type, NameLoc);
1166     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1167     return BuildTypeFor(Type, *Result.begin());
1168   }
1169 
1170   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1171   if (!Class) {
1172     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1173     if (ObjCCompatibleAliasDecl *Alias =
1174             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1175       Class = Alias->getClassInterface();
1176   }
1177 
1178   if (Class) {
1179     DiagnoseUseOfDecl(Class, NameLoc);
1180 
1181     if (NextToken.is(tok::period)) {
1182       // Interface. <something> is parsed as a property reference expression.
1183       // Just return "unknown" as a fall-through for now.
1184       Result.suppressDiagnostics();
1185       return NameClassification::Unknown();
1186     }
1187 
1188     QualType T = Context.getObjCInterfaceType(Class);
1189     return ParsedType::make(T);
1190   }
1191 
1192   if (isa<ConceptDecl>(FirstDecl))
1193     return NameClassification::Concept(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1197     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1198     return NameClassification::Error();
1199   }
1200 
1201   // We can have a type template here if we're classifying a template argument.
1202   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1203       !isa<VarTemplateDecl>(FirstDecl))
1204     return NameClassification::TypeTemplate(
1205         TemplateName(cast<TemplateDecl>(FirstDecl)));
1206 
1207   // Check for a tag type hidden by a non-type decl in a few cases where it
1208   // seems likely a type is wanted instead of the non-type that was found.
1209   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1210   if ((NextToken.is(tok::identifier) ||
1211        (NextIsOp &&
1212         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1213       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1214     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1215     DiagnoseUseOfDecl(Type, NameLoc);
1216     return BuildTypeFor(Type, *Result.begin());
1217   }
1218 
1219   // If we already know which single declaration is referenced, just annotate
1220   // that declaration directly. Defer resolving even non-overloaded class
1221   // member accesses, as we need to defer certain access checks until we know
1222   // the context.
1223   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1224   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1225     return NameClassification::NonType(Result.getRepresentativeDecl());
1226 
1227   // Otherwise, this is an overload set that we will need to resolve later.
1228   Result.suppressDiagnostics();
1229   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1230       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1231       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1232       Result.begin(), Result.end()));
1233 }
1234 
1235 ExprResult
1236 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1237                                              SourceLocation NameLoc) {
1238   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1239   CXXScopeSpec SS;
1240   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1241   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1242 }
1243 
1244 ExprResult
1245 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1246                                             IdentifierInfo *Name,
1247                                             SourceLocation NameLoc,
1248                                             bool IsAddressOfOperand) {
1249   DeclarationNameInfo NameInfo(Name, NameLoc);
1250   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1251                                     NameInfo, IsAddressOfOperand,
1252                                     /*TemplateArgs=*/nullptr);
1253 }
1254 
1255 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1256                                               NamedDecl *Found,
1257                                               SourceLocation NameLoc,
1258                                               const Token &NextToken) {
1259   if (getCurMethodDecl() && SS.isEmpty())
1260     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1261       return BuildIvarRefExpr(S, NameLoc, Ivar);
1262 
1263   // Reconstruct the lookup result.
1264   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1265   Result.addDecl(Found);
1266   Result.resolveKind();
1267 
1268   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1269   return BuildDeclarationNameExpr(SS, Result, ADL);
1270 }
1271 
1272 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1273   // For an implicit class member access, transform the result into a member
1274   // access expression if necessary.
1275   auto *ULE = cast<UnresolvedLookupExpr>(E);
1276   if ((*ULE->decls_begin())->isCXXClassMember()) {
1277     CXXScopeSpec SS;
1278     SS.Adopt(ULE->getQualifierLoc());
1279 
1280     // Reconstruct the lookup result.
1281     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1282                         LookupOrdinaryName);
1283     Result.setNamingClass(ULE->getNamingClass());
1284     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1285       Result.addDecl(*I, I.getAccess());
1286     Result.resolveKind();
1287     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1288                                            nullptr, S);
1289   }
1290 
1291   // Otherwise, this is already in the form we needed, and no further checks
1292   // are necessary.
1293   return ULE;
1294 }
1295 
1296 Sema::TemplateNameKindForDiagnostics
1297 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1298   auto *TD = Name.getAsTemplateDecl();
1299   if (!TD)
1300     return TemplateNameKindForDiagnostics::DependentTemplate;
1301   if (isa<ClassTemplateDecl>(TD))
1302     return TemplateNameKindForDiagnostics::ClassTemplate;
1303   if (isa<FunctionTemplateDecl>(TD))
1304     return TemplateNameKindForDiagnostics::FunctionTemplate;
1305   if (isa<VarTemplateDecl>(TD))
1306     return TemplateNameKindForDiagnostics::VarTemplate;
1307   if (isa<TypeAliasTemplateDecl>(TD))
1308     return TemplateNameKindForDiagnostics::AliasTemplate;
1309   if (isa<TemplateTemplateParmDecl>(TD))
1310     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1311   if (isa<ConceptDecl>(TD))
1312     return TemplateNameKindForDiagnostics::Concept;
1313   return TemplateNameKindForDiagnostics::DependentTemplate;
1314 }
1315 
1316 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1317   assert(DC->getLexicalParent() == CurContext &&
1318       "The next DeclContext should be lexically contained in the current one.");
1319   CurContext = DC;
1320   S->setEntity(DC);
1321 }
1322 
1323 void Sema::PopDeclContext() {
1324   assert(CurContext && "DeclContext imbalance!");
1325 
1326   CurContext = CurContext->getLexicalParent();
1327   assert(CurContext && "Popped translation unit!");
1328 }
1329 
1330 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1331                                                                     Decl *D) {
1332   // Unlike PushDeclContext, the context to which we return is not necessarily
1333   // the containing DC of TD, because the new context will be some pre-existing
1334   // TagDecl definition instead of a fresh one.
1335   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1336   CurContext = cast<TagDecl>(D)->getDefinition();
1337   assert(CurContext && "skipping definition of undefined tag");
1338   // Start lookups from the parent of the current context; we don't want to look
1339   // into the pre-existing complete definition.
1340   S->setEntity(CurContext->getLookupParent());
1341   return Result;
1342 }
1343 
1344 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1345   CurContext = static_cast<decltype(CurContext)>(Context);
1346 }
1347 
1348 /// EnterDeclaratorContext - Used when we must lookup names in the context
1349 /// of a declarator's nested name specifier.
1350 ///
1351 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1352   // C++0x [basic.lookup.unqual]p13:
1353   //   A name used in the definition of a static data member of class
1354   //   X (after the qualified-id of the static member) is looked up as
1355   //   if the name was used in a member function of X.
1356   // C++0x [basic.lookup.unqual]p14:
1357   //   If a variable member of a namespace is defined outside of the
1358   //   scope of its namespace then any name used in the definition of
1359   //   the variable member (after the declarator-id) is looked up as
1360   //   if the definition of the variable member occurred in its
1361   //   namespace.
1362   // Both of these imply that we should push a scope whose context
1363   // is the semantic context of the declaration.  We can't use
1364   // PushDeclContext here because that context is not necessarily
1365   // lexically contained in the current context.  Fortunately,
1366   // the containing scope should have the appropriate information.
1367 
1368   assert(!S->getEntity() && "scope already has entity");
1369 
1370 #ifndef NDEBUG
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1374 #endif
1375 
1376   CurContext = DC;
1377   S->setEntity(DC);
1378 
1379   if (S->getParent()->isTemplateParamScope()) {
1380     // Also set the corresponding entities for all immediately-enclosing
1381     // template parameter scopes.
1382     EnterTemplatedContext(S->getParent(), DC);
1383   }
1384 }
1385 
1386 void Sema::ExitDeclaratorContext(Scope *S) {
1387   assert(S->getEntity() == CurContext && "Context imbalance!");
1388 
1389   // Switch back to the lexical context.  The safety of this is
1390   // enforced by an assert in EnterDeclaratorContext.
1391   Scope *Ancestor = S->getParent();
1392   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1393   CurContext = Ancestor->getEntity();
1394 
1395   // We don't need to do anything with the scope, which is going to
1396   // disappear.
1397 }
1398 
1399 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1400   assert(S->isTemplateParamScope() &&
1401          "expected to be initializing a template parameter scope");
1402 
1403   // C++20 [temp.local]p7:
1404   //   In the definition of a member of a class template that appears outside
1405   //   of the class template definition, the name of a member of the class
1406   //   template hides the name of a template-parameter of any enclosing class
1407   //   templates (but not a template-parameter of the member if the member is a
1408   //   class or function template).
1409   // C++20 [temp.local]p9:
1410   //   In the definition of a class template or in the definition of a member
1411   //   of such a template that appears outside of the template definition, for
1412   //   each non-dependent base class (13.8.2.1), if the name of the base class
1413   //   or the name of a member of the base class is the same as the name of a
1414   //   template-parameter, the base class name or member name hides the
1415   //   template-parameter name (6.4.10).
1416   //
1417   // This means that a template parameter scope should be searched immediately
1418   // after searching the DeclContext for which it is a template parameter
1419   // scope. For example, for
1420   //   template<typename T> template<typename U> template<typename V>
1421   //     void N::A<T>::B<U>::f(...)
1422   // we search V then B<U> (and base classes) then U then A<T> (and base
1423   // classes) then T then N then ::.
1424   unsigned ScopeDepth = getTemplateDepth(S);
1425   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1426     DeclContext *SearchDCAfterScope = DC;
1427     for (; DC; DC = DC->getLookupParent()) {
1428       if (const TemplateParameterList *TPL =
1429               cast<Decl>(DC)->getDescribedTemplateParams()) {
1430         unsigned DCDepth = TPL->getDepth() + 1;
1431         if (DCDepth > ScopeDepth)
1432           continue;
1433         if (ScopeDepth == DCDepth)
1434           SearchDCAfterScope = DC = DC->getLookupParent();
1435         break;
1436       }
1437     }
1438     S->setLookupEntity(SearchDCAfterScope);
1439   }
1440 }
1441 
1442 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1443   // We assume that the caller has already called
1444   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1445   FunctionDecl *FD = D->getAsFunction();
1446   if (!FD)
1447     return;
1448 
1449   // Same implementation as PushDeclContext, but enters the context
1450   // from the lexical parent, rather than the top-level class.
1451   assert(CurContext == FD->getLexicalParent() &&
1452     "The next DeclContext should be lexically contained in the current one.");
1453   CurContext = FD;
1454   S->setEntity(CurContext);
1455 
1456   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1457     ParmVarDecl *Param = FD->getParamDecl(P);
1458     // If the parameter has an identifier, then add it to the scope
1459     if (Param->getIdentifier()) {
1460       S->AddDecl(Param);
1461       IdResolver.AddDecl(Param);
1462     }
1463   }
1464 }
1465 
1466 void Sema::ActOnExitFunctionContext() {
1467   // Same implementation as PopDeclContext, but returns to the lexical parent,
1468   // rather than the top-level class.
1469   assert(CurContext && "DeclContext imbalance!");
1470   CurContext = CurContext->getLexicalParent();
1471   assert(CurContext && "Popped translation unit!");
1472 }
1473 
1474 /// Determine whether overloading is allowed for a new function
1475 /// declaration considering prior declarations of the same name.
1476 ///
1477 /// This routine determines whether overloading is possible, not
1478 /// whether a new declaration actually overloads a previous one.
1479 /// It will return true in C++ (where overloads are alway permitted)
1480 /// or, as a C extension, when either the new declaration or a
1481 /// previous one is declared with the 'overloadable' attribute.
1482 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1483                                        ASTContext &Context,
1484                                        const FunctionDecl *New) {
1485   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1486     return true;
1487 
1488   // Multiversion function declarations are not overloads in the
1489   // usual sense of that term, but lookup will report that an
1490   // overload set was found if more than one multiversion function
1491   // declaration is present for the same name. It is therefore
1492   // inadequate to assume that some prior declaration(s) had
1493   // the overloadable attribute; checking is required. Since one
1494   // declaration is permitted to omit the attribute, it is necessary
1495   // to check at least two; hence the 'any_of' check below. Note that
1496   // the overloadable attribute is implicitly added to declarations
1497   // that were required to have it but did not.
1498   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1499     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1500       return ND->hasAttr<OverloadableAttr>();
1501     });
1502   } else if (Previous.getResultKind() == LookupResult::Found)
1503     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1504 
1505   return false;
1506 }
1507 
1508 /// Add this decl to the scope shadowed decl chains.
1509 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1510   // Move up the scope chain until we find the nearest enclosing
1511   // non-transparent context. The declaration will be introduced into this
1512   // scope.
1513   while (S->getEntity() && S->getEntity()->isTransparentContext())
1514     S = S->getParent();
1515 
1516   // Add scoped declarations into their context, so that they can be
1517   // found later. Declarations without a context won't be inserted
1518   // into any context.
1519   if (AddToContext)
1520     CurContext->addDecl(D);
1521 
1522   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1523   // are function-local declarations.
1524   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1525     return;
1526 
1527   // Template instantiations should also not be pushed into scope.
1528   if (isa<FunctionDecl>(D) &&
1529       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1530     return;
1531 
1532   // If this replaces anything in the current scope,
1533   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1534                                IEnd = IdResolver.end();
1535   for (; I != IEnd; ++I) {
1536     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1537       S->RemoveDecl(*I);
1538       IdResolver.RemoveDecl(*I);
1539 
1540       // Should only need to replace one decl.
1541       break;
1542     }
1543   }
1544 
1545   S->AddDecl(D);
1546 
1547   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1548     // Implicitly-generated labels may end up getting generated in an order that
1549     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1550     // the label at the appropriate place in the identifier chain.
1551     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1552       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1553       if (IDC == CurContext) {
1554         if (!S->isDeclScope(*I))
1555           continue;
1556       } else if (IDC->Encloses(CurContext))
1557         break;
1558     }
1559 
1560     IdResolver.InsertDeclAfter(I, D);
1561   } else {
1562     IdResolver.AddDecl(D);
1563   }
1564   warnOnReservedIdentifier(D);
1565 }
1566 
1567 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1568                          bool AllowInlineNamespace) {
1569   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1570 }
1571 
1572 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1573   DeclContext *TargetDC = DC->getPrimaryContext();
1574   do {
1575     if (DeclContext *ScopeDC = S->getEntity())
1576       if (ScopeDC->getPrimaryContext() == TargetDC)
1577         return S;
1578   } while ((S = S->getParent()));
1579 
1580   return nullptr;
1581 }
1582 
1583 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1584                                             DeclContext*,
1585                                             ASTContext&);
1586 
1587 /// Filters out lookup results that don't fall within the given scope
1588 /// as determined by isDeclInScope.
1589 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1590                                 bool ConsiderLinkage,
1591                                 bool AllowInlineNamespace) {
1592   LookupResult::Filter F = R.makeFilter();
1593   while (F.hasNext()) {
1594     NamedDecl *D = F.next();
1595 
1596     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1597       continue;
1598 
1599     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1600       continue;
1601 
1602     F.erase();
1603   }
1604 
1605   F.done();
1606 }
1607 
1608 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1609 /// have compatible owning modules.
1610 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1611   // [module.interface]p7:
1612   // A declaration is attached to a module as follows:
1613   // - If the declaration is a non-dependent friend declaration that nominates a
1614   // function with a declarator-id that is a qualified-id or template-id or that
1615   // nominates a class other than with an elaborated-type-specifier with neither
1616   // a nested-name-specifier nor a simple-template-id, it is attached to the
1617   // module to which the friend is attached ([basic.link]).
1618   if (New->getFriendObjectKind() &&
1619       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1620     New->setLocalOwningModule(Old->getOwningModule());
1621     makeMergedDefinitionVisible(New);
1622     return false;
1623   }
1624 
1625   Module *NewM = New->getOwningModule();
1626   Module *OldM = Old->getOwningModule();
1627 
1628   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1631     OldM = OldM->Parent;
1632 
1633   // If we have a decl in a module partition, it is part of the containing
1634   // module (which is the only thing that can be importing it).
1635   if (NewM && OldM &&
1636       (OldM->Kind == Module::ModulePartitionInterface ||
1637        OldM->Kind == Module::ModulePartitionImplementation)) {
1638     return false;
1639   }
1640 
1641   if (NewM == OldM)
1642     return false;
1643 
1644   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1645   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1646   if (NewIsModuleInterface || OldIsModuleInterface) {
1647     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1648     //   if a declaration of D [...] appears in the purview of a module, all
1649     //   other such declarations shall appear in the purview of the same module
1650     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1651       << New
1652       << NewIsModuleInterface
1653       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1654       << OldIsModuleInterface
1655       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1656     Diag(Old->getLocation(), diag::note_previous_declaration);
1657     New->setInvalidDecl();
1658     return true;
1659   }
1660 
1661   return false;
1662 }
1663 
1664 // [module.interface]p6:
1665 // A redeclaration of an entity X is implicitly exported if X was introduced by
1666 // an exported declaration; otherwise it shall not be exported.
1667 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1668   // [module.interface]p1:
1669   // An export-declaration shall inhabit a namespace scope.
1670   //
1671   // So it is meaningless to talk about redeclaration which is not at namespace
1672   // scope.
1673   if (!New->getLexicalDeclContext()
1674            ->getNonTransparentContext()
1675            ->isFileContext() ||
1676       !Old->getLexicalDeclContext()
1677            ->getNonTransparentContext()
1678            ->isFileContext())
1679     return false;
1680 
1681   bool IsNewExported = New->isInExportDeclContext();
1682   bool IsOldExported = Old->isInExportDeclContext();
1683 
1684   // It should be irrevelant if both of them are not exported.
1685   if (!IsNewExported && !IsOldExported)
1686     return false;
1687 
1688   if (IsOldExported)
1689     return false;
1690 
1691   assert(IsNewExported);
1692 
1693   auto Lk = Old->getFormalLinkage();
1694   int S = 0;
1695   if (Lk == Linkage::InternalLinkage)
1696     S = 1;
1697   else if (Lk == Linkage::ModuleLinkage)
1698     S = 2;
1699   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1700   Diag(Old->getLocation(), diag::note_previous_declaration);
1701   return true;
1702 }
1703 
1704 // A wrapper function for checking the semantic restrictions of
1705 // a redeclaration within a module.
1706 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1707   if (CheckRedeclarationModuleOwnership(New, Old))
1708     return true;
1709 
1710   if (CheckRedeclarationExported(New, Old))
1711     return true;
1712 
1713   return false;
1714 }
1715 
1716 static bool isUsingDecl(NamedDecl *D) {
1717   return isa<UsingShadowDecl>(D) ||
1718          isa<UnresolvedUsingTypenameDecl>(D) ||
1719          isa<UnresolvedUsingValueDecl>(D);
1720 }
1721 
1722 /// Removes using shadow declarations from the lookup results.
1723 static void RemoveUsingDecls(LookupResult &R) {
1724   LookupResult::Filter F = R.makeFilter();
1725   while (F.hasNext())
1726     if (isUsingDecl(F.next()))
1727       F.erase();
1728 
1729   F.done();
1730 }
1731 
1732 /// Check for this common pattern:
1733 /// @code
1734 /// class S {
1735 ///   S(const S&); // DO NOT IMPLEMENT
1736 ///   void operator=(const S&); // DO NOT IMPLEMENT
1737 /// };
1738 /// @endcode
1739 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1740   // FIXME: Should check for private access too but access is set after we get
1741   // the decl here.
1742   if (D->doesThisDeclarationHaveABody())
1743     return false;
1744 
1745   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1746     return CD->isCopyConstructor();
1747   return D->isCopyAssignmentOperator();
1748 }
1749 
1750 // We need this to handle
1751 //
1752 // typedef struct {
1753 //   void *foo() { return 0; }
1754 // } A;
1755 //
1756 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1757 // for example. If 'A', foo will have external linkage. If we have '*A',
1758 // foo will have no linkage. Since we can't know until we get to the end
1759 // of the typedef, this function finds out if D might have non-external linkage.
1760 // Callers should verify at the end of the TU if it D has external linkage or
1761 // not.
1762 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1763   const DeclContext *DC = D->getDeclContext();
1764   while (!DC->isTranslationUnit()) {
1765     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1766       if (!RD->hasNameForLinkage())
1767         return true;
1768     }
1769     DC = DC->getParent();
1770   }
1771 
1772   return !D->isExternallyVisible();
1773 }
1774 
1775 // FIXME: This needs to be refactored; some other isInMainFile users want
1776 // these semantics.
1777 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1778   if (S.TUKind != TU_Complete)
1779     return false;
1780   return S.SourceMgr.isInMainFile(Loc);
1781 }
1782 
1783 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1784   assert(D);
1785 
1786   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1787     return false;
1788 
1789   // Ignore all entities declared within templates, and out-of-line definitions
1790   // of members of class templates.
1791   if (D->getDeclContext()->isDependentContext() ||
1792       D->getLexicalDeclContext()->isDependentContext())
1793     return false;
1794 
1795   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1796     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1797       return false;
1798     // A non-out-of-line declaration of a member specialization was implicitly
1799     // instantiated; it's the out-of-line declaration that we're interested in.
1800     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1801         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1802       return false;
1803 
1804     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1805       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1806         return false;
1807     } else {
1808       // 'static inline' functions are defined in headers; don't warn.
1809       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1810         return false;
1811     }
1812 
1813     if (FD->doesThisDeclarationHaveABody() &&
1814         Context.DeclMustBeEmitted(FD))
1815       return false;
1816   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1817     // Constants and utility variables are defined in headers with internal
1818     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1819     // like "inline".)
1820     if (!isMainFileLoc(*this, VD->getLocation()))
1821       return false;
1822 
1823     if (Context.DeclMustBeEmitted(VD))
1824       return false;
1825 
1826     if (VD->isStaticDataMember() &&
1827         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1828       return false;
1829     if (VD->isStaticDataMember() &&
1830         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1831         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1832       return false;
1833 
1834     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1835       return false;
1836   } else {
1837     return false;
1838   }
1839 
1840   // Only warn for unused decls internal to the translation unit.
1841   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1842   // for inline functions defined in the main source file, for instance.
1843   return mightHaveNonExternalLinkage(D);
1844 }
1845 
1846 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1847   if (!D)
1848     return;
1849 
1850   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1851     const FunctionDecl *First = FD->getFirstDecl();
1852     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1853       return; // First should already be in the vector.
1854   }
1855 
1856   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1857     const VarDecl *First = VD->getFirstDecl();
1858     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1859       return; // First should already be in the vector.
1860   }
1861 
1862   if (ShouldWarnIfUnusedFileScopedDecl(D))
1863     UnusedFileScopedDecls.push_back(D);
1864 }
1865 
1866 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1867   if (D->isInvalidDecl())
1868     return false;
1869 
1870   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1871     // For a decomposition declaration, warn if none of the bindings are
1872     // referenced, instead of if the variable itself is referenced (which
1873     // it is, by the bindings' expressions).
1874     for (auto *BD : DD->bindings())
1875       if (BD->isReferenced())
1876         return false;
1877   } else if (!D->getDeclName()) {
1878     return false;
1879   } else if (D->isReferenced() || D->isUsed()) {
1880     return false;
1881   }
1882 
1883   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1884     return false;
1885 
1886   if (isa<LabelDecl>(D))
1887     return true;
1888 
1889   // Except for labels, we only care about unused decls that are local to
1890   // functions.
1891   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1892   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1893     // For dependent types, the diagnostic is deferred.
1894     WithinFunction =
1895         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1896   if (!WithinFunction)
1897     return false;
1898 
1899   if (isa<TypedefNameDecl>(D))
1900     return true;
1901 
1902   // White-list anything that isn't a local variable.
1903   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1904     return false;
1905 
1906   // Types of valid local variables should be complete, so this should succeed.
1907   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1908 
1909     const Expr *Init = VD->getInit();
1910     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1911       Init = Cleanups->getSubExpr();
1912 
1913     const auto *Ty = VD->getType().getTypePtr();
1914 
1915     // Only look at the outermost level of typedef.
1916     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1917       // Allow anything marked with __attribute__((unused)).
1918       if (TT->getDecl()->hasAttr<UnusedAttr>())
1919         return false;
1920     }
1921 
1922     // Warn for reference variables whose initializtion performs lifetime
1923     // extension.
1924     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1925       if (MTE->getExtendingDecl()) {
1926         Ty = VD->getType().getNonReferenceType().getTypePtr();
1927         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1928       }
1929     }
1930 
1931     // If we failed to complete the type for some reason, or if the type is
1932     // dependent, don't diagnose the variable.
1933     if (Ty->isIncompleteType() || Ty->isDependentType())
1934       return false;
1935 
1936     // Look at the element type to ensure that the warning behaviour is
1937     // consistent for both scalars and arrays.
1938     Ty = Ty->getBaseElementTypeUnsafe();
1939 
1940     if (const TagType *TT = Ty->getAs<TagType>()) {
1941       const TagDecl *Tag = TT->getDecl();
1942       if (Tag->hasAttr<UnusedAttr>())
1943         return false;
1944 
1945       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1946         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1947           return false;
1948 
1949         if (Init) {
1950           const CXXConstructExpr *Construct =
1951             dyn_cast<CXXConstructExpr>(Init);
1952           if (Construct && !Construct->isElidable()) {
1953             CXXConstructorDecl *CD = Construct->getConstructor();
1954             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1955                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1956               return false;
1957           }
1958 
1959           // Suppress the warning if we don't know how this is constructed, and
1960           // it could possibly be non-trivial constructor.
1961           if (Init->isTypeDependent()) {
1962             for (const CXXConstructorDecl *Ctor : RD->ctors())
1963               if (!Ctor->isTrivial())
1964                 return false;
1965           }
1966 
1967           // Suppress the warning if the constructor is unresolved because
1968           // its arguments are dependent.
1969           if (isa<CXXUnresolvedConstructExpr>(Init))
1970             return false;
1971         }
1972       }
1973     }
1974 
1975     // TODO: __attribute__((unused)) templates?
1976   }
1977 
1978   return true;
1979 }
1980 
1981 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1982                                      FixItHint &Hint) {
1983   if (isa<LabelDecl>(D)) {
1984     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1985         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1986         true);
1987     if (AfterColon.isInvalid())
1988       return;
1989     Hint = FixItHint::CreateRemoval(
1990         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1991   }
1992 }
1993 
1994 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1995   if (D->getTypeForDecl()->isDependentType())
1996     return;
1997 
1998   for (auto *TmpD : D->decls()) {
1999     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2000       DiagnoseUnusedDecl(T);
2001     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2002       DiagnoseUnusedNestedTypedefs(R);
2003   }
2004 }
2005 
2006 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2007 /// unless they are marked attr(unused).
2008 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2009   if (!ShouldDiagnoseUnusedDecl(D))
2010     return;
2011 
2012   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2013     // typedefs can be referenced later on, so the diagnostics are emitted
2014     // at end-of-translation-unit.
2015     UnusedLocalTypedefNameCandidates.insert(TD);
2016     return;
2017   }
2018 
2019   FixItHint Hint;
2020   GenerateFixForUnusedDecl(D, Context, Hint);
2021 
2022   unsigned DiagID;
2023   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2024     DiagID = diag::warn_unused_exception_param;
2025   else if (isa<LabelDecl>(D))
2026     DiagID = diag::warn_unused_label;
2027   else
2028     DiagID = diag::warn_unused_variable;
2029 
2030   Diag(D->getLocation(), DiagID) << D << Hint;
2031 }
2032 
2033 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2034   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2035   // it's not really unused.
2036   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2037       VD->hasAttr<CleanupAttr>())
2038     return;
2039 
2040   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2041 
2042   if (Ty->isReferenceType() || Ty->isDependentType())
2043     return;
2044 
2045   if (const TagType *TT = Ty->getAs<TagType>()) {
2046     const TagDecl *Tag = TT->getDecl();
2047     if (Tag->hasAttr<UnusedAttr>())
2048       return;
2049     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2050     // mimic gcc's behavior.
2051     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2052       if (!RD->hasAttr<WarnUnusedAttr>())
2053         return;
2054     }
2055   }
2056 
2057   // Don't warn about __block Objective-C pointer variables, as they might
2058   // be assigned in the block but not used elsewhere for the purpose of lifetime
2059   // extension.
2060   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2061     return;
2062 
2063   // Don't warn about Objective-C pointer variables with precise lifetime
2064   // semantics; they can be used to ensure ARC releases the object at a known
2065   // time, which may mean assignment but no other references.
2066   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2067     return;
2068 
2069   auto iter = RefsMinusAssignments.find(VD);
2070   if (iter == RefsMinusAssignments.end())
2071     return;
2072 
2073   assert(iter->getSecond() >= 0 &&
2074          "Found a negative number of references to a VarDecl");
2075   if (iter->getSecond() != 0)
2076     return;
2077   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2078                                          : diag::warn_unused_but_set_variable;
2079   Diag(VD->getLocation(), DiagID) << VD;
2080 }
2081 
2082 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2083   // Verify that we have no forward references left.  If so, there was a goto
2084   // or address of a label taken, but no definition of it.  Label fwd
2085   // definitions are indicated with a null substmt which is also not a resolved
2086   // MS inline assembly label name.
2087   bool Diagnose = false;
2088   if (L->isMSAsmLabel())
2089     Diagnose = !L->isResolvedMSAsmLabel();
2090   else
2091     Diagnose = L->getStmt() == nullptr;
2092   if (Diagnose)
2093     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2094 }
2095 
2096 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2097   S->mergeNRVOIntoParent();
2098 
2099   if (S->decl_empty()) return;
2100   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2101          "Scope shouldn't contain decls!");
2102 
2103   for (auto *TmpD : S->decls()) {
2104     assert(TmpD && "This decl didn't get pushed??");
2105 
2106     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2107     NamedDecl *D = cast<NamedDecl>(TmpD);
2108 
2109     // Diagnose unused variables in this scope.
2110     if (!S->hasUnrecoverableErrorOccurred()) {
2111       DiagnoseUnusedDecl(D);
2112       if (const auto *RD = dyn_cast<RecordDecl>(D))
2113         DiagnoseUnusedNestedTypedefs(RD);
2114       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2115         DiagnoseUnusedButSetDecl(VD);
2116         RefsMinusAssignments.erase(VD);
2117       }
2118     }
2119 
2120     if (!D->getDeclName()) continue;
2121 
2122     // If this was a forward reference to a label, verify it was defined.
2123     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2124       CheckPoppedLabel(LD, *this);
2125 
2126     // Remove this name from our lexical scope, and warn on it if we haven't
2127     // already.
2128     IdResolver.RemoveDecl(D);
2129     auto ShadowI = ShadowingDecls.find(D);
2130     if (ShadowI != ShadowingDecls.end()) {
2131       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2132         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2133             << D << FD << FD->getParent();
2134         Diag(FD->getLocation(), diag::note_previous_declaration);
2135       }
2136       ShadowingDecls.erase(ShadowI);
2137     }
2138   }
2139 }
2140 
2141 /// Look for an Objective-C class in the translation unit.
2142 ///
2143 /// \param Id The name of the Objective-C class we're looking for. If
2144 /// typo-correction fixes this name, the Id will be updated
2145 /// to the fixed name.
2146 ///
2147 /// \param IdLoc The location of the name in the translation unit.
2148 ///
2149 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2150 /// if there is no class with the given name.
2151 ///
2152 /// \returns The declaration of the named Objective-C class, or NULL if the
2153 /// class could not be found.
2154 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2155                                               SourceLocation IdLoc,
2156                                               bool DoTypoCorrection) {
2157   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2158   // creation from this context.
2159   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2160 
2161   if (!IDecl && DoTypoCorrection) {
2162     // Perform typo correction at the given location, but only if we
2163     // find an Objective-C class name.
2164     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2165     if (TypoCorrection C =
2166             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2167                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2168       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2169       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2170       Id = IDecl->getIdentifier();
2171     }
2172   }
2173   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2174   // This routine must always return a class definition, if any.
2175   if (Def && Def->getDefinition())
2176       Def = Def->getDefinition();
2177   return Def;
2178 }
2179 
2180 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2181 /// from S, where a non-field would be declared. This routine copes
2182 /// with the difference between C and C++ scoping rules in structs and
2183 /// unions. For example, the following code is well-formed in C but
2184 /// ill-formed in C++:
2185 /// @code
2186 /// struct S6 {
2187 ///   enum { BAR } e;
2188 /// };
2189 ///
2190 /// void test_S6() {
2191 ///   struct S6 a;
2192 ///   a.e = BAR;
2193 /// }
2194 /// @endcode
2195 /// For the declaration of BAR, this routine will return a different
2196 /// scope. The scope S will be the scope of the unnamed enumeration
2197 /// within S6. In C++, this routine will return the scope associated
2198 /// with S6, because the enumeration's scope is a transparent
2199 /// context but structures can contain non-field names. In C, this
2200 /// routine will return the translation unit scope, since the
2201 /// enumeration's scope is a transparent context and structures cannot
2202 /// contain non-field names.
2203 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2204   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2205          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2206          (S->isClassScope() && !getLangOpts().CPlusPlus))
2207     S = S->getParent();
2208   return S;
2209 }
2210 
2211 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2212                                ASTContext::GetBuiltinTypeError Error) {
2213   switch (Error) {
2214   case ASTContext::GE_None:
2215     return "";
2216   case ASTContext::GE_Missing_type:
2217     return BuiltinInfo.getHeaderName(ID);
2218   case ASTContext::GE_Missing_stdio:
2219     return "stdio.h";
2220   case ASTContext::GE_Missing_setjmp:
2221     return "setjmp.h";
2222   case ASTContext::GE_Missing_ucontext:
2223     return "ucontext.h";
2224   }
2225   llvm_unreachable("unhandled error kind");
2226 }
2227 
2228 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2229                                   unsigned ID, SourceLocation Loc) {
2230   DeclContext *Parent = Context.getTranslationUnitDecl();
2231 
2232   if (getLangOpts().CPlusPlus) {
2233     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2234         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2235     CLinkageDecl->setImplicit();
2236     Parent->addDecl(CLinkageDecl);
2237     Parent = CLinkageDecl;
2238   }
2239 
2240   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2241                                            /*TInfo=*/nullptr, SC_Extern,
2242                                            getCurFPFeatures().isFPConstrained(),
2243                                            false, Type->isFunctionProtoType());
2244   New->setImplicit();
2245   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2246 
2247   // Create Decl objects for each parameter, adding them to the
2248   // FunctionDecl.
2249   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2250     SmallVector<ParmVarDecl *, 16> Params;
2251     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2252       ParmVarDecl *parm = ParmVarDecl::Create(
2253           Context, New, SourceLocation(), SourceLocation(), nullptr,
2254           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2255       parm->setScopeInfo(0, i);
2256       Params.push_back(parm);
2257     }
2258     New->setParams(Params);
2259   }
2260 
2261   AddKnownFunctionAttributes(New);
2262   return New;
2263 }
2264 
2265 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2266 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2267 /// if we're creating this built-in in anticipation of redeclaring the
2268 /// built-in.
2269 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2270                                      Scope *S, bool ForRedeclaration,
2271                                      SourceLocation Loc) {
2272   LookupNecessaryTypesForBuiltin(S, ID);
2273 
2274   ASTContext::GetBuiltinTypeError Error;
2275   QualType R = Context.GetBuiltinType(ID, Error);
2276   if (Error) {
2277     if (!ForRedeclaration)
2278       return nullptr;
2279 
2280     // If we have a builtin without an associated type we should not emit a
2281     // warning when we were not able to find a type for it.
2282     if (Error == ASTContext::GE_Missing_type ||
2283         Context.BuiltinInfo.allowTypeMismatch(ID))
2284       return nullptr;
2285 
2286     // If we could not find a type for setjmp it is because the jmp_buf type was
2287     // not defined prior to the setjmp declaration.
2288     if (Error == ASTContext::GE_Missing_setjmp) {
2289       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2290           << Context.BuiltinInfo.getName(ID);
2291       return nullptr;
2292     }
2293 
2294     // Generally, we emit a warning that the declaration requires the
2295     // appropriate header.
2296     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2297         << getHeaderName(Context.BuiltinInfo, ID, Error)
2298         << Context.BuiltinInfo.getName(ID);
2299     return nullptr;
2300   }
2301 
2302   if (!ForRedeclaration &&
2303       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2304        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2305     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2306                            : diag::ext_implicit_lib_function_decl)
2307         << Context.BuiltinInfo.getName(ID) << R;
2308     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2309       Diag(Loc, diag::note_include_header_or_declare)
2310           << Header << Context.BuiltinInfo.getName(ID);
2311   }
2312 
2313   if (R.isNull())
2314     return nullptr;
2315 
2316   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2317   RegisterLocallyScopedExternCDecl(New, S);
2318 
2319   // TUScope is the translation-unit scope to insert this function into.
2320   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2321   // relate Scopes to DeclContexts, and probably eliminate CurContext
2322   // entirely, but we're not there yet.
2323   DeclContext *SavedContext = CurContext;
2324   CurContext = New->getDeclContext();
2325   PushOnScopeChains(New, TUScope);
2326   CurContext = SavedContext;
2327   return New;
2328 }
2329 
2330 /// Typedef declarations don't have linkage, but they still denote the same
2331 /// entity if their types are the same.
2332 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2333 /// isSameEntity.
2334 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2335                                                      TypedefNameDecl *Decl,
2336                                                      LookupResult &Previous) {
2337   // This is only interesting when modules are enabled.
2338   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2339     return;
2340 
2341   // Empty sets are uninteresting.
2342   if (Previous.empty())
2343     return;
2344 
2345   LookupResult::Filter Filter = Previous.makeFilter();
2346   while (Filter.hasNext()) {
2347     NamedDecl *Old = Filter.next();
2348 
2349     // Non-hidden declarations are never ignored.
2350     if (S.isVisible(Old))
2351       continue;
2352 
2353     // Declarations of the same entity are not ignored, even if they have
2354     // different linkages.
2355     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2356       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2357                                 Decl->getUnderlyingType()))
2358         continue;
2359 
2360       // If both declarations give a tag declaration a typedef name for linkage
2361       // purposes, then they declare the same entity.
2362       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2363           Decl->getAnonDeclWithTypedefName())
2364         continue;
2365     }
2366 
2367     Filter.erase();
2368   }
2369 
2370   Filter.done();
2371 }
2372 
2373 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2374   QualType OldType;
2375   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2376     OldType = OldTypedef->getUnderlyingType();
2377   else
2378     OldType = Context.getTypeDeclType(Old);
2379   QualType NewType = New->getUnderlyingType();
2380 
2381   if (NewType->isVariablyModifiedType()) {
2382     // Must not redefine a typedef with a variably-modified type.
2383     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2384     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2385       << Kind << NewType;
2386     if (Old->getLocation().isValid())
2387       notePreviousDefinition(Old, New->getLocation());
2388     New->setInvalidDecl();
2389     return true;
2390   }
2391 
2392   if (OldType != NewType &&
2393       !OldType->isDependentType() &&
2394       !NewType->isDependentType() &&
2395       !Context.hasSameType(OldType, NewType)) {
2396     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2397     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2398       << Kind << NewType << OldType;
2399     if (Old->getLocation().isValid())
2400       notePreviousDefinition(Old, New->getLocation());
2401     New->setInvalidDecl();
2402     return true;
2403   }
2404   return false;
2405 }
2406 
2407 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2408 /// same name and scope as a previous declaration 'Old'.  Figure out
2409 /// how to resolve this situation, merging decls or emitting
2410 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2411 ///
2412 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2413                                 LookupResult &OldDecls) {
2414   // If the new decl is known invalid already, don't bother doing any
2415   // merging checks.
2416   if (New->isInvalidDecl()) return;
2417 
2418   // Allow multiple definitions for ObjC built-in typedefs.
2419   // FIXME: Verify the underlying types are equivalent!
2420   if (getLangOpts().ObjC) {
2421     const IdentifierInfo *TypeID = New->getIdentifier();
2422     switch (TypeID->getLength()) {
2423     default: break;
2424     case 2:
2425       {
2426         if (!TypeID->isStr("id"))
2427           break;
2428         QualType T = New->getUnderlyingType();
2429         if (!T->isPointerType())
2430           break;
2431         if (!T->isVoidPointerType()) {
2432           QualType PT = T->castAs<PointerType>()->getPointeeType();
2433           if (!PT->isStructureType())
2434             break;
2435         }
2436         Context.setObjCIdRedefinitionType(T);
2437         // Install the built-in type for 'id', ignoring the current definition.
2438         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2439         return;
2440       }
2441     case 5:
2442       if (!TypeID->isStr("Class"))
2443         break;
2444       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2445       // Install the built-in type for 'Class', ignoring the current definition.
2446       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2447       return;
2448     case 3:
2449       if (!TypeID->isStr("SEL"))
2450         break;
2451       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2452       // Install the built-in type for 'SEL', ignoring the current definition.
2453       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2454       return;
2455     }
2456     // Fall through - the typedef name was not a builtin type.
2457   }
2458 
2459   // Verify the old decl was also a type.
2460   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2461   if (!Old) {
2462     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2463       << New->getDeclName();
2464 
2465     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2466     if (OldD->getLocation().isValid())
2467       notePreviousDefinition(OldD, New->getLocation());
2468 
2469     return New->setInvalidDecl();
2470   }
2471 
2472   // If the old declaration is invalid, just give up here.
2473   if (Old->isInvalidDecl())
2474     return New->setInvalidDecl();
2475 
2476   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2477     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2478     auto *NewTag = New->getAnonDeclWithTypedefName();
2479     NamedDecl *Hidden = nullptr;
2480     if (OldTag && NewTag &&
2481         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2482         !hasVisibleDefinition(OldTag, &Hidden)) {
2483       // There is a definition of this tag, but it is not visible. Use it
2484       // instead of our tag.
2485       New->setTypeForDecl(OldTD->getTypeForDecl());
2486       if (OldTD->isModed())
2487         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2488                                     OldTD->getUnderlyingType());
2489       else
2490         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2491 
2492       // Make the old tag definition visible.
2493       makeMergedDefinitionVisible(Hidden);
2494 
2495       // If this was an unscoped enumeration, yank all of its enumerators
2496       // out of the scope.
2497       if (isa<EnumDecl>(NewTag)) {
2498         Scope *EnumScope = getNonFieldDeclScope(S);
2499         for (auto *D : NewTag->decls()) {
2500           auto *ED = cast<EnumConstantDecl>(D);
2501           assert(EnumScope->isDeclScope(ED));
2502           EnumScope->RemoveDecl(ED);
2503           IdResolver.RemoveDecl(ED);
2504           ED->getLexicalDeclContext()->removeDecl(ED);
2505         }
2506       }
2507     }
2508   }
2509 
2510   // If the typedef types are not identical, reject them in all languages and
2511   // with any extensions enabled.
2512   if (isIncompatibleTypedef(Old, New))
2513     return;
2514 
2515   // The types match.  Link up the redeclaration chain and merge attributes if
2516   // the old declaration was a typedef.
2517   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2518     New->setPreviousDecl(Typedef);
2519     mergeDeclAttributes(New, Old);
2520   }
2521 
2522   if (getLangOpts().MicrosoftExt)
2523     return;
2524 
2525   if (getLangOpts().CPlusPlus) {
2526     // C++ [dcl.typedef]p2:
2527     //   In a given non-class scope, a typedef specifier can be used to
2528     //   redefine the name of any type declared in that scope to refer
2529     //   to the type to which it already refers.
2530     if (!isa<CXXRecordDecl>(CurContext))
2531       return;
2532 
2533     // C++0x [dcl.typedef]p4:
2534     //   In a given class scope, a typedef specifier can be used to redefine
2535     //   any class-name declared in that scope that is not also a typedef-name
2536     //   to refer to the type to which it already refers.
2537     //
2538     // This wording came in via DR424, which was a correction to the
2539     // wording in DR56, which accidentally banned code like:
2540     //
2541     //   struct S {
2542     //     typedef struct A { } A;
2543     //   };
2544     //
2545     // in the C++03 standard. We implement the C++0x semantics, which
2546     // allow the above but disallow
2547     //
2548     //   struct S {
2549     //     typedef int I;
2550     //     typedef int I;
2551     //   };
2552     //
2553     // since that was the intent of DR56.
2554     if (!isa<TypedefNameDecl>(Old))
2555       return;
2556 
2557     Diag(New->getLocation(), diag::err_redefinition)
2558       << New->getDeclName();
2559     notePreviousDefinition(Old, New->getLocation());
2560     return New->setInvalidDecl();
2561   }
2562 
2563   // Modules always permit redefinition of typedefs, as does C11.
2564   if (getLangOpts().Modules || getLangOpts().C11)
2565     return;
2566 
2567   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2568   // is normally mapped to an error, but can be controlled with
2569   // -Wtypedef-redefinition.  If either the original or the redefinition is
2570   // in a system header, don't emit this for compatibility with GCC.
2571   if (getDiagnostics().getSuppressSystemWarnings() &&
2572       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2573       (Old->isImplicit() ||
2574        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2575        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2576     return;
2577 
2578   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2579     << New->getDeclName();
2580   notePreviousDefinition(Old, New->getLocation());
2581 }
2582 
2583 /// DeclhasAttr - returns true if decl Declaration already has the target
2584 /// attribute.
2585 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2586   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2587   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2588   for (const auto *i : D->attrs())
2589     if (i->getKind() == A->getKind()) {
2590       if (Ann) {
2591         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2592           return true;
2593         continue;
2594       }
2595       // FIXME: Don't hardcode this check
2596       if (OA && isa<OwnershipAttr>(i))
2597         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2598       return true;
2599     }
2600 
2601   return false;
2602 }
2603 
2604 static bool isAttributeTargetADefinition(Decl *D) {
2605   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2606     return VD->isThisDeclarationADefinition();
2607   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2608     return TD->isCompleteDefinition() || TD->isBeingDefined();
2609   return true;
2610 }
2611 
2612 /// Merge alignment attributes from \p Old to \p New, taking into account the
2613 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2614 ///
2615 /// \return \c true if any attributes were added to \p New.
2616 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2617   // Look for alignas attributes on Old, and pick out whichever attribute
2618   // specifies the strictest alignment requirement.
2619   AlignedAttr *OldAlignasAttr = nullptr;
2620   AlignedAttr *OldStrictestAlignAttr = nullptr;
2621   unsigned OldAlign = 0;
2622   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2623     // FIXME: We have no way of representing inherited dependent alignments
2624     // in a case like:
2625     //   template<int A, int B> struct alignas(A) X;
2626     //   template<int A, int B> struct alignas(B) X {};
2627     // For now, we just ignore any alignas attributes which are not on the
2628     // definition in such a case.
2629     if (I->isAlignmentDependent())
2630       return false;
2631 
2632     if (I->isAlignas())
2633       OldAlignasAttr = I;
2634 
2635     unsigned Align = I->getAlignment(S.Context);
2636     if (Align > OldAlign) {
2637       OldAlign = Align;
2638       OldStrictestAlignAttr = I;
2639     }
2640   }
2641 
2642   // Look for alignas attributes on New.
2643   AlignedAttr *NewAlignasAttr = nullptr;
2644   unsigned NewAlign = 0;
2645   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2646     if (I->isAlignmentDependent())
2647       return false;
2648 
2649     if (I->isAlignas())
2650       NewAlignasAttr = I;
2651 
2652     unsigned Align = I->getAlignment(S.Context);
2653     if (Align > NewAlign)
2654       NewAlign = Align;
2655   }
2656 
2657   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2658     // Both declarations have 'alignas' attributes. We require them to match.
2659     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2660     // fall short. (If two declarations both have alignas, they must both match
2661     // every definition, and so must match each other if there is a definition.)
2662 
2663     // If either declaration only contains 'alignas(0)' specifiers, then it
2664     // specifies the natural alignment for the type.
2665     if (OldAlign == 0 || NewAlign == 0) {
2666       QualType Ty;
2667       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2668         Ty = VD->getType();
2669       else
2670         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2671 
2672       if (OldAlign == 0)
2673         OldAlign = S.Context.getTypeAlign(Ty);
2674       if (NewAlign == 0)
2675         NewAlign = S.Context.getTypeAlign(Ty);
2676     }
2677 
2678     if (OldAlign != NewAlign) {
2679       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2680         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2681         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2682       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2683     }
2684   }
2685 
2686   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2687     // C++11 [dcl.align]p6:
2688     //   if any declaration of an entity has an alignment-specifier,
2689     //   every defining declaration of that entity shall specify an
2690     //   equivalent alignment.
2691     // C11 6.7.5/7:
2692     //   If the definition of an object does not have an alignment
2693     //   specifier, any other declaration of that object shall also
2694     //   have no alignment specifier.
2695     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2696       << OldAlignasAttr;
2697     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2698       << OldAlignasAttr;
2699   }
2700 
2701   bool AnyAdded = false;
2702 
2703   // Ensure we have an attribute representing the strictest alignment.
2704   if (OldAlign > NewAlign) {
2705     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2706     Clone->setInherited(true);
2707     New->addAttr(Clone);
2708     AnyAdded = true;
2709   }
2710 
2711   // Ensure we have an alignas attribute if the old declaration had one.
2712   if (OldAlignasAttr && !NewAlignasAttr &&
2713       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2714     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2715     Clone->setInherited(true);
2716     New->addAttr(Clone);
2717     AnyAdded = true;
2718   }
2719 
2720   return AnyAdded;
2721 }
2722 
2723 #define WANT_DECL_MERGE_LOGIC
2724 #include "clang/Sema/AttrParsedAttrImpl.inc"
2725 #undef WANT_DECL_MERGE_LOGIC
2726 
2727 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2728                                const InheritableAttr *Attr,
2729                                Sema::AvailabilityMergeKind AMK) {
2730   // Diagnose any mutual exclusions between the attribute that we want to add
2731   // and attributes that already exist on the declaration.
2732   if (!DiagnoseMutualExclusions(S, D, Attr))
2733     return false;
2734 
2735   // This function copies an attribute Attr from a previous declaration to the
2736   // new declaration D if the new declaration doesn't itself have that attribute
2737   // yet or if that attribute allows duplicates.
2738   // If you're adding a new attribute that requires logic different from
2739   // "use explicit attribute on decl if present, else use attribute from
2740   // previous decl", for example if the attribute needs to be consistent
2741   // between redeclarations, you need to call a custom merge function here.
2742   InheritableAttr *NewAttr = nullptr;
2743   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2744     NewAttr = S.mergeAvailabilityAttr(
2745         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2746         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2747         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2748         AA->getPriority());
2749   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2750     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2752     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2753   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2754     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2755   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2756     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2757   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2758     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2759   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2760     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2761                                 FA->getFirstArg());
2762   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2763     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2764   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2765     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2766   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2767     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2768                                        IA->getInheritanceModel());
2769   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2770     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2771                                       &S.Context.Idents.get(AA->getSpelling()));
2772   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2773            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2774             isa<CUDAGlobalAttr>(Attr))) {
2775     // CUDA target attributes are part of function signature for
2776     // overloading purposes and must not be merged.
2777     return false;
2778   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2779     NewAttr = S.mergeMinSizeAttr(D, *MA);
2780   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2781     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2782   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2783     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2784   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2785     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2786   else if (isa<AlignedAttr>(Attr))
2787     // AlignedAttrs are handled separately, because we need to handle all
2788     // such attributes on a declaration at the same time.
2789     NewAttr = nullptr;
2790   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2791            (AMK == Sema::AMK_Override ||
2792             AMK == Sema::AMK_ProtocolImplementation ||
2793             AMK == Sema::AMK_OptionalProtocolImplementation))
2794     NewAttr = nullptr;
2795   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2796     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2797   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2798     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2799   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2800     NewAttr = S.mergeImportNameAttr(D, *INA);
2801   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2803   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2804     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2805   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2806     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2807   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2808     NewAttr =
2809         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2810   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2811     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2812   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2813     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2814 
2815   if (NewAttr) {
2816     NewAttr->setInherited(true);
2817     D->addAttr(NewAttr);
2818     if (isa<MSInheritanceAttr>(NewAttr))
2819       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2820     return true;
2821   }
2822 
2823   return false;
2824 }
2825 
2826 static const NamedDecl *getDefinition(const Decl *D) {
2827   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2828     return TD->getDefinition();
2829   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2830     const VarDecl *Def = VD->getDefinition();
2831     if (Def)
2832       return Def;
2833     return VD->getActingDefinition();
2834   }
2835   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2836     const FunctionDecl *Def = nullptr;
2837     if (FD->isDefined(Def, true))
2838       return Def;
2839   }
2840   return nullptr;
2841 }
2842 
2843 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2844   for (const auto *Attribute : D->attrs())
2845     if (Attribute->getKind() == Kind)
2846       return true;
2847   return false;
2848 }
2849 
2850 /// checkNewAttributesAfterDef - If we already have a definition, check that
2851 /// there are no new attributes in this declaration.
2852 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2853   if (!New->hasAttrs())
2854     return;
2855 
2856   const NamedDecl *Def = getDefinition(Old);
2857   if (!Def || Def == New)
2858     return;
2859 
2860   AttrVec &NewAttributes = New->getAttrs();
2861   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2862     const Attr *NewAttribute = NewAttributes[I];
2863 
2864     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2865       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2866         Sema::SkipBodyInfo SkipBody;
2867         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2868 
2869         // If we're skipping this definition, drop the "alias" attribute.
2870         if (SkipBody.ShouldSkip) {
2871           NewAttributes.erase(NewAttributes.begin() + I);
2872           --E;
2873           continue;
2874         }
2875       } else {
2876         VarDecl *VD = cast<VarDecl>(New);
2877         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2878                                 VarDecl::TentativeDefinition
2879                             ? diag::err_alias_after_tentative
2880                             : diag::err_redefinition;
2881         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2882         if (Diag == diag::err_redefinition)
2883           S.notePreviousDefinition(Def, VD->getLocation());
2884         else
2885           S.Diag(Def->getLocation(), diag::note_previous_definition);
2886         VD->setInvalidDecl();
2887       }
2888       ++I;
2889       continue;
2890     }
2891 
2892     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2893       // Tentative definitions are only interesting for the alias check above.
2894       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2895         ++I;
2896         continue;
2897       }
2898     }
2899 
2900     if (hasAttribute(Def, NewAttribute->getKind())) {
2901       ++I;
2902       continue; // regular attr merging will take care of validating this.
2903     }
2904 
2905     if (isa<C11NoReturnAttr>(NewAttribute)) {
2906       // C's _Noreturn is allowed to be added to a function after it is defined.
2907       ++I;
2908       continue;
2909     } else if (isa<UuidAttr>(NewAttribute)) {
2910       // msvc will allow a subsequent definition to add an uuid to a class
2911       ++I;
2912       continue;
2913     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2914       if (AA->isAlignas()) {
2915         // C++11 [dcl.align]p6:
2916         //   if any declaration of an entity has an alignment-specifier,
2917         //   every defining declaration of that entity shall specify an
2918         //   equivalent alignment.
2919         // C11 6.7.5/7:
2920         //   If the definition of an object does not have an alignment
2921         //   specifier, any other declaration of that object shall also
2922         //   have no alignment specifier.
2923         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2924           << AA;
2925         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2926           << AA;
2927         NewAttributes.erase(NewAttributes.begin() + I);
2928         --E;
2929         continue;
2930       }
2931     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2932       // If there is a C definition followed by a redeclaration with this
2933       // attribute then there are two different definitions. In C++, prefer the
2934       // standard diagnostics.
2935       if (!S.getLangOpts().CPlusPlus) {
2936         S.Diag(NewAttribute->getLocation(),
2937                diag::err_loader_uninitialized_redeclaration);
2938         S.Diag(Def->getLocation(), diag::note_previous_definition);
2939         NewAttributes.erase(NewAttributes.begin() + I);
2940         --E;
2941         continue;
2942       }
2943     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2944                cast<VarDecl>(New)->isInline() &&
2945                !cast<VarDecl>(New)->isInlineSpecified()) {
2946       // Don't warn about applying selectany to implicitly inline variables.
2947       // Older compilers and language modes would require the use of selectany
2948       // to make such variables inline, and it would have no effect if we
2949       // honored it.
2950       ++I;
2951       continue;
2952     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2953       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2954       // declarations after defintions.
2955       ++I;
2956       continue;
2957     }
2958 
2959     S.Diag(NewAttribute->getLocation(),
2960            diag::warn_attribute_precede_definition);
2961     S.Diag(Def->getLocation(), diag::note_previous_definition);
2962     NewAttributes.erase(NewAttributes.begin() + I);
2963     --E;
2964   }
2965 }
2966 
2967 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2968                                      const ConstInitAttr *CIAttr,
2969                                      bool AttrBeforeInit) {
2970   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2971 
2972   // Figure out a good way to write this specifier on the old declaration.
2973   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2974   // enough of the attribute list spelling information to extract that without
2975   // heroics.
2976   std::string SuitableSpelling;
2977   if (S.getLangOpts().CPlusPlus20)
2978     SuitableSpelling = std::string(
2979         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2980   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2981     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2982         InsertLoc, {tok::l_square, tok::l_square,
2983                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2984                     S.PP.getIdentifierInfo("require_constant_initialization"),
2985                     tok::r_square, tok::r_square}));
2986   if (SuitableSpelling.empty())
2987     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2988         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2989                     S.PP.getIdentifierInfo("require_constant_initialization"),
2990                     tok::r_paren, tok::r_paren}));
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2992     SuitableSpelling = "constinit";
2993   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2994     SuitableSpelling = "[[clang::require_constant_initialization]]";
2995   if (SuitableSpelling.empty())
2996     SuitableSpelling = "__attribute__((require_constant_initialization))";
2997   SuitableSpelling += " ";
2998 
2999   if (AttrBeforeInit) {
3000     // extern constinit int a;
3001     // int a = 0; // error (missing 'constinit'), accepted as extension
3002     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3003     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3004         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3005     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3006   } else {
3007     // int a = 0;
3008     // constinit extern int a; // error (missing 'constinit')
3009     S.Diag(CIAttr->getLocation(),
3010            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3011                                  : diag::warn_require_const_init_added_too_late)
3012         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3013     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3014         << CIAttr->isConstinit()
3015         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3016   }
3017 }
3018 
3019 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3020 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3021                                AvailabilityMergeKind AMK) {
3022   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3023     UsedAttr *NewAttr = OldAttr->clone(Context);
3024     NewAttr->setInherited(true);
3025     New->addAttr(NewAttr);
3026   }
3027   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3028     RetainAttr *NewAttr = OldAttr->clone(Context);
3029     NewAttr->setInherited(true);
3030     New->addAttr(NewAttr);
3031   }
3032 
3033   if (!Old->hasAttrs() && !New->hasAttrs())
3034     return;
3035 
3036   // [dcl.constinit]p1:
3037   //   If the [constinit] specifier is applied to any declaration of a
3038   //   variable, it shall be applied to the initializing declaration.
3039   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3040   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3041   if (bool(OldConstInit) != bool(NewConstInit)) {
3042     const auto *OldVD = cast<VarDecl>(Old);
3043     auto *NewVD = cast<VarDecl>(New);
3044 
3045     // Find the initializing declaration. Note that we might not have linked
3046     // the new declaration into the redeclaration chain yet.
3047     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3048     if (!InitDecl &&
3049         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3050       InitDecl = NewVD;
3051 
3052     if (InitDecl == NewVD) {
3053       // This is the initializing declaration. If it would inherit 'constinit',
3054       // that's ill-formed. (Note that we do not apply this to the attribute
3055       // form).
3056       if (OldConstInit && OldConstInit->isConstinit())
3057         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3058                                  /*AttrBeforeInit=*/true);
3059     } else if (NewConstInit) {
3060       // This is the first time we've been told that this declaration should
3061       // have a constant initializer. If we already saw the initializing
3062       // declaration, this is too late.
3063       if (InitDecl && InitDecl != NewVD) {
3064         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3065                                  /*AttrBeforeInit=*/false);
3066         NewVD->dropAttr<ConstInitAttr>();
3067       }
3068     }
3069   }
3070 
3071   // Attributes declared post-definition are currently ignored.
3072   checkNewAttributesAfterDef(*this, New, Old);
3073 
3074   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3075     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3076       if (!OldA->isEquivalent(NewA)) {
3077         // This redeclaration changes __asm__ label.
3078         Diag(New->getLocation(), diag::err_different_asm_label);
3079         Diag(OldA->getLocation(), diag::note_previous_declaration);
3080       }
3081     } else if (Old->isUsed()) {
3082       // This redeclaration adds an __asm__ label to a declaration that has
3083       // already been ODR-used.
3084       Diag(New->getLocation(), diag::err_late_asm_label_name)
3085         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3086     }
3087   }
3088 
3089   // Re-declaration cannot add abi_tag's.
3090   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3091     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3092       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3093         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3094           Diag(NewAbiTagAttr->getLocation(),
3095                diag::err_new_abi_tag_on_redeclaration)
3096               << NewTag;
3097           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3098         }
3099       }
3100     } else {
3101       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3102       Diag(Old->getLocation(), diag::note_previous_declaration);
3103     }
3104   }
3105 
3106   // This redeclaration adds a section attribute.
3107   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3108     if (auto *VD = dyn_cast<VarDecl>(New)) {
3109       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3110         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3111         Diag(Old->getLocation(), diag::note_previous_declaration);
3112       }
3113     }
3114   }
3115 
3116   // Redeclaration adds code-seg attribute.
3117   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3118   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3119       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3120     Diag(New->getLocation(), diag::warn_mismatched_section)
3121          << 0 /*codeseg*/;
3122     Diag(Old->getLocation(), diag::note_previous_declaration);
3123   }
3124 
3125   if (!Old->hasAttrs())
3126     return;
3127 
3128   bool foundAny = New->hasAttrs();
3129 
3130   // Ensure that any moving of objects within the allocated map is done before
3131   // we process them.
3132   if (!foundAny) New->setAttrs(AttrVec());
3133 
3134   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3135     // Ignore deprecated/unavailable/availability attributes if requested.
3136     AvailabilityMergeKind LocalAMK = AMK_None;
3137     if (isa<DeprecatedAttr>(I) ||
3138         isa<UnavailableAttr>(I) ||
3139         isa<AvailabilityAttr>(I)) {
3140       switch (AMK) {
3141       case AMK_None:
3142         continue;
3143 
3144       case AMK_Redeclaration:
3145       case AMK_Override:
3146       case AMK_ProtocolImplementation:
3147       case AMK_OptionalProtocolImplementation:
3148         LocalAMK = AMK;
3149         break;
3150       }
3151     }
3152 
3153     // Already handled.
3154     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3155       continue;
3156 
3157     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3158       foundAny = true;
3159   }
3160 
3161   if (mergeAlignedAttrs(*this, New, Old))
3162     foundAny = true;
3163 
3164   if (!foundAny) New->dropAttrs();
3165 }
3166 
3167 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3168 /// to the new one.
3169 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3170                                      const ParmVarDecl *oldDecl,
3171                                      Sema &S) {
3172   // C++11 [dcl.attr.depend]p2:
3173   //   The first declaration of a function shall specify the
3174   //   carries_dependency attribute for its declarator-id if any declaration
3175   //   of the function specifies the carries_dependency attribute.
3176   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3177   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3178     S.Diag(CDA->getLocation(),
3179            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3180     // Find the first declaration of the parameter.
3181     // FIXME: Should we build redeclaration chains for function parameters?
3182     const FunctionDecl *FirstFD =
3183       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3184     const ParmVarDecl *FirstVD =
3185       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3186     S.Diag(FirstVD->getLocation(),
3187            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3188   }
3189 
3190   if (!oldDecl->hasAttrs())
3191     return;
3192 
3193   bool foundAny = newDecl->hasAttrs();
3194 
3195   // Ensure that any moving of objects within the allocated map is
3196   // done before we process them.
3197   if (!foundAny) newDecl->setAttrs(AttrVec());
3198 
3199   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3200     if (!DeclHasAttr(newDecl, I)) {
3201       InheritableAttr *newAttr =
3202         cast<InheritableParamAttr>(I->clone(S.Context));
3203       newAttr->setInherited(true);
3204       newDecl->addAttr(newAttr);
3205       foundAny = true;
3206     }
3207   }
3208 
3209   if (!foundAny) newDecl->dropAttrs();
3210 }
3211 
3212 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3213                                 const ParmVarDecl *OldParam,
3214                                 Sema &S) {
3215   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3216     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3217       if (*Oldnullability != *Newnullability) {
3218         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3219           << DiagNullabilityKind(
3220                *Newnullability,
3221                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3222                 != 0))
3223           << DiagNullabilityKind(
3224                *Oldnullability,
3225                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3226                 != 0));
3227         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3228       }
3229     } else {
3230       QualType NewT = NewParam->getType();
3231       NewT = S.Context.getAttributedType(
3232                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3233                          NewT, NewT);
3234       NewParam->setType(NewT);
3235     }
3236   }
3237 }
3238 
3239 namespace {
3240 
3241 /// Used in MergeFunctionDecl to keep track of function parameters in
3242 /// C.
3243 struct GNUCompatibleParamWarning {
3244   ParmVarDecl *OldParm;
3245   ParmVarDecl *NewParm;
3246   QualType PromotedType;
3247 };
3248 
3249 } // end anonymous namespace
3250 
3251 // Determine whether the previous declaration was a definition, implicit
3252 // declaration, or a declaration.
3253 template <typename T>
3254 static std::pair<diag::kind, SourceLocation>
3255 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3256   diag::kind PrevDiag;
3257   SourceLocation OldLocation = Old->getLocation();
3258   if (Old->isThisDeclarationADefinition())
3259     PrevDiag = diag::note_previous_definition;
3260   else if (Old->isImplicit()) {
3261     PrevDiag = diag::note_previous_implicit_declaration;
3262     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3263       if (FD->getBuiltinID())
3264         PrevDiag = diag::note_previous_builtin_declaration;
3265     }
3266     if (OldLocation.isInvalid())
3267       OldLocation = New->getLocation();
3268   } else
3269     PrevDiag = diag::note_previous_declaration;
3270   return std::make_pair(PrevDiag, OldLocation);
3271 }
3272 
3273 /// canRedefineFunction - checks if a function can be redefined. Currently,
3274 /// only extern inline functions can be redefined, and even then only in
3275 /// GNU89 mode.
3276 static bool canRedefineFunction(const FunctionDecl *FD,
3277                                 const LangOptions& LangOpts) {
3278   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3279           !LangOpts.CPlusPlus &&
3280           FD->isInlineSpecified() &&
3281           FD->getStorageClass() == SC_Extern);
3282 }
3283 
3284 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3285   const AttributedType *AT = T->getAs<AttributedType>();
3286   while (AT && !AT->isCallingConv())
3287     AT = AT->getModifiedType()->getAs<AttributedType>();
3288   return AT;
3289 }
3290 
3291 template <typename T>
3292 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3293   const DeclContext *DC = Old->getDeclContext();
3294   if (DC->isRecord())
3295     return false;
3296 
3297   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3298   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3299     return true;
3300   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3301     return true;
3302   return false;
3303 }
3304 
3305 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3306 static bool isExternC(VarTemplateDecl *) { return false; }
3307 static bool isExternC(FunctionTemplateDecl *) { return false; }
3308 
3309 /// Check whether a redeclaration of an entity introduced by a
3310 /// using-declaration is valid, given that we know it's not an overload
3311 /// (nor a hidden tag declaration).
3312 template<typename ExpectedDecl>
3313 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3314                                    ExpectedDecl *New) {
3315   // C++11 [basic.scope.declarative]p4:
3316   //   Given a set of declarations in a single declarative region, each of
3317   //   which specifies the same unqualified name,
3318   //   -- they shall all refer to the same entity, or all refer to functions
3319   //      and function templates; or
3320   //   -- exactly one declaration shall declare a class name or enumeration
3321   //      name that is not a typedef name and the other declarations shall all
3322   //      refer to the same variable or enumerator, or all refer to functions
3323   //      and function templates; in this case the class name or enumeration
3324   //      name is hidden (3.3.10).
3325 
3326   // C++11 [namespace.udecl]p14:
3327   //   If a function declaration in namespace scope or block scope has the
3328   //   same name and the same parameter-type-list as a function introduced
3329   //   by a using-declaration, and the declarations do not declare the same
3330   //   function, the program is ill-formed.
3331 
3332   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3333   if (Old &&
3334       !Old->getDeclContext()->getRedeclContext()->Equals(
3335           New->getDeclContext()->getRedeclContext()) &&
3336       !(isExternC(Old) && isExternC(New)))
3337     Old = nullptr;
3338 
3339   if (!Old) {
3340     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3341     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3342     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3343     return true;
3344   }
3345   return false;
3346 }
3347 
3348 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3349                                             const FunctionDecl *B) {
3350   assert(A->getNumParams() == B->getNumParams());
3351 
3352   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3353     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3354     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3355     if (AttrA == AttrB)
3356       return true;
3357     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3358            AttrA->isDynamic() == AttrB->isDynamic();
3359   };
3360 
3361   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3362 }
3363 
3364 /// If necessary, adjust the semantic declaration context for a qualified
3365 /// declaration to name the correct inline namespace within the qualifier.
3366 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3367                                                DeclaratorDecl *OldD) {
3368   // The only case where we need to update the DeclContext is when
3369   // redeclaration lookup for a qualified name finds a declaration
3370   // in an inline namespace within the context named by the qualifier:
3371   //
3372   //   inline namespace N { int f(); }
3373   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3374   //
3375   // For unqualified declarations, the semantic context *can* change
3376   // along the redeclaration chain (for local extern declarations,
3377   // extern "C" declarations, and friend declarations in particular).
3378   if (!NewD->getQualifier())
3379     return;
3380 
3381   // NewD is probably already in the right context.
3382   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3383   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3384   if (NamedDC->Equals(SemaDC))
3385     return;
3386 
3387   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3388           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3389          "unexpected context for redeclaration");
3390 
3391   auto *LexDC = NewD->getLexicalDeclContext();
3392   auto FixSemaDC = [=](NamedDecl *D) {
3393     if (!D)
3394       return;
3395     D->setDeclContext(SemaDC);
3396     D->setLexicalDeclContext(LexDC);
3397   };
3398 
3399   FixSemaDC(NewD);
3400   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3401     FixSemaDC(FD->getDescribedFunctionTemplate());
3402   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3403     FixSemaDC(VD->getDescribedVarTemplate());
3404 }
3405 
3406 /// MergeFunctionDecl - We just parsed a function 'New' from
3407 /// declarator D which has the same name and scope as a previous
3408 /// declaration 'Old'.  Figure out how to resolve this situation,
3409 /// merging decls or emitting diagnostics as appropriate.
3410 ///
3411 /// In C++, New and Old must be declarations that are not
3412 /// overloaded. Use IsOverload to determine whether New and Old are
3413 /// overloaded, and to select the Old declaration that New should be
3414 /// merged with.
3415 ///
3416 /// Returns true if there was an error, false otherwise.
3417 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3418                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3419   // Verify the old decl was also a function.
3420   FunctionDecl *Old = OldD->getAsFunction();
3421   if (!Old) {
3422     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3423       if (New->getFriendObjectKind()) {
3424         Diag(New->getLocation(), diag::err_using_decl_friend);
3425         Diag(Shadow->getTargetDecl()->getLocation(),
3426              diag::note_using_decl_target);
3427         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3428             << 0;
3429         return true;
3430       }
3431 
3432       // Check whether the two declarations might declare the same function or
3433       // function template.
3434       if (FunctionTemplateDecl *NewTemplate =
3435               New->getDescribedFunctionTemplate()) {
3436         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3437                                                          NewTemplate))
3438           return true;
3439         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3440                          ->getAsFunction();
3441       } else {
3442         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3443           return true;
3444         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3445       }
3446     } else {
3447       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3448         << New->getDeclName();
3449       notePreviousDefinition(OldD, New->getLocation());
3450       return true;
3451     }
3452   }
3453 
3454   // If the old declaration was found in an inline namespace and the new
3455   // declaration was qualified, update the DeclContext to match.
3456   adjustDeclContextForDeclaratorDecl(New, Old);
3457 
3458   // If the old declaration is invalid, just give up here.
3459   if (Old->isInvalidDecl())
3460     return true;
3461 
3462   // Disallow redeclaration of some builtins.
3463   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3464     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3465     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3466         << Old << Old->getType();
3467     return true;
3468   }
3469 
3470   diag::kind PrevDiag;
3471   SourceLocation OldLocation;
3472   std::tie(PrevDiag, OldLocation) =
3473       getNoteDiagForInvalidRedeclaration(Old, New);
3474 
3475   // Don't complain about this if we're in GNU89 mode and the old function
3476   // is an extern inline function.
3477   // Don't complain about specializations. They are not supposed to have
3478   // storage classes.
3479   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3480       New->getStorageClass() == SC_Static &&
3481       Old->hasExternalFormalLinkage() &&
3482       !New->getTemplateSpecializationInfo() &&
3483       !canRedefineFunction(Old, getLangOpts())) {
3484     if (getLangOpts().MicrosoftExt) {
3485       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3486       Diag(OldLocation, PrevDiag);
3487     } else {
3488       Diag(New->getLocation(), diag::err_static_non_static) << New;
3489       Diag(OldLocation, PrevDiag);
3490       return true;
3491     }
3492   }
3493 
3494   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3495     if (!Old->hasAttr<InternalLinkageAttr>()) {
3496       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3497           << ILA;
3498       Diag(Old->getLocation(), diag::note_previous_declaration);
3499       New->dropAttr<InternalLinkageAttr>();
3500     }
3501 
3502   if (auto *EA = New->getAttr<ErrorAttr>()) {
3503     if (!Old->hasAttr<ErrorAttr>()) {
3504       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3505       Diag(Old->getLocation(), diag::note_previous_declaration);
3506       New->dropAttr<ErrorAttr>();
3507     }
3508   }
3509 
3510   if (CheckRedeclarationInModule(New, Old))
3511     return true;
3512 
3513   if (!getLangOpts().CPlusPlus) {
3514     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3515     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3516       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3517         << New << OldOvl;
3518 
3519       // Try our best to find a decl that actually has the overloadable
3520       // attribute for the note. In most cases (e.g. programs with only one
3521       // broken declaration/definition), this won't matter.
3522       //
3523       // FIXME: We could do this if we juggled some extra state in
3524       // OverloadableAttr, rather than just removing it.
3525       const Decl *DiagOld = Old;
3526       if (OldOvl) {
3527         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3528           const auto *A = D->getAttr<OverloadableAttr>();
3529           return A && !A->isImplicit();
3530         });
3531         // If we've implicitly added *all* of the overloadable attrs to this
3532         // chain, emitting a "previous redecl" note is pointless.
3533         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3534       }
3535 
3536       if (DiagOld)
3537         Diag(DiagOld->getLocation(),
3538              diag::note_attribute_overloadable_prev_overload)
3539           << OldOvl;
3540 
3541       if (OldOvl)
3542         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3543       else
3544         New->dropAttr<OverloadableAttr>();
3545     }
3546   }
3547 
3548   // If a function is first declared with a calling convention, but is later
3549   // declared or defined without one, all following decls assume the calling
3550   // convention of the first.
3551   //
3552   // It's OK if a function is first declared without a calling convention,
3553   // but is later declared or defined with the default calling convention.
3554   //
3555   // To test if either decl has an explicit calling convention, we look for
3556   // AttributedType sugar nodes on the type as written.  If they are missing or
3557   // were canonicalized away, we assume the calling convention was implicit.
3558   //
3559   // Note also that we DO NOT return at this point, because we still have
3560   // other tests to run.
3561   QualType OldQType = Context.getCanonicalType(Old->getType());
3562   QualType NewQType = Context.getCanonicalType(New->getType());
3563   const FunctionType *OldType = cast<FunctionType>(OldQType);
3564   const FunctionType *NewType = cast<FunctionType>(NewQType);
3565   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3566   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3567   bool RequiresAdjustment = false;
3568 
3569   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3570     FunctionDecl *First = Old->getFirstDecl();
3571     const FunctionType *FT =
3572         First->getType().getCanonicalType()->castAs<FunctionType>();
3573     FunctionType::ExtInfo FI = FT->getExtInfo();
3574     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3575     if (!NewCCExplicit) {
3576       // Inherit the CC from the previous declaration if it was specified
3577       // there but not here.
3578       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3579       RequiresAdjustment = true;
3580     } else if (Old->getBuiltinID()) {
3581       // Builtin attribute isn't propagated to the new one yet at this point,
3582       // so we check if the old one is a builtin.
3583 
3584       // Calling Conventions on a Builtin aren't really useful and setting a
3585       // default calling convention and cdecl'ing some builtin redeclarations is
3586       // common, so warn and ignore the calling convention on the redeclaration.
3587       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3588           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3589           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3590       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3591       RequiresAdjustment = true;
3592     } else {
3593       // Calling conventions aren't compatible, so complain.
3594       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3595       Diag(New->getLocation(), diag::err_cconv_change)
3596         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3597         << !FirstCCExplicit
3598         << (!FirstCCExplicit ? "" :
3599             FunctionType::getNameForCallConv(FI.getCC()));
3600 
3601       // Put the note on the first decl, since it is the one that matters.
3602       Diag(First->getLocation(), diag::note_previous_declaration);
3603       return true;
3604     }
3605   }
3606 
3607   // FIXME: diagnose the other way around?
3608   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3609     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3610     RequiresAdjustment = true;
3611   }
3612 
3613   // Merge regparm attribute.
3614   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3615       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3616     if (NewTypeInfo.getHasRegParm()) {
3617       Diag(New->getLocation(), diag::err_regparm_mismatch)
3618         << NewType->getRegParmType()
3619         << OldType->getRegParmType();
3620       Diag(OldLocation, diag::note_previous_declaration);
3621       return true;
3622     }
3623 
3624     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3625     RequiresAdjustment = true;
3626   }
3627 
3628   // Merge ns_returns_retained attribute.
3629   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3630     if (NewTypeInfo.getProducesResult()) {
3631       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3632           << "'ns_returns_retained'";
3633       Diag(OldLocation, diag::note_previous_declaration);
3634       return true;
3635     }
3636 
3637     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3638     RequiresAdjustment = true;
3639   }
3640 
3641   if (OldTypeInfo.getNoCallerSavedRegs() !=
3642       NewTypeInfo.getNoCallerSavedRegs()) {
3643     if (NewTypeInfo.getNoCallerSavedRegs()) {
3644       AnyX86NoCallerSavedRegistersAttr *Attr =
3645         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3646       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3647       Diag(OldLocation, diag::note_previous_declaration);
3648       return true;
3649     }
3650 
3651     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3652     RequiresAdjustment = true;
3653   }
3654 
3655   if (RequiresAdjustment) {
3656     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3657     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3658     New->setType(QualType(AdjustedType, 0));
3659     NewQType = Context.getCanonicalType(New->getType());
3660   }
3661 
3662   // If this redeclaration makes the function inline, we may need to add it to
3663   // UndefinedButUsed.
3664   if (!Old->isInlined() && New->isInlined() &&
3665       !New->hasAttr<GNUInlineAttr>() &&
3666       !getLangOpts().GNUInline &&
3667       Old->isUsed(false) &&
3668       !Old->isDefined() && !New->isThisDeclarationADefinition())
3669     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3670                                            SourceLocation()));
3671 
3672   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3673   // about it.
3674   if (New->hasAttr<GNUInlineAttr>() &&
3675       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3676     UndefinedButUsed.erase(Old->getCanonicalDecl());
3677   }
3678 
3679   // If pass_object_size params don't match up perfectly, this isn't a valid
3680   // redeclaration.
3681   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3682       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3683     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3684         << New->getDeclName();
3685     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3686     return true;
3687   }
3688 
3689   if (getLangOpts().CPlusPlus) {
3690     // C++1z [over.load]p2
3691     //   Certain function declarations cannot be overloaded:
3692     //     -- Function declarations that differ only in the return type,
3693     //        the exception specification, or both cannot be overloaded.
3694 
3695     // Check the exception specifications match. This may recompute the type of
3696     // both Old and New if it resolved exception specifications, so grab the
3697     // types again after this. Because this updates the type, we do this before
3698     // any of the other checks below, which may update the "de facto" NewQType
3699     // but do not necessarily update the type of New.
3700     if (CheckEquivalentExceptionSpec(Old, New))
3701       return true;
3702     OldQType = Context.getCanonicalType(Old->getType());
3703     NewQType = Context.getCanonicalType(New->getType());
3704 
3705     // Go back to the type source info to compare the declared return types,
3706     // per C++1y [dcl.type.auto]p13:
3707     //   Redeclarations or specializations of a function or function template
3708     //   with a declared return type that uses a placeholder type shall also
3709     //   use that placeholder, not a deduced type.
3710     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3711     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3712     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3713         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3714                                        OldDeclaredReturnType)) {
3715       QualType ResQT;
3716       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3717           OldDeclaredReturnType->isObjCObjectPointerType())
3718         // FIXME: This does the wrong thing for a deduced return type.
3719         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3720       if (ResQT.isNull()) {
3721         if (New->isCXXClassMember() && New->isOutOfLine())
3722           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3723               << New << New->getReturnTypeSourceRange();
3724         else
3725           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3726               << New->getReturnTypeSourceRange();
3727         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3728                                     << Old->getReturnTypeSourceRange();
3729         return true;
3730       }
3731       else
3732         NewQType = ResQT;
3733     }
3734 
3735     QualType OldReturnType = OldType->getReturnType();
3736     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3737     if (OldReturnType != NewReturnType) {
3738       // If this function has a deduced return type and has already been
3739       // defined, copy the deduced value from the old declaration.
3740       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3741       if (OldAT && OldAT->isDeduced()) {
3742         QualType DT = OldAT->getDeducedType();
3743         if (DT.isNull()) {
3744           New->setType(SubstAutoTypeDependent(New->getType()));
3745           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3746         } else {
3747           New->setType(SubstAutoType(New->getType(), DT));
3748           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3749         }
3750       }
3751     }
3752 
3753     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3754     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3755     if (OldMethod && NewMethod) {
3756       // Preserve triviality.
3757       NewMethod->setTrivial(OldMethod->isTrivial());
3758 
3759       // MSVC allows explicit template specialization at class scope:
3760       // 2 CXXMethodDecls referring to the same function will be injected.
3761       // We don't want a redeclaration error.
3762       bool IsClassScopeExplicitSpecialization =
3763                               OldMethod->isFunctionTemplateSpecialization() &&
3764                               NewMethod->isFunctionTemplateSpecialization();
3765       bool isFriend = NewMethod->getFriendObjectKind();
3766 
3767       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3768           !IsClassScopeExplicitSpecialization) {
3769         //    -- Member function declarations with the same name and the
3770         //       same parameter types cannot be overloaded if any of them
3771         //       is a static member function declaration.
3772         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3773           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3774           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3775           return true;
3776         }
3777 
3778         // C++ [class.mem]p1:
3779         //   [...] A member shall not be declared twice in the
3780         //   member-specification, except that a nested class or member
3781         //   class template can be declared and then later defined.
3782         if (!inTemplateInstantiation()) {
3783           unsigned NewDiag;
3784           if (isa<CXXConstructorDecl>(OldMethod))
3785             NewDiag = diag::err_constructor_redeclared;
3786           else if (isa<CXXDestructorDecl>(NewMethod))
3787             NewDiag = diag::err_destructor_redeclared;
3788           else if (isa<CXXConversionDecl>(NewMethod))
3789             NewDiag = diag::err_conv_function_redeclared;
3790           else
3791             NewDiag = diag::err_member_redeclared;
3792 
3793           Diag(New->getLocation(), NewDiag);
3794         } else {
3795           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3796             << New << New->getType();
3797         }
3798         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3799         return true;
3800 
3801       // Complain if this is an explicit declaration of a special
3802       // member that was initially declared implicitly.
3803       //
3804       // As an exception, it's okay to befriend such methods in order
3805       // to permit the implicit constructor/destructor/operator calls.
3806       } else if (OldMethod->isImplicit()) {
3807         if (isFriend) {
3808           NewMethod->setImplicit();
3809         } else {
3810           Diag(NewMethod->getLocation(),
3811                diag::err_definition_of_implicitly_declared_member)
3812             << New << getSpecialMember(OldMethod);
3813           return true;
3814         }
3815       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3816         Diag(NewMethod->getLocation(),
3817              diag::err_definition_of_explicitly_defaulted_member)
3818           << getSpecialMember(OldMethod);
3819         return true;
3820       }
3821     }
3822 
3823     // C++11 [dcl.attr.noreturn]p1:
3824     //   The first declaration of a function shall specify the noreturn
3825     //   attribute if any declaration of that function specifies the noreturn
3826     //   attribute.
3827     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3828       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3829         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3830             << NRA;
3831         Diag(Old->getLocation(), diag::note_previous_declaration);
3832       }
3833 
3834     // C++11 [dcl.attr.depend]p2:
3835     //   The first declaration of a function shall specify the
3836     //   carries_dependency attribute for its declarator-id if any declaration
3837     //   of the function specifies the carries_dependency attribute.
3838     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3839     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3840       Diag(CDA->getLocation(),
3841            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3842       Diag(Old->getFirstDecl()->getLocation(),
3843            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3844     }
3845 
3846     // (C++98 8.3.5p3):
3847     //   All declarations for a function shall agree exactly in both the
3848     //   return type and the parameter-type-list.
3849     // We also want to respect all the extended bits except noreturn.
3850 
3851     // noreturn should now match unless the old type info didn't have it.
3852     QualType OldQTypeForComparison = OldQType;
3853     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3854       auto *OldType = OldQType->castAs<FunctionProtoType>();
3855       const FunctionType *OldTypeForComparison
3856         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3857       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3858       assert(OldQTypeForComparison.isCanonical());
3859     }
3860 
3861     if (haveIncompatibleLanguageLinkages(Old, New)) {
3862       // As a special case, retain the language linkage from previous
3863       // declarations of a friend function as an extension.
3864       //
3865       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3866       // and is useful because there's otherwise no way to specify language
3867       // linkage within class scope.
3868       //
3869       // Check cautiously as the friend object kind isn't yet complete.
3870       if (New->getFriendObjectKind() != Decl::FOK_None) {
3871         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3872         Diag(OldLocation, PrevDiag);
3873       } else {
3874         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3875         Diag(OldLocation, PrevDiag);
3876         return true;
3877       }
3878     }
3879 
3880     // If the function types are compatible, merge the declarations. Ignore the
3881     // exception specifier because it was already checked above in
3882     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3883     // about incompatible types under -fms-compatibility.
3884     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3885                                                          NewQType))
3886       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3887 
3888     // If the types are imprecise (due to dependent constructs in friends or
3889     // local extern declarations), it's OK if they differ. We'll check again
3890     // during instantiation.
3891     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3892       return false;
3893 
3894     // Fall through for conflicting redeclarations and redefinitions.
3895   }
3896 
3897   // C: Function types need to be compatible, not identical. This handles
3898   // duplicate function decls like "void f(int); void f(enum X);" properly.
3899   if (!getLangOpts().CPlusPlus) {
3900     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3901     // type is specified by a function definition that contains a (possibly
3902     // empty) identifier list, both shall agree in the number of parameters
3903     // and the type of each parameter shall be compatible with the type that
3904     // results from the application of default argument promotions to the
3905     // type of the corresponding identifier. ...
3906     // This cannot be handled by ASTContext::typesAreCompatible() because that
3907     // doesn't know whether the function type is for a definition or not when
3908     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3909     // we need to cover here is that the number of arguments agree as the
3910     // default argument promotion rules were already checked by
3911     // ASTContext::typesAreCompatible().
3912     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3913         Old->getNumParams() != New->getNumParams()) {
3914       if (Old->hasInheritedPrototype())
3915         Old = Old->getCanonicalDecl();
3916       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3917       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3918       return true;
3919     }
3920 
3921     // If we are merging two functions where only one of them has a prototype,
3922     // we may have enough information to decide to issue a diagnostic that the
3923     // function without a protoype will change behavior in C2x. This handles
3924     // cases like:
3925     //   void i(); void i(int j);
3926     //   void i(int j); void i();
3927     //   void i(); void i(int j) {}
3928     // See ActOnFinishFunctionBody() for other cases of the behavior change
3929     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3930     // type without a prototype.
3931     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3932         !New->isImplicit() && !Old->isImplicit()) {
3933       const FunctionDecl *WithProto, *WithoutProto;
3934       if (New->hasWrittenPrototype()) {
3935         WithProto = New;
3936         WithoutProto = Old;
3937       } else {
3938         WithProto = Old;
3939         WithoutProto = New;
3940       }
3941 
3942       if (WithProto->getNumParams() != 0) {
3943         // The function definition has parameters, so this will change
3944         // behavior in C2x.
3945         //
3946         // If we already warned about about the function without a prototype
3947         // being deprecated, add a note that it also changes behavior. If we
3948         // didn't warn about it being deprecated (because the diagnostic is
3949         // not enabled), warn now that it is deprecated and changes behavior.
3950         bool AddNote = false;
3951         if (Diags.isIgnored(diag::warn_strict_prototypes,
3952                             WithoutProto->getLocation())) {
3953           if (WithoutProto->getBuiltinID() == 0 &&
3954               !WithoutProto->isImplicit() &&
3955               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3956                                                   WithProto->getLocation())) {
3957             PartialDiagnostic PD =
3958                 PDiag(diag::warn_non_prototype_changes_behavior);
3959             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3960               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3961                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3962             }
3963             Diag(WithoutProto->getLocation(), PD);
3964           }
3965         } else {
3966           AddNote = true;
3967         }
3968 
3969         // Because the function with a prototype has parameters but a previous
3970         // declaration had none, the function with the prototype will also
3971         // change behavior in C2x.
3972         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3973           if (SourceMgr.isBeforeInTranslationUnit(
3974                   WithProto->getLocation(), WithoutProto->getLocation())) {
3975             // If the function with the prototype comes before the function
3976             // without the prototype, we only want to diagnose the one without
3977             // the prototype.
3978             Diag(WithoutProto->getLocation(),
3979                  diag::warn_non_prototype_changes_behavior);
3980           } else {
3981             // Otherwise, diagnose the one with the prototype, and potentially
3982             // attach a note to the one without a prototype if needed.
3983             Diag(WithProto->getLocation(),
3984                  diag::warn_non_prototype_changes_behavior);
3985             if (AddNote && WithoutProto->getBuiltinID() == 0)
3986               Diag(WithoutProto->getLocation(),
3987                    diag::note_func_decl_changes_behavior);
3988           }
3989         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3990                    !WithoutProto->isImplicit()) {
3991           // If we were supposed to add a note but the function with a
3992           // prototype is a builtin or was implicitly declared, which means we
3993           // have nothing to attach the note to, so we issue a warning instead.
3994           Diag(WithoutProto->getLocation(),
3995                diag::warn_non_prototype_changes_behavior);
3996         }
3997       }
3998     }
3999 
4000     if (Context.typesAreCompatible(OldQType, NewQType)) {
4001       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4002       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4003       const FunctionProtoType *OldProto = nullptr;
4004       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4005           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4006         // The old declaration provided a function prototype, but the
4007         // new declaration does not. Merge in the prototype.
4008         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4009         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4010         NewQType =
4011             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4012                                     OldProto->getExtProtoInfo());
4013         New->setType(NewQType);
4014         New->setHasInheritedPrototype();
4015 
4016         // Synthesize parameters with the same types.
4017         SmallVector<ParmVarDecl *, 16> Params;
4018         for (const auto &ParamType : OldProto->param_types()) {
4019           ParmVarDecl *Param = ParmVarDecl::Create(
4020               Context, New, SourceLocation(), SourceLocation(), nullptr,
4021               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4022           Param->setScopeInfo(0, Params.size());
4023           Param->setImplicit();
4024           Params.push_back(Param);
4025         }
4026 
4027         New->setParams(Params);
4028       }
4029 
4030       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4031     }
4032   }
4033 
4034   // Check if the function types are compatible when pointer size address
4035   // spaces are ignored.
4036   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4037     return false;
4038 
4039   // GNU C permits a K&R definition to follow a prototype declaration
4040   // if the declared types of the parameters in the K&R definition
4041   // match the types in the prototype declaration, even when the
4042   // promoted types of the parameters from the K&R definition differ
4043   // from the types in the prototype. GCC then keeps the types from
4044   // the prototype.
4045   //
4046   // If a variadic prototype is followed by a non-variadic K&R definition,
4047   // the K&R definition becomes variadic.  This is sort of an edge case, but
4048   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4049   // C99 6.9.1p8.
4050   if (!getLangOpts().CPlusPlus &&
4051       Old->hasPrototype() && !New->hasPrototype() &&
4052       New->getType()->getAs<FunctionProtoType>() &&
4053       Old->getNumParams() == New->getNumParams()) {
4054     SmallVector<QualType, 16> ArgTypes;
4055     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4056     const FunctionProtoType *OldProto
4057       = Old->getType()->getAs<FunctionProtoType>();
4058     const FunctionProtoType *NewProto
4059       = New->getType()->getAs<FunctionProtoType>();
4060 
4061     // Determine whether this is the GNU C extension.
4062     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4063                                                NewProto->getReturnType());
4064     bool LooseCompatible = !MergedReturn.isNull();
4065     for (unsigned Idx = 0, End = Old->getNumParams();
4066          LooseCompatible && Idx != End; ++Idx) {
4067       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4068       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4069       if (Context.typesAreCompatible(OldParm->getType(),
4070                                      NewProto->getParamType(Idx))) {
4071         ArgTypes.push_back(NewParm->getType());
4072       } else if (Context.typesAreCompatible(OldParm->getType(),
4073                                             NewParm->getType(),
4074                                             /*CompareUnqualified=*/true)) {
4075         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4076                                            NewProto->getParamType(Idx) };
4077         Warnings.push_back(Warn);
4078         ArgTypes.push_back(NewParm->getType());
4079       } else
4080         LooseCompatible = false;
4081     }
4082 
4083     if (LooseCompatible) {
4084       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4085         Diag(Warnings[Warn].NewParm->getLocation(),
4086              diag::ext_param_promoted_not_compatible_with_prototype)
4087           << Warnings[Warn].PromotedType
4088           << Warnings[Warn].OldParm->getType();
4089         if (Warnings[Warn].OldParm->getLocation().isValid())
4090           Diag(Warnings[Warn].OldParm->getLocation(),
4091                diag::note_previous_declaration);
4092       }
4093 
4094       if (MergeTypeWithOld)
4095         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4096                                              OldProto->getExtProtoInfo()));
4097       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4098     }
4099 
4100     // Fall through to diagnose conflicting types.
4101   }
4102 
4103   // A function that has already been declared has been redeclared or
4104   // defined with a different type; show an appropriate diagnostic.
4105 
4106   // If the previous declaration was an implicitly-generated builtin
4107   // declaration, then at the very least we should use a specialized note.
4108   unsigned BuiltinID;
4109   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4110     // If it's actually a library-defined builtin function like 'malloc'
4111     // or 'printf', just warn about the incompatible redeclaration.
4112     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4113       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4114       Diag(OldLocation, diag::note_previous_builtin_declaration)
4115         << Old << Old->getType();
4116       return false;
4117     }
4118 
4119     PrevDiag = diag::note_previous_builtin_declaration;
4120   }
4121 
4122   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4123   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4124   return true;
4125 }
4126 
4127 /// Completes the merge of two function declarations that are
4128 /// known to be compatible.
4129 ///
4130 /// This routine handles the merging of attributes and other
4131 /// properties of function declarations from the old declaration to
4132 /// the new declaration, once we know that New is in fact a
4133 /// redeclaration of Old.
4134 ///
4135 /// \returns false
4136 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4137                                         Scope *S, bool MergeTypeWithOld) {
4138   // Merge the attributes
4139   mergeDeclAttributes(New, Old);
4140 
4141   // Merge "pure" flag.
4142   if (Old->isPure())
4143     New->setPure();
4144 
4145   // Merge "used" flag.
4146   if (Old->getMostRecentDecl()->isUsed(false))
4147     New->setIsUsed();
4148 
4149   // Merge attributes from the parameters.  These can mismatch with K&R
4150   // declarations.
4151   if (New->getNumParams() == Old->getNumParams())
4152       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4153         ParmVarDecl *NewParam = New->getParamDecl(i);
4154         ParmVarDecl *OldParam = Old->getParamDecl(i);
4155         mergeParamDeclAttributes(NewParam, OldParam, *this);
4156         mergeParamDeclTypes(NewParam, OldParam, *this);
4157       }
4158 
4159   if (getLangOpts().CPlusPlus)
4160     return MergeCXXFunctionDecl(New, Old, S);
4161 
4162   // Merge the function types so the we get the composite types for the return
4163   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4164   // was visible.
4165   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4166   if (!Merged.isNull() && MergeTypeWithOld)
4167     New->setType(Merged);
4168 
4169   return false;
4170 }
4171 
4172 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4173                                 ObjCMethodDecl *oldMethod) {
4174   // Merge the attributes, including deprecated/unavailable
4175   AvailabilityMergeKind MergeKind =
4176       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4177           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4178                                      : AMK_ProtocolImplementation)
4179           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4180                                                            : AMK_Override;
4181 
4182   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4183 
4184   // Merge attributes from the parameters.
4185   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4186                                        oe = oldMethod->param_end();
4187   for (ObjCMethodDecl::param_iterator
4188          ni = newMethod->param_begin(), ne = newMethod->param_end();
4189        ni != ne && oi != oe; ++ni, ++oi)
4190     mergeParamDeclAttributes(*ni, *oi, *this);
4191 
4192   CheckObjCMethodOverride(newMethod, oldMethod);
4193 }
4194 
4195 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4196   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4197 
4198   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4199          ? diag::err_redefinition_different_type
4200          : diag::err_redeclaration_different_type)
4201     << New->getDeclName() << New->getType() << Old->getType();
4202 
4203   diag::kind PrevDiag;
4204   SourceLocation OldLocation;
4205   std::tie(PrevDiag, OldLocation)
4206     = getNoteDiagForInvalidRedeclaration(Old, New);
4207   S.Diag(OldLocation, PrevDiag);
4208   New->setInvalidDecl();
4209 }
4210 
4211 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4212 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4213 /// emitting diagnostics as appropriate.
4214 ///
4215 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4216 /// to here in AddInitializerToDecl. We can't check them before the initializer
4217 /// is attached.
4218 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4219                              bool MergeTypeWithOld) {
4220   if (New->isInvalidDecl() || Old->isInvalidDecl())
4221     return;
4222 
4223   QualType MergedT;
4224   if (getLangOpts().CPlusPlus) {
4225     if (New->getType()->isUndeducedType()) {
4226       // We don't know what the new type is until the initializer is attached.
4227       return;
4228     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4229       // These could still be something that needs exception specs checked.
4230       return MergeVarDeclExceptionSpecs(New, Old);
4231     }
4232     // C++ [basic.link]p10:
4233     //   [...] the types specified by all declarations referring to a given
4234     //   object or function shall be identical, except that declarations for an
4235     //   array object can specify array types that differ by the presence or
4236     //   absence of a major array bound (8.3.4).
4237     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4238       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4239       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4240 
4241       // We are merging a variable declaration New into Old. If it has an array
4242       // bound, and that bound differs from Old's bound, we should diagnose the
4243       // mismatch.
4244       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4245         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4246              PrevVD = PrevVD->getPreviousDecl()) {
4247           QualType PrevVDTy = PrevVD->getType();
4248           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4249             continue;
4250 
4251           if (!Context.hasSameType(New->getType(), PrevVDTy))
4252             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4253         }
4254       }
4255 
4256       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4257         if (Context.hasSameType(OldArray->getElementType(),
4258                                 NewArray->getElementType()))
4259           MergedT = New->getType();
4260       }
4261       // FIXME: Check visibility. New is hidden but has a complete type. If New
4262       // has no array bound, it should not inherit one from Old, if Old is not
4263       // visible.
4264       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4265         if (Context.hasSameType(OldArray->getElementType(),
4266                                 NewArray->getElementType()))
4267           MergedT = Old->getType();
4268       }
4269     }
4270     else if (New->getType()->isObjCObjectPointerType() &&
4271                Old->getType()->isObjCObjectPointerType()) {
4272       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4273                                               Old->getType());
4274     }
4275   } else {
4276     // C 6.2.7p2:
4277     //   All declarations that refer to the same object or function shall have
4278     //   compatible type.
4279     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4280   }
4281   if (MergedT.isNull()) {
4282     // It's OK if we couldn't merge types if either type is dependent, for a
4283     // block-scope variable. In other cases (static data members of class
4284     // templates, variable templates, ...), we require the types to be
4285     // equivalent.
4286     // FIXME: The C++ standard doesn't say anything about this.
4287     if ((New->getType()->isDependentType() ||
4288          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4289       // If the old type was dependent, we can't merge with it, so the new type
4290       // becomes dependent for now. We'll reproduce the original type when we
4291       // instantiate the TypeSourceInfo for the variable.
4292       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4293         New->setType(Context.DependentTy);
4294       return;
4295     }
4296     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4297   }
4298 
4299   // Don't actually update the type on the new declaration if the old
4300   // declaration was an extern declaration in a different scope.
4301   if (MergeTypeWithOld)
4302     New->setType(MergedT);
4303 }
4304 
4305 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4306                                   LookupResult &Previous) {
4307   // C11 6.2.7p4:
4308   //   For an identifier with internal or external linkage declared
4309   //   in a scope in which a prior declaration of that identifier is
4310   //   visible, if the prior declaration specifies internal or
4311   //   external linkage, the type of the identifier at the later
4312   //   declaration becomes the composite type.
4313   //
4314   // If the variable isn't visible, we do not merge with its type.
4315   if (Previous.isShadowed())
4316     return false;
4317 
4318   if (S.getLangOpts().CPlusPlus) {
4319     // C++11 [dcl.array]p3:
4320     //   If there is a preceding declaration of the entity in the same
4321     //   scope in which the bound was specified, an omitted array bound
4322     //   is taken to be the same as in that earlier declaration.
4323     return NewVD->isPreviousDeclInSameBlockScope() ||
4324            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4325             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4326   } else {
4327     // If the old declaration was function-local, don't merge with its
4328     // type unless we're in the same function.
4329     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4330            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4331   }
4332 }
4333 
4334 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4335 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4336 /// situation, merging decls or emitting diagnostics as appropriate.
4337 ///
4338 /// Tentative definition rules (C99 6.9.2p2) are checked by
4339 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4340 /// definitions here, since the initializer hasn't been attached.
4341 ///
4342 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4343   // If the new decl is already invalid, don't do any other checking.
4344   if (New->isInvalidDecl())
4345     return;
4346 
4347   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4348     return;
4349 
4350   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4351 
4352   // Verify the old decl was also a variable or variable template.
4353   VarDecl *Old = nullptr;
4354   VarTemplateDecl *OldTemplate = nullptr;
4355   if (Previous.isSingleResult()) {
4356     if (NewTemplate) {
4357       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4358       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4359 
4360       if (auto *Shadow =
4361               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4362         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4363           return New->setInvalidDecl();
4364     } else {
4365       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4366 
4367       if (auto *Shadow =
4368               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4369         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4370           return New->setInvalidDecl();
4371     }
4372   }
4373   if (!Old) {
4374     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4375         << New->getDeclName();
4376     notePreviousDefinition(Previous.getRepresentativeDecl(),
4377                            New->getLocation());
4378     return New->setInvalidDecl();
4379   }
4380 
4381   // If the old declaration was found in an inline namespace and the new
4382   // declaration was qualified, update the DeclContext to match.
4383   adjustDeclContextForDeclaratorDecl(New, Old);
4384 
4385   // Ensure the template parameters are compatible.
4386   if (NewTemplate &&
4387       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4388                                       OldTemplate->getTemplateParameters(),
4389                                       /*Complain=*/true, TPL_TemplateMatch))
4390     return New->setInvalidDecl();
4391 
4392   // C++ [class.mem]p1:
4393   //   A member shall not be declared twice in the member-specification [...]
4394   //
4395   // Here, we need only consider static data members.
4396   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4397     Diag(New->getLocation(), diag::err_duplicate_member)
4398       << New->getIdentifier();
4399     Diag(Old->getLocation(), diag::note_previous_declaration);
4400     New->setInvalidDecl();
4401   }
4402 
4403   mergeDeclAttributes(New, Old);
4404   // Warn if an already-declared variable is made a weak_import in a subsequent
4405   // declaration
4406   if (New->hasAttr<WeakImportAttr>() &&
4407       Old->getStorageClass() == SC_None &&
4408       !Old->hasAttr<WeakImportAttr>()) {
4409     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4410     Diag(Old->getLocation(), diag::note_previous_declaration);
4411     // Remove weak_import attribute on new declaration.
4412     New->dropAttr<WeakImportAttr>();
4413   }
4414 
4415   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4416     if (!Old->hasAttr<InternalLinkageAttr>()) {
4417       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4418           << ILA;
4419       Diag(Old->getLocation(), diag::note_previous_declaration);
4420       New->dropAttr<InternalLinkageAttr>();
4421     }
4422 
4423   // Merge the types.
4424   VarDecl *MostRecent = Old->getMostRecentDecl();
4425   if (MostRecent != Old) {
4426     MergeVarDeclTypes(New, MostRecent,
4427                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4428     if (New->isInvalidDecl())
4429       return;
4430   }
4431 
4432   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4433   if (New->isInvalidDecl())
4434     return;
4435 
4436   diag::kind PrevDiag;
4437   SourceLocation OldLocation;
4438   std::tie(PrevDiag, OldLocation) =
4439       getNoteDiagForInvalidRedeclaration(Old, New);
4440 
4441   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4442   if (New->getStorageClass() == SC_Static &&
4443       !New->isStaticDataMember() &&
4444       Old->hasExternalFormalLinkage()) {
4445     if (getLangOpts().MicrosoftExt) {
4446       Diag(New->getLocation(), diag::ext_static_non_static)
4447           << New->getDeclName();
4448       Diag(OldLocation, PrevDiag);
4449     } else {
4450       Diag(New->getLocation(), diag::err_static_non_static)
4451           << New->getDeclName();
4452       Diag(OldLocation, PrevDiag);
4453       return New->setInvalidDecl();
4454     }
4455   }
4456   // C99 6.2.2p4:
4457   //   For an identifier declared with the storage-class specifier
4458   //   extern in a scope in which a prior declaration of that
4459   //   identifier is visible,23) if the prior declaration specifies
4460   //   internal or external linkage, the linkage of the identifier at
4461   //   the later declaration is the same as the linkage specified at
4462   //   the prior declaration. If no prior declaration is visible, or
4463   //   if the prior declaration specifies no linkage, then the
4464   //   identifier has external linkage.
4465   if (New->hasExternalStorage() && Old->hasLinkage())
4466     /* Okay */;
4467   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4468            !New->isStaticDataMember() &&
4469            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4470     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4471     Diag(OldLocation, PrevDiag);
4472     return New->setInvalidDecl();
4473   }
4474 
4475   // Check if extern is followed by non-extern and vice-versa.
4476   if (New->hasExternalStorage() &&
4477       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4478     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4479     Diag(OldLocation, PrevDiag);
4480     return New->setInvalidDecl();
4481   }
4482   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4483       !New->hasExternalStorage()) {
4484     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4485     Diag(OldLocation, PrevDiag);
4486     return New->setInvalidDecl();
4487   }
4488 
4489   if (CheckRedeclarationInModule(New, Old))
4490     return;
4491 
4492   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4493 
4494   // FIXME: The test for external storage here seems wrong? We still
4495   // need to check for mismatches.
4496   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4497       // Don't complain about out-of-line definitions of static members.
4498       !(Old->getLexicalDeclContext()->isRecord() &&
4499         !New->getLexicalDeclContext()->isRecord())) {
4500     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4501     Diag(OldLocation, PrevDiag);
4502     return New->setInvalidDecl();
4503   }
4504 
4505   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4506     if (VarDecl *Def = Old->getDefinition()) {
4507       // C++1z [dcl.fcn.spec]p4:
4508       //   If the definition of a variable appears in a translation unit before
4509       //   its first declaration as inline, the program is ill-formed.
4510       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4511       Diag(Def->getLocation(), diag::note_previous_definition);
4512     }
4513   }
4514 
4515   // If this redeclaration makes the variable inline, we may need to add it to
4516   // UndefinedButUsed.
4517   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4518       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4519     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4520                                            SourceLocation()));
4521 
4522   if (New->getTLSKind() != Old->getTLSKind()) {
4523     if (!Old->getTLSKind()) {
4524       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4525       Diag(OldLocation, PrevDiag);
4526     } else if (!New->getTLSKind()) {
4527       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4528       Diag(OldLocation, PrevDiag);
4529     } else {
4530       // Do not allow redeclaration to change the variable between requiring
4531       // static and dynamic initialization.
4532       // FIXME: GCC allows this, but uses the TLS keyword on the first
4533       // declaration to determine the kind. Do we need to be compatible here?
4534       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4535         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4536       Diag(OldLocation, PrevDiag);
4537     }
4538   }
4539 
4540   // C++ doesn't have tentative definitions, so go right ahead and check here.
4541   if (getLangOpts().CPlusPlus &&
4542       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4543     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4544         Old->getCanonicalDecl()->isConstexpr()) {
4545       // This definition won't be a definition any more once it's been merged.
4546       Diag(New->getLocation(),
4547            diag::warn_deprecated_redundant_constexpr_static_def);
4548     } else if (VarDecl *Def = Old->getDefinition()) {
4549       if (checkVarDeclRedefinition(Def, New))
4550         return;
4551     }
4552   }
4553 
4554   if (haveIncompatibleLanguageLinkages(Old, New)) {
4555     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4556     Diag(OldLocation, PrevDiag);
4557     New->setInvalidDecl();
4558     return;
4559   }
4560 
4561   // Merge "used" flag.
4562   if (Old->getMostRecentDecl()->isUsed(false))
4563     New->setIsUsed();
4564 
4565   // Keep a chain of previous declarations.
4566   New->setPreviousDecl(Old);
4567   if (NewTemplate)
4568     NewTemplate->setPreviousDecl(OldTemplate);
4569 
4570   // Inherit access appropriately.
4571   New->setAccess(Old->getAccess());
4572   if (NewTemplate)
4573     NewTemplate->setAccess(New->getAccess());
4574 
4575   if (Old->isInline())
4576     New->setImplicitlyInline();
4577 }
4578 
4579 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4580   SourceManager &SrcMgr = getSourceManager();
4581   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4582   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4583   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4584   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4585   auto &HSI = PP.getHeaderSearchInfo();
4586   StringRef HdrFilename =
4587       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4588 
4589   auto noteFromModuleOrInclude = [&](Module *Mod,
4590                                      SourceLocation IncLoc) -> bool {
4591     // Redefinition errors with modules are common with non modular mapped
4592     // headers, example: a non-modular header H in module A that also gets
4593     // included directly in a TU. Pointing twice to the same header/definition
4594     // is confusing, try to get better diagnostics when modules is on.
4595     if (IncLoc.isValid()) {
4596       if (Mod) {
4597         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4598             << HdrFilename.str() << Mod->getFullModuleName();
4599         if (!Mod->DefinitionLoc.isInvalid())
4600           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4601               << Mod->getFullModuleName();
4602       } else {
4603         Diag(IncLoc, diag::note_redefinition_include_same_file)
4604             << HdrFilename.str();
4605       }
4606       return true;
4607     }
4608 
4609     return false;
4610   };
4611 
4612   // Is it the same file and same offset? Provide more information on why
4613   // this leads to a redefinition error.
4614   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4615     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4616     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4617     bool EmittedDiag =
4618         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4619     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4620 
4621     // If the header has no guards, emit a note suggesting one.
4622     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4623       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4624 
4625     if (EmittedDiag)
4626       return;
4627   }
4628 
4629   // Redefinition coming from different files or couldn't do better above.
4630   if (Old->getLocation().isValid())
4631     Diag(Old->getLocation(), diag::note_previous_definition);
4632 }
4633 
4634 /// We've just determined that \p Old and \p New both appear to be definitions
4635 /// of the same variable. Either diagnose or fix the problem.
4636 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4637   if (!hasVisibleDefinition(Old) &&
4638       (New->getFormalLinkage() == InternalLinkage ||
4639        New->isInline() ||
4640        New->getDescribedVarTemplate() ||
4641        New->getNumTemplateParameterLists() ||
4642        New->getDeclContext()->isDependentContext())) {
4643     // The previous definition is hidden, and multiple definitions are
4644     // permitted (in separate TUs). Demote this to a declaration.
4645     New->demoteThisDefinitionToDeclaration();
4646 
4647     // Make the canonical definition visible.
4648     if (auto *OldTD = Old->getDescribedVarTemplate())
4649       makeMergedDefinitionVisible(OldTD);
4650     makeMergedDefinitionVisible(Old);
4651     return false;
4652   } else {
4653     Diag(New->getLocation(), diag::err_redefinition) << New;
4654     notePreviousDefinition(Old, New->getLocation());
4655     New->setInvalidDecl();
4656     return true;
4657   }
4658 }
4659 
4660 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4661 /// no declarator (e.g. "struct foo;") is parsed.
4662 Decl *
4663 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4664                                  RecordDecl *&AnonRecord) {
4665   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4666                                     AnonRecord);
4667 }
4668 
4669 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4670 // disambiguate entities defined in different scopes.
4671 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4672 // compatibility.
4673 // We will pick our mangling number depending on which version of MSVC is being
4674 // targeted.
4675 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4676   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4677              ? S->getMSCurManglingNumber()
4678              : S->getMSLastManglingNumber();
4679 }
4680 
4681 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4682   if (!Context.getLangOpts().CPlusPlus)
4683     return;
4684 
4685   if (isa<CXXRecordDecl>(Tag->getParent())) {
4686     // If this tag is the direct child of a class, number it if
4687     // it is anonymous.
4688     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4689       return;
4690     MangleNumberingContext &MCtx =
4691         Context.getManglingNumberContext(Tag->getParent());
4692     Context.setManglingNumber(
4693         Tag, MCtx.getManglingNumber(
4694                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4695     return;
4696   }
4697 
4698   // If this tag isn't a direct child of a class, number it if it is local.
4699   MangleNumberingContext *MCtx;
4700   Decl *ManglingContextDecl;
4701   std::tie(MCtx, ManglingContextDecl) =
4702       getCurrentMangleNumberContext(Tag->getDeclContext());
4703   if (MCtx) {
4704     Context.setManglingNumber(
4705         Tag, MCtx->getManglingNumber(
4706                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4707   }
4708 }
4709 
4710 namespace {
4711 struct NonCLikeKind {
4712   enum {
4713     None,
4714     BaseClass,
4715     DefaultMemberInit,
4716     Lambda,
4717     Friend,
4718     OtherMember,
4719     Invalid,
4720   } Kind = None;
4721   SourceRange Range;
4722 
4723   explicit operator bool() { return Kind != None; }
4724 };
4725 }
4726 
4727 /// Determine whether a class is C-like, according to the rules of C++
4728 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4729 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4730   if (RD->isInvalidDecl())
4731     return {NonCLikeKind::Invalid, {}};
4732 
4733   // C++ [dcl.typedef]p9: [P1766R1]
4734   //   An unnamed class with a typedef name for linkage purposes shall not
4735   //
4736   //    -- have any base classes
4737   if (RD->getNumBases())
4738     return {NonCLikeKind::BaseClass,
4739             SourceRange(RD->bases_begin()->getBeginLoc(),
4740                         RD->bases_end()[-1].getEndLoc())};
4741   bool Invalid = false;
4742   for (Decl *D : RD->decls()) {
4743     // Don't complain about things we already diagnosed.
4744     if (D->isInvalidDecl()) {
4745       Invalid = true;
4746       continue;
4747     }
4748 
4749     //  -- have any [...] default member initializers
4750     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4751       if (FD->hasInClassInitializer()) {
4752         auto *Init = FD->getInClassInitializer();
4753         return {NonCLikeKind::DefaultMemberInit,
4754                 Init ? Init->getSourceRange() : D->getSourceRange()};
4755       }
4756       continue;
4757     }
4758 
4759     // FIXME: We don't allow friend declarations. This violates the wording of
4760     // P1766, but not the intent.
4761     if (isa<FriendDecl>(D))
4762       return {NonCLikeKind::Friend, D->getSourceRange()};
4763 
4764     //  -- declare any members other than non-static data members, member
4765     //     enumerations, or member classes,
4766     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4767         isa<EnumDecl>(D))
4768       continue;
4769     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4770     if (!MemberRD) {
4771       if (D->isImplicit())
4772         continue;
4773       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4774     }
4775 
4776     //  -- contain a lambda-expression,
4777     if (MemberRD->isLambda())
4778       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4779 
4780     //  and all member classes shall also satisfy these requirements
4781     //  (recursively).
4782     if (MemberRD->isThisDeclarationADefinition()) {
4783       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4784         return Kind;
4785     }
4786   }
4787 
4788   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4789 }
4790 
4791 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4792                                         TypedefNameDecl *NewTD) {
4793   if (TagFromDeclSpec->isInvalidDecl())
4794     return;
4795 
4796   // Do nothing if the tag already has a name for linkage purposes.
4797   if (TagFromDeclSpec->hasNameForLinkage())
4798     return;
4799 
4800   // A well-formed anonymous tag must always be a TUK_Definition.
4801   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4802 
4803   // The type must match the tag exactly;  no qualifiers allowed.
4804   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4805                            Context.getTagDeclType(TagFromDeclSpec))) {
4806     if (getLangOpts().CPlusPlus)
4807       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4808     return;
4809   }
4810 
4811   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4812   //   An unnamed class with a typedef name for linkage purposes shall [be
4813   //   C-like].
4814   //
4815   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4816   // shouldn't happen, but there are constructs that the language rule doesn't
4817   // disallow for which we can't reasonably avoid computing linkage early.
4818   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4819   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4820                              : NonCLikeKind();
4821   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4822   if (NonCLike || ChangesLinkage) {
4823     if (NonCLike.Kind == NonCLikeKind::Invalid)
4824       return;
4825 
4826     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4827     if (ChangesLinkage) {
4828       // If the linkage changes, we can't accept this as an extension.
4829       if (NonCLike.Kind == NonCLikeKind::None)
4830         DiagID = diag::err_typedef_changes_linkage;
4831       else
4832         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4833     }
4834 
4835     SourceLocation FixitLoc =
4836         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4837     llvm::SmallString<40> TextToInsert;
4838     TextToInsert += ' ';
4839     TextToInsert += NewTD->getIdentifier()->getName();
4840 
4841     Diag(FixitLoc, DiagID)
4842       << isa<TypeAliasDecl>(NewTD)
4843       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4844     if (NonCLike.Kind != NonCLikeKind::None) {
4845       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4846         << NonCLike.Kind - 1 << NonCLike.Range;
4847     }
4848     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4849       << NewTD << isa<TypeAliasDecl>(NewTD);
4850 
4851     if (ChangesLinkage)
4852       return;
4853   }
4854 
4855   // Otherwise, set this as the anon-decl typedef for the tag.
4856   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4857 }
4858 
4859 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4860   switch (T) {
4861   case DeclSpec::TST_class:
4862     return 0;
4863   case DeclSpec::TST_struct:
4864     return 1;
4865   case DeclSpec::TST_interface:
4866     return 2;
4867   case DeclSpec::TST_union:
4868     return 3;
4869   case DeclSpec::TST_enum:
4870     return 4;
4871   default:
4872     llvm_unreachable("unexpected type specifier");
4873   }
4874 }
4875 
4876 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4877 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4878 /// parameters to cope with template friend declarations.
4879 Decl *
4880 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4881                                  MultiTemplateParamsArg TemplateParams,
4882                                  bool IsExplicitInstantiation,
4883                                  RecordDecl *&AnonRecord) {
4884   Decl *TagD = nullptr;
4885   TagDecl *Tag = nullptr;
4886   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4887       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4888       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4889       DS.getTypeSpecType() == DeclSpec::TST_union ||
4890       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4891     TagD = DS.getRepAsDecl();
4892 
4893     if (!TagD) // We probably had an error
4894       return nullptr;
4895 
4896     // Note that the above type specs guarantee that the
4897     // type rep is a Decl, whereas in many of the others
4898     // it's a Type.
4899     if (isa<TagDecl>(TagD))
4900       Tag = cast<TagDecl>(TagD);
4901     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4902       Tag = CTD->getTemplatedDecl();
4903   }
4904 
4905   if (Tag) {
4906     handleTagNumbering(Tag, S);
4907     Tag->setFreeStanding();
4908     if (Tag->isInvalidDecl())
4909       return Tag;
4910   }
4911 
4912   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4913     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4914     // or incomplete types shall not be restrict-qualified."
4915     if (TypeQuals & DeclSpec::TQ_restrict)
4916       Diag(DS.getRestrictSpecLoc(),
4917            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4918            << DS.getSourceRange();
4919   }
4920 
4921   if (DS.isInlineSpecified())
4922     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4923         << getLangOpts().CPlusPlus17;
4924 
4925   if (DS.hasConstexprSpecifier()) {
4926     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4927     // and definitions of functions and variables.
4928     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4929     // the declaration of a function or function template
4930     if (Tag)
4931       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4932           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4933           << static_cast<int>(DS.getConstexprSpecifier());
4934     else
4935       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4936           << static_cast<int>(DS.getConstexprSpecifier());
4937     // Don't emit warnings after this error.
4938     return TagD;
4939   }
4940 
4941   DiagnoseFunctionSpecifiers(DS);
4942 
4943   if (DS.isFriendSpecified()) {
4944     // If we're dealing with a decl but not a TagDecl, assume that
4945     // whatever routines created it handled the friendship aspect.
4946     if (TagD && !Tag)
4947       return nullptr;
4948     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4949   }
4950 
4951   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4952   bool IsExplicitSpecialization =
4953     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4954   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4955       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4956       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4957     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4958     // nested-name-specifier unless it is an explicit instantiation
4959     // or an explicit specialization.
4960     //
4961     // FIXME: We allow class template partial specializations here too, per the
4962     // obvious intent of DR1819.
4963     //
4964     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4965     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4966         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4967     return nullptr;
4968   }
4969 
4970   // Track whether this decl-specifier declares anything.
4971   bool DeclaresAnything = true;
4972 
4973   // Handle anonymous struct definitions.
4974   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4975     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4976         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4977       if (getLangOpts().CPlusPlus ||
4978           Record->getDeclContext()->isRecord()) {
4979         // If CurContext is a DeclContext that can contain statements,
4980         // RecursiveASTVisitor won't visit the decls that
4981         // BuildAnonymousStructOrUnion() will put into CurContext.
4982         // Also store them here so that they can be part of the
4983         // DeclStmt that gets created in this case.
4984         // FIXME: Also return the IndirectFieldDecls created by
4985         // BuildAnonymousStructOr union, for the same reason?
4986         if (CurContext->isFunctionOrMethod())
4987           AnonRecord = Record;
4988         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4989                                            Context.getPrintingPolicy());
4990       }
4991 
4992       DeclaresAnything = false;
4993     }
4994   }
4995 
4996   // C11 6.7.2.1p2:
4997   //   A struct-declaration that does not declare an anonymous structure or
4998   //   anonymous union shall contain a struct-declarator-list.
4999   //
5000   // This rule also existed in C89 and C99; the grammar for struct-declaration
5001   // did not permit a struct-declaration without a struct-declarator-list.
5002   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5003       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5004     // Check for Microsoft C extension: anonymous struct/union member.
5005     // Handle 2 kinds of anonymous struct/union:
5006     //   struct STRUCT;
5007     //   union UNION;
5008     // and
5009     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5010     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5011     if ((Tag && Tag->getDeclName()) ||
5012         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5013       RecordDecl *Record = nullptr;
5014       if (Tag)
5015         Record = dyn_cast<RecordDecl>(Tag);
5016       else if (const RecordType *RT =
5017                    DS.getRepAsType().get()->getAsStructureType())
5018         Record = RT->getDecl();
5019       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5020         Record = UT->getDecl();
5021 
5022       if (Record && getLangOpts().MicrosoftExt) {
5023         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5024             << Record->isUnion() << DS.getSourceRange();
5025         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5026       }
5027 
5028       DeclaresAnything = false;
5029     }
5030   }
5031 
5032   // Skip all the checks below if we have a type error.
5033   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5034       (TagD && TagD->isInvalidDecl()))
5035     return TagD;
5036 
5037   if (getLangOpts().CPlusPlus &&
5038       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5039     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5040       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5041           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5042         DeclaresAnything = false;
5043 
5044   if (!DS.isMissingDeclaratorOk()) {
5045     // Customize diagnostic for a typedef missing a name.
5046     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5047       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5048           << DS.getSourceRange();
5049     else
5050       DeclaresAnything = false;
5051   }
5052 
5053   if (DS.isModulePrivateSpecified() &&
5054       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5055     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5056       << Tag->getTagKind()
5057       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5058 
5059   ActOnDocumentableDecl(TagD);
5060 
5061   // C 6.7/2:
5062   //   A declaration [...] shall declare at least a declarator [...], a tag,
5063   //   or the members of an enumeration.
5064   // C++ [dcl.dcl]p3:
5065   //   [If there are no declarators], and except for the declaration of an
5066   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5067   //   names into the program, or shall redeclare a name introduced by a
5068   //   previous declaration.
5069   if (!DeclaresAnything) {
5070     // In C, we allow this as a (popular) extension / bug. Don't bother
5071     // producing further diagnostics for redundant qualifiers after this.
5072     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5073                                ? diag::err_no_declarators
5074                                : diag::ext_no_declarators)
5075         << DS.getSourceRange();
5076     return TagD;
5077   }
5078 
5079   // C++ [dcl.stc]p1:
5080   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5081   //   init-declarator-list of the declaration shall not be empty.
5082   // C++ [dcl.fct.spec]p1:
5083   //   If a cv-qualifier appears in a decl-specifier-seq, the
5084   //   init-declarator-list of the declaration shall not be empty.
5085   //
5086   // Spurious qualifiers here appear to be valid in C.
5087   unsigned DiagID = diag::warn_standalone_specifier;
5088   if (getLangOpts().CPlusPlus)
5089     DiagID = diag::ext_standalone_specifier;
5090 
5091   // Note that a linkage-specification sets a storage class, but
5092   // 'extern "C" struct foo;' is actually valid and not theoretically
5093   // useless.
5094   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5095     if (SCS == DeclSpec::SCS_mutable)
5096       // Since mutable is not a viable storage class specifier in C, there is
5097       // no reason to treat it as an extension. Instead, diagnose as an error.
5098       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5099     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5100       Diag(DS.getStorageClassSpecLoc(), DiagID)
5101         << DeclSpec::getSpecifierName(SCS);
5102   }
5103 
5104   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5105     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5106       << DeclSpec::getSpecifierName(TSCS);
5107   if (DS.getTypeQualifiers()) {
5108     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5109       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5110     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5111       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5112     // Restrict is covered above.
5113     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5114       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5115     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5116       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5117   }
5118 
5119   // Warn about ignored type attributes, for example:
5120   // __attribute__((aligned)) struct A;
5121   // Attributes should be placed after tag to apply to type declaration.
5122   if (!DS.getAttributes().empty()) {
5123     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5124     if (TypeSpecType == DeclSpec::TST_class ||
5125         TypeSpecType == DeclSpec::TST_struct ||
5126         TypeSpecType == DeclSpec::TST_interface ||
5127         TypeSpecType == DeclSpec::TST_union ||
5128         TypeSpecType == DeclSpec::TST_enum) {
5129       for (const ParsedAttr &AL : DS.getAttributes())
5130         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5131             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5132     }
5133   }
5134 
5135   return TagD;
5136 }
5137 
5138 /// We are trying to inject an anonymous member into the given scope;
5139 /// check if there's an existing declaration that can't be overloaded.
5140 ///
5141 /// \return true if this is a forbidden redeclaration
5142 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5143                                          Scope *S,
5144                                          DeclContext *Owner,
5145                                          DeclarationName Name,
5146                                          SourceLocation NameLoc,
5147                                          bool IsUnion) {
5148   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5149                  Sema::ForVisibleRedeclaration);
5150   if (!SemaRef.LookupName(R, S)) return false;
5151 
5152   // Pick a representative declaration.
5153   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5154   assert(PrevDecl && "Expected a non-null Decl");
5155 
5156   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5157     return false;
5158 
5159   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5160     << IsUnion << Name;
5161   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5162 
5163   return true;
5164 }
5165 
5166 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5167 /// anonymous struct or union AnonRecord into the owning context Owner
5168 /// and scope S. This routine will be invoked just after we realize
5169 /// that an unnamed union or struct is actually an anonymous union or
5170 /// struct, e.g.,
5171 ///
5172 /// @code
5173 /// union {
5174 ///   int i;
5175 ///   float f;
5176 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5177 ///    // f into the surrounding scope.x
5178 /// @endcode
5179 ///
5180 /// This routine is recursive, injecting the names of nested anonymous
5181 /// structs/unions into the owning context and scope as well.
5182 static bool
5183 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5184                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5185                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5186   bool Invalid = false;
5187 
5188   // Look every FieldDecl and IndirectFieldDecl with a name.
5189   for (auto *D : AnonRecord->decls()) {
5190     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5191         cast<NamedDecl>(D)->getDeclName()) {
5192       ValueDecl *VD = cast<ValueDecl>(D);
5193       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5194                                        VD->getLocation(),
5195                                        AnonRecord->isUnion())) {
5196         // C++ [class.union]p2:
5197         //   The names of the members of an anonymous union shall be
5198         //   distinct from the names of any other entity in the
5199         //   scope in which the anonymous union is declared.
5200         Invalid = true;
5201       } else {
5202         // C++ [class.union]p2:
5203         //   For the purpose of name lookup, after the anonymous union
5204         //   definition, the members of the anonymous union are
5205         //   considered to have been defined in the scope in which the
5206         //   anonymous union is declared.
5207         unsigned OldChainingSize = Chaining.size();
5208         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5209           Chaining.append(IF->chain_begin(), IF->chain_end());
5210         else
5211           Chaining.push_back(VD);
5212 
5213         assert(Chaining.size() >= 2);
5214         NamedDecl **NamedChain =
5215           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5216         for (unsigned i = 0; i < Chaining.size(); i++)
5217           NamedChain[i] = Chaining[i];
5218 
5219         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5220             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5221             VD->getType(), {NamedChain, Chaining.size()});
5222 
5223         for (const auto *Attr : VD->attrs())
5224           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5225 
5226         IndirectField->setAccess(AS);
5227         IndirectField->setImplicit();
5228         SemaRef.PushOnScopeChains(IndirectField, S);
5229 
5230         // That includes picking up the appropriate access specifier.
5231         if (AS != AS_none) IndirectField->setAccess(AS);
5232 
5233         Chaining.resize(OldChainingSize);
5234       }
5235     }
5236   }
5237 
5238   return Invalid;
5239 }
5240 
5241 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5242 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5243 /// illegal input values are mapped to SC_None.
5244 static StorageClass
5245 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5246   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5247   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5248          "Parser allowed 'typedef' as storage class VarDecl.");
5249   switch (StorageClassSpec) {
5250   case DeclSpec::SCS_unspecified:    return SC_None;
5251   case DeclSpec::SCS_extern:
5252     if (DS.isExternInLinkageSpec())
5253       return SC_None;
5254     return SC_Extern;
5255   case DeclSpec::SCS_static:         return SC_Static;
5256   case DeclSpec::SCS_auto:           return SC_Auto;
5257   case DeclSpec::SCS_register:       return SC_Register;
5258   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5259     // Illegal SCSs map to None: error reporting is up to the caller.
5260   case DeclSpec::SCS_mutable:        // Fall through.
5261   case DeclSpec::SCS_typedef:        return SC_None;
5262   }
5263   llvm_unreachable("unknown storage class specifier");
5264 }
5265 
5266 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5267   assert(Record->hasInClassInitializer());
5268 
5269   for (const auto *I : Record->decls()) {
5270     const auto *FD = dyn_cast<FieldDecl>(I);
5271     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5272       FD = IFD->getAnonField();
5273     if (FD && FD->hasInClassInitializer())
5274       return FD->getLocation();
5275   }
5276 
5277   llvm_unreachable("couldn't find in-class initializer");
5278 }
5279 
5280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5281                                       SourceLocation DefaultInitLoc) {
5282   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5283     return;
5284 
5285   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5286   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5287 }
5288 
5289 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5290                                       CXXRecordDecl *AnonUnion) {
5291   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5292     return;
5293 
5294   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5295 }
5296 
5297 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5298 /// anonymous structure or union. Anonymous unions are a C++ feature
5299 /// (C++ [class.union]) and a C11 feature; anonymous structures
5300 /// are a C11 feature and GNU C++ extension.
5301 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5302                                         AccessSpecifier AS,
5303                                         RecordDecl *Record,
5304                                         const PrintingPolicy &Policy) {
5305   DeclContext *Owner = Record->getDeclContext();
5306 
5307   // Diagnose whether this anonymous struct/union is an extension.
5308   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5309     Diag(Record->getLocation(), diag::ext_anonymous_union);
5310   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5311     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5312   else if (!Record->isUnion() && !getLangOpts().C11)
5313     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5314 
5315   // C and C++ require different kinds of checks for anonymous
5316   // structs/unions.
5317   bool Invalid = false;
5318   if (getLangOpts().CPlusPlus) {
5319     const char *PrevSpec = nullptr;
5320     if (Record->isUnion()) {
5321       // C++ [class.union]p6:
5322       // C++17 [class.union.anon]p2:
5323       //   Anonymous unions declared in a named namespace or in the
5324       //   global namespace shall be declared static.
5325       unsigned DiagID;
5326       DeclContext *OwnerScope = Owner->getRedeclContext();
5327       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5328           (OwnerScope->isTranslationUnit() ||
5329            (OwnerScope->isNamespace() &&
5330             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5331         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5332           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5333 
5334         // Recover by adding 'static'.
5335         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5336                                PrevSpec, DiagID, Policy);
5337       }
5338       // C++ [class.union]p6:
5339       //   A storage class is not allowed in a declaration of an
5340       //   anonymous union in a class scope.
5341       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5342                isa<RecordDecl>(Owner)) {
5343         Diag(DS.getStorageClassSpecLoc(),
5344              diag::err_anonymous_union_with_storage_spec)
5345           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5346 
5347         // Recover by removing the storage specifier.
5348         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5349                                SourceLocation(),
5350                                PrevSpec, DiagID, Context.getPrintingPolicy());
5351       }
5352     }
5353 
5354     // Ignore const/volatile/restrict qualifiers.
5355     if (DS.getTypeQualifiers()) {
5356       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5357         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5358           << Record->isUnion() << "const"
5359           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5360       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5361         Diag(DS.getVolatileSpecLoc(),
5362              diag::ext_anonymous_struct_union_qualified)
5363           << Record->isUnion() << "volatile"
5364           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5365       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5366         Diag(DS.getRestrictSpecLoc(),
5367              diag::ext_anonymous_struct_union_qualified)
5368           << Record->isUnion() << "restrict"
5369           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5370       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5371         Diag(DS.getAtomicSpecLoc(),
5372              diag::ext_anonymous_struct_union_qualified)
5373           << Record->isUnion() << "_Atomic"
5374           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5375       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5376         Diag(DS.getUnalignedSpecLoc(),
5377              diag::ext_anonymous_struct_union_qualified)
5378           << Record->isUnion() << "__unaligned"
5379           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5380 
5381       DS.ClearTypeQualifiers();
5382     }
5383 
5384     // C++ [class.union]p2:
5385     //   The member-specification of an anonymous union shall only
5386     //   define non-static data members. [Note: nested types and
5387     //   functions cannot be declared within an anonymous union. ]
5388     for (auto *Mem : Record->decls()) {
5389       // Ignore invalid declarations; we already diagnosed them.
5390       if (Mem->isInvalidDecl())
5391         continue;
5392 
5393       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5394         // C++ [class.union]p3:
5395         //   An anonymous union shall not have private or protected
5396         //   members (clause 11).
5397         assert(FD->getAccess() != AS_none);
5398         if (FD->getAccess() != AS_public) {
5399           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5400             << Record->isUnion() << (FD->getAccess() == AS_protected);
5401           Invalid = true;
5402         }
5403 
5404         // C++ [class.union]p1
5405         //   An object of a class with a non-trivial constructor, a non-trivial
5406         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5407         //   assignment operator cannot be a member of a union, nor can an
5408         //   array of such objects.
5409         if (CheckNontrivialField(FD))
5410           Invalid = true;
5411       } else if (Mem->isImplicit()) {
5412         // Any implicit members are fine.
5413       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5414         // This is a type that showed up in an
5415         // elaborated-type-specifier inside the anonymous struct or
5416         // union, but which actually declares a type outside of the
5417         // anonymous struct or union. It's okay.
5418       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5419         if (!MemRecord->isAnonymousStructOrUnion() &&
5420             MemRecord->getDeclName()) {
5421           // Visual C++ allows type definition in anonymous struct or union.
5422           if (getLangOpts().MicrosoftExt)
5423             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5424               << Record->isUnion();
5425           else {
5426             // This is a nested type declaration.
5427             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5428               << Record->isUnion();
5429             Invalid = true;
5430           }
5431         } else {
5432           // This is an anonymous type definition within another anonymous type.
5433           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5434           // not part of standard C++.
5435           Diag(MemRecord->getLocation(),
5436                diag::ext_anonymous_record_with_anonymous_type)
5437             << Record->isUnion();
5438         }
5439       } else if (isa<AccessSpecDecl>(Mem)) {
5440         // Any access specifier is fine.
5441       } else if (isa<StaticAssertDecl>(Mem)) {
5442         // In C++1z, static_assert declarations are also fine.
5443       } else {
5444         // We have something that isn't a non-static data
5445         // member. Complain about it.
5446         unsigned DK = diag::err_anonymous_record_bad_member;
5447         if (isa<TypeDecl>(Mem))
5448           DK = diag::err_anonymous_record_with_type;
5449         else if (isa<FunctionDecl>(Mem))
5450           DK = diag::err_anonymous_record_with_function;
5451         else if (isa<VarDecl>(Mem))
5452           DK = diag::err_anonymous_record_with_static;
5453 
5454         // Visual C++ allows type definition in anonymous struct or union.
5455         if (getLangOpts().MicrosoftExt &&
5456             DK == diag::err_anonymous_record_with_type)
5457           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5458             << Record->isUnion();
5459         else {
5460           Diag(Mem->getLocation(), DK) << Record->isUnion();
5461           Invalid = true;
5462         }
5463       }
5464     }
5465 
5466     // C++11 [class.union]p8 (DR1460):
5467     //   At most one variant member of a union may have a
5468     //   brace-or-equal-initializer.
5469     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5470         Owner->isRecord())
5471       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5472                                 cast<CXXRecordDecl>(Record));
5473   }
5474 
5475   if (!Record->isUnion() && !Owner->isRecord()) {
5476     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5477       << getLangOpts().CPlusPlus;
5478     Invalid = true;
5479   }
5480 
5481   // C++ [dcl.dcl]p3:
5482   //   [If there are no declarators], and except for the declaration of an
5483   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5484   //   names into the program
5485   // C++ [class.mem]p2:
5486   //   each such member-declaration shall either declare at least one member
5487   //   name of the class or declare at least one unnamed bit-field
5488   //
5489   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5490   if (getLangOpts().CPlusPlus && Record->field_empty())
5491     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5492 
5493   // Mock up a declarator.
5494   Declarator Dc(DS, DeclaratorContext::Member);
5495   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5496   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5497 
5498   // Create a declaration for this anonymous struct/union.
5499   NamedDecl *Anon = nullptr;
5500   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5501     Anon = FieldDecl::Create(
5502         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5503         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5504         /*BitWidth=*/nullptr, /*Mutable=*/false,
5505         /*InitStyle=*/ICIS_NoInit);
5506     Anon->setAccess(AS);
5507     ProcessDeclAttributes(S, Anon, Dc);
5508 
5509     if (getLangOpts().CPlusPlus)
5510       FieldCollector->Add(cast<FieldDecl>(Anon));
5511   } else {
5512     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5513     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5514     if (SCSpec == DeclSpec::SCS_mutable) {
5515       // mutable can only appear on non-static class members, so it's always
5516       // an error here
5517       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5518       Invalid = true;
5519       SC = SC_None;
5520     }
5521 
5522     assert(DS.getAttributes().empty() && "No attribute expected");
5523     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5524                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5525                            Context.getTypeDeclType(Record), TInfo, SC);
5526 
5527     // Default-initialize the implicit variable. This initialization will be
5528     // trivial in almost all cases, except if a union member has an in-class
5529     // initializer:
5530     //   union { int n = 0; };
5531     ActOnUninitializedDecl(Anon);
5532   }
5533   Anon->setImplicit();
5534 
5535   // Mark this as an anonymous struct/union type.
5536   Record->setAnonymousStructOrUnion(true);
5537 
5538   // Add the anonymous struct/union object to the current
5539   // context. We'll be referencing this object when we refer to one of
5540   // its members.
5541   Owner->addDecl(Anon);
5542 
5543   // Inject the members of the anonymous struct/union into the owning
5544   // context and into the identifier resolver chain for name lookup
5545   // purposes.
5546   SmallVector<NamedDecl*, 2> Chain;
5547   Chain.push_back(Anon);
5548 
5549   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5550     Invalid = true;
5551 
5552   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5553     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5554       MangleNumberingContext *MCtx;
5555       Decl *ManglingContextDecl;
5556       std::tie(MCtx, ManglingContextDecl) =
5557           getCurrentMangleNumberContext(NewVD->getDeclContext());
5558       if (MCtx) {
5559         Context.setManglingNumber(
5560             NewVD, MCtx->getManglingNumber(
5561                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5562         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5563       }
5564     }
5565   }
5566 
5567   if (Invalid)
5568     Anon->setInvalidDecl();
5569 
5570   return Anon;
5571 }
5572 
5573 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5574 /// Microsoft C anonymous structure.
5575 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5576 /// Example:
5577 ///
5578 /// struct A { int a; };
5579 /// struct B { struct A; int b; };
5580 ///
5581 /// void foo() {
5582 ///   B var;
5583 ///   var.a = 3;
5584 /// }
5585 ///
5586 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5587                                            RecordDecl *Record) {
5588   assert(Record && "expected a record!");
5589 
5590   // Mock up a declarator.
5591   Declarator Dc(DS, DeclaratorContext::TypeName);
5592   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5593   assert(TInfo && "couldn't build declarator info for anonymous struct");
5594 
5595   auto *ParentDecl = cast<RecordDecl>(CurContext);
5596   QualType RecTy = Context.getTypeDeclType(Record);
5597 
5598   // Create a declaration for this anonymous struct.
5599   NamedDecl *Anon =
5600       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5601                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5602                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5603                         /*InitStyle=*/ICIS_NoInit);
5604   Anon->setImplicit();
5605 
5606   // Add the anonymous struct object to the current context.
5607   CurContext->addDecl(Anon);
5608 
5609   // Inject the members of the anonymous struct into the current
5610   // context and into the identifier resolver chain for name lookup
5611   // purposes.
5612   SmallVector<NamedDecl*, 2> Chain;
5613   Chain.push_back(Anon);
5614 
5615   RecordDecl *RecordDef = Record->getDefinition();
5616   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5617                                diag::err_field_incomplete_or_sizeless) ||
5618       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5619                                           AS_none, Chain)) {
5620     Anon->setInvalidDecl();
5621     ParentDecl->setInvalidDecl();
5622   }
5623 
5624   return Anon;
5625 }
5626 
5627 /// GetNameForDeclarator - Determine the full declaration name for the
5628 /// given Declarator.
5629 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5630   return GetNameFromUnqualifiedId(D.getName());
5631 }
5632 
5633 /// Retrieves the declaration name from a parsed unqualified-id.
5634 DeclarationNameInfo
5635 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5636   DeclarationNameInfo NameInfo;
5637   NameInfo.setLoc(Name.StartLocation);
5638 
5639   switch (Name.getKind()) {
5640 
5641   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5642   case UnqualifiedIdKind::IK_Identifier:
5643     NameInfo.setName(Name.Identifier);
5644     return NameInfo;
5645 
5646   case UnqualifiedIdKind::IK_DeductionGuideName: {
5647     // C++ [temp.deduct.guide]p3:
5648     //   The simple-template-id shall name a class template specialization.
5649     //   The template-name shall be the same identifier as the template-name
5650     //   of the simple-template-id.
5651     // These together intend to imply that the template-name shall name a
5652     // class template.
5653     // FIXME: template<typename T> struct X {};
5654     //        template<typename T> using Y = X<T>;
5655     //        Y(int) -> Y<int>;
5656     //   satisfies these rules but does not name a class template.
5657     TemplateName TN = Name.TemplateName.get().get();
5658     auto *Template = TN.getAsTemplateDecl();
5659     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5660       Diag(Name.StartLocation,
5661            diag::err_deduction_guide_name_not_class_template)
5662         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5663       if (Template)
5664         Diag(Template->getLocation(), diag::note_template_decl_here);
5665       return DeclarationNameInfo();
5666     }
5667 
5668     NameInfo.setName(
5669         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5670     return NameInfo;
5671   }
5672 
5673   case UnqualifiedIdKind::IK_OperatorFunctionId:
5674     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5675                                            Name.OperatorFunctionId.Operator));
5676     NameInfo.setCXXOperatorNameRange(SourceRange(
5677         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5678     return NameInfo;
5679 
5680   case UnqualifiedIdKind::IK_LiteralOperatorId:
5681     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5682                                                            Name.Identifier));
5683     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5684     return NameInfo;
5685 
5686   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5687     TypeSourceInfo *TInfo;
5688     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5689     if (Ty.isNull())
5690       return DeclarationNameInfo();
5691     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5692                                                Context.getCanonicalType(Ty)));
5693     NameInfo.setNamedTypeInfo(TInfo);
5694     return NameInfo;
5695   }
5696 
5697   case UnqualifiedIdKind::IK_ConstructorName: {
5698     TypeSourceInfo *TInfo;
5699     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5700     if (Ty.isNull())
5701       return DeclarationNameInfo();
5702     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5703                                               Context.getCanonicalType(Ty)));
5704     NameInfo.setNamedTypeInfo(TInfo);
5705     return NameInfo;
5706   }
5707 
5708   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5709     // In well-formed code, we can only have a constructor
5710     // template-id that refers to the current context, so go there
5711     // to find the actual type being constructed.
5712     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5713     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5714       return DeclarationNameInfo();
5715 
5716     // Determine the type of the class being constructed.
5717     QualType CurClassType = Context.getTypeDeclType(CurClass);
5718 
5719     // FIXME: Check two things: that the template-id names the same type as
5720     // CurClassType, and that the template-id does not occur when the name
5721     // was qualified.
5722 
5723     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5724                                     Context.getCanonicalType(CurClassType)));
5725     // FIXME: should we retrieve TypeSourceInfo?
5726     NameInfo.setNamedTypeInfo(nullptr);
5727     return NameInfo;
5728   }
5729 
5730   case UnqualifiedIdKind::IK_DestructorName: {
5731     TypeSourceInfo *TInfo;
5732     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5733     if (Ty.isNull())
5734       return DeclarationNameInfo();
5735     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5736                                               Context.getCanonicalType(Ty)));
5737     NameInfo.setNamedTypeInfo(TInfo);
5738     return NameInfo;
5739   }
5740 
5741   case UnqualifiedIdKind::IK_TemplateId: {
5742     TemplateName TName = Name.TemplateId->Template.get();
5743     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5744     return Context.getNameForTemplate(TName, TNameLoc);
5745   }
5746 
5747   } // switch (Name.getKind())
5748 
5749   llvm_unreachable("Unknown name kind");
5750 }
5751 
5752 static QualType getCoreType(QualType Ty) {
5753   do {
5754     if (Ty->isPointerType() || Ty->isReferenceType())
5755       Ty = Ty->getPointeeType();
5756     else if (Ty->isArrayType())
5757       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5758     else
5759       return Ty.withoutLocalFastQualifiers();
5760   } while (true);
5761 }
5762 
5763 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5764 /// and Definition have "nearly" matching parameters. This heuristic is
5765 /// used to improve diagnostics in the case where an out-of-line function
5766 /// definition doesn't match any declaration within the class or namespace.
5767 /// Also sets Params to the list of indices to the parameters that differ
5768 /// between the declaration and the definition. If hasSimilarParameters
5769 /// returns true and Params is empty, then all of the parameters match.
5770 static bool hasSimilarParameters(ASTContext &Context,
5771                                      FunctionDecl *Declaration,
5772                                      FunctionDecl *Definition,
5773                                      SmallVectorImpl<unsigned> &Params) {
5774   Params.clear();
5775   if (Declaration->param_size() != Definition->param_size())
5776     return false;
5777   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5778     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5779     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5780 
5781     // The parameter types are identical
5782     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5783       continue;
5784 
5785     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5786     QualType DefParamBaseTy = getCoreType(DefParamTy);
5787     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5788     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5789 
5790     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5791         (DeclTyName && DeclTyName == DefTyName))
5792       Params.push_back(Idx);
5793     else  // The two parameters aren't even close
5794       return false;
5795   }
5796 
5797   return true;
5798 }
5799 
5800 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5801 /// declarator needs to be rebuilt in the current instantiation.
5802 /// Any bits of declarator which appear before the name are valid for
5803 /// consideration here.  That's specifically the type in the decl spec
5804 /// and the base type in any member-pointer chunks.
5805 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5806                                                     DeclarationName Name) {
5807   // The types we specifically need to rebuild are:
5808   //   - typenames, typeofs, and decltypes
5809   //   - types which will become injected class names
5810   // Of course, we also need to rebuild any type referencing such a
5811   // type.  It's safest to just say "dependent", but we call out a
5812   // few cases here.
5813 
5814   DeclSpec &DS = D.getMutableDeclSpec();
5815   switch (DS.getTypeSpecType()) {
5816   case DeclSpec::TST_typename:
5817   case DeclSpec::TST_typeofType:
5818   case DeclSpec::TST_underlyingType:
5819   case DeclSpec::TST_atomic: {
5820     // Grab the type from the parser.
5821     TypeSourceInfo *TSI = nullptr;
5822     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5823     if (T.isNull() || !T->isInstantiationDependentType()) break;
5824 
5825     // Make sure there's a type source info.  This isn't really much
5826     // of a waste; most dependent types should have type source info
5827     // attached already.
5828     if (!TSI)
5829       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5830 
5831     // Rebuild the type in the current instantiation.
5832     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5833     if (!TSI) return true;
5834 
5835     // Store the new type back in the decl spec.
5836     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5837     DS.UpdateTypeRep(LocType);
5838     break;
5839   }
5840 
5841   case DeclSpec::TST_decltype:
5842   case DeclSpec::TST_typeofExpr: {
5843     Expr *E = DS.getRepAsExpr();
5844     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5845     if (Result.isInvalid()) return true;
5846     DS.UpdateExprRep(Result.get());
5847     break;
5848   }
5849 
5850   default:
5851     // Nothing to do for these decl specs.
5852     break;
5853   }
5854 
5855   // It doesn't matter what order we do this in.
5856   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5857     DeclaratorChunk &Chunk = D.getTypeObject(I);
5858 
5859     // The only type information in the declarator which can come
5860     // before the declaration name is the base type of a member
5861     // pointer.
5862     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5863       continue;
5864 
5865     // Rebuild the scope specifier in-place.
5866     CXXScopeSpec &SS = Chunk.Mem.Scope();
5867     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5868       return true;
5869   }
5870 
5871   return false;
5872 }
5873 
5874 /// Returns true if the declaration is declared in a system header or from a
5875 /// system macro.
5876 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5877   return SM.isInSystemHeader(D->getLocation()) ||
5878          SM.isInSystemMacro(D->getLocation());
5879 }
5880 
5881 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5882   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5883   // of system decl.
5884   if (D->getPreviousDecl() || D->isImplicit())
5885     return;
5886   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5887   if (Status != ReservedIdentifierStatus::NotReserved &&
5888       !isFromSystemHeader(Context.getSourceManager(), D)) {
5889     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5890         << D << static_cast<int>(Status);
5891   }
5892 }
5893 
5894 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5895   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5896   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5897 
5898   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5899       Dcl && Dcl->getDeclContext()->isFileContext())
5900     Dcl->setTopLevelDeclInObjCContainer();
5901 
5902   return Dcl;
5903 }
5904 
5905 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5906 ///   If T is the name of a class, then each of the following shall have a
5907 ///   name different from T:
5908 ///     - every static data member of class T;
5909 ///     - every member function of class T
5910 ///     - every member of class T that is itself a type;
5911 /// \returns true if the declaration name violates these rules.
5912 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5913                                    DeclarationNameInfo NameInfo) {
5914   DeclarationName Name = NameInfo.getName();
5915 
5916   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5917   while (Record && Record->isAnonymousStructOrUnion())
5918     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5919   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5920     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5921     return true;
5922   }
5923 
5924   return false;
5925 }
5926 
5927 /// Diagnose a declaration whose declarator-id has the given
5928 /// nested-name-specifier.
5929 ///
5930 /// \param SS The nested-name-specifier of the declarator-id.
5931 ///
5932 /// \param DC The declaration context to which the nested-name-specifier
5933 /// resolves.
5934 ///
5935 /// \param Name The name of the entity being declared.
5936 ///
5937 /// \param Loc The location of the name of the entity being declared.
5938 ///
5939 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5940 /// we're declaring an explicit / partial specialization / instantiation.
5941 ///
5942 /// \returns true if we cannot safely recover from this error, false otherwise.
5943 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5944                                         DeclarationName Name,
5945                                         SourceLocation Loc, bool IsTemplateId) {
5946   DeclContext *Cur = CurContext;
5947   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5948     Cur = Cur->getParent();
5949 
5950   // If the user provided a superfluous scope specifier that refers back to the
5951   // class in which the entity is already declared, diagnose and ignore it.
5952   //
5953   // class X {
5954   //   void X::f();
5955   // };
5956   //
5957   // Note, it was once ill-formed to give redundant qualification in all
5958   // contexts, but that rule was removed by DR482.
5959   if (Cur->Equals(DC)) {
5960     if (Cur->isRecord()) {
5961       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5962                                       : diag::err_member_extra_qualification)
5963         << Name << FixItHint::CreateRemoval(SS.getRange());
5964       SS.clear();
5965     } else {
5966       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5967     }
5968     return false;
5969   }
5970 
5971   // Check whether the qualifying scope encloses the scope of the original
5972   // declaration. For a template-id, we perform the checks in
5973   // CheckTemplateSpecializationScope.
5974   if (!Cur->Encloses(DC) && !IsTemplateId) {
5975     if (Cur->isRecord())
5976       Diag(Loc, diag::err_member_qualification)
5977         << Name << SS.getRange();
5978     else if (isa<TranslationUnitDecl>(DC))
5979       Diag(Loc, diag::err_invalid_declarator_global_scope)
5980         << Name << SS.getRange();
5981     else if (isa<FunctionDecl>(Cur))
5982       Diag(Loc, diag::err_invalid_declarator_in_function)
5983         << Name << SS.getRange();
5984     else if (isa<BlockDecl>(Cur))
5985       Diag(Loc, diag::err_invalid_declarator_in_block)
5986         << Name << SS.getRange();
5987     else if (isa<ExportDecl>(Cur)) {
5988       if (!isa<NamespaceDecl>(DC))
5989         Diag(Loc, diag::err_export_non_namespace_scope_name)
5990             << Name << SS.getRange();
5991       else
5992         // The cases that DC is not NamespaceDecl should be handled in
5993         // CheckRedeclarationExported.
5994         return false;
5995     } else
5996       Diag(Loc, diag::err_invalid_declarator_scope)
5997       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5998 
5999     return true;
6000   }
6001 
6002   if (Cur->isRecord()) {
6003     // Cannot qualify members within a class.
6004     Diag(Loc, diag::err_member_qualification)
6005       << Name << SS.getRange();
6006     SS.clear();
6007 
6008     // C++ constructors and destructors with incorrect scopes can break
6009     // our AST invariants by having the wrong underlying types. If
6010     // that's the case, then drop this declaration entirely.
6011     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6012          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6013         !Context.hasSameType(Name.getCXXNameType(),
6014                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6015       return true;
6016 
6017     return false;
6018   }
6019 
6020   // C++11 [dcl.meaning]p1:
6021   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6022   //   not begin with a decltype-specifer"
6023   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6024   while (SpecLoc.getPrefix())
6025     SpecLoc = SpecLoc.getPrefix();
6026   if (isa_and_nonnull<DecltypeType>(
6027           SpecLoc.getNestedNameSpecifier()->getAsType()))
6028     Diag(Loc, diag::err_decltype_in_declarator)
6029       << SpecLoc.getTypeLoc().getSourceRange();
6030 
6031   return false;
6032 }
6033 
6034 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6035                                   MultiTemplateParamsArg TemplateParamLists) {
6036   // TODO: consider using NameInfo for diagnostic.
6037   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6038   DeclarationName Name = NameInfo.getName();
6039 
6040   // All of these full declarators require an identifier.  If it doesn't have
6041   // one, the ParsedFreeStandingDeclSpec action should be used.
6042   if (D.isDecompositionDeclarator()) {
6043     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6044   } else if (!Name) {
6045     if (!D.isInvalidType())  // Reject this if we think it is valid.
6046       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6047           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6048     return nullptr;
6049   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6050     return nullptr;
6051 
6052   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6053   // we find one that is.
6054   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6055          (S->getFlags() & Scope::TemplateParamScope) != 0)
6056     S = S->getParent();
6057 
6058   DeclContext *DC = CurContext;
6059   if (D.getCXXScopeSpec().isInvalid())
6060     D.setInvalidType();
6061   else if (D.getCXXScopeSpec().isSet()) {
6062     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6063                                         UPPC_DeclarationQualifier))
6064       return nullptr;
6065 
6066     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6067     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6068     if (!DC || isa<EnumDecl>(DC)) {
6069       // If we could not compute the declaration context, it's because the
6070       // declaration context is dependent but does not refer to a class,
6071       // class template, or class template partial specialization. Complain
6072       // and return early, to avoid the coming semantic disaster.
6073       Diag(D.getIdentifierLoc(),
6074            diag::err_template_qualified_declarator_no_match)
6075         << D.getCXXScopeSpec().getScopeRep()
6076         << D.getCXXScopeSpec().getRange();
6077       return nullptr;
6078     }
6079     bool IsDependentContext = DC->isDependentContext();
6080 
6081     if (!IsDependentContext &&
6082         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6083       return nullptr;
6084 
6085     // If a class is incomplete, do not parse entities inside it.
6086     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6087       Diag(D.getIdentifierLoc(),
6088            diag::err_member_def_undefined_record)
6089         << Name << DC << D.getCXXScopeSpec().getRange();
6090       return nullptr;
6091     }
6092     if (!D.getDeclSpec().isFriendSpecified()) {
6093       if (diagnoseQualifiedDeclaration(
6094               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6095               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6096         if (DC->isRecord())
6097           return nullptr;
6098 
6099         D.setInvalidType();
6100       }
6101     }
6102 
6103     // Check whether we need to rebuild the type of the given
6104     // declaration in the current instantiation.
6105     if (EnteringContext && IsDependentContext &&
6106         TemplateParamLists.size() != 0) {
6107       ContextRAII SavedContext(*this, DC);
6108       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6109         D.setInvalidType();
6110     }
6111   }
6112 
6113   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6114   QualType R = TInfo->getType();
6115 
6116   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6117                                       UPPC_DeclarationType))
6118     D.setInvalidType();
6119 
6120   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6121                         forRedeclarationInCurContext());
6122 
6123   // See if this is a redefinition of a variable in the same scope.
6124   if (!D.getCXXScopeSpec().isSet()) {
6125     bool IsLinkageLookup = false;
6126     bool CreateBuiltins = false;
6127 
6128     // If the declaration we're planning to build will be a function
6129     // or object with linkage, then look for another declaration with
6130     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6131     //
6132     // If the declaration we're planning to build will be declared with
6133     // external linkage in the translation unit, create any builtin with
6134     // the same name.
6135     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6136       /* Do nothing*/;
6137     else if (CurContext->isFunctionOrMethod() &&
6138              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6139               R->isFunctionType())) {
6140       IsLinkageLookup = true;
6141       CreateBuiltins =
6142           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6143     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6144                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6145       CreateBuiltins = true;
6146 
6147     if (IsLinkageLookup) {
6148       Previous.clear(LookupRedeclarationWithLinkage);
6149       Previous.setRedeclarationKind(ForExternalRedeclaration);
6150     }
6151 
6152     LookupName(Previous, S, CreateBuiltins);
6153   } else { // Something like "int foo::x;"
6154     LookupQualifiedName(Previous, DC);
6155 
6156     // C++ [dcl.meaning]p1:
6157     //   When the declarator-id is qualified, the declaration shall refer to a
6158     //  previously declared member of the class or namespace to which the
6159     //  qualifier refers (or, in the case of a namespace, of an element of the
6160     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6161     //  thereof; [...]
6162     //
6163     // Note that we already checked the context above, and that we do not have
6164     // enough information to make sure that Previous contains the declaration
6165     // we want to match. For example, given:
6166     //
6167     //   class X {
6168     //     void f();
6169     //     void f(float);
6170     //   };
6171     //
6172     //   void X::f(int) { } // ill-formed
6173     //
6174     // In this case, Previous will point to the overload set
6175     // containing the two f's declared in X, but neither of them
6176     // matches.
6177 
6178     // C++ [dcl.meaning]p1:
6179     //   [...] the member shall not merely have been introduced by a
6180     //   using-declaration in the scope of the class or namespace nominated by
6181     //   the nested-name-specifier of the declarator-id.
6182     RemoveUsingDecls(Previous);
6183   }
6184 
6185   if (Previous.isSingleResult() &&
6186       Previous.getFoundDecl()->isTemplateParameter()) {
6187     // Maybe we will complain about the shadowed template parameter.
6188     if (!D.isInvalidType())
6189       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6190                                       Previous.getFoundDecl());
6191 
6192     // Just pretend that we didn't see the previous declaration.
6193     Previous.clear();
6194   }
6195 
6196   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6197     // Forget that the previous declaration is the injected-class-name.
6198     Previous.clear();
6199 
6200   // In C++, the previous declaration we find might be a tag type
6201   // (class or enum). In this case, the new declaration will hide the
6202   // tag type. Note that this applies to functions, function templates, and
6203   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6204   if (Previous.isSingleTagDecl() &&
6205       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6206       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6207     Previous.clear();
6208 
6209   // Check that there are no default arguments other than in the parameters
6210   // of a function declaration (C++ only).
6211   if (getLangOpts().CPlusPlus)
6212     CheckExtraCXXDefaultArguments(D);
6213 
6214   NamedDecl *New;
6215 
6216   bool AddToScope = true;
6217   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6218     if (TemplateParamLists.size()) {
6219       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6220       return nullptr;
6221     }
6222 
6223     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6224   } else if (R->isFunctionType()) {
6225     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6226                                   TemplateParamLists,
6227                                   AddToScope);
6228   } else {
6229     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6230                                   AddToScope);
6231   }
6232 
6233   if (!New)
6234     return nullptr;
6235 
6236   // If this has an identifier and is not a function template specialization,
6237   // add it to the scope stack.
6238   if (New->getDeclName() && AddToScope)
6239     PushOnScopeChains(New, S);
6240 
6241   if (isInOpenMPDeclareTargetContext())
6242     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6243 
6244   return New;
6245 }
6246 
6247 /// Helper method to turn variable array types into constant array
6248 /// types in certain situations which would otherwise be errors (for
6249 /// GCC compatibility).
6250 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6251                                                     ASTContext &Context,
6252                                                     bool &SizeIsNegative,
6253                                                     llvm::APSInt &Oversized) {
6254   // This method tries to turn a variable array into a constant
6255   // array even when the size isn't an ICE.  This is necessary
6256   // for compatibility with code that depends on gcc's buggy
6257   // constant expression folding, like struct {char x[(int)(char*)2];}
6258   SizeIsNegative = false;
6259   Oversized = 0;
6260 
6261   if (T->isDependentType())
6262     return QualType();
6263 
6264   QualifierCollector Qs;
6265   const Type *Ty = Qs.strip(T);
6266 
6267   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6268     QualType Pointee = PTy->getPointeeType();
6269     QualType FixedType =
6270         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6271                                             Oversized);
6272     if (FixedType.isNull()) return FixedType;
6273     FixedType = Context.getPointerType(FixedType);
6274     return Qs.apply(Context, FixedType);
6275   }
6276   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6277     QualType Inner = PTy->getInnerType();
6278     QualType FixedType =
6279         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6280                                             Oversized);
6281     if (FixedType.isNull()) return FixedType;
6282     FixedType = Context.getParenType(FixedType);
6283     return Qs.apply(Context, FixedType);
6284   }
6285 
6286   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6287   if (!VLATy)
6288     return QualType();
6289 
6290   QualType ElemTy = VLATy->getElementType();
6291   if (ElemTy->isVariablyModifiedType()) {
6292     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6293                                                  SizeIsNegative, Oversized);
6294     if (ElemTy.isNull())
6295       return QualType();
6296   }
6297 
6298   Expr::EvalResult Result;
6299   if (!VLATy->getSizeExpr() ||
6300       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6301     return QualType();
6302 
6303   llvm::APSInt Res = Result.Val.getInt();
6304 
6305   // Check whether the array size is negative.
6306   if (Res.isSigned() && Res.isNegative()) {
6307     SizeIsNegative = true;
6308     return QualType();
6309   }
6310 
6311   // Check whether the array is too large to be addressed.
6312   unsigned ActiveSizeBits =
6313       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6314        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6315           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6316           : Res.getActiveBits();
6317   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6318     Oversized = Res;
6319     return QualType();
6320   }
6321 
6322   QualType FoldedArrayType = Context.getConstantArrayType(
6323       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6324   return Qs.apply(Context, FoldedArrayType);
6325 }
6326 
6327 static void
6328 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6329   SrcTL = SrcTL.getUnqualifiedLoc();
6330   DstTL = DstTL.getUnqualifiedLoc();
6331   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6332     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6333     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6334                                       DstPTL.getPointeeLoc());
6335     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6336     return;
6337   }
6338   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6339     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6340     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6341                                       DstPTL.getInnerLoc());
6342     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6343     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6344     return;
6345   }
6346   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6347   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6348   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6349   TypeLoc DstElemTL = DstATL.getElementLoc();
6350   if (VariableArrayTypeLoc SrcElemATL =
6351           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6352     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6353     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6354   } else {
6355     DstElemTL.initializeFullCopy(SrcElemTL);
6356   }
6357   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6358   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6359   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6360 }
6361 
6362 /// Helper method to turn variable array types into constant array
6363 /// types in certain situations which would otherwise be errors (for
6364 /// GCC compatibility).
6365 static TypeSourceInfo*
6366 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6367                                               ASTContext &Context,
6368                                               bool &SizeIsNegative,
6369                                               llvm::APSInt &Oversized) {
6370   QualType FixedTy
6371     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6372                                           SizeIsNegative, Oversized);
6373   if (FixedTy.isNull())
6374     return nullptr;
6375   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6376   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6377                                     FixedTInfo->getTypeLoc());
6378   return FixedTInfo;
6379 }
6380 
6381 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6382 /// true if we were successful.
6383 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6384                                            QualType &T, SourceLocation Loc,
6385                                            unsigned FailedFoldDiagID) {
6386   bool SizeIsNegative;
6387   llvm::APSInt Oversized;
6388   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6389       TInfo, Context, SizeIsNegative, Oversized);
6390   if (FixedTInfo) {
6391     Diag(Loc, diag::ext_vla_folded_to_constant);
6392     TInfo = FixedTInfo;
6393     T = FixedTInfo->getType();
6394     return true;
6395   }
6396 
6397   if (SizeIsNegative)
6398     Diag(Loc, diag::err_typecheck_negative_array_size);
6399   else if (Oversized.getBoolValue())
6400     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6401   else if (FailedFoldDiagID)
6402     Diag(Loc, FailedFoldDiagID);
6403   return false;
6404 }
6405 
6406 /// Register the given locally-scoped extern "C" declaration so
6407 /// that it can be found later for redeclarations. We include any extern "C"
6408 /// declaration that is not visible in the translation unit here, not just
6409 /// function-scope declarations.
6410 void
6411 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6412   if (!getLangOpts().CPlusPlus &&
6413       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6414     // Don't need to track declarations in the TU in C.
6415     return;
6416 
6417   // Note that we have a locally-scoped external with this name.
6418   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6419 }
6420 
6421 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6422   // FIXME: We can have multiple results via __attribute__((overloadable)).
6423   auto Result = Context.getExternCContextDecl()->lookup(Name);
6424   return Result.empty() ? nullptr : *Result.begin();
6425 }
6426 
6427 /// Diagnose function specifiers on a declaration of an identifier that
6428 /// does not identify a function.
6429 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6430   // FIXME: We should probably indicate the identifier in question to avoid
6431   // confusion for constructs like "virtual int a(), b;"
6432   if (DS.isVirtualSpecified())
6433     Diag(DS.getVirtualSpecLoc(),
6434          diag::err_virtual_non_function);
6435 
6436   if (DS.hasExplicitSpecifier())
6437     Diag(DS.getExplicitSpecLoc(),
6438          diag::err_explicit_non_function);
6439 
6440   if (DS.isNoreturnSpecified())
6441     Diag(DS.getNoreturnSpecLoc(),
6442          diag::err_noreturn_non_function);
6443 }
6444 
6445 NamedDecl*
6446 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6447                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6448   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6449   if (D.getCXXScopeSpec().isSet()) {
6450     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6451       << D.getCXXScopeSpec().getRange();
6452     D.setInvalidType();
6453     // Pretend we didn't see the scope specifier.
6454     DC = CurContext;
6455     Previous.clear();
6456   }
6457 
6458   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6459 
6460   if (D.getDeclSpec().isInlineSpecified())
6461     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6462         << getLangOpts().CPlusPlus17;
6463   if (D.getDeclSpec().hasConstexprSpecifier())
6464     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6465         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6466 
6467   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6468     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6469       Diag(D.getName().StartLocation,
6470            diag::err_deduction_guide_invalid_specifier)
6471           << "typedef";
6472     else
6473       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6474           << D.getName().getSourceRange();
6475     return nullptr;
6476   }
6477 
6478   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6479   if (!NewTD) return nullptr;
6480 
6481   // Handle attributes prior to checking for duplicates in MergeVarDecl
6482   ProcessDeclAttributes(S, NewTD, D);
6483 
6484   CheckTypedefForVariablyModifiedType(S, NewTD);
6485 
6486   bool Redeclaration = D.isRedeclaration();
6487   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6488   D.setRedeclaration(Redeclaration);
6489   return ND;
6490 }
6491 
6492 void
6493 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6494   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6495   // then it shall have block scope.
6496   // Note that variably modified types must be fixed before merging the decl so
6497   // that redeclarations will match.
6498   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6499   QualType T = TInfo->getType();
6500   if (T->isVariablyModifiedType()) {
6501     setFunctionHasBranchProtectedScope();
6502 
6503     if (S->getFnParent() == nullptr) {
6504       bool SizeIsNegative;
6505       llvm::APSInt Oversized;
6506       TypeSourceInfo *FixedTInfo =
6507         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6508                                                       SizeIsNegative,
6509                                                       Oversized);
6510       if (FixedTInfo) {
6511         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6512         NewTD->setTypeSourceInfo(FixedTInfo);
6513       } else {
6514         if (SizeIsNegative)
6515           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6516         else if (T->isVariableArrayType())
6517           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6518         else if (Oversized.getBoolValue())
6519           Diag(NewTD->getLocation(), diag::err_array_too_large)
6520             << toString(Oversized, 10);
6521         else
6522           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6523         NewTD->setInvalidDecl();
6524       }
6525     }
6526   }
6527 }
6528 
6529 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6530 /// declares a typedef-name, either using the 'typedef' type specifier or via
6531 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6532 NamedDecl*
6533 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6534                            LookupResult &Previous, bool &Redeclaration) {
6535 
6536   // Find the shadowed declaration before filtering for scope.
6537   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6538 
6539   // Merge the decl with the existing one if appropriate. If the decl is
6540   // in an outer scope, it isn't the same thing.
6541   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6542                        /*AllowInlineNamespace*/false);
6543   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6544   if (!Previous.empty()) {
6545     Redeclaration = true;
6546     MergeTypedefNameDecl(S, NewTD, Previous);
6547   } else {
6548     inferGslPointerAttribute(NewTD);
6549   }
6550 
6551   if (ShadowedDecl && !Redeclaration)
6552     CheckShadow(NewTD, ShadowedDecl, Previous);
6553 
6554   // If this is the C FILE type, notify the AST context.
6555   if (IdentifierInfo *II = NewTD->getIdentifier())
6556     if (!NewTD->isInvalidDecl() &&
6557         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6558       if (II->isStr("FILE"))
6559         Context.setFILEDecl(NewTD);
6560       else if (II->isStr("jmp_buf"))
6561         Context.setjmp_bufDecl(NewTD);
6562       else if (II->isStr("sigjmp_buf"))
6563         Context.setsigjmp_bufDecl(NewTD);
6564       else if (II->isStr("ucontext_t"))
6565         Context.setucontext_tDecl(NewTD);
6566     }
6567 
6568   return NewTD;
6569 }
6570 
6571 /// Determines whether the given declaration is an out-of-scope
6572 /// previous declaration.
6573 ///
6574 /// This routine should be invoked when name lookup has found a
6575 /// previous declaration (PrevDecl) that is not in the scope where a
6576 /// new declaration by the same name is being introduced. If the new
6577 /// declaration occurs in a local scope, previous declarations with
6578 /// linkage may still be considered previous declarations (C99
6579 /// 6.2.2p4-5, C++ [basic.link]p6).
6580 ///
6581 /// \param PrevDecl the previous declaration found by name
6582 /// lookup
6583 ///
6584 /// \param DC the context in which the new declaration is being
6585 /// declared.
6586 ///
6587 /// \returns true if PrevDecl is an out-of-scope previous declaration
6588 /// for a new delcaration with the same name.
6589 static bool
6590 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6591                                 ASTContext &Context) {
6592   if (!PrevDecl)
6593     return false;
6594 
6595   if (!PrevDecl->hasLinkage())
6596     return false;
6597 
6598   if (Context.getLangOpts().CPlusPlus) {
6599     // C++ [basic.link]p6:
6600     //   If there is a visible declaration of an entity with linkage
6601     //   having the same name and type, ignoring entities declared
6602     //   outside the innermost enclosing namespace scope, the block
6603     //   scope declaration declares that same entity and receives the
6604     //   linkage of the previous declaration.
6605     DeclContext *OuterContext = DC->getRedeclContext();
6606     if (!OuterContext->isFunctionOrMethod())
6607       // This rule only applies to block-scope declarations.
6608       return false;
6609 
6610     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6611     if (PrevOuterContext->isRecord())
6612       // We found a member function: ignore it.
6613       return false;
6614 
6615     // Find the innermost enclosing namespace for the new and
6616     // previous declarations.
6617     OuterContext = OuterContext->getEnclosingNamespaceContext();
6618     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6619 
6620     // The previous declaration is in a different namespace, so it
6621     // isn't the same function.
6622     if (!OuterContext->Equals(PrevOuterContext))
6623       return false;
6624   }
6625 
6626   return true;
6627 }
6628 
6629 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6630   CXXScopeSpec &SS = D.getCXXScopeSpec();
6631   if (!SS.isSet()) return;
6632   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6633 }
6634 
6635 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6636   QualType type = decl->getType();
6637   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6638   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6639     // Various kinds of declaration aren't allowed to be __autoreleasing.
6640     unsigned kind = -1U;
6641     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6642       if (var->hasAttr<BlocksAttr>())
6643         kind = 0; // __block
6644       else if (!var->hasLocalStorage())
6645         kind = 1; // global
6646     } else if (isa<ObjCIvarDecl>(decl)) {
6647       kind = 3; // ivar
6648     } else if (isa<FieldDecl>(decl)) {
6649       kind = 2; // field
6650     }
6651 
6652     if (kind != -1U) {
6653       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6654         << kind;
6655     }
6656   } else if (lifetime == Qualifiers::OCL_None) {
6657     // Try to infer lifetime.
6658     if (!type->isObjCLifetimeType())
6659       return false;
6660 
6661     lifetime = type->getObjCARCImplicitLifetime();
6662     type = Context.getLifetimeQualifiedType(type, lifetime);
6663     decl->setType(type);
6664   }
6665 
6666   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6667     // Thread-local variables cannot have lifetime.
6668     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6669         var->getTLSKind()) {
6670       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6671         << var->getType();
6672       return true;
6673     }
6674   }
6675 
6676   return false;
6677 }
6678 
6679 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6680   if (Decl->getType().hasAddressSpace())
6681     return;
6682   if (Decl->getType()->isDependentType())
6683     return;
6684   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6685     QualType Type = Var->getType();
6686     if (Type->isSamplerT() || Type->isVoidType())
6687       return;
6688     LangAS ImplAS = LangAS::opencl_private;
6689     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6690     // __opencl_c_program_scope_global_variables feature, the address space
6691     // for a variable at program scope or a static or extern variable inside
6692     // a function are inferred to be __global.
6693     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6694         Var->hasGlobalStorage())
6695       ImplAS = LangAS::opencl_global;
6696     // If the original type from a decayed type is an array type and that array
6697     // type has no address space yet, deduce it now.
6698     if (auto DT = dyn_cast<DecayedType>(Type)) {
6699       auto OrigTy = DT->getOriginalType();
6700       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6701         // Add the address space to the original array type and then propagate
6702         // that to the element type through `getAsArrayType`.
6703         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6704         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6705         // Re-generate the decayed type.
6706         Type = Context.getDecayedType(OrigTy);
6707       }
6708     }
6709     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6710     // Apply any qualifiers (including address space) from the array type to
6711     // the element type. This implements C99 6.7.3p8: "If the specification of
6712     // an array type includes any type qualifiers, the element type is so
6713     // qualified, not the array type."
6714     if (Type->isArrayType())
6715       Type = QualType(Context.getAsArrayType(Type), 0);
6716     Decl->setType(Type);
6717   }
6718 }
6719 
6720 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6721   // Ensure that an auto decl is deduced otherwise the checks below might cache
6722   // the wrong linkage.
6723   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6724 
6725   // 'weak' only applies to declarations with external linkage.
6726   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6727     if (!ND.isExternallyVisible()) {
6728       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6729       ND.dropAttr<WeakAttr>();
6730     }
6731   }
6732   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6733     if (ND.isExternallyVisible()) {
6734       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6735       ND.dropAttr<WeakRefAttr>();
6736       ND.dropAttr<AliasAttr>();
6737     }
6738   }
6739 
6740   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6741     if (VD->hasInit()) {
6742       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6743         assert(VD->isThisDeclarationADefinition() &&
6744                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6745         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6746         VD->dropAttr<AliasAttr>();
6747       }
6748     }
6749   }
6750 
6751   // 'selectany' only applies to externally visible variable declarations.
6752   // It does not apply to functions.
6753   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6754     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6755       S.Diag(Attr->getLocation(),
6756              diag::err_attribute_selectany_non_extern_data);
6757       ND.dropAttr<SelectAnyAttr>();
6758     }
6759   }
6760 
6761   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6762     auto *VD = dyn_cast<VarDecl>(&ND);
6763     bool IsAnonymousNS = false;
6764     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6765     if (VD) {
6766       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6767       while (NS && !IsAnonymousNS) {
6768         IsAnonymousNS = NS->isAnonymousNamespace();
6769         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6770       }
6771     }
6772     // dll attributes require external linkage. Static locals may have external
6773     // linkage but still cannot be explicitly imported or exported.
6774     // In Microsoft mode, a variable defined in anonymous namespace must have
6775     // external linkage in order to be exported.
6776     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6777     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6778         (!AnonNSInMicrosoftMode &&
6779          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6780       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6781         << &ND << Attr;
6782       ND.setInvalidDecl();
6783     }
6784   }
6785 
6786   // Check the attributes on the function type, if any.
6787   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6788     // Don't declare this variable in the second operand of the for-statement;
6789     // GCC miscompiles that by ending its lifetime before evaluating the
6790     // third operand. See gcc.gnu.org/PR86769.
6791     AttributedTypeLoc ATL;
6792     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6793          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6794          TL = ATL.getModifiedLoc()) {
6795       // The [[lifetimebound]] attribute can be applied to the implicit object
6796       // parameter of a non-static member function (other than a ctor or dtor)
6797       // by applying it to the function type.
6798       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6799         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6800         if (!MD || MD->isStatic()) {
6801           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6802               << !MD << A->getRange();
6803         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6804           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6805               << isa<CXXDestructorDecl>(MD) << A->getRange();
6806         }
6807       }
6808     }
6809   }
6810 }
6811 
6812 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6813                                            NamedDecl *NewDecl,
6814                                            bool IsSpecialization,
6815                                            bool IsDefinition) {
6816   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6817     return;
6818 
6819   bool IsTemplate = false;
6820   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6821     OldDecl = OldTD->getTemplatedDecl();
6822     IsTemplate = true;
6823     if (!IsSpecialization)
6824       IsDefinition = false;
6825   }
6826   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6827     NewDecl = NewTD->getTemplatedDecl();
6828     IsTemplate = true;
6829   }
6830 
6831   if (!OldDecl || !NewDecl)
6832     return;
6833 
6834   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6835   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6836   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6837   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6838 
6839   // dllimport and dllexport are inheritable attributes so we have to exclude
6840   // inherited attribute instances.
6841   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6842                     (NewExportAttr && !NewExportAttr->isInherited());
6843 
6844   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6845   // the only exception being explicit specializations.
6846   // Implicitly generated declarations are also excluded for now because there
6847   // is no other way to switch these to use dllimport or dllexport.
6848   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6849 
6850   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6851     // Allow with a warning for free functions and global variables.
6852     bool JustWarn = false;
6853     if (!OldDecl->isCXXClassMember()) {
6854       auto *VD = dyn_cast<VarDecl>(OldDecl);
6855       if (VD && !VD->getDescribedVarTemplate())
6856         JustWarn = true;
6857       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6858       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6859         JustWarn = true;
6860     }
6861 
6862     // We cannot change a declaration that's been used because IR has already
6863     // been emitted. Dllimported functions will still work though (modulo
6864     // address equality) as they can use the thunk.
6865     if (OldDecl->isUsed())
6866       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6867         JustWarn = false;
6868 
6869     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6870                                : diag::err_attribute_dll_redeclaration;
6871     S.Diag(NewDecl->getLocation(), DiagID)
6872         << NewDecl
6873         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6874     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6875     if (!JustWarn) {
6876       NewDecl->setInvalidDecl();
6877       return;
6878     }
6879   }
6880 
6881   // A redeclaration is not allowed to drop a dllimport attribute, the only
6882   // exceptions being inline function definitions (except for function
6883   // templates), local extern declarations, qualified friend declarations or
6884   // special MSVC extension: in the last case, the declaration is treated as if
6885   // it were marked dllexport.
6886   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6887   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6888   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6889     // Ignore static data because out-of-line definitions are diagnosed
6890     // separately.
6891     IsStaticDataMember = VD->isStaticDataMember();
6892     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6893                    VarDecl::DeclarationOnly;
6894   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6895     IsInline = FD->isInlined();
6896     IsQualifiedFriend = FD->getQualifier() &&
6897                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6898   }
6899 
6900   if (OldImportAttr && !HasNewAttr &&
6901       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6902       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6903     if (IsMicrosoftABI && IsDefinition) {
6904       S.Diag(NewDecl->getLocation(),
6905              diag::warn_redeclaration_without_import_attribute)
6906           << NewDecl;
6907       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6908       NewDecl->dropAttr<DLLImportAttr>();
6909       NewDecl->addAttr(
6910           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6911     } else {
6912       S.Diag(NewDecl->getLocation(),
6913              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6914           << NewDecl << OldImportAttr;
6915       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6916       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6917       OldDecl->dropAttr<DLLImportAttr>();
6918       NewDecl->dropAttr<DLLImportAttr>();
6919     }
6920   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6921     // In MinGW, seeing a function declared inline drops the dllimport
6922     // attribute.
6923     OldDecl->dropAttr<DLLImportAttr>();
6924     NewDecl->dropAttr<DLLImportAttr>();
6925     S.Diag(NewDecl->getLocation(),
6926            diag::warn_dllimport_dropped_from_inline_function)
6927         << NewDecl << OldImportAttr;
6928   }
6929 
6930   // A specialization of a class template member function is processed here
6931   // since it's a redeclaration. If the parent class is dllexport, the
6932   // specialization inherits that attribute. This doesn't happen automatically
6933   // since the parent class isn't instantiated until later.
6934   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6935     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6936         !NewImportAttr && !NewExportAttr) {
6937       if (const DLLExportAttr *ParentExportAttr =
6938               MD->getParent()->getAttr<DLLExportAttr>()) {
6939         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6940         NewAttr->setInherited(true);
6941         NewDecl->addAttr(NewAttr);
6942       }
6943     }
6944   }
6945 }
6946 
6947 /// Given that we are within the definition of the given function,
6948 /// will that definition behave like C99's 'inline', where the
6949 /// definition is discarded except for optimization purposes?
6950 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6951   // Try to avoid calling GetGVALinkageForFunction.
6952 
6953   // All cases of this require the 'inline' keyword.
6954   if (!FD->isInlined()) return false;
6955 
6956   // This is only possible in C++ with the gnu_inline attribute.
6957   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6958     return false;
6959 
6960   // Okay, go ahead and call the relatively-more-expensive function.
6961   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6962 }
6963 
6964 /// Determine whether a variable is extern "C" prior to attaching
6965 /// an initializer. We can't just call isExternC() here, because that
6966 /// will also compute and cache whether the declaration is externally
6967 /// visible, which might change when we attach the initializer.
6968 ///
6969 /// This can only be used if the declaration is known to not be a
6970 /// redeclaration of an internal linkage declaration.
6971 ///
6972 /// For instance:
6973 ///
6974 ///   auto x = []{};
6975 ///
6976 /// Attaching the initializer here makes this declaration not externally
6977 /// visible, because its type has internal linkage.
6978 ///
6979 /// FIXME: This is a hack.
6980 template<typename T>
6981 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6982   if (S.getLangOpts().CPlusPlus) {
6983     // In C++, the overloadable attribute negates the effects of extern "C".
6984     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6985       return false;
6986 
6987     // So do CUDA's host/device attributes.
6988     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6989                                  D->template hasAttr<CUDAHostAttr>()))
6990       return false;
6991   }
6992   return D->isExternC();
6993 }
6994 
6995 static bool shouldConsiderLinkage(const VarDecl *VD) {
6996   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6997   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6998       isa<OMPDeclareMapperDecl>(DC))
6999     return VD->hasExternalStorage();
7000   if (DC->isFileContext())
7001     return true;
7002   if (DC->isRecord())
7003     return false;
7004   if (isa<RequiresExprBodyDecl>(DC))
7005     return false;
7006   llvm_unreachable("Unexpected context");
7007 }
7008 
7009 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7010   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7011   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7012       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7013     return true;
7014   if (DC->isRecord())
7015     return false;
7016   llvm_unreachable("Unexpected context");
7017 }
7018 
7019 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7020                           ParsedAttr::Kind Kind) {
7021   // Check decl attributes on the DeclSpec.
7022   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7023     return true;
7024 
7025   // Walk the declarator structure, checking decl attributes that were in a type
7026   // position to the decl itself.
7027   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7028     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7029       return true;
7030   }
7031 
7032   // Finally, check attributes on the decl itself.
7033   return PD.getAttributes().hasAttribute(Kind);
7034 }
7035 
7036 /// Adjust the \c DeclContext for a function or variable that might be a
7037 /// function-local external declaration.
7038 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7039   if (!DC->isFunctionOrMethod())
7040     return false;
7041 
7042   // If this is a local extern function or variable declared within a function
7043   // template, don't add it into the enclosing namespace scope until it is
7044   // instantiated; it might have a dependent type right now.
7045   if (DC->isDependentContext())
7046     return true;
7047 
7048   // C++11 [basic.link]p7:
7049   //   When a block scope declaration of an entity with linkage is not found to
7050   //   refer to some other declaration, then that entity is a member of the
7051   //   innermost enclosing namespace.
7052   //
7053   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7054   // semantically-enclosing namespace, not a lexically-enclosing one.
7055   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7056     DC = DC->getParent();
7057   return true;
7058 }
7059 
7060 /// Returns true if given declaration has external C language linkage.
7061 static bool isDeclExternC(const Decl *D) {
7062   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7063     return FD->isExternC();
7064   if (const auto *VD = dyn_cast<VarDecl>(D))
7065     return VD->isExternC();
7066 
7067   llvm_unreachable("Unknown type of decl!");
7068 }
7069 
7070 /// Returns true if there hasn't been any invalid type diagnosed.
7071 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7072   DeclContext *DC = NewVD->getDeclContext();
7073   QualType R = NewVD->getType();
7074 
7075   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7076   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7077   // argument.
7078   if (R->isImageType() || R->isPipeType()) {
7079     Se.Diag(NewVD->getLocation(),
7080             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7081         << R;
7082     NewVD->setInvalidDecl();
7083     return false;
7084   }
7085 
7086   // OpenCL v1.2 s6.9.r:
7087   // The event type cannot be used to declare a program scope variable.
7088   // OpenCL v2.0 s6.9.q:
7089   // The clk_event_t and reserve_id_t types cannot be declared in program
7090   // scope.
7091   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7092     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7093       Se.Diag(NewVD->getLocation(),
7094               diag::err_invalid_type_for_program_scope_var)
7095           << R;
7096       NewVD->setInvalidDecl();
7097       return false;
7098     }
7099   }
7100 
7101   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7102   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7103                                                Se.getLangOpts())) {
7104     QualType NR = R.getCanonicalType();
7105     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7106            NR->isReferenceType()) {
7107       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7108           NR->isFunctionReferenceType()) {
7109         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7110             << NR->isReferenceType();
7111         NewVD->setInvalidDecl();
7112         return false;
7113       }
7114       NR = NR->getPointeeType();
7115     }
7116   }
7117 
7118   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7119                                                Se.getLangOpts())) {
7120     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7121     // half array type (unless the cl_khr_fp16 extension is enabled).
7122     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7123       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7124       NewVD->setInvalidDecl();
7125       return false;
7126     }
7127   }
7128 
7129   // OpenCL v1.2 s6.9.r:
7130   // The event type cannot be used with the __local, __constant and __global
7131   // address space qualifiers.
7132   if (R->isEventT()) {
7133     if (R.getAddressSpace() != LangAS::opencl_private) {
7134       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7135       NewVD->setInvalidDecl();
7136       return false;
7137     }
7138   }
7139 
7140   if (R->isSamplerT()) {
7141     // OpenCL v1.2 s6.9.b p4:
7142     // The sampler type cannot be used with the __local and __global address
7143     // space qualifiers.
7144     if (R.getAddressSpace() == LangAS::opencl_local ||
7145         R.getAddressSpace() == LangAS::opencl_global) {
7146       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7147       NewVD->setInvalidDecl();
7148     }
7149 
7150     // OpenCL v1.2 s6.12.14.1:
7151     // A global sampler must be declared with either the constant address
7152     // space qualifier or with the const qualifier.
7153     if (DC->isTranslationUnit() &&
7154         !(R.getAddressSpace() == LangAS::opencl_constant ||
7155           R.isConstQualified())) {
7156       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7157       NewVD->setInvalidDecl();
7158     }
7159     if (NewVD->isInvalidDecl())
7160       return false;
7161   }
7162 
7163   return true;
7164 }
7165 
7166 template <typename AttrTy>
7167 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7168   const TypedefNameDecl *TND = TT->getDecl();
7169   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7170     AttrTy *Clone = Attribute->clone(S.Context);
7171     Clone->setInherited(true);
7172     D->addAttr(Clone);
7173   }
7174 }
7175 
7176 NamedDecl *Sema::ActOnVariableDeclarator(
7177     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7178     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7179     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7180   QualType R = TInfo->getType();
7181   DeclarationName Name = GetNameForDeclarator(D).getName();
7182 
7183   IdentifierInfo *II = Name.getAsIdentifierInfo();
7184 
7185   if (D.isDecompositionDeclarator()) {
7186     // Take the name of the first declarator as our name for diagnostic
7187     // purposes.
7188     auto &Decomp = D.getDecompositionDeclarator();
7189     if (!Decomp.bindings().empty()) {
7190       II = Decomp.bindings()[0].Name;
7191       Name = II;
7192     }
7193   } else if (!II) {
7194     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7195     return nullptr;
7196   }
7197 
7198 
7199   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7200   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7201 
7202   // dllimport globals without explicit storage class are treated as extern. We
7203   // have to change the storage class this early to get the right DeclContext.
7204   if (SC == SC_None && !DC->isRecord() &&
7205       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7206       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7207     SC = SC_Extern;
7208 
7209   DeclContext *OriginalDC = DC;
7210   bool IsLocalExternDecl = SC == SC_Extern &&
7211                            adjustContextForLocalExternDecl(DC);
7212 
7213   if (SCSpec == DeclSpec::SCS_mutable) {
7214     // mutable can only appear on non-static class members, so it's always
7215     // an error here
7216     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7217     D.setInvalidType();
7218     SC = SC_None;
7219   }
7220 
7221   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7222       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7223                               D.getDeclSpec().getStorageClassSpecLoc())) {
7224     // In C++11, the 'register' storage class specifier is deprecated.
7225     // Suppress the warning in system macros, it's used in macros in some
7226     // popular C system headers, such as in glibc's htonl() macro.
7227     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7228          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7229                                    : diag::warn_deprecated_register)
7230       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7231   }
7232 
7233   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7234 
7235   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7236     // C99 6.9p2: The storage-class specifiers auto and register shall not
7237     // appear in the declaration specifiers in an external declaration.
7238     // Global Register+Asm is a GNU extension we support.
7239     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7240       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7241       D.setInvalidType();
7242     }
7243   }
7244 
7245   // If this variable has a VLA type and an initializer, try to
7246   // fold to a constant-sized type. This is otherwise invalid.
7247   if (D.hasInitializer() && R->isVariableArrayType())
7248     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7249                                     /*DiagID=*/0);
7250 
7251   bool IsMemberSpecialization = false;
7252   bool IsVariableTemplateSpecialization = false;
7253   bool IsPartialSpecialization = false;
7254   bool IsVariableTemplate = false;
7255   VarDecl *NewVD = nullptr;
7256   VarTemplateDecl *NewTemplate = nullptr;
7257   TemplateParameterList *TemplateParams = nullptr;
7258   if (!getLangOpts().CPlusPlus) {
7259     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7260                             II, R, TInfo, SC);
7261 
7262     if (R->getContainedDeducedType())
7263       ParsingInitForAutoVars.insert(NewVD);
7264 
7265     if (D.isInvalidType())
7266       NewVD->setInvalidDecl();
7267 
7268     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7269         NewVD->hasLocalStorage())
7270       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7271                             NTCUC_AutoVar, NTCUK_Destruct);
7272   } else {
7273     bool Invalid = false;
7274 
7275     if (DC->isRecord() && !CurContext->isRecord()) {
7276       // This is an out-of-line definition of a static data member.
7277       switch (SC) {
7278       case SC_None:
7279         break;
7280       case SC_Static:
7281         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7282              diag::err_static_out_of_line)
7283           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7284         break;
7285       case SC_Auto:
7286       case SC_Register:
7287       case SC_Extern:
7288         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7289         // to names of variables declared in a block or to function parameters.
7290         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7291         // of class members
7292 
7293         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7294              diag::err_storage_class_for_static_member)
7295           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7296         break;
7297       case SC_PrivateExtern:
7298         llvm_unreachable("C storage class in c++!");
7299       }
7300     }
7301 
7302     if (SC == SC_Static && CurContext->isRecord()) {
7303       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7304         // Walk up the enclosing DeclContexts to check for any that are
7305         // incompatible with static data members.
7306         const DeclContext *FunctionOrMethod = nullptr;
7307         const CXXRecordDecl *AnonStruct = nullptr;
7308         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7309           if (Ctxt->isFunctionOrMethod()) {
7310             FunctionOrMethod = Ctxt;
7311             break;
7312           }
7313           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7314           if (ParentDecl && !ParentDecl->getDeclName()) {
7315             AnonStruct = ParentDecl;
7316             break;
7317           }
7318         }
7319         if (FunctionOrMethod) {
7320           // C++ [class.static.data]p5: A local class shall not have static data
7321           // members.
7322           Diag(D.getIdentifierLoc(),
7323                diag::err_static_data_member_not_allowed_in_local_class)
7324             << Name << RD->getDeclName() << RD->getTagKind();
7325         } else if (AnonStruct) {
7326           // C++ [class.static.data]p4: Unnamed classes and classes contained
7327           // directly or indirectly within unnamed classes shall not contain
7328           // static data members.
7329           Diag(D.getIdentifierLoc(),
7330                diag::err_static_data_member_not_allowed_in_anon_struct)
7331             << Name << AnonStruct->getTagKind();
7332           Invalid = true;
7333         } else if (RD->isUnion()) {
7334           // C++98 [class.union]p1: If a union contains a static data member,
7335           // the program is ill-formed. C++11 drops this restriction.
7336           Diag(D.getIdentifierLoc(),
7337                getLangOpts().CPlusPlus11
7338                  ? diag::warn_cxx98_compat_static_data_member_in_union
7339                  : diag::ext_static_data_member_in_union) << Name;
7340         }
7341       }
7342     }
7343 
7344     // Match up the template parameter lists with the scope specifier, then
7345     // determine whether we have a template or a template specialization.
7346     bool InvalidScope = false;
7347     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7348         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7349         D.getCXXScopeSpec(),
7350         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7351             ? D.getName().TemplateId
7352             : nullptr,
7353         TemplateParamLists,
7354         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7355     Invalid |= InvalidScope;
7356 
7357     if (TemplateParams) {
7358       if (!TemplateParams->size() &&
7359           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7360         // There is an extraneous 'template<>' for this variable. Complain
7361         // about it, but allow the declaration of the variable.
7362         Diag(TemplateParams->getTemplateLoc(),
7363              diag::err_template_variable_noparams)
7364           << II
7365           << SourceRange(TemplateParams->getTemplateLoc(),
7366                          TemplateParams->getRAngleLoc());
7367         TemplateParams = nullptr;
7368       } else {
7369         // Check that we can declare a template here.
7370         if (CheckTemplateDeclScope(S, TemplateParams))
7371           return nullptr;
7372 
7373         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7374           // This is an explicit specialization or a partial specialization.
7375           IsVariableTemplateSpecialization = true;
7376           IsPartialSpecialization = TemplateParams->size() > 0;
7377         } else { // if (TemplateParams->size() > 0)
7378           // This is a template declaration.
7379           IsVariableTemplate = true;
7380 
7381           // Only C++1y supports variable templates (N3651).
7382           Diag(D.getIdentifierLoc(),
7383                getLangOpts().CPlusPlus14
7384                    ? diag::warn_cxx11_compat_variable_template
7385                    : diag::ext_variable_template);
7386         }
7387       }
7388     } else {
7389       // Check that we can declare a member specialization here.
7390       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7391           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7392         return nullptr;
7393       assert((Invalid ||
7394               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7395              "should have a 'template<>' for this decl");
7396     }
7397 
7398     if (IsVariableTemplateSpecialization) {
7399       SourceLocation TemplateKWLoc =
7400           TemplateParamLists.size() > 0
7401               ? TemplateParamLists[0]->getTemplateLoc()
7402               : SourceLocation();
7403       DeclResult Res = ActOnVarTemplateSpecialization(
7404           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7405           IsPartialSpecialization);
7406       if (Res.isInvalid())
7407         return nullptr;
7408       NewVD = cast<VarDecl>(Res.get());
7409       AddToScope = false;
7410     } else if (D.isDecompositionDeclarator()) {
7411       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7412                                         D.getIdentifierLoc(), R, TInfo, SC,
7413                                         Bindings);
7414     } else
7415       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7416                               D.getIdentifierLoc(), II, R, TInfo, SC);
7417 
7418     // If this is supposed to be a variable template, create it as such.
7419     if (IsVariableTemplate) {
7420       NewTemplate =
7421           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7422                                   TemplateParams, NewVD);
7423       NewVD->setDescribedVarTemplate(NewTemplate);
7424     }
7425 
7426     // If this decl has an auto type in need of deduction, make a note of the
7427     // Decl so we can diagnose uses of it in its own initializer.
7428     if (R->getContainedDeducedType())
7429       ParsingInitForAutoVars.insert(NewVD);
7430 
7431     if (D.isInvalidType() || Invalid) {
7432       NewVD->setInvalidDecl();
7433       if (NewTemplate)
7434         NewTemplate->setInvalidDecl();
7435     }
7436 
7437     SetNestedNameSpecifier(*this, NewVD, D);
7438 
7439     // If we have any template parameter lists that don't directly belong to
7440     // the variable (matching the scope specifier), store them.
7441     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7442     if (TemplateParamLists.size() > VDTemplateParamLists)
7443       NewVD->setTemplateParameterListsInfo(
7444           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7445   }
7446 
7447   if (D.getDeclSpec().isInlineSpecified()) {
7448     if (!getLangOpts().CPlusPlus) {
7449       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7450           << 0;
7451     } else if (CurContext->isFunctionOrMethod()) {
7452       // 'inline' is not allowed on block scope variable declaration.
7453       Diag(D.getDeclSpec().getInlineSpecLoc(),
7454            diag::err_inline_declaration_block_scope) << Name
7455         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7456     } else {
7457       Diag(D.getDeclSpec().getInlineSpecLoc(),
7458            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7459                                      : diag::ext_inline_variable);
7460       NewVD->setInlineSpecified();
7461     }
7462   }
7463 
7464   // Set the lexical context. If the declarator has a C++ scope specifier, the
7465   // lexical context will be different from the semantic context.
7466   NewVD->setLexicalDeclContext(CurContext);
7467   if (NewTemplate)
7468     NewTemplate->setLexicalDeclContext(CurContext);
7469 
7470   if (IsLocalExternDecl) {
7471     if (D.isDecompositionDeclarator())
7472       for (auto *B : Bindings)
7473         B->setLocalExternDecl();
7474     else
7475       NewVD->setLocalExternDecl();
7476   }
7477 
7478   bool EmitTLSUnsupportedError = false;
7479   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7480     // C++11 [dcl.stc]p4:
7481     //   When thread_local is applied to a variable of block scope the
7482     //   storage-class-specifier static is implied if it does not appear
7483     //   explicitly.
7484     // Core issue: 'static' is not implied if the variable is declared
7485     //   'extern'.
7486     if (NewVD->hasLocalStorage() &&
7487         (SCSpec != DeclSpec::SCS_unspecified ||
7488          TSCS != DeclSpec::TSCS_thread_local ||
7489          !DC->isFunctionOrMethod()))
7490       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7491            diag::err_thread_non_global)
7492         << DeclSpec::getSpecifierName(TSCS);
7493     else if (!Context.getTargetInfo().isTLSSupported()) {
7494       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7495           getLangOpts().SYCLIsDevice) {
7496         // Postpone error emission until we've collected attributes required to
7497         // figure out whether it's a host or device variable and whether the
7498         // error should be ignored.
7499         EmitTLSUnsupportedError = true;
7500         // We still need to mark the variable as TLS so it shows up in AST with
7501         // proper storage class for other tools to use even if we're not going
7502         // to emit any code for it.
7503         NewVD->setTSCSpec(TSCS);
7504       } else
7505         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7506              diag::err_thread_unsupported);
7507     } else
7508       NewVD->setTSCSpec(TSCS);
7509   }
7510 
7511   switch (D.getDeclSpec().getConstexprSpecifier()) {
7512   case ConstexprSpecKind::Unspecified:
7513     break;
7514 
7515   case ConstexprSpecKind::Consteval:
7516     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7517          diag::err_constexpr_wrong_decl_kind)
7518         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7519     LLVM_FALLTHROUGH;
7520 
7521   case ConstexprSpecKind::Constexpr:
7522     NewVD->setConstexpr(true);
7523     // C++1z [dcl.spec.constexpr]p1:
7524     //   A static data member declared with the constexpr specifier is
7525     //   implicitly an inline variable.
7526     if (NewVD->isStaticDataMember() &&
7527         (getLangOpts().CPlusPlus17 ||
7528          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7529       NewVD->setImplicitlyInline();
7530     break;
7531 
7532   case ConstexprSpecKind::Constinit:
7533     if (!NewVD->hasGlobalStorage())
7534       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7535            diag::err_constinit_local_variable);
7536     else
7537       NewVD->addAttr(ConstInitAttr::Create(
7538           Context, D.getDeclSpec().getConstexprSpecLoc(),
7539           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7540     break;
7541   }
7542 
7543   // C99 6.7.4p3
7544   //   An inline definition of a function with external linkage shall
7545   //   not contain a definition of a modifiable object with static or
7546   //   thread storage duration...
7547   // We only apply this when the function is required to be defined
7548   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7549   // that a local variable with thread storage duration still has to
7550   // be marked 'static'.  Also note that it's possible to get these
7551   // semantics in C++ using __attribute__((gnu_inline)).
7552   if (SC == SC_Static && S->getFnParent() != nullptr &&
7553       !NewVD->getType().isConstQualified()) {
7554     FunctionDecl *CurFD = getCurFunctionDecl();
7555     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7556       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7557            diag::warn_static_local_in_extern_inline);
7558       MaybeSuggestAddingStaticToDecl(CurFD);
7559     }
7560   }
7561 
7562   if (D.getDeclSpec().isModulePrivateSpecified()) {
7563     if (IsVariableTemplateSpecialization)
7564       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7565           << (IsPartialSpecialization ? 1 : 0)
7566           << FixItHint::CreateRemoval(
7567                  D.getDeclSpec().getModulePrivateSpecLoc());
7568     else if (IsMemberSpecialization)
7569       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7570         << 2
7571         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7572     else if (NewVD->hasLocalStorage())
7573       Diag(NewVD->getLocation(), diag::err_module_private_local)
7574           << 0 << NewVD
7575           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7576           << FixItHint::CreateRemoval(
7577                  D.getDeclSpec().getModulePrivateSpecLoc());
7578     else {
7579       NewVD->setModulePrivate();
7580       if (NewTemplate)
7581         NewTemplate->setModulePrivate();
7582       for (auto *B : Bindings)
7583         B->setModulePrivate();
7584     }
7585   }
7586 
7587   if (getLangOpts().OpenCL) {
7588     deduceOpenCLAddressSpace(NewVD);
7589 
7590     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7591     if (TSC != TSCS_unspecified) {
7592       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7593            diag::err_opencl_unknown_type_specifier)
7594           << getLangOpts().getOpenCLVersionString()
7595           << DeclSpec::getSpecifierName(TSC) << 1;
7596       NewVD->setInvalidDecl();
7597     }
7598   }
7599 
7600   // Handle attributes prior to checking for duplicates in MergeVarDecl
7601   ProcessDeclAttributes(S, NewVD, D);
7602 
7603   // FIXME: This is probably the wrong location to be doing this and we should
7604   // probably be doing this for more attributes (especially for function
7605   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7606   // the code to copy attributes would be generated by TableGen.
7607   if (R->isFunctionPointerType())
7608     if (const auto *TT = R->getAs<TypedefType>())
7609       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7610 
7611   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7612       getLangOpts().SYCLIsDevice) {
7613     if (EmitTLSUnsupportedError &&
7614         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7615          (getLangOpts().OpenMPIsDevice &&
7616           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7617       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7618            diag::err_thread_unsupported);
7619 
7620     if (EmitTLSUnsupportedError &&
7621         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7622       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7623     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7624     // storage [duration]."
7625     if (SC == SC_None && S->getFnParent() != nullptr &&
7626         (NewVD->hasAttr<CUDASharedAttr>() ||
7627          NewVD->hasAttr<CUDAConstantAttr>())) {
7628       NewVD->setStorageClass(SC_Static);
7629     }
7630   }
7631 
7632   // Ensure that dllimport globals without explicit storage class are treated as
7633   // extern. The storage class is set above using parsed attributes. Now we can
7634   // check the VarDecl itself.
7635   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7636          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7637          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7638 
7639   // In auto-retain/release, infer strong retension for variables of
7640   // retainable type.
7641   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7642     NewVD->setInvalidDecl();
7643 
7644   // Handle GNU asm-label extension (encoded as an attribute).
7645   if (Expr *E = (Expr*)D.getAsmLabel()) {
7646     // The parser guarantees this is a string.
7647     StringLiteral *SE = cast<StringLiteral>(E);
7648     StringRef Label = SE->getString();
7649     if (S->getFnParent() != nullptr) {
7650       switch (SC) {
7651       case SC_None:
7652       case SC_Auto:
7653         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7654         break;
7655       case SC_Register:
7656         // Local Named register
7657         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7658             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7659           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7660         break;
7661       case SC_Static:
7662       case SC_Extern:
7663       case SC_PrivateExtern:
7664         break;
7665       }
7666     } else if (SC == SC_Register) {
7667       // Global Named register
7668       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7669         const auto &TI = Context.getTargetInfo();
7670         bool HasSizeMismatch;
7671 
7672         if (!TI.isValidGCCRegisterName(Label))
7673           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7674         else if (!TI.validateGlobalRegisterVariable(Label,
7675                                                     Context.getTypeSize(R),
7676                                                     HasSizeMismatch))
7677           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7678         else if (HasSizeMismatch)
7679           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7680       }
7681 
7682       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7683         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7684         NewVD->setInvalidDecl(true);
7685       }
7686     }
7687 
7688     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7689                                         /*IsLiteralLabel=*/true,
7690                                         SE->getStrTokenLoc(0)));
7691   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7692     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7693       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7694     if (I != ExtnameUndeclaredIdentifiers.end()) {
7695       if (isDeclExternC(NewVD)) {
7696         NewVD->addAttr(I->second);
7697         ExtnameUndeclaredIdentifiers.erase(I);
7698       } else
7699         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7700             << /*Variable*/1 << NewVD;
7701     }
7702   }
7703 
7704   // Find the shadowed declaration before filtering for scope.
7705   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7706                                 ? getShadowedDeclaration(NewVD, Previous)
7707                                 : nullptr;
7708 
7709   // Don't consider existing declarations that are in a different
7710   // scope and are out-of-semantic-context declarations (if the new
7711   // declaration has linkage).
7712   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7713                        D.getCXXScopeSpec().isNotEmpty() ||
7714                        IsMemberSpecialization ||
7715                        IsVariableTemplateSpecialization);
7716 
7717   // Check whether the previous declaration is in the same block scope. This
7718   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7719   if (getLangOpts().CPlusPlus &&
7720       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7721     NewVD->setPreviousDeclInSameBlockScope(
7722         Previous.isSingleResult() && !Previous.isShadowed() &&
7723         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7724 
7725   if (!getLangOpts().CPlusPlus) {
7726     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7727   } else {
7728     // If this is an explicit specialization of a static data member, check it.
7729     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7730         CheckMemberSpecialization(NewVD, Previous))
7731       NewVD->setInvalidDecl();
7732 
7733     // Merge the decl with the existing one if appropriate.
7734     if (!Previous.empty()) {
7735       if (Previous.isSingleResult() &&
7736           isa<FieldDecl>(Previous.getFoundDecl()) &&
7737           D.getCXXScopeSpec().isSet()) {
7738         // The user tried to define a non-static data member
7739         // out-of-line (C++ [dcl.meaning]p1).
7740         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7741           << D.getCXXScopeSpec().getRange();
7742         Previous.clear();
7743         NewVD->setInvalidDecl();
7744       }
7745     } else if (D.getCXXScopeSpec().isSet()) {
7746       // No previous declaration in the qualifying scope.
7747       Diag(D.getIdentifierLoc(), diag::err_no_member)
7748         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7749         << D.getCXXScopeSpec().getRange();
7750       NewVD->setInvalidDecl();
7751     }
7752 
7753     if (!IsVariableTemplateSpecialization)
7754       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7755 
7756     if (NewTemplate) {
7757       VarTemplateDecl *PrevVarTemplate =
7758           NewVD->getPreviousDecl()
7759               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7760               : nullptr;
7761 
7762       // Check the template parameter list of this declaration, possibly
7763       // merging in the template parameter list from the previous variable
7764       // template declaration.
7765       if (CheckTemplateParameterList(
7766               TemplateParams,
7767               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7768                               : nullptr,
7769               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7770                DC->isDependentContext())
7771                   ? TPC_ClassTemplateMember
7772                   : TPC_VarTemplate))
7773         NewVD->setInvalidDecl();
7774 
7775       // If we are providing an explicit specialization of a static variable
7776       // template, make a note of that.
7777       if (PrevVarTemplate &&
7778           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7779         PrevVarTemplate->setMemberSpecialization();
7780     }
7781   }
7782 
7783   // Diagnose shadowed variables iff this isn't a redeclaration.
7784   if (ShadowedDecl && !D.isRedeclaration())
7785     CheckShadow(NewVD, ShadowedDecl, Previous);
7786 
7787   ProcessPragmaWeak(S, NewVD);
7788 
7789   // If this is the first declaration of an extern C variable, update
7790   // the map of such variables.
7791   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7792       isIncompleteDeclExternC(*this, NewVD))
7793     RegisterLocallyScopedExternCDecl(NewVD, S);
7794 
7795   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7796     MangleNumberingContext *MCtx;
7797     Decl *ManglingContextDecl;
7798     std::tie(MCtx, ManglingContextDecl) =
7799         getCurrentMangleNumberContext(NewVD->getDeclContext());
7800     if (MCtx) {
7801       Context.setManglingNumber(
7802           NewVD, MCtx->getManglingNumber(
7803                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7804       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7805     }
7806   }
7807 
7808   // Special handling of variable named 'main'.
7809   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7810       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7811       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7812 
7813     // C++ [basic.start.main]p3
7814     // A program that declares a variable main at global scope is ill-formed.
7815     if (getLangOpts().CPlusPlus)
7816       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7817 
7818     // In C, and external-linkage variable named main results in undefined
7819     // behavior.
7820     else if (NewVD->hasExternalFormalLinkage())
7821       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7822   }
7823 
7824   if (D.isRedeclaration() && !Previous.empty()) {
7825     NamedDecl *Prev = Previous.getRepresentativeDecl();
7826     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7827                                    D.isFunctionDefinition());
7828   }
7829 
7830   if (NewTemplate) {
7831     if (NewVD->isInvalidDecl())
7832       NewTemplate->setInvalidDecl();
7833     ActOnDocumentableDecl(NewTemplate);
7834     return NewTemplate;
7835   }
7836 
7837   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7838     CompleteMemberSpecialization(NewVD, Previous);
7839 
7840   return NewVD;
7841 }
7842 
7843 /// Enum describing the %select options in diag::warn_decl_shadow.
7844 enum ShadowedDeclKind {
7845   SDK_Local,
7846   SDK_Global,
7847   SDK_StaticMember,
7848   SDK_Field,
7849   SDK_Typedef,
7850   SDK_Using,
7851   SDK_StructuredBinding
7852 };
7853 
7854 /// Determine what kind of declaration we're shadowing.
7855 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7856                                                 const DeclContext *OldDC) {
7857   if (isa<TypeAliasDecl>(ShadowedDecl))
7858     return SDK_Using;
7859   else if (isa<TypedefDecl>(ShadowedDecl))
7860     return SDK_Typedef;
7861   else if (isa<BindingDecl>(ShadowedDecl))
7862     return SDK_StructuredBinding;
7863   else if (isa<RecordDecl>(OldDC))
7864     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7865 
7866   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7867 }
7868 
7869 /// Return the location of the capture if the given lambda captures the given
7870 /// variable \p VD, or an invalid source location otherwise.
7871 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7872                                          const VarDecl *VD) {
7873   for (const Capture &Capture : LSI->Captures) {
7874     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7875       return Capture.getLocation();
7876   }
7877   return SourceLocation();
7878 }
7879 
7880 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7881                                      const LookupResult &R) {
7882   // Only diagnose if we're shadowing an unambiguous field or variable.
7883   if (R.getResultKind() != LookupResult::Found)
7884     return false;
7885 
7886   // Return false if warning is ignored.
7887   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7888 }
7889 
7890 /// Return the declaration shadowed by the given variable \p D, or null
7891 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7892 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7893                                         const LookupResult &R) {
7894   if (!shouldWarnIfShadowedDecl(Diags, R))
7895     return nullptr;
7896 
7897   // Don't diagnose declarations at file scope.
7898   if (D->hasGlobalStorage())
7899     return nullptr;
7900 
7901   NamedDecl *ShadowedDecl = R.getFoundDecl();
7902   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7903                                                             : nullptr;
7904 }
7905 
7906 /// Return the declaration shadowed by the given typedef \p D, or null
7907 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7908 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7909                                         const LookupResult &R) {
7910   // Don't warn if typedef declaration is part of a class
7911   if (D->getDeclContext()->isRecord())
7912     return nullptr;
7913 
7914   if (!shouldWarnIfShadowedDecl(Diags, R))
7915     return nullptr;
7916 
7917   NamedDecl *ShadowedDecl = R.getFoundDecl();
7918   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7919 }
7920 
7921 /// Return the declaration shadowed by the given variable \p D, or null
7922 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7923 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7924                                         const LookupResult &R) {
7925   if (!shouldWarnIfShadowedDecl(Diags, R))
7926     return nullptr;
7927 
7928   NamedDecl *ShadowedDecl = R.getFoundDecl();
7929   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7930                                                             : nullptr;
7931 }
7932 
7933 /// Diagnose variable or built-in function shadowing.  Implements
7934 /// -Wshadow.
7935 ///
7936 /// This method is called whenever a VarDecl is added to a "useful"
7937 /// scope.
7938 ///
7939 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7940 /// \param R the lookup of the name
7941 ///
7942 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7943                        const LookupResult &R) {
7944   DeclContext *NewDC = D->getDeclContext();
7945 
7946   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7947     // Fields are not shadowed by variables in C++ static methods.
7948     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7949       if (MD->isStatic())
7950         return;
7951 
7952     // Fields shadowed by constructor parameters are a special case. Usually
7953     // the constructor initializes the field with the parameter.
7954     if (isa<CXXConstructorDecl>(NewDC))
7955       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7956         // Remember that this was shadowed so we can either warn about its
7957         // modification or its existence depending on warning settings.
7958         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7959         return;
7960       }
7961   }
7962 
7963   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7964     if (shadowedVar->isExternC()) {
7965       // For shadowing external vars, make sure that we point to the global
7966       // declaration, not a locally scoped extern declaration.
7967       for (auto I : shadowedVar->redecls())
7968         if (I->isFileVarDecl()) {
7969           ShadowedDecl = I;
7970           break;
7971         }
7972     }
7973 
7974   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7975 
7976   unsigned WarningDiag = diag::warn_decl_shadow;
7977   SourceLocation CaptureLoc;
7978   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7979       isa<CXXMethodDecl>(NewDC)) {
7980     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7981       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7982         if (RD->getLambdaCaptureDefault() == LCD_None) {
7983           // Try to avoid warnings for lambdas with an explicit capture list.
7984           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7985           // Warn only when the lambda captures the shadowed decl explicitly.
7986           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7987           if (CaptureLoc.isInvalid())
7988             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7989         } else {
7990           // Remember that this was shadowed so we can avoid the warning if the
7991           // shadowed decl isn't captured and the warning settings allow it.
7992           cast<LambdaScopeInfo>(getCurFunction())
7993               ->ShadowingDecls.push_back(
7994                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7995           return;
7996         }
7997       }
7998 
7999       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8000         // A variable can't shadow a local variable in an enclosing scope, if
8001         // they are separated by a non-capturing declaration context.
8002         for (DeclContext *ParentDC = NewDC;
8003              ParentDC && !ParentDC->Equals(OldDC);
8004              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8005           // Only block literals, captured statements, and lambda expressions
8006           // can capture; other scopes don't.
8007           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8008               !isLambdaCallOperator(ParentDC)) {
8009             return;
8010           }
8011         }
8012       }
8013     }
8014   }
8015 
8016   // Only warn about certain kinds of shadowing for class members.
8017   if (NewDC && NewDC->isRecord()) {
8018     // In particular, don't warn about shadowing non-class members.
8019     if (!OldDC->isRecord())
8020       return;
8021 
8022     // TODO: should we warn about static data members shadowing
8023     // static data members from base classes?
8024 
8025     // TODO: don't diagnose for inaccessible shadowed members.
8026     // This is hard to do perfectly because we might friend the
8027     // shadowing context, but that's just a false negative.
8028   }
8029 
8030 
8031   DeclarationName Name = R.getLookupName();
8032 
8033   // Emit warning and note.
8034   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8035   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8036   if (!CaptureLoc.isInvalid())
8037     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8038         << Name << /*explicitly*/ 1;
8039   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8040 }
8041 
8042 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8043 /// when these variables are captured by the lambda.
8044 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8045   for (const auto &Shadow : LSI->ShadowingDecls) {
8046     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8047     // Try to avoid the warning when the shadowed decl isn't captured.
8048     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8049     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8050     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8051                                        ? diag::warn_decl_shadow_uncaptured_local
8052                                        : diag::warn_decl_shadow)
8053         << Shadow.VD->getDeclName()
8054         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8055     if (!CaptureLoc.isInvalid())
8056       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8057           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8058     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8059   }
8060 }
8061 
8062 /// Check -Wshadow without the advantage of a previous lookup.
8063 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8064   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8065     return;
8066 
8067   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8068                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8069   LookupName(R, S);
8070   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8071     CheckShadow(D, ShadowedDecl, R);
8072 }
8073 
8074 /// Check if 'E', which is an expression that is about to be modified, refers
8075 /// to a constructor parameter that shadows a field.
8076 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8077   // Quickly ignore expressions that can't be shadowing ctor parameters.
8078   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8079     return;
8080   E = E->IgnoreParenImpCasts();
8081   auto *DRE = dyn_cast<DeclRefExpr>(E);
8082   if (!DRE)
8083     return;
8084   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8085   auto I = ShadowingDecls.find(D);
8086   if (I == ShadowingDecls.end())
8087     return;
8088   const NamedDecl *ShadowedDecl = I->second;
8089   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8090   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8091   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8092   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8093 
8094   // Avoid issuing multiple warnings about the same decl.
8095   ShadowingDecls.erase(I);
8096 }
8097 
8098 /// Check for conflict between this global or extern "C" declaration and
8099 /// previous global or extern "C" declarations. This is only used in C++.
8100 template<typename T>
8101 static bool checkGlobalOrExternCConflict(
8102     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8103   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8104   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8105 
8106   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8107     // The common case: this global doesn't conflict with any extern "C"
8108     // declaration.
8109     return false;
8110   }
8111 
8112   if (Prev) {
8113     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8114       // Both the old and new declarations have C language linkage. This is a
8115       // redeclaration.
8116       Previous.clear();
8117       Previous.addDecl(Prev);
8118       return true;
8119     }
8120 
8121     // This is a global, non-extern "C" declaration, and there is a previous
8122     // non-global extern "C" declaration. Diagnose if this is a variable
8123     // declaration.
8124     if (!isa<VarDecl>(ND))
8125       return false;
8126   } else {
8127     // The declaration is extern "C". Check for any declaration in the
8128     // translation unit which might conflict.
8129     if (IsGlobal) {
8130       // We have already performed the lookup into the translation unit.
8131       IsGlobal = false;
8132       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8133            I != E; ++I) {
8134         if (isa<VarDecl>(*I)) {
8135           Prev = *I;
8136           break;
8137         }
8138       }
8139     } else {
8140       DeclContext::lookup_result R =
8141           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8142       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8143            I != E; ++I) {
8144         if (isa<VarDecl>(*I)) {
8145           Prev = *I;
8146           break;
8147         }
8148         // FIXME: If we have any other entity with this name in global scope,
8149         // the declaration is ill-formed, but that is a defect: it breaks the
8150         // 'stat' hack, for instance. Only variables can have mangled name
8151         // clashes with extern "C" declarations, so only they deserve a
8152         // diagnostic.
8153       }
8154     }
8155 
8156     if (!Prev)
8157       return false;
8158   }
8159 
8160   // Use the first declaration's location to ensure we point at something which
8161   // is lexically inside an extern "C" linkage-spec.
8162   assert(Prev && "should have found a previous declaration to diagnose");
8163   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8164     Prev = FD->getFirstDecl();
8165   else
8166     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8167 
8168   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8169     << IsGlobal << ND;
8170   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8171     << IsGlobal;
8172   return false;
8173 }
8174 
8175 /// Apply special rules for handling extern "C" declarations. Returns \c true
8176 /// if we have found that this is a redeclaration of some prior entity.
8177 ///
8178 /// Per C++ [dcl.link]p6:
8179 ///   Two declarations [for a function or variable] with C language linkage
8180 ///   with the same name that appear in different scopes refer to the same
8181 ///   [entity]. An entity with C language linkage shall not be declared with
8182 ///   the same name as an entity in global scope.
8183 template<typename T>
8184 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8185                                                   LookupResult &Previous) {
8186   if (!S.getLangOpts().CPlusPlus) {
8187     // In C, when declaring a global variable, look for a corresponding 'extern'
8188     // variable declared in function scope. We don't need this in C++, because
8189     // we find local extern decls in the surrounding file-scope DeclContext.
8190     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8191       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8192         Previous.clear();
8193         Previous.addDecl(Prev);
8194         return true;
8195       }
8196     }
8197     return false;
8198   }
8199 
8200   // A declaration in the translation unit can conflict with an extern "C"
8201   // declaration.
8202   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8203     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8204 
8205   // An extern "C" declaration can conflict with a declaration in the
8206   // translation unit or can be a redeclaration of an extern "C" declaration
8207   // in another scope.
8208   if (isIncompleteDeclExternC(S,ND))
8209     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8210 
8211   // Neither global nor extern "C": nothing to do.
8212   return false;
8213 }
8214 
8215 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8216   // If the decl is already known invalid, don't check it.
8217   if (NewVD->isInvalidDecl())
8218     return;
8219 
8220   QualType T = NewVD->getType();
8221 
8222   // Defer checking an 'auto' type until its initializer is attached.
8223   if (T->isUndeducedType())
8224     return;
8225 
8226   if (NewVD->hasAttrs())
8227     CheckAlignasUnderalignment(NewVD);
8228 
8229   if (T->isObjCObjectType()) {
8230     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8231       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8232     T = Context.getObjCObjectPointerType(T);
8233     NewVD->setType(T);
8234   }
8235 
8236   // Emit an error if an address space was applied to decl with local storage.
8237   // This includes arrays of objects with address space qualifiers, but not
8238   // automatic variables that point to other address spaces.
8239   // ISO/IEC TR 18037 S5.1.2
8240   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8241       T.getAddressSpace() != LangAS::Default) {
8242     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8243     NewVD->setInvalidDecl();
8244     return;
8245   }
8246 
8247   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8248   // scope.
8249   if (getLangOpts().OpenCLVersion == 120 &&
8250       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8251                                             getLangOpts()) &&
8252       NewVD->isStaticLocal()) {
8253     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8254     NewVD->setInvalidDecl();
8255     return;
8256   }
8257 
8258   if (getLangOpts().OpenCL) {
8259     if (!diagnoseOpenCLTypes(*this, NewVD))
8260       return;
8261 
8262     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8263     if (NewVD->hasAttr<BlocksAttr>()) {
8264       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8265       return;
8266     }
8267 
8268     if (T->isBlockPointerType()) {
8269       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8270       // can't use 'extern' storage class.
8271       if (!T.isConstQualified()) {
8272         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8273             << 0 /*const*/;
8274         NewVD->setInvalidDecl();
8275         return;
8276       }
8277       if (NewVD->hasExternalStorage()) {
8278         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8279         NewVD->setInvalidDecl();
8280         return;
8281       }
8282     }
8283 
8284     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8285     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8286         NewVD->hasExternalStorage()) {
8287       if (!T->isSamplerT() && !T->isDependentType() &&
8288           !(T.getAddressSpace() == LangAS::opencl_constant ||
8289             (T.getAddressSpace() == LangAS::opencl_global &&
8290              getOpenCLOptions().areProgramScopeVariablesSupported(
8291                  getLangOpts())))) {
8292         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8293         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8294           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8295               << Scope << "global or constant";
8296         else
8297           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8298               << Scope << "constant";
8299         NewVD->setInvalidDecl();
8300         return;
8301       }
8302     } else {
8303       if (T.getAddressSpace() == LangAS::opencl_global) {
8304         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8305             << 1 /*is any function*/ << "global";
8306         NewVD->setInvalidDecl();
8307         return;
8308       }
8309       if (T.getAddressSpace() == LangAS::opencl_constant ||
8310           T.getAddressSpace() == LangAS::opencl_local) {
8311         FunctionDecl *FD = getCurFunctionDecl();
8312         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8313         // in functions.
8314         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8315           if (T.getAddressSpace() == LangAS::opencl_constant)
8316             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8317                 << 0 /*non-kernel only*/ << "constant";
8318           else
8319             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8320                 << 0 /*non-kernel only*/ << "local";
8321           NewVD->setInvalidDecl();
8322           return;
8323         }
8324         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8325         // in the outermost scope of a kernel function.
8326         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8327           if (!getCurScope()->isFunctionScope()) {
8328             if (T.getAddressSpace() == LangAS::opencl_constant)
8329               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8330                   << "constant";
8331             else
8332               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8333                   << "local";
8334             NewVD->setInvalidDecl();
8335             return;
8336           }
8337         }
8338       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8339                  // If we are parsing a template we didn't deduce an addr
8340                  // space yet.
8341                  T.getAddressSpace() != LangAS::Default) {
8342         // Do not allow other address spaces on automatic variable.
8343         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8344         NewVD->setInvalidDecl();
8345         return;
8346       }
8347     }
8348   }
8349 
8350   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8351       && !NewVD->hasAttr<BlocksAttr>()) {
8352     if (getLangOpts().getGC() != LangOptions::NonGC)
8353       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8354     else {
8355       assert(!getLangOpts().ObjCAutoRefCount);
8356       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8357     }
8358   }
8359 
8360   bool isVM = T->isVariablyModifiedType();
8361   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8362       NewVD->hasAttr<BlocksAttr>())
8363     setFunctionHasBranchProtectedScope();
8364 
8365   if ((isVM && NewVD->hasLinkage()) ||
8366       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8367     bool SizeIsNegative;
8368     llvm::APSInt Oversized;
8369     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8370         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8371     QualType FixedT;
8372     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8373       FixedT = FixedTInfo->getType();
8374     else if (FixedTInfo) {
8375       // Type and type-as-written are canonically different. We need to fix up
8376       // both types separately.
8377       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8378                                                    Oversized);
8379     }
8380     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8381       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8382       // FIXME: This won't give the correct result for
8383       // int a[10][n];
8384       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8385 
8386       if (NewVD->isFileVarDecl())
8387         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8388         << SizeRange;
8389       else if (NewVD->isStaticLocal())
8390         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8391         << SizeRange;
8392       else
8393         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8394         << SizeRange;
8395       NewVD->setInvalidDecl();
8396       return;
8397     }
8398 
8399     if (!FixedTInfo) {
8400       if (NewVD->isFileVarDecl())
8401         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8402       else
8403         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8404       NewVD->setInvalidDecl();
8405       return;
8406     }
8407 
8408     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8409     NewVD->setType(FixedT);
8410     NewVD->setTypeSourceInfo(FixedTInfo);
8411   }
8412 
8413   if (T->isVoidType()) {
8414     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8415     //                    of objects and functions.
8416     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8417       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8418         << T;
8419       NewVD->setInvalidDecl();
8420       return;
8421     }
8422   }
8423 
8424   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8425     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8426     NewVD->setInvalidDecl();
8427     return;
8428   }
8429 
8430   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8431     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8432     NewVD->setInvalidDecl();
8433     return;
8434   }
8435 
8436   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8437     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8438     NewVD->setInvalidDecl();
8439     return;
8440   }
8441 
8442   if (NewVD->isConstexpr() && !T->isDependentType() &&
8443       RequireLiteralType(NewVD->getLocation(), T,
8444                          diag::err_constexpr_var_non_literal)) {
8445     NewVD->setInvalidDecl();
8446     return;
8447   }
8448 
8449   // PPC MMA non-pointer types are not allowed as non-local variable types.
8450   if (Context.getTargetInfo().getTriple().isPPC64() &&
8451       !NewVD->isLocalVarDecl() &&
8452       CheckPPCMMAType(T, NewVD->getLocation())) {
8453     NewVD->setInvalidDecl();
8454     return;
8455   }
8456 }
8457 
8458 /// Perform semantic checking on a newly-created variable
8459 /// declaration.
8460 ///
8461 /// This routine performs all of the type-checking required for a
8462 /// variable declaration once it has been built. It is used both to
8463 /// check variables after they have been parsed and their declarators
8464 /// have been translated into a declaration, and to check variables
8465 /// that have been instantiated from a template.
8466 ///
8467 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8468 ///
8469 /// Returns true if the variable declaration is a redeclaration.
8470 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8471   CheckVariableDeclarationType(NewVD);
8472 
8473   // If the decl is already known invalid, don't check it.
8474   if (NewVD->isInvalidDecl())
8475     return false;
8476 
8477   // If we did not find anything by this name, look for a non-visible
8478   // extern "C" declaration with the same name.
8479   if (Previous.empty() &&
8480       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8481     Previous.setShadowed();
8482 
8483   if (!Previous.empty()) {
8484     MergeVarDecl(NewVD, Previous);
8485     return true;
8486   }
8487   return false;
8488 }
8489 
8490 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8491 /// and if so, check that it's a valid override and remember it.
8492 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8493   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8494 
8495   // Look for methods in base classes that this method might override.
8496   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8497                      /*DetectVirtual=*/false);
8498   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8499     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8500     DeclarationName Name = MD->getDeclName();
8501 
8502     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8503       // We really want to find the base class destructor here.
8504       QualType T = Context.getTypeDeclType(BaseRecord);
8505       CanQualType CT = Context.getCanonicalType(T);
8506       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8507     }
8508 
8509     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8510       CXXMethodDecl *BaseMD =
8511           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8512       if (!BaseMD || !BaseMD->isVirtual() ||
8513           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8514                      /*ConsiderCudaAttrs=*/true,
8515                      // C++2a [class.virtual]p2 does not consider requires
8516                      // clauses when overriding.
8517                      /*ConsiderRequiresClauses=*/false))
8518         continue;
8519 
8520       if (Overridden.insert(BaseMD).second) {
8521         MD->addOverriddenMethod(BaseMD);
8522         CheckOverridingFunctionReturnType(MD, BaseMD);
8523         CheckOverridingFunctionAttributes(MD, BaseMD);
8524         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8525         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8526       }
8527 
8528       // A method can only override one function from each base class. We
8529       // don't track indirectly overridden methods from bases of bases.
8530       return true;
8531     }
8532 
8533     return false;
8534   };
8535 
8536   DC->lookupInBases(VisitBase, Paths);
8537   return !Overridden.empty();
8538 }
8539 
8540 namespace {
8541   // Struct for holding all of the extra arguments needed by
8542   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8543   struct ActOnFDArgs {
8544     Scope *S;
8545     Declarator &D;
8546     MultiTemplateParamsArg TemplateParamLists;
8547     bool AddToScope;
8548   };
8549 } // end anonymous namespace
8550 
8551 namespace {
8552 
8553 // Callback to only accept typo corrections that have a non-zero edit distance.
8554 // Also only accept corrections that have the same parent decl.
8555 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8556  public:
8557   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8558                             CXXRecordDecl *Parent)
8559       : Context(Context), OriginalFD(TypoFD),
8560         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8561 
8562   bool ValidateCandidate(const TypoCorrection &candidate) override {
8563     if (candidate.getEditDistance() == 0)
8564       return false;
8565 
8566     SmallVector<unsigned, 1> MismatchedParams;
8567     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8568                                           CDeclEnd = candidate.end();
8569          CDecl != CDeclEnd; ++CDecl) {
8570       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8571 
8572       if (FD && !FD->hasBody() &&
8573           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8574         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8575           CXXRecordDecl *Parent = MD->getParent();
8576           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8577             return true;
8578         } else if (!ExpectedParent) {
8579           return true;
8580         }
8581       }
8582     }
8583 
8584     return false;
8585   }
8586 
8587   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8588     return std::make_unique<DifferentNameValidatorCCC>(*this);
8589   }
8590 
8591  private:
8592   ASTContext &Context;
8593   FunctionDecl *OriginalFD;
8594   CXXRecordDecl *ExpectedParent;
8595 };
8596 
8597 } // end anonymous namespace
8598 
8599 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8600   TypoCorrectedFunctionDefinitions.insert(F);
8601 }
8602 
8603 /// Generate diagnostics for an invalid function redeclaration.
8604 ///
8605 /// This routine handles generating the diagnostic messages for an invalid
8606 /// function redeclaration, including finding possible similar declarations
8607 /// or performing typo correction if there are no previous declarations with
8608 /// the same name.
8609 ///
8610 /// Returns a NamedDecl iff typo correction was performed and substituting in
8611 /// the new declaration name does not cause new errors.
8612 static NamedDecl *DiagnoseInvalidRedeclaration(
8613     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8614     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8615   DeclarationName Name = NewFD->getDeclName();
8616   DeclContext *NewDC = NewFD->getDeclContext();
8617   SmallVector<unsigned, 1> MismatchedParams;
8618   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8619   TypoCorrection Correction;
8620   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8621   unsigned DiagMsg =
8622     IsLocalFriend ? diag::err_no_matching_local_friend :
8623     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8624     diag::err_member_decl_does_not_match;
8625   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8626                     IsLocalFriend ? Sema::LookupLocalFriendName
8627                                   : Sema::LookupOrdinaryName,
8628                     Sema::ForVisibleRedeclaration);
8629 
8630   NewFD->setInvalidDecl();
8631   if (IsLocalFriend)
8632     SemaRef.LookupName(Prev, S);
8633   else
8634     SemaRef.LookupQualifiedName(Prev, NewDC);
8635   assert(!Prev.isAmbiguous() &&
8636          "Cannot have an ambiguity in previous-declaration lookup");
8637   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8638   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8639                                 MD ? MD->getParent() : nullptr);
8640   if (!Prev.empty()) {
8641     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8642          Func != FuncEnd; ++Func) {
8643       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8644       if (FD &&
8645           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8646         // Add 1 to the index so that 0 can mean the mismatch didn't
8647         // involve a parameter
8648         unsigned ParamNum =
8649             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8650         NearMatches.push_back(std::make_pair(FD, ParamNum));
8651       }
8652     }
8653   // If the qualified name lookup yielded nothing, try typo correction
8654   } else if ((Correction = SemaRef.CorrectTypo(
8655                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8656                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8657                   IsLocalFriend ? nullptr : NewDC))) {
8658     // Set up everything for the call to ActOnFunctionDeclarator
8659     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8660                               ExtraArgs.D.getIdentifierLoc());
8661     Previous.clear();
8662     Previous.setLookupName(Correction.getCorrection());
8663     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8664                                     CDeclEnd = Correction.end();
8665          CDecl != CDeclEnd; ++CDecl) {
8666       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8667       if (FD && !FD->hasBody() &&
8668           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8669         Previous.addDecl(FD);
8670       }
8671     }
8672     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8673 
8674     NamedDecl *Result;
8675     // Retry building the function declaration with the new previous
8676     // declarations, and with errors suppressed.
8677     {
8678       // Trap errors.
8679       Sema::SFINAETrap Trap(SemaRef);
8680 
8681       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8682       // pieces need to verify the typo-corrected C++ declaration and hopefully
8683       // eliminate the need for the parameter pack ExtraArgs.
8684       Result = SemaRef.ActOnFunctionDeclarator(
8685           ExtraArgs.S, ExtraArgs.D,
8686           Correction.getCorrectionDecl()->getDeclContext(),
8687           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8688           ExtraArgs.AddToScope);
8689 
8690       if (Trap.hasErrorOccurred())
8691         Result = nullptr;
8692     }
8693 
8694     if (Result) {
8695       // Determine which correction we picked.
8696       Decl *Canonical = Result->getCanonicalDecl();
8697       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8698            I != E; ++I)
8699         if ((*I)->getCanonicalDecl() == Canonical)
8700           Correction.setCorrectionDecl(*I);
8701 
8702       // Let Sema know about the correction.
8703       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8704       SemaRef.diagnoseTypo(
8705           Correction,
8706           SemaRef.PDiag(IsLocalFriend
8707                           ? diag::err_no_matching_local_friend_suggest
8708                           : diag::err_member_decl_does_not_match_suggest)
8709             << Name << NewDC << IsDefinition);
8710       return Result;
8711     }
8712 
8713     // Pretend the typo correction never occurred
8714     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8715                               ExtraArgs.D.getIdentifierLoc());
8716     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8717     Previous.clear();
8718     Previous.setLookupName(Name);
8719   }
8720 
8721   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8722       << Name << NewDC << IsDefinition << NewFD->getLocation();
8723 
8724   bool NewFDisConst = false;
8725   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8726     NewFDisConst = NewMD->isConst();
8727 
8728   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8729        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8730        NearMatch != NearMatchEnd; ++NearMatch) {
8731     FunctionDecl *FD = NearMatch->first;
8732     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8733     bool FDisConst = MD && MD->isConst();
8734     bool IsMember = MD || !IsLocalFriend;
8735 
8736     // FIXME: These notes are poorly worded for the local friend case.
8737     if (unsigned Idx = NearMatch->second) {
8738       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8739       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8740       if (Loc.isInvalid()) Loc = FD->getLocation();
8741       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8742                                  : diag::note_local_decl_close_param_match)
8743         << Idx << FDParam->getType()
8744         << NewFD->getParamDecl(Idx - 1)->getType();
8745     } else if (FDisConst != NewFDisConst) {
8746       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8747           << NewFDisConst << FD->getSourceRange().getEnd()
8748           << (NewFDisConst
8749                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8750                                                  .getConstQualifierLoc())
8751                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8752                                                    .getRParenLoc()
8753                                                    .getLocWithOffset(1),
8754                                                " const"));
8755     } else
8756       SemaRef.Diag(FD->getLocation(),
8757                    IsMember ? diag::note_member_def_close_match
8758                             : diag::note_local_decl_close_match);
8759   }
8760   return nullptr;
8761 }
8762 
8763 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8764   switch (D.getDeclSpec().getStorageClassSpec()) {
8765   default: llvm_unreachable("Unknown storage class!");
8766   case DeclSpec::SCS_auto:
8767   case DeclSpec::SCS_register:
8768   case DeclSpec::SCS_mutable:
8769     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8770                  diag::err_typecheck_sclass_func);
8771     D.getMutableDeclSpec().ClearStorageClassSpecs();
8772     D.setInvalidType();
8773     break;
8774   case DeclSpec::SCS_unspecified: break;
8775   case DeclSpec::SCS_extern:
8776     if (D.getDeclSpec().isExternInLinkageSpec())
8777       return SC_None;
8778     return SC_Extern;
8779   case DeclSpec::SCS_static: {
8780     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8781       // C99 6.7.1p5:
8782       //   The declaration of an identifier for a function that has
8783       //   block scope shall have no explicit storage-class specifier
8784       //   other than extern
8785       // See also (C++ [dcl.stc]p4).
8786       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8787                    diag::err_static_block_func);
8788       break;
8789     } else
8790       return SC_Static;
8791   }
8792   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8793   }
8794 
8795   // No explicit storage class has already been returned
8796   return SC_None;
8797 }
8798 
8799 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8800                                            DeclContext *DC, QualType &R,
8801                                            TypeSourceInfo *TInfo,
8802                                            StorageClass SC,
8803                                            bool &IsVirtualOkay) {
8804   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8805   DeclarationName Name = NameInfo.getName();
8806 
8807   FunctionDecl *NewFD = nullptr;
8808   bool isInline = D.getDeclSpec().isInlineSpecified();
8809 
8810   if (!SemaRef.getLangOpts().CPlusPlus) {
8811     // Determine whether the function was written with a prototype. This is
8812     // true when:
8813     //   - there is a prototype in the declarator, or
8814     //   - the type R of the function is some kind of typedef or other non-
8815     //     attributed reference to a type name (which eventually refers to a
8816     //     function type). Note, we can't always look at the adjusted type to
8817     //     check this case because attributes may cause a non-function
8818     //     declarator to still have a function type. e.g.,
8819     //       typedef void func(int a);
8820     //       __attribute__((noreturn)) func other_func; // This has a prototype
8821     bool HasPrototype =
8822         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8823         (D.getDeclSpec().isTypeRep() &&
8824          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8825         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8826     assert(
8827         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8828         "Strict prototypes are required");
8829 
8830     NewFD = FunctionDecl::Create(
8831         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8832         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8833         ConstexprSpecKind::Unspecified,
8834         /*TrailingRequiresClause=*/nullptr);
8835     if (D.isInvalidType())
8836       NewFD->setInvalidDecl();
8837 
8838     return NewFD;
8839   }
8840 
8841   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8842 
8843   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8844   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8845     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8846                  diag::err_constexpr_wrong_decl_kind)
8847         << static_cast<int>(ConstexprKind);
8848     ConstexprKind = ConstexprSpecKind::Unspecified;
8849     D.getMutableDeclSpec().ClearConstexprSpec();
8850   }
8851   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8852 
8853   // Check that the return type is not an abstract class type.
8854   // For record types, this is done by the AbstractClassUsageDiagnoser once
8855   // the class has been completely parsed.
8856   if (!DC->isRecord() &&
8857       SemaRef.RequireNonAbstractType(
8858           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8859           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8860     D.setInvalidType();
8861 
8862   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8863     // This is a C++ constructor declaration.
8864     assert(DC->isRecord() &&
8865            "Constructors can only be declared in a member context");
8866 
8867     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8868     return CXXConstructorDecl::Create(
8869         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8870         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8871         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8872         InheritedConstructor(), TrailingRequiresClause);
8873 
8874   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8875     // This is a C++ destructor declaration.
8876     if (DC->isRecord()) {
8877       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8878       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8879       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8880           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8881           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8882           /*isImplicitlyDeclared=*/false, ConstexprKind,
8883           TrailingRequiresClause);
8884 
8885       // If the destructor needs an implicit exception specification, set it
8886       // now. FIXME: It'd be nice to be able to create the right type to start
8887       // with, but the type needs to reference the destructor declaration.
8888       if (SemaRef.getLangOpts().CPlusPlus11)
8889         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8890 
8891       IsVirtualOkay = true;
8892       return NewDD;
8893 
8894     } else {
8895       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8896       D.setInvalidType();
8897 
8898       // Create a FunctionDecl to satisfy the function definition parsing
8899       // code path.
8900       return FunctionDecl::Create(
8901           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8902           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8903           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8904     }
8905 
8906   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8907     if (!DC->isRecord()) {
8908       SemaRef.Diag(D.getIdentifierLoc(),
8909            diag::err_conv_function_not_member);
8910       return nullptr;
8911     }
8912 
8913     SemaRef.CheckConversionDeclarator(D, R, SC);
8914     if (D.isInvalidType())
8915       return nullptr;
8916 
8917     IsVirtualOkay = true;
8918     return CXXConversionDecl::Create(
8919         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8920         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8921         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8922         TrailingRequiresClause);
8923 
8924   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8925     if (TrailingRequiresClause)
8926       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8927                    diag::err_trailing_requires_clause_on_deduction_guide)
8928           << TrailingRequiresClause->getSourceRange();
8929     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8930 
8931     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8932                                          ExplicitSpecifier, NameInfo, R, TInfo,
8933                                          D.getEndLoc());
8934   } else if (DC->isRecord()) {
8935     // If the name of the function is the same as the name of the record,
8936     // then this must be an invalid constructor that has a return type.
8937     // (The parser checks for a return type and makes the declarator a
8938     // constructor if it has no return type).
8939     if (Name.getAsIdentifierInfo() &&
8940         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8941       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8942         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8943         << SourceRange(D.getIdentifierLoc());
8944       return nullptr;
8945     }
8946 
8947     // This is a C++ method declaration.
8948     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8949         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8950         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8951         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8952     IsVirtualOkay = !Ret->isStatic();
8953     return Ret;
8954   } else {
8955     bool isFriend =
8956         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8957     if (!isFriend && SemaRef.CurContext->isRecord())
8958       return nullptr;
8959 
8960     // Determine whether the function was written with a
8961     // prototype. This true when:
8962     //   - we're in C++ (where every function has a prototype),
8963     return FunctionDecl::Create(
8964         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8965         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8966         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8967   }
8968 }
8969 
8970 enum OpenCLParamType {
8971   ValidKernelParam,
8972   PtrPtrKernelParam,
8973   PtrKernelParam,
8974   InvalidAddrSpacePtrKernelParam,
8975   InvalidKernelParam,
8976   RecordKernelParam
8977 };
8978 
8979 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8980   // Size dependent types are just typedefs to normal integer types
8981   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8982   // integers other than by their names.
8983   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8984 
8985   // Remove typedefs one by one until we reach a typedef
8986   // for a size dependent type.
8987   QualType DesugaredTy = Ty;
8988   do {
8989     ArrayRef<StringRef> Names(SizeTypeNames);
8990     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8991     if (Names.end() != Match)
8992       return true;
8993 
8994     Ty = DesugaredTy;
8995     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8996   } while (DesugaredTy != Ty);
8997 
8998   return false;
8999 }
9000 
9001 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9002   if (PT->isDependentType())
9003     return InvalidKernelParam;
9004 
9005   if (PT->isPointerType() || PT->isReferenceType()) {
9006     QualType PointeeType = PT->getPointeeType();
9007     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9008         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9009         PointeeType.getAddressSpace() == LangAS::Default)
9010       return InvalidAddrSpacePtrKernelParam;
9011 
9012     if (PointeeType->isPointerType()) {
9013       // This is a pointer to pointer parameter.
9014       // Recursively check inner type.
9015       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9016       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9017           ParamKind == InvalidKernelParam)
9018         return ParamKind;
9019 
9020       return PtrPtrKernelParam;
9021     }
9022 
9023     // C++ for OpenCL v1.0 s2.4:
9024     // Moreover the types used in parameters of the kernel functions must be:
9025     // Standard layout types for pointer parameters. The same applies to
9026     // reference if an implementation supports them in kernel parameters.
9027     if (S.getLangOpts().OpenCLCPlusPlus &&
9028         !S.getOpenCLOptions().isAvailableOption(
9029             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9030         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9031         !PointeeType->isStandardLayoutType())
9032       return InvalidKernelParam;
9033 
9034     return PtrKernelParam;
9035   }
9036 
9037   // OpenCL v1.2 s6.9.k:
9038   // Arguments to kernel functions in a program cannot be declared with the
9039   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9040   // uintptr_t or a struct and/or union that contain fields declared to be one
9041   // of these built-in scalar types.
9042   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9043     return InvalidKernelParam;
9044 
9045   if (PT->isImageType())
9046     return PtrKernelParam;
9047 
9048   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9049     return InvalidKernelParam;
9050 
9051   // OpenCL extension spec v1.2 s9.5:
9052   // This extension adds support for half scalar and vector types as built-in
9053   // types that can be used for arithmetic operations, conversions etc.
9054   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9055       PT->isHalfType())
9056     return InvalidKernelParam;
9057 
9058   // Look into an array argument to check if it has a forbidden type.
9059   if (PT->isArrayType()) {
9060     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9061     // Call ourself to check an underlying type of an array. Since the
9062     // getPointeeOrArrayElementType returns an innermost type which is not an
9063     // array, this recursive call only happens once.
9064     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9065   }
9066 
9067   // C++ for OpenCL v1.0 s2.4:
9068   // Moreover the types used in parameters of the kernel functions must be:
9069   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9070   // types) for parameters passed by value;
9071   if (S.getLangOpts().OpenCLCPlusPlus &&
9072       !S.getOpenCLOptions().isAvailableOption(
9073           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9074       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9075     return InvalidKernelParam;
9076 
9077   if (PT->isRecordType())
9078     return RecordKernelParam;
9079 
9080   return ValidKernelParam;
9081 }
9082 
9083 static void checkIsValidOpenCLKernelParameter(
9084   Sema &S,
9085   Declarator &D,
9086   ParmVarDecl *Param,
9087   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9088   QualType PT = Param->getType();
9089 
9090   // Cache the valid types we encounter to avoid rechecking structs that are
9091   // used again
9092   if (ValidTypes.count(PT.getTypePtr()))
9093     return;
9094 
9095   switch (getOpenCLKernelParameterType(S, PT)) {
9096   case PtrPtrKernelParam:
9097     // OpenCL v3.0 s6.11.a:
9098     // A kernel function argument cannot be declared as a pointer to a pointer
9099     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9100     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9101       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9102       D.setInvalidType();
9103       return;
9104     }
9105 
9106     ValidTypes.insert(PT.getTypePtr());
9107     return;
9108 
9109   case InvalidAddrSpacePtrKernelParam:
9110     // OpenCL v1.0 s6.5:
9111     // __kernel function arguments declared to be a pointer of a type can point
9112     // to one of the following address spaces only : __global, __local or
9113     // __constant.
9114     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9115     D.setInvalidType();
9116     return;
9117 
9118     // OpenCL v1.2 s6.9.k:
9119     // Arguments to kernel functions in a program cannot be declared with the
9120     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9121     // uintptr_t or a struct and/or union that contain fields declared to be
9122     // one of these built-in scalar types.
9123 
9124   case InvalidKernelParam:
9125     // OpenCL v1.2 s6.8 n:
9126     // A kernel function argument cannot be declared
9127     // of event_t type.
9128     // Do not diagnose half type since it is diagnosed as invalid argument
9129     // type for any function elsewhere.
9130     if (!PT->isHalfType()) {
9131       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9132 
9133       // Explain what typedefs are involved.
9134       const TypedefType *Typedef = nullptr;
9135       while ((Typedef = PT->getAs<TypedefType>())) {
9136         SourceLocation Loc = Typedef->getDecl()->getLocation();
9137         // SourceLocation may be invalid for a built-in type.
9138         if (Loc.isValid())
9139           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9140         PT = Typedef->desugar();
9141       }
9142     }
9143 
9144     D.setInvalidType();
9145     return;
9146 
9147   case PtrKernelParam:
9148   case ValidKernelParam:
9149     ValidTypes.insert(PT.getTypePtr());
9150     return;
9151 
9152   case RecordKernelParam:
9153     break;
9154   }
9155 
9156   // Track nested structs we will inspect
9157   SmallVector<const Decl *, 4> VisitStack;
9158 
9159   // Track where we are in the nested structs. Items will migrate from
9160   // VisitStack to HistoryStack as we do the DFS for bad field.
9161   SmallVector<const FieldDecl *, 4> HistoryStack;
9162   HistoryStack.push_back(nullptr);
9163 
9164   // At this point we already handled everything except of a RecordType or
9165   // an ArrayType of a RecordType.
9166   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9167   const RecordType *RecTy =
9168       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9169   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9170 
9171   VisitStack.push_back(RecTy->getDecl());
9172   assert(VisitStack.back() && "First decl null?");
9173 
9174   do {
9175     const Decl *Next = VisitStack.pop_back_val();
9176     if (!Next) {
9177       assert(!HistoryStack.empty());
9178       // Found a marker, we have gone up a level
9179       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9180         ValidTypes.insert(Hist->getType().getTypePtr());
9181 
9182       continue;
9183     }
9184 
9185     // Adds everything except the original parameter declaration (which is not a
9186     // field itself) to the history stack.
9187     const RecordDecl *RD;
9188     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9189       HistoryStack.push_back(Field);
9190 
9191       QualType FieldTy = Field->getType();
9192       // Other field types (known to be valid or invalid) are handled while we
9193       // walk around RecordDecl::fields().
9194       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9195              "Unexpected type.");
9196       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9197 
9198       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9199     } else {
9200       RD = cast<RecordDecl>(Next);
9201     }
9202 
9203     // Add a null marker so we know when we've gone back up a level
9204     VisitStack.push_back(nullptr);
9205 
9206     for (const auto *FD : RD->fields()) {
9207       QualType QT = FD->getType();
9208 
9209       if (ValidTypes.count(QT.getTypePtr()))
9210         continue;
9211 
9212       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9213       if (ParamType == ValidKernelParam)
9214         continue;
9215 
9216       if (ParamType == RecordKernelParam) {
9217         VisitStack.push_back(FD);
9218         continue;
9219       }
9220 
9221       // OpenCL v1.2 s6.9.p:
9222       // Arguments to kernel functions that are declared to be a struct or union
9223       // do not allow OpenCL objects to be passed as elements of the struct or
9224       // union.
9225       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9226           ParamType == InvalidAddrSpacePtrKernelParam) {
9227         S.Diag(Param->getLocation(),
9228                diag::err_record_with_pointers_kernel_param)
9229           << PT->isUnionType()
9230           << PT;
9231       } else {
9232         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9233       }
9234 
9235       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9236           << OrigRecDecl->getDeclName();
9237 
9238       // We have an error, now let's go back up through history and show where
9239       // the offending field came from
9240       for (ArrayRef<const FieldDecl *>::const_iterator
9241                I = HistoryStack.begin() + 1,
9242                E = HistoryStack.end();
9243            I != E; ++I) {
9244         const FieldDecl *OuterField = *I;
9245         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9246           << OuterField->getType();
9247       }
9248 
9249       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9250         << QT->isPointerType()
9251         << QT;
9252       D.setInvalidType();
9253       return;
9254     }
9255   } while (!VisitStack.empty());
9256 }
9257 
9258 /// Find the DeclContext in which a tag is implicitly declared if we see an
9259 /// elaborated type specifier in the specified context, and lookup finds
9260 /// nothing.
9261 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9262   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9263     DC = DC->getParent();
9264   return DC;
9265 }
9266 
9267 /// Find the Scope in which a tag is implicitly declared if we see an
9268 /// elaborated type specifier in the specified context, and lookup finds
9269 /// nothing.
9270 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9271   while (S->isClassScope() ||
9272          (LangOpts.CPlusPlus &&
9273           S->isFunctionPrototypeScope()) ||
9274          ((S->getFlags() & Scope::DeclScope) == 0) ||
9275          (S->getEntity() && S->getEntity()->isTransparentContext()))
9276     S = S->getParent();
9277   return S;
9278 }
9279 
9280 /// Determine whether a declaration matches a known function in namespace std.
9281 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9282                          unsigned BuiltinID) {
9283   switch (BuiltinID) {
9284   case Builtin::BI__GetExceptionInfo:
9285     // No type checking whatsoever.
9286     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9287 
9288   case Builtin::BIaddressof:
9289   case Builtin::BI__addressof:
9290   case Builtin::BIforward:
9291   case Builtin::BImove:
9292   case Builtin::BImove_if_noexcept:
9293   case Builtin::BIas_const: {
9294     // Ensure that we don't treat the algorithm
9295     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9296     // as the builtin std::move.
9297     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9298     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9299   }
9300 
9301   default:
9302     return false;
9303   }
9304 }
9305 
9306 NamedDecl*
9307 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9308                               TypeSourceInfo *TInfo, LookupResult &Previous,
9309                               MultiTemplateParamsArg TemplateParamListsRef,
9310                               bool &AddToScope) {
9311   QualType R = TInfo->getType();
9312 
9313   assert(R->isFunctionType());
9314   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9315     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9316 
9317   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9318   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9319   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9320     if (!TemplateParamLists.empty() &&
9321         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9322       TemplateParamLists.back() = Invented;
9323     else
9324       TemplateParamLists.push_back(Invented);
9325   }
9326 
9327   // TODO: consider using NameInfo for diagnostic.
9328   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9329   DeclarationName Name = NameInfo.getName();
9330   StorageClass SC = getFunctionStorageClass(*this, D);
9331 
9332   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9333     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9334          diag::err_invalid_thread)
9335       << DeclSpec::getSpecifierName(TSCS);
9336 
9337   if (D.isFirstDeclarationOfMember())
9338     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9339                            D.getIdentifierLoc());
9340 
9341   bool isFriend = false;
9342   FunctionTemplateDecl *FunctionTemplate = nullptr;
9343   bool isMemberSpecialization = false;
9344   bool isFunctionTemplateSpecialization = false;
9345 
9346   bool isDependentClassScopeExplicitSpecialization = false;
9347   bool HasExplicitTemplateArgs = false;
9348   TemplateArgumentListInfo TemplateArgs;
9349 
9350   bool isVirtualOkay = false;
9351 
9352   DeclContext *OriginalDC = DC;
9353   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9354 
9355   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9356                                               isVirtualOkay);
9357   if (!NewFD) return nullptr;
9358 
9359   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9360     NewFD->setTopLevelDeclInObjCContainer();
9361 
9362   // Set the lexical context. If this is a function-scope declaration, or has a
9363   // C++ scope specifier, or is the object of a friend declaration, the lexical
9364   // context will be different from the semantic context.
9365   NewFD->setLexicalDeclContext(CurContext);
9366 
9367   if (IsLocalExternDecl)
9368     NewFD->setLocalExternDecl();
9369 
9370   if (getLangOpts().CPlusPlus) {
9371     bool isInline = D.getDeclSpec().isInlineSpecified();
9372     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9373     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9374     isFriend = D.getDeclSpec().isFriendSpecified();
9375     if (isFriend && !isInline && D.isFunctionDefinition()) {
9376       // C++ [class.friend]p5
9377       //   A function can be defined in a friend declaration of a
9378       //   class . . . . Such a function is implicitly inline.
9379       NewFD->setImplicitlyInline();
9380     }
9381 
9382     // If this is a method defined in an __interface, and is not a constructor
9383     // or an overloaded operator, then set the pure flag (isVirtual will already
9384     // return true).
9385     if (const CXXRecordDecl *Parent =
9386           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9387       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9388         NewFD->setPure(true);
9389 
9390       // C++ [class.union]p2
9391       //   A union can have member functions, but not virtual functions.
9392       if (isVirtual && Parent->isUnion()) {
9393         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9394         NewFD->setInvalidDecl();
9395       }
9396       if ((Parent->isClass() || Parent->isStruct()) &&
9397           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9398           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9399           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9400         if (auto *Def = Parent->getDefinition())
9401           Def->setInitMethod(true);
9402       }
9403     }
9404 
9405     SetNestedNameSpecifier(*this, NewFD, D);
9406     isMemberSpecialization = false;
9407     isFunctionTemplateSpecialization = false;
9408     if (D.isInvalidType())
9409       NewFD->setInvalidDecl();
9410 
9411     // Match up the template parameter lists with the scope specifier, then
9412     // determine whether we have a template or a template specialization.
9413     bool Invalid = false;
9414     TemplateParameterList *TemplateParams =
9415         MatchTemplateParametersToScopeSpecifier(
9416             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9417             D.getCXXScopeSpec(),
9418             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9419                 ? D.getName().TemplateId
9420                 : nullptr,
9421             TemplateParamLists, isFriend, isMemberSpecialization,
9422             Invalid);
9423     if (TemplateParams) {
9424       // Check that we can declare a template here.
9425       if (CheckTemplateDeclScope(S, TemplateParams))
9426         NewFD->setInvalidDecl();
9427 
9428       if (TemplateParams->size() > 0) {
9429         // This is a function template
9430 
9431         // A destructor cannot be a template.
9432         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9433           Diag(NewFD->getLocation(), diag::err_destructor_template);
9434           NewFD->setInvalidDecl();
9435         }
9436 
9437         // If we're adding a template to a dependent context, we may need to
9438         // rebuilding some of the types used within the template parameter list,
9439         // now that we know what the current instantiation is.
9440         if (DC->isDependentContext()) {
9441           ContextRAII SavedContext(*this, DC);
9442           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9443             Invalid = true;
9444         }
9445 
9446         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9447                                                         NewFD->getLocation(),
9448                                                         Name, TemplateParams,
9449                                                         NewFD);
9450         FunctionTemplate->setLexicalDeclContext(CurContext);
9451         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9452 
9453         // For source fidelity, store the other template param lists.
9454         if (TemplateParamLists.size() > 1) {
9455           NewFD->setTemplateParameterListsInfo(Context,
9456               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9457                   .drop_back(1));
9458         }
9459       } else {
9460         // This is a function template specialization.
9461         isFunctionTemplateSpecialization = true;
9462         // For source fidelity, store all the template param lists.
9463         if (TemplateParamLists.size() > 0)
9464           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9465 
9466         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9467         if (isFriend) {
9468           // We want to remove the "template<>", found here.
9469           SourceRange RemoveRange = TemplateParams->getSourceRange();
9470 
9471           // If we remove the template<> and the name is not a
9472           // template-id, we're actually silently creating a problem:
9473           // the friend declaration will refer to an untemplated decl,
9474           // and clearly the user wants a template specialization.  So
9475           // we need to insert '<>' after the name.
9476           SourceLocation InsertLoc;
9477           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9478             InsertLoc = D.getName().getSourceRange().getEnd();
9479             InsertLoc = getLocForEndOfToken(InsertLoc);
9480           }
9481 
9482           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9483             << Name << RemoveRange
9484             << FixItHint::CreateRemoval(RemoveRange)
9485             << FixItHint::CreateInsertion(InsertLoc, "<>");
9486           Invalid = true;
9487         }
9488       }
9489     } else {
9490       // Check that we can declare a template here.
9491       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9492           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9493         NewFD->setInvalidDecl();
9494 
9495       // All template param lists were matched against the scope specifier:
9496       // this is NOT (an explicit specialization of) a template.
9497       if (TemplateParamLists.size() > 0)
9498         // For source fidelity, store all the template param lists.
9499         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9500     }
9501 
9502     if (Invalid) {
9503       NewFD->setInvalidDecl();
9504       if (FunctionTemplate)
9505         FunctionTemplate->setInvalidDecl();
9506     }
9507 
9508     // C++ [dcl.fct.spec]p5:
9509     //   The virtual specifier shall only be used in declarations of
9510     //   nonstatic class member functions that appear within a
9511     //   member-specification of a class declaration; see 10.3.
9512     //
9513     if (isVirtual && !NewFD->isInvalidDecl()) {
9514       if (!isVirtualOkay) {
9515         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9516              diag::err_virtual_non_function);
9517       } else if (!CurContext->isRecord()) {
9518         // 'virtual' was specified outside of the class.
9519         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9520              diag::err_virtual_out_of_class)
9521           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9522       } else if (NewFD->getDescribedFunctionTemplate()) {
9523         // C++ [temp.mem]p3:
9524         //  A member function template shall not be virtual.
9525         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9526              diag::err_virtual_member_function_template)
9527           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9528       } else {
9529         // Okay: Add virtual to the method.
9530         NewFD->setVirtualAsWritten(true);
9531       }
9532 
9533       if (getLangOpts().CPlusPlus14 &&
9534           NewFD->getReturnType()->isUndeducedType())
9535         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9536     }
9537 
9538     if (getLangOpts().CPlusPlus14 &&
9539         (NewFD->isDependentContext() ||
9540          (isFriend && CurContext->isDependentContext())) &&
9541         NewFD->getReturnType()->isUndeducedType()) {
9542       // If the function template is referenced directly (for instance, as a
9543       // member of the current instantiation), pretend it has a dependent type.
9544       // This is not really justified by the standard, but is the only sane
9545       // thing to do.
9546       // FIXME: For a friend function, we have not marked the function as being
9547       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9548       const FunctionProtoType *FPT =
9549           NewFD->getType()->castAs<FunctionProtoType>();
9550       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9551       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9552                                              FPT->getExtProtoInfo()));
9553     }
9554 
9555     // C++ [dcl.fct.spec]p3:
9556     //  The inline specifier shall not appear on a block scope function
9557     //  declaration.
9558     if (isInline && !NewFD->isInvalidDecl()) {
9559       if (CurContext->isFunctionOrMethod()) {
9560         // 'inline' is not allowed on block scope function declaration.
9561         Diag(D.getDeclSpec().getInlineSpecLoc(),
9562              diag::err_inline_declaration_block_scope) << Name
9563           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9564       }
9565     }
9566 
9567     // C++ [dcl.fct.spec]p6:
9568     //  The explicit specifier shall be used only in the declaration of a
9569     //  constructor or conversion function within its class definition;
9570     //  see 12.3.1 and 12.3.2.
9571     if (hasExplicit && !NewFD->isInvalidDecl() &&
9572         !isa<CXXDeductionGuideDecl>(NewFD)) {
9573       if (!CurContext->isRecord()) {
9574         // 'explicit' was specified outside of the class.
9575         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9576              diag::err_explicit_out_of_class)
9577             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9578       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9579                  !isa<CXXConversionDecl>(NewFD)) {
9580         // 'explicit' was specified on a function that wasn't a constructor
9581         // or conversion function.
9582         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9583              diag::err_explicit_non_ctor_or_conv_function)
9584             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9585       }
9586     }
9587 
9588     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9589     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9590       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9591       // are implicitly inline.
9592       NewFD->setImplicitlyInline();
9593 
9594       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9595       // be either constructors or to return a literal type. Therefore,
9596       // destructors cannot be declared constexpr.
9597       if (isa<CXXDestructorDecl>(NewFD) &&
9598           (!getLangOpts().CPlusPlus20 ||
9599            ConstexprKind == ConstexprSpecKind::Consteval)) {
9600         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9601             << static_cast<int>(ConstexprKind);
9602         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9603                                     ? ConstexprSpecKind::Unspecified
9604                                     : ConstexprSpecKind::Constexpr);
9605       }
9606       // C++20 [dcl.constexpr]p2: An allocation function, or a
9607       // deallocation function shall not be declared with the consteval
9608       // specifier.
9609       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9610           (NewFD->getOverloadedOperator() == OO_New ||
9611            NewFD->getOverloadedOperator() == OO_Array_New ||
9612            NewFD->getOverloadedOperator() == OO_Delete ||
9613            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9614         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9615              diag::err_invalid_consteval_decl_kind)
9616             << NewFD;
9617         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9618       }
9619     }
9620 
9621     // If __module_private__ was specified, mark the function accordingly.
9622     if (D.getDeclSpec().isModulePrivateSpecified()) {
9623       if (isFunctionTemplateSpecialization) {
9624         SourceLocation ModulePrivateLoc
9625           = D.getDeclSpec().getModulePrivateSpecLoc();
9626         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9627           << 0
9628           << FixItHint::CreateRemoval(ModulePrivateLoc);
9629       } else {
9630         NewFD->setModulePrivate();
9631         if (FunctionTemplate)
9632           FunctionTemplate->setModulePrivate();
9633       }
9634     }
9635 
9636     if (isFriend) {
9637       if (FunctionTemplate) {
9638         FunctionTemplate->setObjectOfFriendDecl();
9639         FunctionTemplate->setAccess(AS_public);
9640       }
9641       NewFD->setObjectOfFriendDecl();
9642       NewFD->setAccess(AS_public);
9643     }
9644 
9645     // If a function is defined as defaulted or deleted, mark it as such now.
9646     // We'll do the relevant checks on defaulted / deleted functions later.
9647     switch (D.getFunctionDefinitionKind()) {
9648     case FunctionDefinitionKind::Declaration:
9649     case FunctionDefinitionKind::Definition:
9650       break;
9651 
9652     case FunctionDefinitionKind::Defaulted:
9653       NewFD->setDefaulted();
9654       break;
9655 
9656     case FunctionDefinitionKind::Deleted:
9657       NewFD->setDeletedAsWritten();
9658       break;
9659     }
9660 
9661     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9662         D.isFunctionDefinition()) {
9663       // C++ [class.mfct]p2:
9664       //   A member function may be defined (8.4) in its class definition, in
9665       //   which case it is an inline member function (7.1.2)
9666       NewFD->setImplicitlyInline();
9667     }
9668 
9669     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9670         !CurContext->isRecord()) {
9671       // C++ [class.static]p1:
9672       //   A data or function member of a class may be declared static
9673       //   in a class definition, in which case it is a static member of
9674       //   the class.
9675 
9676       // Complain about the 'static' specifier if it's on an out-of-line
9677       // member function definition.
9678 
9679       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9680       // member function template declaration and class member template
9681       // declaration (MSVC versions before 2015), warn about this.
9682       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9683            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9684              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9685            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9686            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9687         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9688     }
9689 
9690     // C++11 [except.spec]p15:
9691     //   A deallocation function with no exception-specification is treated
9692     //   as if it were specified with noexcept(true).
9693     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9694     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9695          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9696         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9697       NewFD->setType(Context.getFunctionType(
9698           FPT->getReturnType(), FPT->getParamTypes(),
9699           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9700   }
9701 
9702   // Filter out previous declarations that don't match the scope.
9703   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9704                        D.getCXXScopeSpec().isNotEmpty() ||
9705                        isMemberSpecialization ||
9706                        isFunctionTemplateSpecialization);
9707 
9708   // Handle GNU asm-label extension (encoded as an attribute).
9709   if (Expr *E = (Expr*) D.getAsmLabel()) {
9710     // The parser guarantees this is a string.
9711     StringLiteral *SE = cast<StringLiteral>(E);
9712     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9713                                         /*IsLiteralLabel=*/true,
9714                                         SE->getStrTokenLoc(0)));
9715   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9716     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9717       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9718     if (I != ExtnameUndeclaredIdentifiers.end()) {
9719       if (isDeclExternC(NewFD)) {
9720         NewFD->addAttr(I->second);
9721         ExtnameUndeclaredIdentifiers.erase(I);
9722       } else
9723         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9724             << /*Variable*/0 << NewFD;
9725     }
9726   }
9727 
9728   // Copy the parameter declarations from the declarator D to the function
9729   // declaration NewFD, if they are available.  First scavenge them into Params.
9730   SmallVector<ParmVarDecl*, 16> Params;
9731   unsigned FTIIdx;
9732   if (D.isFunctionDeclarator(FTIIdx)) {
9733     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9734 
9735     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9736     // function that takes no arguments, not a function that takes a
9737     // single void argument.
9738     // We let through "const void" here because Sema::GetTypeForDeclarator
9739     // already checks for that case.
9740     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9741       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9742         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9743         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9744         Param->setDeclContext(NewFD);
9745         Params.push_back(Param);
9746 
9747         if (Param->isInvalidDecl())
9748           NewFD->setInvalidDecl();
9749       }
9750     }
9751 
9752     if (!getLangOpts().CPlusPlus) {
9753       // In C, find all the tag declarations from the prototype and move them
9754       // into the function DeclContext. Remove them from the surrounding tag
9755       // injection context of the function, which is typically but not always
9756       // the TU.
9757       DeclContext *PrototypeTagContext =
9758           getTagInjectionContext(NewFD->getLexicalDeclContext());
9759       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9760         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9761 
9762         // We don't want to reparent enumerators. Look at their parent enum
9763         // instead.
9764         if (!TD) {
9765           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9766             TD = cast<EnumDecl>(ECD->getDeclContext());
9767         }
9768         if (!TD)
9769           continue;
9770         DeclContext *TagDC = TD->getLexicalDeclContext();
9771         if (!TagDC->containsDecl(TD))
9772           continue;
9773         TagDC->removeDecl(TD);
9774         TD->setDeclContext(NewFD);
9775         NewFD->addDecl(TD);
9776 
9777         // Preserve the lexical DeclContext if it is not the surrounding tag
9778         // injection context of the FD. In this example, the semantic context of
9779         // E will be f and the lexical context will be S, while both the
9780         // semantic and lexical contexts of S will be f:
9781         //   void f(struct S { enum E { a } f; } s);
9782         if (TagDC != PrototypeTagContext)
9783           TD->setLexicalDeclContext(TagDC);
9784       }
9785     }
9786   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9787     // When we're declaring a function with a typedef, typeof, etc as in the
9788     // following example, we'll need to synthesize (unnamed)
9789     // parameters for use in the declaration.
9790     //
9791     // @code
9792     // typedef void fn(int);
9793     // fn f;
9794     // @endcode
9795 
9796     // Synthesize a parameter for each argument type.
9797     for (const auto &AI : FT->param_types()) {
9798       ParmVarDecl *Param =
9799           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9800       Param->setScopeInfo(0, Params.size());
9801       Params.push_back(Param);
9802     }
9803   } else {
9804     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9805            "Should not need args for typedef of non-prototype fn");
9806   }
9807 
9808   // Finally, we know we have the right number of parameters, install them.
9809   NewFD->setParams(Params);
9810 
9811   if (D.getDeclSpec().isNoreturnSpecified())
9812     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9813                                            D.getDeclSpec().getNoreturnSpecLoc(),
9814                                            AttributeCommonInfo::AS_Keyword));
9815 
9816   // Functions returning a variably modified type violate C99 6.7.5.2p2
9817   // because all functions have linkage.
9818   if (!NewFD->isInvalidDecl() &&
9819       NewFD->getReturnType()->isVariablyModifiedType()) {
9820     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9821     NewFD->setInvalidDecl();
9822   }
9823 
9824   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9825   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9826       !NewFD->hasAttr<SectionAttr>())
9827     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9828         Context, PragmaClangTextSection.SectionName,
9829         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9830 
9831   // Apply an implicit SectionAttr if #pragma code_seg is active.
9832   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9833       !NewFD->hasAttr<SectionAttr>()) {
9834     NewFD->addAttr(SectionAttr::CreateImplicit(
9835         Context, CodeSegStack.CurrentValue->getString(),
9836         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9837         SectionAttr::Declspec_allocate));
9838     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9839                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9840                          ASTContext::PSF_Read,
9841                      NewFD))
9842       NewFD->dropAttr<SectionAttr>();
9843   }
9844 
9845   // Apply an implicit CodeSegAttr from class declspec or
9846   // apply an implicit SectionAttr from #pragma code_seg if active.
9847   if (!NewFD->hasAttr<CodeSegAttr>()) {
9848     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9849                                                                  D.isFunctionDefinition())) {
9850       NewFD->addAttr(SAttr);
9851     }
9852   }
9853 
9854   // Handle attributes.
9855   ProcessDeclAttributes(S, NewFD, D);
9856 
9857   if (getLangOpts().OpenCL) {
9858     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9859     // type declaration will generate a compilation error.
9860     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9861     if (AddressSpace != LangAS::Default) {
9862       Diag(NewFD->getLocation(),
9863            diag::err_opencl_return_value_with_address_space);
9864       NewFD->setInvalidDecl();
9865     }
9866   }
9867 
9868   if (!getLangOpts().CPlusPlus) {
9869     // Perform semantic checking on the function declaration.
9870     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9871       CheckMain(NewFD, D.getDeclSpec());
9872 
9873     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9874       CheckMSVCRTEntryPoint(NewFD);
9875 
9876     if (!NewFD->isInvalidDecl())
9877       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9878                                                   isMemberSpecialization,
9879                                                   D.isFunctionDefinition()));
9880     else if (!Previous.empty())
9881       // Recover gracefully from an invalid redeclaration.
9882       D.setRedeclaration(true);
9883     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9884             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9885            "previous declaration set still overloaded");
9886 
9887     // Diagnose no-prototype function declarations with calling conventions that
9888     // don't support variadic calls. Only do this in C and do it after merging
9889     // possibly prototyped redeclarations.
9890     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9891     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9892       CallingConv CC = FT->getExtInfo().getCC();
9893       if (!supportsVariadicCall(CC)) {
9894         // Windows system headers sometimes accidentally use stdcall without
9895         // (void) parameters, so we relax this to a warning.
9896         int DiagID =
9897             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9898         Diag(NewFD->getLocation(), DiagID)
9899             << FunctionType::getNameForCallConv(CC);
9900       }
9901     }
9902 
9903    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9904        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9905      checkNonTrivialCUnion(NewFD->getReturnType(),
9906                            NewFD->getReturnTypeSourceRange().getBegin(),
9907                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9908   } else {
9909     // C++11 [replacement.functions]p3:
9910     //  The program's definitions shall not be specified as inline.
9911     //
9912     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9913     //
9914     // Suppress the diagnostic if the function is __attribute__((used)), since
9915     // that forces an external definition to be emitted.
9916     if (D.getDeclSpec().isInlineSpecified() &&
9917         NewFD->isReplaceableGlobalAllocationFunction() &&
9918         !NewFD->hasAttr<UsedAttr>())
9919       Diag(D.getDeclSpec().getInlineSpecLoc(),
9920            diag::ext_operator_new_delete_declared_inline)
9921         << NewFD->getDeclName();
9922 
9923     // If the declarator is a template-id, translate the parser's template
9924     // argument list into our AST format.
9925     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9926       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9927       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9928       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9929       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9930                                          TemplateId->NumArgs);
9931       translateTemplateArguments(TemplateArgsPtr,
9932                                  TemplateArgs);
9933 
9934       HasExplicitTemplateArgs = true;
9935 
9936       if (NewFD->isInvalidDecl()) {
9937         HasExplicitTemplateArgs = false;
9938       } else if (FunctionTemplate) {
9939         // Function template with explicit template arguments.
9940         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9941           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9942 
9943         HasExplicitTemplateArgs = false;
9944       } else {
9945         assert((isFunctionTemplateSpecialization ||
9946                 D.getDeclSpec().isFriendSpecified()) &&
9947                "should have a 'template<>' for this decl");
9948         // "friend void foo<>(int);" is an implicit specialization decl.
9949         isFunctionTemplateSpecialization = true;
9950       }
9951     } else if (isFriend && isFunctionTemplateSpecialization) {
9952       // This combination is only possible in a recovery case;  the user
9953       // wrote something like:
9954       //   template <> friend void foo(int);
9955       // which we're recovering from as if the user had written:
9956       //   friend void foo<>(int);
9957       // Go ahead and fake up a template id.
9958       HasExplicitTemplateArgs = true;
9959       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9960       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9961     }
9962 
9963     // We do not add HD attributes to specializations here because
9964     // they may have different constexpr-ness compared to their
9965     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9966     // may end up with different effective targets. Instead, a
9967     // specialization inherits its target attributes from its template
9968     // in the CheckFunctionTemplateSpecialization() call below.
9969     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9970       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9971 
9972     // If it's a friend (and only if it's a friend), it's possible
9973     // that either the specialized function type or the specialized
9974     // template is dependent, and therefore matching will fail.  In
9975     // this case, don't check the specialization yet.
9976     if (isFunctionTemplateSpecialization && isFriend &&
9977         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9978          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9979              TemplateArgs.arguments()))) {
9980       assert(HasExplicitTemplateArgs &&
9981              "friend function specialization without template args");
9982       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9983                                                        Previous))
9984         NewFD->setInvalidDecl();
9985     } else if (isFunctionTemplateSpecialization) {
9986       if (CurContext->isDependentContext() && CurContext->isRecord()
9987           && !isFriend) {
9988         isDependentClassScopeExplicitSpecialization = true;
9989       } else if (!NewFD->isInvalidDecl() &&
9990                  CheckFunctionTemplateSpecialization(
9991                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9992                      Previous))
9993         NewFD->setInvalidDecl();
9994 
9995       // C++ [dcl.stc]p1:
9996       //   A storage-class-specifier shall not be specified in an explicit
9997       //   specialization (14.7.3)
9998       FunctionTemplateSpecializationInfo *Info =
9999           NewFD->getTemplateSpecializationInfo();
10000       if (Info && SC != SC_None) {
10001         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10002           Diag(NewFD->getLocation(),
10003                diag::err_explicit_specialization_inconsistent_storage_class)
10004             << SC
10005             << FixItHint::CreateRemoval(
10006                                       D.getDeclSpec().getStorageClassSpecLoc());
10007 
10008         else
10009           Diag(NewFD->getLocation(),
10010                diag::ext_explicit_specialization_storage_class)
10011             << FixItHint::CreateRemoval(
10012                                       D.getDeclSpec().getStorageClassSpecLoc());
10013       }
10014     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10015       if (CheckMemberSpecialization(NewFD, Previous))
10016           NewFD->setInvalidDecl();
10017     }
10018 
10019     // Perform semantic checking on the function declaration.
10020     if (!isDependentClassScopeExplicitSpecialization) {
10021       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10022         CheckMain(NewFD, D.getDeclSpec());
10023 
10024       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10025         CheckMSVCRTEntryPoint(NewFD);
10026 
10027       if (!NewFD->isInvalidDecl())
10028         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10029                                                     isMemberSpecialization,
10030                                                     D.isFunctionDefinition()));
10031       else if (!Previous.empty())
10032         // Recover gracefully from an invalid redeclaration.
10033         D.setRedeclaration(true);
10034     }
10035 
10036     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10037             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10038            "previous declaration set still overloaded");
10039 
10040     NamedDecl *PrincipalDecl = (FunctionTemplate
10041                                 ? cast<NamedDecl>(FunctionTemplate)
10042                                 : NewFD);
10043 
10044     if (isFriend && NewFD->getPreviousDecl()) {
10045       AccessSpecifier Access = AS_public;
10046       if (!NewFD->isInvalidDecl())
10047         Access = NewFD->getPreviousDecl()->getAccess();
10048 
10049       NewFD->setAccess(Access);
10050       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10051     }
10052 
10053     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10054         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10055       PrincipalDecl->setNonMemberOperator();
10056 
10057     // If we have a function template, check the template parameter
10058     // list. This will check and merge default template arguments.
10059     if (FunctionTemplate) {
10060       FunctionTemplateDecl *PrevTemplate =
10061                                      FunctionTemplate->getPreviousDecl();
10062       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10063                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10064                                     : nullptr,
10065                             D.getDeclSpec().isFriendSpecified()
10066                               ? (D.isFunctionDefinition()
10067                                    ? TPC_FriendFunctionTemplateDefinition
10068                                    : TPC_FriendFunctionTemplate)
10069                               : (D.getCXXScopeSpec().isSet() &&
10070                                  DC && DC->isRecord() &&
10071                                  DC->isDependentContext())
10072                                   ? TPC_ClassTemplateMember
10073                                   : TPC_FunctionTemplate);
10074     }
10075 
10076     if (NewFD->isInvalidDecl()) {
10077       // Ignore all the rest of this.
10078     } else if (!D.isRedeclaration()) {
10079       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10080                                        AddToScope };
10081       // Fake up an access specifier if it's supposed to be a class member.
10082       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10083         NewFD->setAccess(AS_public);
10084 
10085       // Qualified decls generally require a previous declaration.
10086       if (D.getCXXScopeSpec().isSet()) {
10087         // ...with the major exception of templated-scope or
10088         // dependent-scope friend declarations.
10089 
10090         // TODO: we currently also suppress this check in dependent
10091         // contexts because (1) the parameter depth will be off when
10092         // matching friend templates and (2) we might actually be
10093         // selecting a friend based on a dependent factor.  But there
10094         // are situations where these conditions don't apply and we
10095         // can actually do this check immediately.
10096         //
10097         // Unless the scope is dependent, it's always an error if qualified
10098         // redeclaration lookup found nothing at all. Diagnose that now;
10099         // nothing will diagnose that error later.
10100         if (isFriend &&
10101             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10102              (!Previous.empty() && CurContext->isDependentContext()))) {
10103           // ignore these
10104         } else if (NewFD->isCPUDispatchMultiVersion() ||
10105                    NewFD->isCPUSpecificMultiVersion()) {
10106           // ignore this, we allow the redeclaration behavior here to create new
10107           // versions of the function.
10108         } else {
10109           // The user tried to provide an out-of-line definition for a
10110           // function that is a member of a class or namespace, but there
10111           // was no such member function declared (C++ [class.mfct]p2,
10112           // C++ [namespace.memdef]p2). For example:
10113           //
10114           // class X {
10115           //   void f() const;
10116           // };
10117           //
10118           // void X::f() { } // ill-formed
10119           //
10120           // Complain about this problem, and attempt to suggest close
10121           // matches (e.g., those that differ only in cv-qualifiers and
10122           // whether the parameter types are references).
10123 
10124           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10125                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10126             AddToScope = ExtraArgs.AddToScope;
10127             return Result;
10128           }
10129         }
10130 
10131         // Unqualified local friend declarations are required to resolve
10132         // to something.
10133       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10134         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10135                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10136           AddToScope = ExtraArgs.AddToScope;
10137           return Result;
10138         }
10139       }
10140     } else if (!D.isFunctionDefinition() &&
10141                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10142                !isFriend && !isFunctionTemplateSpecialization &&
10143                !isMemberSpecialization) {
10144       // An out-of-line member function declaration must also be a
10145       // definition (C++ [class.mfct]p2).
10146       // Note that this is not the case for explicit specializations of
10147       // function templates or member functions of class templates, per
10148       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10149       // extension for compatibility with old SWIG code which likes to
10150       // generate them.
10151       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10152         << D.getCXXScopeSpec().getRange();
10153     }
10154   }
10155 
10156   // If this is the first declaration of a library builtin function, add
10157   // attributes as appropriate.
10158   if (!D.isRedeclaration()) {
10159     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10160       if (unsigned BuiltinID = II->getBuiltinID()) {
10161         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10162         if (!InStdNamespace &&
10163             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10164           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10165             // Validate the type matches unless this builtin is specified as
10166             // matching regardless of its declared type.
10167             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10168               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10169             } else {
10170               ASTContext::GetBuiltinTypeError Error;
10171               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10172               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10173 
10174               if (!Error && !BuiltinType.isNull() &&
10175                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10176                       NewFD->getType(), BuiltinType))
10177                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10178             }
10179           }
10180         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10181                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10182           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10183         }
10184       }
10185     }
10186   }
10187 
10188   ProcessPragmaWeak(S, NewFD);
10189   checkAttributesAfterMerging(*this, *NewFD);
10190 
10191   AddKnownFunctionAttributes(NewFD);
10192 
10193   if (NewFD->hasAttr<OverloadableAttr>() &&
10194       !NewFD->getType()->getAs<FunctionProtoType>()) {
10195     Diag(NewFD->getLocation(),
10196          diag::err_attribute_overloadable_no_prototype)
10197       << NewFD;
10198 
10199     // Turn this into a variadic function with no parameters.
10200     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10201     FunctionProtoType::ExtProtoInfo EPI(
10202         Context.getDefaultCallingConvention(true, false));
10203     EPI.Variadic = true;
10204     EPI.ExtInfo = FT->getExtInfo();
10205 
10206     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10207     NewFD->setType(R);
10208   }
10209 
10210   // If there's a #pragma GCC visibility in scope, and this isn't a class
10211   // member, set the visibility of this function.
10212   if (!DC->isRecord() && NewFD->isExternallyVisible())
10213     AddPushedVisibilityAttribute(NewFD);
10214 
10215   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10216   // marking the function.
10217   AddCFAuditedAttribute(NewFD);
10218 
10219   // If this is a function definition, check if we have to apply any
10220   // attributes (i.e. optnone and no_builtin) due to a pragma.
10221   if (D.isFunctionDefinition()) {
10222     AddRangeBasedOptnone(NewFD);
10223     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10224     AddSectionMSAllocText(NewFD);
10225   }
10226 
10227   // If this is the first declaration of an extern C variable, update
10228   // the map of such variables.
10229   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10230       isIncompleteDeclExternC(*this, NewFD))
10231     RegisterLocallyScopedExternCDecl(NewFD, S);
10232 
10233   // Set this FunctionDecl's range up to the right paren.
10234   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10235 
10236   if (D.isRedeclaration() && !Previous.empty()) {
10237     NamedDecl *Prev = Previous.getRepresentativeDecl();
10238     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10239                                    isMemberSpecialization ||
10240                                        isFunctionTemplateSpecialization,
10241                                    D.isFunctionDefinition());
10242   }
10243 
10244   if (getLangOpts().CUDA) {
10245     IdentifierInfo *II = NewFD->getIdentifier();
10246     if (II && II->isStr(getCudaConfigureFuncName()) &&
10247         !NewFD->isInvalidDecl() &&
10248         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10249       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10250         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10251             << getCudaConfigureFuncName();
10252       Context.setcudaConfigureCallDecl(NewFD);
10253     }
10254 
10255     // Variadic functions, other than a *declaration* of printf, are not allowed
10256     // in device-side CUDA code, unless someone passed
10257     // -fcuda-allow-variadic-functions.
10258     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10259         (NewFD->hasAttr<CUDADeviceAttr>() ||
10260          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10261         !(II && II->isStr("printf") && NewFD->isExternC() &&
10262           !D.isFunctionDefinition())) {
10263       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10264     }
10265   }
10266 
10267   MarkUnusedFileScopedDecl(NewFD);
10268 
10269 
10270 
10271   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10272     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10273     if (SC == SC_Static) {
10274       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10275       D.setInvalidType();
10276     }
10277 
10278     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10279     if (!NewFD->getReturnType()->isVoidType()) {
10280       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10281       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10282           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10283                                 : FixItHint());
10284       D.setInvalidType();
10285     }
10286 
10287     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10288     for (auto Param : NewFD->parameters())
10289       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10290 
10291     if (getLangOpts().OpenCLCPlusPlus) {
10292       if (DC->isRecord()) {
10293         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10294         D.setInvalidType();
10295       }
10296       if (FunctionTemplate) {
10297         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10298         D.setInvalidType();
10299       }
10300     }
10301   }
10302 
10303   if (getLangOpts().CPlusPlus) {
10304     if (FunctionTemplate) {
10305       if (NewFD->isInvalidDecl())
10306         FunctionTemplate->setInvalidDecl();
10307       return FunctionTemplate;
10308     }
10309 
10310     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10311       CompleteMemberSpecialization(NewFD, Previous);
10312   }
10313 
10314   for (const ParmVarDecl *Param : NewFD->parameters()) {
10315     QualType PT = Param->getType();
10316 
10317     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10318     // types.
10319     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10320       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10321         QualType ElemTy = PipeTy->getElementType();
10322           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10323             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10324             D.setInvalidType();
10325           }
10326       }
10327     }
10328   }
10329 
10330   // Here we have an function template explicit specialization at class scope.
10331   // The actual specialization will be postponed to template instatiation
10332   // time via the ClassScopeFunctionSpecializationDecl node.
10333   if (isDependentClassScopeExplicitSpecialization) {
10334     ClassScopeFunctionSpecializationDecl *NewSpec =
10335                          ClassScopeFunctionSpecializationDecl::Create(
10336                                 Context, CurContext, NewFD->getLocation(),
10337                                 cast<CXXMethodDecl>(NewFD),
10338                                 HasExplicitTemplateArgs, TemplateArgs);
10339     CurContext->addDecl(NewSpec);
10340     AddToScope = false;
10341   }
10342 
10343   // Diagnose availability attributes. Availability cannot be used on functions
10344   // that are run during load/unload.
10345   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10346     if (NewFD->hasAttr<ConstructorAttr>()) {
10347       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10348           << 1;
10349       NewFD->dropAttr<AvailabilityAttr>();
10350     }
10351     if (NewFD->hasAttr<DestructorAttr>()) {
10352       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10353           << 2;
10354       NewFD->dropAttr<AvailabilityAttr>();
10355     }
10356   }
10357 
10358   // Diagnose no_builtin attribute on function declaration that are not a
10359   // definition.
10360   // FIXME: We should really be doing this in
10361   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10362   // the FunctionDecl and at this point of the code
10363   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10364   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10365   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10366     switch (D.getFunctionDefinitionKind()) {
10367     case FunctionDefinitionKind::Defaulted:
10368     case FunctionDefinitionKind::Deleted:
10369       Diag(NBA->getLocation(),
10370            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10371           << NBA->getSpelling();
10372       break;
10373     case FunctionDefinitionKind::Declaration:
10374       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10375           << NBA->getSpelling();
10376       break;
10377     case FunctionDefinitionKind::Definition:
10378       break;
10379     }
10380 
10381   return NewFD;
10382 }
10383 
10384 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10385 /// when __declspec(code_seg) "is applied to a class, all member functions of
10386 /// the class and nested classes -- this includes compiler-generated special
10387 /// member functions -- are put in the specified segment."
10388 /// The actual behavior is a little more complicated. The Microsoft compiler
10389 /// won't check outer classes if there is an active value from #pragma code_seg.
10390 /// The CodeSeg is always applied from the direct parent but only from outer
10391 /// classes when the #pragma code_seg stack is empty. See:
10392 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10393 /// available since MS has removed the page.
10394 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10395   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10396   if (!Method)
10397     return nullptr;
10398   const CXXRecordDecl *Parent = Method->getParent();
10399   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10400     Attr *NewAttr = SAttr->clone(S.getASTContext());
10401     NewAttr->setImplicit(true);
10402     return NewAttr;
10403   }
10404 
10405   // The Microsoft compiler won't check outer classes for the CodeSeg
10406   // when the #pragma code_seg stack is active.
10407   if (S.CodeSegStack.CurrentValue)
10408    return nullptr;
10409 
10410   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10411     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10412       Attr *NewAttr = SAttr->clone(S.getASTContext());
10413       NewAttr->setImplicit(true);
10414       return NewAttr;
10415     }
10416   }
10417   return nullptr;
10418 }
10419 
10420 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10421 /// containing class. Otherwise it will return implicit SectionAttr if the
10422 /// function is a definition and there is an active value on CodeSegStack
10423 /// (from the current #pragma code-seg value).
10424 ///
10425 /// \param FD Function being declared.
10426 /// \param IsDefinition Whether it is a definition or just a declarartion.
10427 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10428 ///          nullptr if no attribute should be added.
10429 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10430                                                        bool IsDefinition) {
10431   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10432     return A;
10433   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10434       CodeSegStack.CurrentValue)
10435     return SectionAttr::CreateImplicit(
10436         getASTContext(), CodeSegStack.CurrentValue->getString(),
10437         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10438         SectionAttr::Declspec_allocate);
10439   return nullptr;
10440 }
10441 
10442 /// Determines if we can perform a correct type check for \p D as a
10443 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10444 /// best-effort check.
10445 ///
10446 /// \param NewD The new declaration.
10447 /// \param OldD The old declaration.
10448 /// \param NewT The portion of the type of the new declaration to check.
10449 /// \param OldT The portion of the type of the old declaration to check.
10450 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10451                                           QualType NewT, QualType OldT) {
10452   if (!NewD->getLexicalDeclContext()->isDependentContext())
10453     return true;
10454 
10455   // For dependently-typed local extern declarations and friends, we can't
10456   // perform a correct type check in general until instantiation:
10457   //
10458   //   int f();
10459   //   template<typename T> void g() { T f(); }
10460   //
10461   // (valid if g() is only instantiated with T = int).
10462   if (NewT->isDependentType() &&
10463       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10464     return false;
10465 
10466   // Similarly, if the previous declaration was a dependent local extern
10467   // declaration, we don't really know its type yet.
10468   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10469     return false;
10470 
10471   return true;
10472 }
10473 
10474 /// Checks if the new declaration declared in dependent context must be
10475 /// put in the same redeclaration chain as the specified declaration.
10476 ///
10477 /// \param D Declaration that is checked.
10478 /// \param PrevDecl Previous declaration found with proper lookup method for the
10479 ///                 same declaration name.
10480 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10481 ///          belongs to.
10482 ///
10483 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10484   if (!D->getLexicalDeclContext()->isDependentContext())
10485     return true;
10486 
10487   // Don't chain dependent friend function definitions until instantiation, to
10488   // permit cases like
10489   //
10490   //   void func();
10491   //   template<typename T> class C1 { friend void func() {} };
10492   //   template<typename T> class C2 { friend void func() {} };
10493   //
10494   // ... which is valid if only one of C1 and C2 is ever instantiated.
10495   //
10496   // FIXME: This need only apply to function definitions. For now, we proxy
10497   // this by checking for a file-scope function. We do not want this to apply
10498   // to friend declarations nominating member functions, because that gets in
10499   // the way of access checks.
10500   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10501     return false;
10502 
10503   auto *VD = dyn_cast<ValueDecl>(D);
10504   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10505   return !VD || !PrevVD ||
10506          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10507                                         PrevVD->getType());
10508 }
10509 
10510 /// Check the target attribute of the function for MultiVersion
10511 /// validity.
10512 ///
10513 /// Returns true if there was an error, false otherwise.
10514 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10515   const auto *TA = FD->getAttr<TargetAttr>();
10516   assert(TA && "MultiVersion Candidate requires a target attribute");
10517   ParsedTargetAttr ParseInfo = TA->parse();
10518   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10519   enum ErrType { Feature = 0, Architecture = 1 };
10520 
10521   if (!ParseInfo.Architecture.empty() &&
10522       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10523     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10524         << Architecture << ParseInfo.Architecture;
10525     return true;
10526   }
10527 
10528   for (const auto &Feat : ParseInfo.Features) {
10529     auto BareFeat = StringRef{Feat}.substr(1);
10530     if (Feat[0] == '-') {
10531       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10532           << Feature << ("no-" + BareFeat).str();
10533       return true;
10534     }
10535 
10536     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10537         !TargetInfo.isValidFeatureName(BareFeat)) {
10538       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10539           << Feature << BareFeat;
10540       return true;
10541     }
10542   }
10543   return false;
10544 }
10545 
10546 // Provide a white-list of attributes that are allowed to be combined with
10547 // multiversion functions.
10548 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10549                                            MultiVersionKind MVKind) {
10550   // Note: this list/diagnosis must match the list in
10551   // checkMultiversionAttributesAllSame.
10552   switch (Kind) {
10553   default:
10554     return false;
10555   case attr::Used:
10556     return MVKind == MultiVersionKind::Target;
10557   case attr::NonNull:
10558   case attr::NoThrow:
10559     return true;
10560   }
10561 }
10562 
10563 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10564                                                  const FunctionDecl *FD,
10565                                                  const FunctionDecl *CausedFD,
10566                                                  MultiVersionKind MVKind) {
10567   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10568     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10569         << static_cast<unsigned>(MVKind) << A;
10570     if (CausedFD)
10571       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10572     return true;
10573   };
10574 
10575   for (const Attr *A : FD->attrs()) {
10576     switch (A->getKind()) {
10577     case attr::CPUDispatch:
10578     case attr::CPUSpecific:
10579       if (MVKind != MultiVersionKind::CPUDispatch &&
10580           MVKind != MultiVersionKind::CPUSpecific)
10581         return Diagnose(S, A);
10582       break;
10583     case attr::Target:
10584       if (MVKind != MultiVersionKind::Target)
10585         return Diagnose(S, A);
10586       break;
10587     case attr::TargetClones:
10588       if (MVKind != MultiVersionKind::TargetClones)
10589         return Diagnose(S, A);
10590       break;
10591     default:
10592       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10593         return Diagnose(S, A);
10594       break;
10595     }
10596   }
10597   return false;
10598 }
10599 
10600 bool Sema::areMultiversionVariantFunctionsCompatible(
10601     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10602     const PartialDiagnostic &NoProtoDiagID,
10603     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10604     const PartialDiagnosticAt &NoSupportDiagIDAt,
10605     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10606     bool ConstexprSupported, bool CLinkageMayDiffer) {
10607   enum DoesntSupport {
10608     FuncTemplates = 0,
10609     VirtFuncs = 1,
10610     DeducedReturn = 2,
10611     Constructors = 3,
10612     Destructors = 4,
10613     DeletedFuncs = 5,
10614     DefaultedFuncs = 6,
10615     ConstexprFuncs = 7,
10616     ConstevalFuncs = 8,
10617     Lambda = 9,
10618   };
10619   enum Different {
10620     CallingConv = 0,
10621     ReturnType = 1,
10622     ConstexprSpec = 2,
10623     InlineSpec = 3,
10624     Linkage = 4,
10625     LanguageLinkage = 5,
10626   };
10627 
10628   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10629       !OldFD->getType()->getAs<FunctionProtoType>()) {
10630     Diag(OldFD->getLocation(), NoProtoDiagID);
10631     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10632     return true;
10633   }
10634 
10635   if (NoProtoDiagID.getDiagID() != 0 &&
10636       !NewFD->getType()->getAs<FunctionProtoType>())
10637     return Diag(NewFD->getLocation(), NoProtoDiagID);
10638 
10639   if (!TemplatesSupported &&
10640       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10641     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10642            << FuncTemplates;
10643 
10644   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10645     if (NewCXXFD->isVirtual())
10646       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10647              << VirtFuncs;
10648 
10649     if (isa<CXXConstructorDecl>(NewCXXFD))
10650       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10651              << Constructors;
10652 
10653     if (isa<CXXDestructorDecl>(NewCXXFD))
10654       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10655              << Destructors;
10656   }
10657 
10658   if (NewFD->isDeleted())
10659     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10660            << DeletedFuncs;
10661 
10662   if (NewFD->isDefaulted())
10663     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10664            << DefaultedFuncs;
10665 
10666   if (!ConstexprSupported && NewFD->isConstexpr())
10667     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10668            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10669 
10670   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10671   const auto *NewType = cast<FunctionType>(NewQType);
10672   QualType NewReturnType = NewType->getReturnType();
10673 
10674   if (NewReturnType->isUndeducedType())
10675     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10676            << DeducedReturn;
10677 
10678   // Ensure the return type is identical.
10679   if (OldFD) {
10680     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10681     const auto *OldType = cast<FunctionType>(OldQType);
10682     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10683     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10684 
10685     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10686       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10687 
10688     QualType OldReturnType = OldType->getReturnType();
10689 
10690     if (OldReturnType != NewReturnType)
10691       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10692 
10693     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10694       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10695 
10696     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10697       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10698 
10699     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10700       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10701 
10702     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10703       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10704 
10705     if (CheckEquivalentExceptionSpec(
10706             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10707             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10708       return true;
10709   }
10710   return false;
10711 }
10712 
10713 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10714                                              const FunctionDecl *NewFD,
10715                                              bool CausesMV,
10716                                              MultiVersionKind MVKind) {
10717   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10718     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10719     if (OldFD)
10720       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10721     return true;
10722   }
10723 
10724   bool IsCPUSpecificCPUDispatchMVKind =
10725       MVKind == MultiVersionKind::CPUDispatch ||
10726       MVKind == MultiVersionKind::CPUSpecific;
10727 
10728   if (CausesMV && OldFD &&
10729       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10730     return true;
10731 
10732   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10733     return true;
10734 
10735   // Only allow transition to MultiVersion if it hasn't been used.
10736   if (OldFD && CausesMV && OldFD->isUsed(false))
10737     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10738 
10739   return S.areMultiversionVariantFunctionsCompatible(
10740       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10741       PartialDiagnosticAt(NewFD->getLocation(),
10742                           S.PDiag(diag::note_multiversioning_caused_here)),
10743       PartialDiagnosticAt(NewFD->getLocation(),
10744                           S.PDiag(diag::err_multiversion_doesnt_support)
10745                               << static_cast<unsigned>(MVKind)),
10746       PartialDiagnosticAt(NewFD->getLocation(),
10747                           S.PDiag(diag::err_multiversion_diff)),
10748       /*TemplatesSupported=*/false,
10749       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10750       /*CLinkageMayDiffer=*/false);
10751 }
10752 
10753 /// Check the validity of a multiversion function declaration that is the
10754 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10755 ///
10756 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10757 ///
10758 /// Returns true if there was an error, false otherwise.
10759 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10760                                            MultiVersionKind MVKind,
10761                                            const TargetAttr *TA) {
10762   assert(MVKind != MultiVersionKind::None &&
10763          "Function lacks multiversion attribute");
10764 
10765   // Target only causes MV if it is default, otherwise this is a normal
10766   // function.
10767   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10768     return false;
10769 
10770   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10771     FD->setInvalidDecl();
10772     return true;
10773   }
10774 
10775   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10776     FD->setInvalidDecl();
10777     return true;
10778   }
10779 
10780   FD->setIsMultiVersion();
10781   return false;
10782 }
10783 
10784 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10785   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10786     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10787       return true;
10788   }
10789 
10790   return false;
10791 }
10792 
10793 static bool CheckTargetCausesMultiVersioning(
10794     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10795     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10796   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10797   ParsedTargetAttr NewParsed = NewTA->parse();
10798   // Sort order doesn't matter, it just needs to be consistent.
10799   llvm::sort(NewParsed.Features);
10800 
10801   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10802   // to change, this is a simple redeclaration.
10803   if (!NewTA->isDefaultVersion() &&
10804       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10805     return false;
10806 
10807   // Otherwise, this decl causes MultiVersioning.
10808   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10809                                        MultiVersionKind::Target)) {
10810     NewFD->setInvalidDecl();
10811     return true;
10812   }
10813 
10814   if (CheckMultiVersionValue(S, NewFD)) {
10815     NewFD->setInvalidDecl();
10816     return true;
10817   }
10818 
10819   // If this is 'default', permit the forward declaration.
10820   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10821     Redeclaration = true;
10822     OldDecl = OldFD;
10823     OldFD->setIsMultiVersion();
10824     NewFD->setIsMultiVersion();
10825     return false;
10826   }
10827 
10828   if (CheckMultiVersionValue(S, OldFD)) {
10829     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10830     NewFD->setInvalidDecl();
10831     return true;
10832   }
10833 
10834   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10835 
10836   if (OldParsed == NewParsed) {
10837     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10838     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10839     NewFD->setInvalidDecl();
10840     return true;
10841   }
10842 
10843   for (const auto *FD : OldFD->redecls()) {
10844     const auto *CurTA = FD->getAttr<TargetAttr>();
10845     // We allow forward declarations before ANY multiversioning attributes, but
10846     // nothing after the fact.
10847     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10848         (!CurTA || CurTA->isInherited())) {
10849       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10850           << 0;
10851       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10852       NewFD->setInvalidDecl();
10853       return true;
10854     }
10855   }
10856 
10857   OldFD->setIsMultiVersion();
10858   NewFD->setIsMultiVersion();
10859   Redeclaration = false;
10860   OldDecl = nullptr;
10861   Previous.clear();
10862   return false;
10863 }
10864 
10865 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10866                                         MultiVersionKind New) {
10867   if (Old == New || Old == MultiVersionKind::None ||
10868       New == MultiVersionKind::None)
10869     return true;
10870 
10871   return (Old == MultiVersionKind::CPUDispatch &&
10872           New == MultiVersionKind::CPUSpecific) ||
10873          (Old == MultiVersionKind::CPUSpecific &&
10874           New == MultiVersionKind::CPUDispatch);
10875 }
10876 
10877 /// Check the validity of a new function declaration being added to an existing
10878 /// multiversioned declaration collection.
10879 static bool CheckMultiVersionAdditionalDecl(
10880     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10881     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10882     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10883     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10884     LookupResult &Previous) {
10885 
10886   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10887   // Disallow mixing of multiversioning types.
10888   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10889     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10890     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10891     NewFD->setInvalidDecl();
10892     return true;
10893   }
10894 
10895   ParsedTargetAttr NewParsed;
10896   if (NewTA) {
10897     NewParsed = NewTA->parse();
10898     llvm::sort(NewParsed.Features);
10899   }
10900 
10901   bool UseMemberUsingDeclRules =
10902       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10903 
10904   bool MayNeedOverloadableChecks =
10905       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10906 
10907   // Next, check ALL non-overloads to see if this is a redeclaration of a
10908   // previous member of the MultiVersion set.
10909   for (NamedDecl *ND : Previous) {
10910     FunctionDecl *CurFD = ND->getAsFunction();
10911     if (!CurFD)
10912       continue;
10913     if (MayNeedOverloadableChecks &&
10914         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10915       continue;
10916 
10917     switch (NewMVKind) {
10918     case MultiVersionKind::None:
10919       assert(OldMVKind == MultiVersionKind::TargetClones &&
10920              "Only target_clones can be omitted in subsequent declarations");
10921       break;
10922     case MultiVersionKind::Target: {
10923       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10924       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10925         NewFD->setIsMultiVersion();
10926         Redeclaration = true;
10927         OldDecl = ND;
10928         return false;
10929       }
10930 
10931       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10932       if (CurParsed == NewParsed) {
10933         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10934         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10935         NewFD->setInvalidDecl();
10936         return true;
10937       }
10938       break;
10939     }
10940     case MultiVersionKind::TargetClones: {
10941       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10942       Redeclaration = true;
10943       OldDecl = CurFD;
10944       NewFD->setIsMultiVersion();
10945 
10946       if (CurClones && NewClones &&
10947           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10948            !std::equal(CurClones->featuresStrs_begin(),
10949                        CurClones->featuresStrs_end(),
10950                        NewClones->featuresStrs_begin()))) {
10951         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10952         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10953         NewFD->setInvalidDecl();
10954         return true;
10955       }
10956 
10957       return false;
10958     }
10959     case MultiVersionKind::CPUSpecific:
10960     case MultiVersionKind::CPUDispatch: {
10961       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10962       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10963       // Handle CPUDispatch/CPUSpecific versions.
10964       // Only 1 CPUDispatch function is allowed, this will make it go through
10965       // the redeclaration errors.
10966       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10967           CurFD->hasAttr<CPUDispatchAttr>()) {
10968         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10969             std::equal(
10970                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10971                 NewCPUDisp->cpus_begin(),
10972                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10973                   return Cur->getName() == New->getName();
10974                 })) {
10975           NewFD->setIsMultiVersion();
10976           Redeclaration = true;
10977           OldDecl = ND;
10978           return false;
10979         }
10980 
10981         // If the declarations don't match, this is an error condition.
10982         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10983         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10984         NewFD->setInvalidDecl();
10985         return true;
10986       }
10987       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10988         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10989             std::equal(
10990                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10991                 NewCPUSpec->cpus_begin(),
10992                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10993                   return Cur->getName() == New->getName();
10994                 })) {
10995           NewFD->setIsMultiVersion();
10996           Redeclaration = true;
10997           OldDecl = ND;
10998           return false;
10999         }
11000 
11001         // Only 1 version of CPUSpecific is allowed for each CPU.
11002         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11003           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11004             if (CurII == NewII) {
11005               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11006                   << NewII;
11007               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11008               NewFD->setInvalidDecl();
11009               return true;
11010             }
11011           }
11012         }
11013       }
11014       break;
11015     }
11016     }
11017   }
11018 
11019   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11020   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11021   // handled in the attribute adding step.
11022   if (NewMVKind == MultiVersionKind::Target &&
11023       CheckMultiVersionValue(S, NewFD)) {
11024     NewFD->setInvalidDecl();
11025     return true;
11026   }
11027 
11028   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11029                                        !OldFD->isMultiVersion(), NewMVKind)) {
11030     NewFD->setInvalidDecl();
11031     return true;
11032   }
11033 
11034   // Permit forward declarations in the case where these two are compatible.
11035   if (!OldFD->isMultiVersion()) {
11036     OldFD->setIsMultiVersion();
11037     NewFD->setIsMultiVersion();
11038     Redeclaration = true;
11039     OldDecl = OldFD;
11040     return false;
11041   }
11042 
11043   NewFD->setIsMultiVersion();
11044   Redeclaration = false;
11045   OldDecl = nullptr;
11046   Previous.clear();
11047   return false;
11048 }
11049 
11050 /// Check the validity of a mulitversion function declaration.
11051 /// Also sets the multiversion'ness' of the function itself.
11052 ///
11053 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11054 ///
11055 /// Returns true if there was an error, false otherwise.
11056 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11057                                       bool &Redeclaration, NamedDecl *&OldDecl,
11058                                       LookupResult &Previous) {
11059   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11060   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11061   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11062   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11063   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11064 
11065   // Main isn't allowed to become a multiversion function, however it IS
11066   // permitted to have 'main' be marked with the 'target' optimization hint.
11067   if (NewFD->isMain()) {
11068     if (MVKind != MultiVersionKind::None &&
11069         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11070       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11071       NewFD->setInvalidDecl();
11072       return true;
11073     }
11074     return false;
11075   }
11076 
11077   if (!OldDecl || !OldDecl->getAsFunction() ||
11078       OldDecl->getDeclContext()->getRedeclContext() !=
11079           NewFD->getDeclContext()->getRedeclContext()) {
11080     // If there's no previous declaration, AND this isn't attempting to cause
11081     // multiversioning, this isn't an error condition.
11082     if (MVKind == MultiVersionKind::None)
11083       return false;
11084     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11085   }
11086 
11087   FunctionDecl *OldFD = OldDecl->getAsFunction();
11088 
11089   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11090     return false;
11091 
11092   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11093   // for target_clones.
11094   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11095       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11096     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11097         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11098     NewFD->setInvalidDecl();
11099     return true;
11100   }
11101 
11102   if (!OldFD->isMultiVersion()) {
11103     switch (MVKind) {
11104     case MultiVersionKind::Target:
11105       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11106                                               Redeclaration, OldDecl, Previous);
11107     case MultiVersionKind::TargetClones:
11108       if (OldFD->isUsed(false)) {
11109         NewFD->setInvalidDecl();
11110         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11111       }
11112       OldFD->setIsMultiVersion();
11113       break;
11114     case MultiVersionKind::CPUDispatch:
11115     case MultiVersionKind::CPUSpecific:
11116     case MultiVersionKind::None:
11117       break;
11118     }
11119   }
11120 
11121   // At this point, we have a multiversion function decl (in OldFD) AND an
11122   // appropriate attribute in the current function decl.  Resolve that these are
11123   // still compatible with previous declarations.
11124   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11125                                          NewCPUDisp, NewCPUSpec, NewClones,
11126                                          Redeclaration, OldDecl, Previous);
11127 }
11128 
11129 /// Perform semantic checking of a new function declaration.
11130 ///
11131 /// Performs semantic analysis of the new function declaration
11132 /// NewFD. This routine performs all semantic checking that does not
11133 /// require the actual declarator involved in the declaration, and is
11134 /// used both for the declaration of functions as they are parsed
11135 /// (called via ActOnDeclarator) and for the declaration of functions
11136 /// that have been instantiated via C++ template instantiation (called
11137 /// via InstantiateDecl).
11138 ///
11139 /// \param IsMemberSpecialization whether this new function declaration is
11140 /// a member specialization (that replaces any definition provided by the
11141 /// previous declaration).
11142 ///
11143 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11144 ///
11145 /// \returns true if the function declaration is a redeclaration.
11146 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11147                                     LookupResult &Previous,
11148                                     bool IsMemberSpecialization,
11149                                     bool DeclIsDefn) {
11150   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11151          "Variably modified return types are not handled here");
11152 
11153   // Determine whether the type of this function should be merged with
11154   // a previous visible declaration. This never happens for functions in C++,
11155   // and always happens in C if the previous declaration was visible.
11156   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11157                                !Previous.isShadowed();
11158 
11159   bool Redeclaration = false;
11160   NamedDecl *OldDecl = nullptr;
11161   bool MayNeedOverloadableChecks = false;
11162 
11163   // Merge or overload the declaration with an existing declaration of
11164   // the same name, if appropriate.
11165   if (!Previous.empty()) {
11166     // Determine whether NewFD is an overload of PrevDecl or
11167     // a declaration that requires merging. If it's an overload,
11168     // there's no more work to do here; we'll just add the new
11169     // function to the scope.
11170     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11171       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11172       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11173         Redeclaration = true;
11174         OldDecl = Candidate;
11175       }
11176     } else {
11177       MayNeedOverloadableChecks = true;
11178       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11179                             /*NewIsUsingDecl*/ false)) {
11180       case Ovl_Match:
11181         Redeclaration = true;
11182         break;
11183 
11184       case Ovl_NonFunction:
11185         Redeclaration = true;
11186         break;
11187 
11188       case Ovl_Overload:
11189         Redeclaration = false;
11190         break;
11191       }
11192     }
11193   }
11194 
11195   // Check for a previous extern "C" declaration with this name.
11196   if (!Redeclaration &&
11197       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11198     if (!Previous.empty()) {
11199       // This is an extern "C" declaration with the same name as a previous
11200       // declaration, and thus redeclares that entity...
11201       Redeclaration = true;
11202       OldDecl = Previous.getFoundDecl();
11203       MergeTypeWithPrevious = false;
11204 
11205       // ... except in the presence of __attribute__((overloadable)).
11206       if (OldDecl->hasAttr<OverloadableAttr>() ||
11207           NewFD->hasAttr<OverloadableAttr>()) {
11208         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11209           MayNeedOverloadableChecks = true;
11210           Redeclaration = false;
11211           OldDecl = nullptr;
11212         }
11213       }
11214     }
11215   }
11216 
11217   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11218     return Redeclaration;
11219 
11220   // PPC MMA non-pointer types are not allowed as function return types.
11221   if (Context.getTargetInfo().getTriple().isPPC64() &&
11222       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11223     NewFD->setInvalidDecl();
11224   }
11225 
11226   // C++11 [dcl.constexpr]p8:
11227   //   A constexpr specifier for a non-static member function that is not
11228   //   a constructor declares that member function to be const.
11229   //
11230   // This needs to be delayed until we know whether this is an out-of-line
11231   // definition of a static member function.
11232   //
11233   // This rule is not present in C++1y, so we produce a backwards
11234   // compatibility warning whenever it happens in C++11.
11235   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11236   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11237       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11238       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11239     CXXMethodDecl *OldMD = nullptr;
11240     if (OldDecl)
11241       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11242     if (!OldMD || !OldMD->isStatic()) {
11243       const FunctionProtoType *FPT =
11244         MD->getType()->castAs<FunctionProtoType>();
11245       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11246       EPI.TypeQuals.addConst();
11247       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11248                                           FPT->getParamTypes(), EPI));
11249 
11250       // Warn that we did this, if we're not performing template instantiation.
11251       // In that case, we'll have warned already when the template was defined.
11252       if (!inTemplateInstantiation()) {
11253         SourceLocation AddConstLoc;
11254         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11255                 .IgnoreParens().getAs<FunctionTypeLoc>())
11256           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11257 
11258         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11259           << FixItHint::CreateInsertion(AddConstLoc, " const");
11260       }
11261     }
11262   }
11263 
11264   if (Redeclaration) {
11265     // NewFD and OldDecl represent declarations that need to be
11266     // merged.
11267     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11268                           DeclIsDefn)) {
11269       NewFD->setInvalidDecl();
11270       return Redeclaration;
11271     }
11272 
11273     Previous.clear();
11274     Previous.addDecl(OldDecl);
11275 
11276     if (FunctionTemplateDecl *OldTemplateDecl =
11277             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11278       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11279       FunctionTemplateDecl *NewTemplateDecl
11280         = NewFD->getDescribedFunctionTemplate();
11281       assert(NewTemplateDecl && "Template/non-template mismatch");
11282 
11283       // The call to MergeFunctionDecl above may have created some state in
11284       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11285       // can add it as a redeclaration.
11286       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11287 
11288       NewFD->setPreviousDeclaration(OldFD);
11289       if (NewFD->isCXXClassMember()) {
11290         NewFD->setAccess(OldTemplateDecl->getAccess());
11291         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11292       }
11293 
11294       // If this is an explicit specialization of a member that is a function
11295       // template, mark it as a member specialization.
11296       if (IsMemberSpecialization &&
11297           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11298         NewTemplateDecl->setMemberSpecialization();
11299         assert(OldTemplateDecl->isMemberSpecialization());
11300         // Explicit specializations of a member template do not inherit deleted
11301         // status from the parent member template that they are specializing.
11302         if (OldFD->isDeleted()) {
11303           // FIXME: This assert will not hold in the presence of modules.
11304           assert(OldFD->getCanonicalDecl() == OldFD);
11305           // FIXME: We need an update record for this AST mutation.
11306           OldFD->setDeletedAsWritten(false);
11307         }
11308       }
11309 
11310     } else {
11311       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11312         auto *OldFD = cast<FunctionDecl>(OldDecl);
11313         // This needs to happen first so that 'inline' propagates.
11314         NewFD->setPreviousDeclaration(OldFD);
11315         if (NewFD->isCXXClassMember())
11316           NewFD->setAccess(OldFD->getAccess());
11317       }
11318     }
11319   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11320              !NewFD->getAttr<OverloadableAttr>()) {
11321     assert((Previous.empty() ||
11322             llvm::any_of(Previous,
11323                          [](const NamedDecl *ND) {
11324                            return ND->hasAttr<OverloadableAttr>();
11325                          })) &&
11326            "Non-redecls shouldn't happen without overloadable present");
11327 
11328     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11329       const auto *FD = dyn_cast<FunctionDecl>(ND);
11330       return FD && !FD->hasAttr<OverloadableAttr>();
11331     });
11332 
11333     if (OtherUnmarkedIter != Previous.end()) {
11334       Diag(NewFD->getLocation(),
11335            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11336       Diag((*OtherUnmarkedIter)->getLocation(),
11337            diag::note_attribute_overloadable_prev_overload)
11338           << false;
11339 
11340       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11341     }
11342   }
11343 
11344   if (LangOpts.OpenMP)
11345     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11346 
11347   // Semantic checking for this function declaration (in isolation).
11348 
11349   if (getLangOpts().CPlusPlus) {
11350     // C++-specific checks.
11351     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11352       CheckConstructor(Constructor);
11353     } else if (CXXDestructorDecl *Destructor =
11354                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11355       CXXRecordDecl *Record = Destructor->getParent();
11356       QualType ClassType = Context.getTypeDeclType(Record);
11357 
11358       // FIXME: Shouldn't we be able to perform this check even when the class
11359       // type is dependent? Both gcc and edg can handle that.
11360       if (!ClassType->isDependentType()) {
11361         DeclarationName Name
11362           = Context.DeclarationNames.getCXXDestructorName(
11363                                         Context.getCanonicalType(ClassType));
11364         if (NewFD->getDeclName() != Name) {
11365           Diag(NewFD->getLocation(), diag::err_destructor_name);
11366           NewFD->setInvalidDecl();
11367           return Redeclaration;
11368         }
11369       }
11370     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11371       if (auto *TD = Guide->getDescribedFunctionTemplate())
11372         CheckDeductionGuideTemplate(TD);
11373 
11374       // A deduction guide is not on the list of entities that can be
11375       // explicitly specialized.
11376       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11377         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11378             << /*explicit specialization*/ 1;
11379     }
11380 
11381     // Find any virtual functions that this function overrides.
11382     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11383       if (!Method->isFunctionTemplateSpecialization() &&
11384           !Method->getDescribedFunctionTemplate() &&
11385           Method->isCanonicalDecl()) {
11386         AddOverriddenMethods(Method->getParent(), Method);
11387       }
11388       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11389         // C++2a [class.virtual]p6
11390         // A virtual method shall not have a requires-clause.
11391         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11392              diag::err_constrained_virtual_method);
11393 
11394       if (Method->isStatic())
11395         checkThisInStaticMemberFunctionType(Method);
11396     }
11397 
11398     // C++20: dcl.decl.general p4:
11399     // The optional requires-clause ([temp.pre]) in an init-declarator or
11400     // member-declarator shall be present only if the declarator declares a
11401     // templated function ([dcl.fct]).
11402     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11403       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11404         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11405     }
11406 
11407     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11408       ActOnConversionDeclarator(Conversion);
11409 
11410     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11411     if (NewFD->isOverloadedOperator() &&
11412         CheckOverloadedOperatorDeclaration(NewFD)) {
11413       NewFD->setInvalidDecl();
11414       return Redeclaration;
11415     }
11416 
11417     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11418     if (NewFD->getLiteralIdentifier() &&
11419         CheckLiteralOperatorDeclaration(NewFD)) {
11420       NewFD->setInvalidDecl();
11421       return Redeclaration;
11422     }
11423 
11424     // In C++, check default arguments now that we have merged decls. Unless
11425     // the lexical context is the class, because in this case this is done
11426     // during delayed parsing anyway.
11427     if (!CurContext->isRecord())
11428       CheckCXXDefaultArguments(NewFD);
11429 
11430     // If this function is declared as being extern "C", then check to see if
11431     // the function returns a UDT (class, struct, or union type) that is not C
11432     // compatible, and if it does, warn the user.
11433     // But, issue any diagnostic on the first declaration only.
11434     if (Previous.empty() && NewFD->isExternC()) {
11435       QualType R = NewFD->getReturnType();
11436       if (R->isIncompleteType() && !R->isVoidType())
11437         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11438             << NewFD << R;
11439       else if (!R.isPODType(Context) && !R->isVoidType() &&
11440                !R->isObjCObjectPointerType())
11441         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11442     }
11443 
11444     // C++1z [dcl.fct]p6:
11445     //   [...] whether the function has a non-throwing exception-specification
11446     //   [is] part of the function type
11447     //
11448     // This results in an ABI break between C++14 and C++17 for functions whose
11449     // declared type includes an exception-specification in a parameter or
11450     // return type. (Exception specifications on the function itself are OK in
11451     // most cases, and exception specifications are not permitted in most other
11452     // contexts where they could make it into a mangling.)
11453     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11454       auto HasNoexcept = [&](QualType T) -> bool {
11455         // Strip off declarator chunks that could be between us and a function
11456         // type. We don't need to look far, exception specifications are very
11457         // restricted prior to C++17.
11458         if (auto *RT = T->getAs<ReferenceType>())
11459           T = RT->getPointeeType();
11460         else if (T->isAnyPointerType())
11461           T = T->getPointeeType();
11462         else if (auto *MPT = T->getAs<MemberPointerType>())
11463           T = MPT->getPointeeType();
11464         if (auto *FPT = T->getAs<FunctionProtoType>())
11465           if (FPT->isNothrow())
11466             return true;
11467         return false;
11468       };
11469 
11470       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11471       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11472       for (QualType T : FPT->param_types())
11473         AnyNoexcept |= HasNoexcept(T);
11474       if (AnyNoexcept)
11475         Diag(NewFD->getLocation(),
11476              diag::warn_cxx17_compat_exception_spec_in_signature)
11477             << NewFD;
11478     }
11479 
11480     if (!Redeclaration && LangOpts.CUDA)
11481       checkCUDATargetOverload(NewFD, Previous);
11482   }
11483   return Redeclaration;
11484 }
11485 
11486 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11487   // C++11 [basic.start.main]p3:
11488   //   A program that [...] declares main to be inline, static or
11489   //   constexpr is ill-formed.
11490   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11491   //   appear in a declaration of main.
11492   // static main is not an error under C99, but we should warn about it.
11493   // We accept _Noreturn main as an extension.
11494   if (FD->getStorageClass() == SC_Static)
11495     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11496          ? diag::err_static_main : diag::warn_static_main)
11497       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11498   if (FD->isInlineSpecified())
11499     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11500       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11501   if (DS.isNoreturnSpecified()) {
11502     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11503     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11504     Diag(NoreturnLoc, diag::ext_noreturn_main);
11505     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11506       << FixItHint::CreateRemoval(NoreturnRange);
11507   }
11508   if (FD->isConstexpr()) {
11509     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11510         << FD->isConsteval()
11511         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11512     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11513   }
11514 
11515   if (getLangOpts().OpenCL) {
11516     Diag(FD->getLocation(), diag::err_opencl_no_main)
11517         << FD->hasAttr<OpenCLKernelAttr>();
11518     FD->setInvalidDecl();
11519     return;
11520   }
11521 
11522   // Functions named main in hlsl are default entries, but don't have specific
11523   // signatures they are required to conform to.
11524   if (getLangOpts().HLSL)
11525     return;
11526 
11527   QualType T = FD->getType();
11528   assert(T->isFunctionType() && "function decl is not of function type");
11529   const FunctionType* FT = T->castAs<FunctionType>();
11530 
11531   // Set default calling convention for main()
11532   if (FT->getCallConv() != CC_C) {
11533     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11534     FD->setType(QualType(FT, 0));
11535     T = Context.getCanonicalType(FD->getType());
11536   }
11537 
11538   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11539     // In C with GNU extensions we allow main() to have non-integer return
11540     // type, but we should warn about the extension, and we disable the
11541     // implicit-return-zero rule.
11542 
11543     // GCC in C mode accepts qualified 'int'.
11544     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11545       FD->setHasImplicitReturnZero(true);
11546     else {
11547       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11548       SourceRange RTRange = FD->getReturnTypeSourceRange();
11549       if (RTRange.isValid())
11550         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11551             << FixItHint::CreateReplacement(RTRange, "int");
11552     }
11553   } else {
11554     // In C and C++, main magically returns 0 if you fall off the end;
11555     // set the flag which tells us that.
11556     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11557 
11558     // All the standards say that main() should return 'int'.
11559     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11560       FD->setHasImplicitReturnZero(true);
11561     else {
11562       // Otherwise, this is just a flat-out error.
11563       SourceRange RTRange = FD->getReturnTypeSourceRange();
11564       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11565           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11566                                 : FixItHint());
11567       FD->setInvalidDecl(true);
11568     }
11569   }
11570 
11571   // Treat protoless main() as nullary.
11572   if (isa<FunctionNoProtoType>(FT)) return;
11573 
11574   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11575   unsigned nparams = FTP->getNumParams();
11576   assert(FD->getNumParams() == nparams);
11577 
11578   bool HasExtraParameters = (nparams > 3);
11579 
11580   if (FTP->isVariadic()) {
11581     Diag(FD->getLocation(), diag::ext_variadic_main);
11582     // FIXME: if we had information about the location of the ellipsis, we
11583     // could add a FixIt hint to remove it as a parameter.
11584   }
11585 
11586   // Darwin passes an undocumented fourth argument of type char**.  If
11587   // other platforms start sprouting these, the logic below will start
11588   // getting shifty.
11589   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11590     HasExtraParameters = false;
11591 
11592   if (HasExtraParameters) {
11593     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11594     FD->setInvalidDecl(true);
11595     nparams = 3;
11596   }
11597 
11598   // FIXME: a lot of the following diagnostics would be improved
11599   // if we had some location information about types.
11600 
11601   QualType CharPP =
11602     Context.getPointerType(Context.getPointerType(Context.CharTy));
11603   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11604 
11605   for (unsigned i = 0; i < nparams; ++i) {
11606     QualType AT = FTP->getParamType(i);
11607 
11608     bool mismatch = true;
11609 
11610     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11611       mismatch = false;
11612     else if (Expected[i] == CharPP) {
11613       // As an extension, the following forms are okay:
11614       //   char const **
11615       //   char const * const *
11616       //   char * const *
11617 
11618       QualifierCollector qs;
11619       const PointerType* PT;
11620       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11621           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11622           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11623                               Context.CharTy)) {
11624         qs.removeConst();
11625         mismatch = !qs.empty();
11626       }
11627     }
11628 
11629     if (mismatch) {
11630       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11631       // TODO: suggest replacing given type with expected type
11632       FD->setInvalidDecl(true);
11633     }
11634   }
11635 
11636   if (nparams == 1 && !FD->isInvalidDecl()) {
11637     Diag(FD->getLocation(), diag::warn_main_one_arg);
11638   }
11639 
11640   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11641     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11642     FD->setInvalidDecl();
11643   }
11644 }
11645 
11646 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11647 
11648   // Default calling convention for main and wmain is __cdecl
11649   if (FD->getName() == "main" || FD->getName() == "wmain")
11650     return false;
11651 
11652   // Default calling convention for MinGW is __cdecl
11653   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11654   if (T.isWindowsGNUEnvironment())
11655     return false;
11656 
11657   // Default calling convention for WinMain, wWinMain and DllMain
11658   // is __stdcall on 32 bit Windows
11659   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11660     return true;
11661 
11662   return false;
11663 }
11664 
11665 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11666   QualType T = FD->getType();
11667   assert(T->isFunctionType() && "function decl is not of function type");
11668   const FunctionType *FT = T->castAs<FunctionType>();
11669 
11670   // Set an implicit return of 'zero' if the function can return some integral,
11671   // enumeration, pointer or nullptr type.
11672   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11673       FT->getReturnType()->isAnyPointerType() ||
11674       FT->getReturnType()->isNullPtrType())
11675     // DllMain is exempt because a return value of zero means it failed.
11676     if (FD->getName() != "DllMain")
11677       FD->setHasImplicitReturnZero(true);
11678 
11679   // Explicity specified calling conventions are applied to MSVC entry points
11680   if (!hasExplicitCallingConv(T)) {
11681     if (isDefaultStdCall(FD, *this)) {
11682       if (FT->getCallConv() != CC_X86StdCall) {
11683         FT = Context.adjustFunctionType(
11684             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11685         FD->setType(QualType(FT, 0));
11686       }
11687     } else if (FT->getCallConv() != CC_C) {
11688       FT = Context.adjustFunctionType(FT,
11689                                       FT->getExtInfo().withCallingConv(CC_C));
11690       FD->setType(QualType(FT, 0));
11691     }
11692   }
11693 
11694   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11695     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11696     FD->setInvalidDecl();
11697   }
11698 }
11699 
11700 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11701   // FIXME: Need strict checking.  In C89, we need to check for
11702   // any assignment, increment, decrement, function-calls, or
11703   // commas outside of a sizeof.  In C99, it's the same list,
11704   // except that the aforementioned are allowed in unevaluated
11705   // expressions.  Everything else falls under the
11706   // "may accept other forms of constant expressions" exception.
11707   //
11708   // Regular C++ code will not end up here (exceptions: language extensions,
11709   // OpenCL C++ etc), so the constant expression rules there don't matter.
11710   if (Init->isValueDependent()) {
11711     assert(Init->containsErrors() &&
11712            "Dependent code should only occur in error-recovery path.");
11713     return true;
11714   }
11715   const Expr *Culprit;
11716   if (Init->isConstantInitializer(Context, false, &Culprit))
11717     return false;
11718   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11719     << Culprit->getSourceRange();
11720   return true;
11721 }
11722 
11723 namespace {
11724   // Visits an initialization expression to see if OrigDecl is evaluated in
11725   // its own initialization and throws a warning if it does.
11726   class SelfReferenceChecker
11727       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11728     Sema &S;
11729     Decl *OrigDecl;
11730     bool isRecordType;
11731     bool isPODType;
11732     bool isReferenceType;
11733 
11734     bool isInitList;
11735     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11736 
11737   public:
11738     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11739 
11740     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11741                                                     S(S), OrigDecl(OrigDecl) {
11742       isPODType = false;
11743       isRecordType = false;
11744       isReferenceType = false;
11745       isInitList = false;
11746       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11747         isPODType = VD->getType().isPODType(S.Context);
11748         isRecordType = VD->getType()->isRecordType();
11749         isReferenceType = VD->getType()->isReferenceType();
11750       }
11751     }
11752 
11753     // For most expressions, just call the visitor.  For initializer lists,
11754     // track the index of the field being initialized since fields are
11755     // initialized in order allowing use of previously initialized fields.
11756     void CheckExpr(Expr *E) {
11757       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11758       if (!InitList) {
11759         Visit(E);
11760         return;
11761       }
11762 
11763       // Track and increment the index here.
11764       isInitList = true;
11765       InitFieldIndex.push_back(0);
11766       for (auto Child : InitList->children()) {
11767         CheckExpr(cast<Expr>(Child));
11768         ++InitFieldIndex.back();
11769       }
11770       InitFieldIndex.pop_back();
11771     }
11772 
11773     // Returns true if MemberExpr is checked and no further checking is needed.
11774     // Returns false if additional checking is required.
11775     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11776       llvm::SmallVector<FieldDecl*, 4> Fields;
11777       Expr *Base = E;
11778       bool ReferenceField = false;
11779 
11780       // Get the field members used.
11781       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11782         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11783         if (!FD)
11784           return false;
11785         Fields.push_back(FD);
11786         if (FD->getType()->isReferenceType())
11787           ReferenceField = true;
11788         Base = ME->getBase()->IgnoreParenImpCasts();
11789       }
11790 
11791       // Keep checking only if the base Decl is the same.
11792       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11793       if (!DRE || DRE->getDecl() != OrigDecl)
11794         return false;
11795 
11796       // A reference field can be bound to an unininitialized field.
11797       if (CheckReference && !ReferenceField)
11798         return true;
11799 
11800       // Convert FieldDecls to their index number.
11801       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11802       for (const FieldDecl *I : llvm::reverse(Fields))
11803         UsedFieldIndex.push_back(I->getFieldIndex());
11804 
11805       // See if a warning is needed by checking the first difference in index
11806       // numbers.  If field being used has index less than the field being
11807       // initialized, then the use is safe.
11808       for (auto UsedIter = UsedFieldIndex.begin(),
11809                 UsedEnd = UsedFieldIndex.end(),
11810                 OrigIter = InitFieldIndex.begin(),
11811                 OrigEnd = InitFieldIndex.end();
11812            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11813         if (*UsedIter < *OrigIter)
11814           return true;
11815         if (*UsedIter > *OrigIter)
11816           break;
11817       }
11818 
11819       // TODO: Add a different warning which will print the field names.
11820       HandleDeclRefExpr(DRE);
11821       return true;
11822     }
11823 
11824     // For most expressions, the cast is directly above the DeclRefExpr.
11825     // For conditional operators, the cast can be outside the conditional
11826     // operator if both expressions are DeclRefExpr's.
11827     void HandleValue(Expr *E) {
11828       E = E->IgnoreParens();
11829       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11830         HandleDeclRefExpr(DRE);
11831         return;
11832       }
11833 
11834       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11835         Visit(CO->getCond());
11836         HandleValue(CO->getTrueExpr());
11837         HandleValue(CO->getFalseExpr());
11838         return;
11839       }
11840 
11841       if (BinaryConditionalOperator *BCO =
11842               dyn_cast<BinaryConditionalOperator>(E)) {
11843         Visit(BCO->getCond());
11844         HandleValue(BCO->getFalseExpr());
11845         return;
11846       }
11847 
11848       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11849         HandleValue(OVE->getSourceExpr());
11850         return;
11851       }
11852 
11853       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11854         if (BO->getOpcode() == BO_Comma) {
11855           Visit(BO->getLHS());
11856           HandleValue(BO->getRHS());
11857           return;
11858         }
11859       }
11860 
11861       if (isa<MemberExpr>(E)) {
11862         if (isInitList) {
11863           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11864                                       false /*CheckReference*/))
11865             return;
11866         }
11867 
11868         Expr *Base = E->IgnoreParenImpCasts();
11869         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11870           // Check for static member variables and don't warn on them.
11871           if (!isa<FieldDecl>(ME->getMemberDecl()))
11872             return;
11873           Base = ME->getBase()->IgnoreParenImpCasts();
11874         }
11875         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11876           HandleDeclRefExpr(DRE);
11877         return;
11878       }
11879 
11880       Visit(E);
11881     }
11882 
11883     // Reference types not handled in HandleValue are handled here since all
11884     // uses of references are bad, not just r-value uses.
11885     void VisitDeclRefExpr(DeclRefExpr *E) {
11886       if (isReferenceType)
11887         HandleDeclRefExpr(E);
11888     }
11889 
11890     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11891       if (E->getCastKind() == CK_LValueToRValue) {
11892         HandleValue(E->getSubExpr());
11893         return;
11894       }
11895 
11896       Inherited::VisitImplicitCastExpr(E);
11897     }
11898 
11899     void VisitMemberExpr(MemberExpr *E) {
11900       if (isInitList) {
11901         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11902           return;
11903       }
11904 
11905       // Don't warn on arrays since they can be treated as pointers.
11906       if (E->getType()->canDecayToPointerType()) return;
11907 
11908       // Warn when a non-static method call is followed by non-static member
11909       // field accesses, which is followed by a DeclRefExpr.
11910       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11911       bool Warn = (MD && !MD->isStatic());
11912       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11913       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11914         if (!isa<FieldDecl>(ME->getMemberDecl()))
11915           Warn = false;
11916         Base = ME->getBase()->IgnoreParenImpCasts();
11917       }
11918 
11919       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11920         if (Warn)
11921           HandleDeclRefExpr(DRE);
11922         return;
11923       }
11924 
11925       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11926       // Visit that expression.
11927       Visit(Base);
11928     }
11929 
11930     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11931       Expr *Callee = E->getCallee();
11932 
11933       if (isa<UnresolvedLookupExpr>(Callee))
11934         return Inherited::VisitCXXOperatorCallExpr(E);
11935 
11936       Visit(Callee);
11937       for (auto Arg: E->arguments())
11938         HandleValue(Arg->IgnoreParenImpCasts());
11939     }
11940 
11941     void VisitUnaryOperator(UnaryOperator *E) {
11942       // For POD record types, addresses of its own members are well-defined.
11943       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11944           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11945         if (!isPODType)
11946           HandleValue(E->getSubExpr());
11947         return;
11948       }
11949 
11950       if (E->isIncrementDecrementOp()) {
11951         HandleValue(E->getSubExpr());
11952         return;
11953       }
11954 
11955       Inherited::VisitUnaryOperator(E);
11956     }
11957 
11958     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11959 
11960     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11961       if (E->getConstructor()->isCopyConstructor()) {
11962         Expr *ArgExpr = E->getArg(0);
11963         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11964           if (ILE->getNumInits() == 1)
11965             ArgExpr = ILE->getInit(0);
11966         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11967           if (ICE->getCastKind() == CK_NoOp)
11968             ArgExpr = ICE->getSubExpr();
11969         HandleValue(ArgExpr);
11970         return;
11971       }
11972       Inherited::VisitCXXConstructExpr(E);
11973     }
11974 
11975     void VisitCallExpr(CallExpr *E) {
11976       // Treat std::move as a use.
11977       if (E->isCallToStdMove()) {
11978         HandleValue(E->getArg(0));
11979         return;
11980       }
11981 
11982       Inherited::VisitCallExpr(E);
11983     }
11984 
11985     void VisitBinaryOperator(BinaryOperator *E) {
11986       if (E->isCompoundAssignmentOp()) {
11987         HandleValue(E->getLHS());
11988         Visit(E->getRHS());
11989         return;
11990       }
11991 
11992       Inherited::VisitBinaryOperator(E);
11993     }
11994 
11995     // A custom visitor for BinaryConditionalOperator is needed because the
11996     // regular visitor would check the condition and true expression separately
11997     // but both point to the same place giving duplicate diagnostics.
11998     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11999       Visit(E->getCond());
12000       Visit(E->getFalseExpr());
12001     }
12002 
12003     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12004       Decl* ReferenceDecl = DRE->getDecl();
12005       if (OrigDecl != ReferenceDecl) return;
12006       unsigned diag;
12007       if (isReferenceType) {
12008         diag = diag::warn_uninit_self_reference_in_reference_init;
12009       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12010         diag = diag::warn_static_self_reference_in_init;
12011       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12012                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12013                  DRE->getDecl()->getType()->isRecordType()) {
12014         diag = diag::warn_uninit_self_reference_in_init;
12015       } else {
12016         // Local variables will be handled by the CFG analysis.
12017         return;
12018       }
12019 
12020       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12021                             S.PDiag(diag)
12022                                 << DRE->getDecl() << OrigDecl->getLocation()
12023                                 << DRE->getSourceRange());
12024     }
12025   };
12026 
12027   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12028   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12029                                  bool DirectInit) {
12030     // Parameters arguments are occassionially constructed with itself,
12031     // for instance, in recursive functions.  Skip them.
12032     if (isa<ParmVarDecl>(OrigDecl))
12033       return;
12034 
12035     E = E->IgnoreParens();
12036 
12037     // Skip checking T a = a where T is not a record or reference type.
12038     // Doing so is a way to silence uninitialized warnings.
12039     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12040       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12041         if (ICE->getCastKind() == CK_LValueToRValue)
12042           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12043             if (DRE->getDecl() == OrigDecl)
12044               return;
12045 
12046     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12047   }
12048 } // end anonymous namespace
12049 
12050 namespace {
12051   // Simple wrapper to add the name of a variable or (if no variable is
12052   // available) a DeclarationName into a diagnostic.
12053   struct VarDeclOrName {
12054     VarDecl *VDecl;
12055     DeclarationName Name;
12056 
12057     friend const Sema::SemaDiagnosticBuilder &
12058     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12059       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12060     }
12061   };
12062 } // end anonymous namespace
12063 
12064 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12065                                             DeclarationName Name, QualType Type,
12066                                             TypeSourceInfo *TSI,
12067                                             SourceRange Range, bool DirectInit,
12068                                             Expr *Init) {
12069   bool IsInitCapture = !VDecl;
12070   assert((!VDecl || !VDecl->isInitCapture()) &&
12071          "init captures are expected to be deduced prior to initialization");
12072 
12073   VarDeclOrName VN{VDecl, Name};
12074 
12075   DeducedType *Deduced = Type->getContainedDeducedType();
12076   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12077 
12078   // C++11 [dcl.spec.auto]p3
12079   if (!Init) {
12080     assert(VDecl && "no init for init capture deduction?");
12081 
12082     // Except for class argument deduction, and then for an initializing
12083     // declaration only, i.e. no static at class scope or extern.
12084     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12085         VDecl->hasExternalStorage() ||
12086         VDecl->isStaticDataMember()) {
12087       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12088         << VDecl->getDeclName() << Type;
12089       return QualType();
12090     }
12091   }
12092 
12093   ArrayRef<Expr*> DeduceInits;
12094   if (Init)
12095     DeduceInits = Init;
12096 
12097   if (DirectInit) {
12098     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12099       DeduceInits = PL->exprs();
12100   }
12101 
12102   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12103     assert(VDecl && "non-auto type for init capture deduction?");
12104     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12105     InitializationKind Kind = InitializationKind::CreateForInit(
12106         VDecl->getLocation(), DirectInit, Init);
12107     // FIXME: Initialization should not be taking a mutable list of inits.
12108     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12109     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12110                                                        InitsCopy);
12111   }
12112 
12113   if (DirectInit) {
12114     if (auto *IL = dyn_cast<InitListExpr>(Init))
12115       DeduceInits = IL->inits();
12116   }
12117 
12118   // Deduction only works if we have exactly one source expression.
12119   if (DeduceInits.empty()) {
12120     // It isn't possible to write this directly, but it is possible to
12121     // end up in this situation with "auto x(some_pack...);"
12122     Diag(Init->getBeginLoc(), IsInitCapture
12123                                   ? diag::err_init_capture_no_expression
12124                                   : diag::err_auto_var_init_no_expression)
12125         << VN << Type << Range;
12126     return QualType();
12127   }
12128 
12129   if (DeduceInits.size() > 1) {
12130     Diag(DeduceInits[1]->getBeginLoc(),
12131          IsInitCapture ? diag::err_init_capture_multiple_expressions
12132                        : diag::err_auto_var_init_multiple_expressions)
12133         << VN << Type << Range;
12134     return QualType();
12135   }
12136 
12137   Expr *DeduceInit = DeduceInits[0];
12138   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12139     Diag(Init->getBeginLoc(), IsInitCapture
12140                                   ? diag::err_init_capture_paren_braces
12141                                   : diag::err_auto_var_init_paren_braces)
12142         << isa<InitListExpr>(Init) << VN << Type << Range;
12143     return QualType();
12144   }
12145 
12146   // Expressions default to 'id' when we're in a debugger.
12147   bool DefaultedAnyToId = false;
12148   if (getLangOpts().DebuggerCastResultToId &&
12149       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12150     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12151     if (Result.isInvalid()) {
12152       return QualType();
12153     }
12154     Init = Result.get();
12155     DefaultedAnyToId = true;
12156   }
12157 
12158   // C++ [dcl.decomp]p1:
12159   //   If the assignment-expression [...] has array type A and no ref-qualifier
12160   //   is present, e has type cv A
12161   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12162       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12163       DeduceInit->getType()->isConstantArrayType())
12164     return Context.getQualifiedType(DeduceInit->getType(),
12165                                     Type.getQualifiers());
12166 
12167   QualType DeducedType;
12168   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12169     if (!IsInitCapture)
12170       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12171     else if (isa<InitListExpr>(Init))
12172       Diag(Range.getBegin(),
12173            diag::err_init_capture_deduction_failure_from_init_list)
12174           << VN
12175           << (DeduceInit->getType().isNull() ? TSI->getType()
12176                                              : DeduceInit->getType())
12177           << DeduceInit->getSourceRange();
12178     else
12179       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12180           << VN << TSI->getType()
12181           << (DeduceInit->getType().isNull() ? TSI->getType()
12182                                              : DeduceInit->getType())
12183           << DeduceInit->getSourceRange();
12184   }
12185 
12186   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12187   // 'id' instead of a specific object type prevents most of our usual
12188   // checks.
12189   // We only want to warn outside of template instantiations, though:
12190   // inside a template, the 'id' could have come from a parameter.
12191   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12192       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12193     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12194     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12195   }
12196 
12197   return DeducedType;
12198 }
12199 
12200 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12201                                          Expr *Init) {
12202   assert(!Init || !Init->containsErrors());
12203   QualType DeducedType = deduceVarTypeFromInitializer(
12204       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12205       VDecl->getSourceRange(), DirectInit, Init);
12206   if (DeducedType.isNull()) {
12207     VDecl->setInvalidDecl();
12208     return true;
12209   }
12210 
12211   VDecl->setType(DeducedType);
12212   assert(VDecl->isLinkageValid());
12213 
12214   // In ARC, infer lifetime.
12215   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12216     VDecl->setInvalidDecl();
12217 
12218   if (getLangOpts().OpenCL)
12219     deduceOpenCLAddressSpace(VDecl);
12220 
12221   // If this is a redeclaration, check that the type we just deduced matches
12222   // the previously declared type.
12223   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12224     // We never need to merge the type, because we cannot form an incomplete
12225     // array of auto, nor deduce such a type.
12226     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12227   }
12228 
12229   // Check the deduced type is valid for a variable declaration.
12230   CheckVariableDeclarationType(VDecl);
12231   return VDecl->isInvalidDecl();
12232 }
12233 
12234 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12235                                               SourceLocation Loc) {
12236   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12237     Init = EWC->getSubExpr();
12238 
12239   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12240     Init = CE->getSubExpr();
12241 
12242   QualType InitType = Init->getType();
12243   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12244           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12245          "shouldn't be called if type doesn't have a non-trivial C struct");
12246   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12247     for (auto I : ILE->inits()) {
12248       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12249           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12250         continue;
12251       SourceLocation SL = I->getExprLoc();
12252       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12253     }
12254     return;
12255   }
12256 
12257   if (isa<ImplicitValueInitExpr>(Init)) {
12258     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12259       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12260                             NTCUK_Init);
12261   } else {
12262     // Assume all other explicit initializers involving copying some existing
12263     // object.
12264     // TODO: ignore any explicit initializers where we can guarantee
12265     // copy-elision.
12266     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12267       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12268   }
12269 }
12270 
12271 namespace {
12272 
12273 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12274   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12275   // in the source code or implicitly by the compiler if it is in a union
12276   // defined in a system header and has non-trivial ObjC ownership
12277   // qualifications. We don't want those fields to participate in determining
12278   // whether the containing union is non-trivial.
12279   return FD->hasAttr<UnavailableAttr>();
12280 }
12281 
12282 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12283     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12284                                     void> {
12285   using Super =
12286       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12287                                     void>;
12288 
12289   DiagNonTrivalCUnionDefaultInitializeVisitor(
12290       QualType OrigTy, SourceLocation OrigLoc,
12291       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12292       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12293 
12294   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12295                      const FieldDecl *FD, bool InNonTrivialUnion) {
12296     if (const auto *AT = S.Context.getAsArrayType(QT))
12297       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12298                                      InNonTrivialUnion);
12299     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12300   }
12301 
12302   void visitARCStrong(QualType QT, const FieldDecl *FD,
12303                       bool InNonTrivialUnion) {
12304     if (InNonTrivialUnion)
12305       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12306           << 1 << 0 << QT << FD->getName();
12307   }
12308 
12309   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12310     if (InNonTrivialUnion)
12311       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12312           << 1 << 0 << QT << FD->getName();
12313   }
12314 
12315   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12316     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12317     if (RD->isUnion()) {
12318       if (OrigLoc.isValid()) {
12319         bool IsUnion = false;
12320         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12321           IsUnion = OrigRD->isUnion();
12322         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12323             << 0 << OrigTy << IsUnion << UseContext;
12324         // Reset OrigLoc so that this diagnostic is emitted only once.
12325         OrigLoc = SourceLocation();
12326       }
12327       InNonTrivialUnion = true;
12328     }
12329 
12330     if (InNonTrivialUnion)
12331       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12332           << 0 << 0 << QT.getUnqualifiedType() << "";
12333 
12334     for (const FieldDecl *FD : RD->fields())
12335       if (!shouldIgnoreForRecordTriviality(FD))
12336         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12337   }
12338 
12339   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12340 
12341   // The non-trivial C union type or the struct/union type that contains a
12342   // non-trivial C union.
12343   QualType OrigTy;
12344   SourceLocation OrigLoc;
12345   Sema::NonTrivialCUnionContext UseContext;
12346   Sema &S;
12347 };
12348 
12349 struct DiagNonTrivalCUnionDestructedTypeVisitor
12350     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12351   using Super =
12352       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12353 
12354   DiagNonTrivalCUnionDestructedTypeVisitor(
12355       QualType OrigTy, SourceLocation OrigLoc,
12356       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12357       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12358 
12359   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12360                      const FieldDecl *FD, bool InNonTrivialUnion) {
12361     if (const auto *AT = S.Context.getAsArrayType(QT))
12362       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12363                                      InNonTrivialUnion);
12364     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12365   }
12366 
12367   void visitARCStrong(QualType QT, const FieldDecl *FD,
12368                       bool InNonTrivialUnion) {
12369     if (InNonTrivialUnion)
12370       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12371           << 1 << 1 << QT << FD->getName();
12372   }
12373 
12374   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12375     if (InNonTrivialUnion)
12376       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12377           << 1 << 1 << QT << FD->getName();
12378   }
12379 
12380   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12381     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12382     if (RD->isUnion()) {
12383       if (OrigLoc.isValid()) {
12384         bool IsUnion = false;
12385         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12386           IsUnion = OrigRD->isUnion();
12387         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12388             << 1 << OrigTy << IsUnion << UseContext;
12389         // Reset OrigLoc so that this diagnostic is emitted only once.
12390         OrigLoc = SourceLocation();
12391       }
12392       InNonTrivialUnion = true;
12393     }
12394 
12395     if (InNonTrivialUnion)
12396       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12397           << 0 << 1 << QT.getUnqualifiedType() << "";
12398 
12399     for (const FieldDecl *FD : RD->fields())
12400       if (!shouldIgnoreForRecordTriviality(FD))
12401         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12402   }
12403 
12404   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12405   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12406                           bool InNonTrivialUnion) {}
12407 
12408   // The non-trivial C union type or the struct/union type that contains a
12409   // non-trivial C union.
12410   QualType OrigTy;
12411   SourceLocation OrigLoc;
12412   Sema::NonTrivialCUnionContext UseContext;
12413   Sema &S;
12414 };
12415 
12416 struct DiagNonTrivalCUnionCopyVisitor
12417     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12418   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12419 
12420   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12421                                  Sema::NonTrivialCUnionContext UseContext,
12422                                  Sema &S)
12423       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12424 
12425   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12426                      const FieldDecl *FD, bool InNonTrivialUnion) {
12427     if (const auto *AT = S.Context.getAsArrayType(QT))
12428       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12429                                      InNonTrivialUnion);
12430     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12431   }
12432 
12433   void visitARCStrong(QualType QT, const FieldDecl *FD,
12434                       bool InNonTrivialUnion) {
12435     if (InNonTrivialUnion)
12436       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12437           << 1 << 2 << QT << FD->getName();
12438   }
12439 
12440   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12441     if (InNonTrivialUnion)
12442       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12443           << 1 << 2 << QT << FD->getName();
12444   }
12445 
12446   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12447     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12448     if (RD->isUnion()) {
12449       if (OrigLoc.isValid()) {
12450         bool IsUnion = false;
12451         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12452           IsUnion = OrigRD->isUnion();
12453         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12454             << 2 << OrigTy << IsUnion << UseContext;
12455         // Reset OrigLoc so that this diagnostic is emitted only once.
12456         OrigLoc = SourceLocation();
12457       }
12458       InNonTrivialUnion = true;
12459     }
12460 
12461     if (InNonTrivialUnion)
12462       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12463           << 0 << 2 << QT.getUnqualifiedType() << "";
12464 
12465     for (const FieldDecl *FD : RD->fields())
12466       if (!shouldIgnoreForRecordTriviality(FD))
12467         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12468   }
12469 
12470   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12471                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12472   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12473   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12474                             bool InNonTrivialUnion) {}
12475 
12476   // The non-trivial C union type or the struct/union type that contains a
12477   // non-trivial C union.
12478   QualType OrigTy;
12479   SourceLocation OrigLoc;
12480   Sema::NonTrivialCUnionContext UseContext;
12481   Sema &S;
12482 };
12483 
12484 } // namespace
12485 
12486 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12487                                  NonTrivialCUnionContext UseContext,
12488                                  unsigned NonTrivialKind) {
12489   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12490           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12491           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12492          "shouldn't be called if type doesn't have a non-trivial C union");
12493 
12494   if ((NonTrivialKind & NTCUK_Init) &&
12495       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12496     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12497         .visit(QT, nullptr, false);
12498   if ((NonTrivialKind & NTCUK_Destruct) &&
12499       QT.hasNonTrivialToPrimitiveDestructCUnion())
12500     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12501         .visit(QT, nullptr, false);
12502   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12503     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12504         .visit(QT, nullptr, false);
12505 }
12506 
12507 /// AddInitializerToDecl - Adds the initializer Init to the
12508 /// declaration dcl. If DirectInit is true, this is C++ direct
12509 /// initialization rather than copy initialization.
12510 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12511   // If there is no declaration, there was an error parsing it.  Just ignore
12512   // the initializer.
12513   if (!RealDecl || RealDecl->isInvalidDecl()) {
12514     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12515     return;
12516   }
12517 
12518   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12519     // Pure-specifiers are handled in ActOnPureSpecifier.
12520     Diag(Method->getLocation(), diag::err_member_function_initialization)
12521       << Method->getDeclName() << Init->getSourceRange();
12522     Method->setInvalidDecl();
12523     return;
12524   }
12525 
12526   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12527   if (!VDecl) {
12528     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12529     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12530     RealDecl->setInvalidDecl();
12531     return;
12532   }
12533 
12534   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12535   if (VDecl->getType()->isUndeducedType()) {
12536     // Attempt typo correction early so that the type of the init expression can
12537     // be deduced based on the chosen correction if the original init contains a
12538     // TypoExpr.
12539     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12540     if (!Res.isUsable()) {
12541       // There are unresolved typos in Init, just drop them.
12542       // FIXME: improve the recovery strategy to preserve the Init.
12543       RealDecl->setInvalidDecl();
12544       return;
12545     }
12546     if (Res.get()->containsErrors()) {
12547       // Invalidate the decl as we don't know the type for recovery-expr yet.
12548       RealDecl->setInvalidDecl();
12549       VDecl->setInit(Res.get());
12550       return;
12551     }
12552     Init = Res.get();
12553 
12554     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12555       return;
12556   }
12557 
12558   // dllimport cannot be used on variable definitions.
12559   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12560     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12561     VDecl->setInvalidDecl();
12562     return;
12563   }
12564 
12565   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12566     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12567     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12568     VDecl->setInvalidDecl();
12569     return;
12570   }
12571 
12572   if (!VDecl->getType()->isDependentType()) {
12573     // A definition must end up with a complete type, which means it must be
12574     // complete with the restriction that an array type might be completed by
12575     // the initializer; note that later code assumes this restriction.
12576     QualType BaseDeclType = VDecl->getType();
12577     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12578       BaseDeclType = Array->getElementType();
12579     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12580                             diag::err_typecheck_decl_incomplete_type)) {
12581       RealDecl->setInvalidDecl();
12582       return;
12583     }
12584 
12585     // The variable can not have an abstract class type.
12586     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12587                                diag::err_abstract_type_in_decl,
12588                                AbstractVariableType))
12589       VDecl->setInvalidDecl();
12590   }
12591 
12592   // If adding the initializer will turn this declaration into a definition,
12593   // and we already have a definition for this variable, diagnose or otherwise
12594   // handle the situation.
12595   if (VarDecl *Def = VDecl->getDefinition())
12596     if (Def != VDecl &&
12597         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12598         !VDecl->isThisDeclarationADemotedDefinition() &&
12599         checkVarDeclRedefinition(Def, VDecl))
12600       return;
12601 
12602   if (getLangOpts().CPlusPlus) {
12603     // C++ [class.static.data]p4
12604     //   If a static data member is of const integral or const
12605     //   enumeration type, its declaration in the class definition can
12606     //   specify a constant-initializer which shall be an integral
12607     //   constant expression (5.19). In that case, the member can appear
12608     //   in integral constant expressions. The member shall still be
12609     //   defined in a namespace scope if it is used in the program and the
12610     //   namespace scope definition shall not contain an initializer.
12611     //
12612     // We already performed a redefinition check above, but for static
12613     // data members we also need to check whether there was an in-class
12614     // declaration with an initializer.
12615     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12616       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12617           << VDecl->getDeclName();
12618       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12619            diag::note_previous_initializer)
12620           << 0;
12621       return;
12622     }
12623 
12624     if (VDecl->hasLocalStorage())
12625       setFunctionHasBranchProtectedScope();
12626 
12627     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12628       VDecl->setInvalidDecl();
12629       return;
12630     }
12631   }
12632 
12633   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12634   // a kernel function cannot be initialized."
12635   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12636     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12637     VDecl->setInvalidDecl();
12638     return;
12639   }
12640 
12641   // The LoaderUninitialized attribute acts as a definition (of undef).
12642   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12643     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12644     VDecl->setInvalidDecl();
12645     return;
12646   }
12647 
12648   // Get the decls type and save a reference for later, since
12649   // CheckInitializerTypes may change it.
12650   QualType DclT = VDecl->getType(), SavT = DclT;
12651 
12652   // Expressions default to 'id' when we're in a debugger
12653   // and we are assigning it to a variable of Objective-C pointer type.
12654   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12655       Init->getType() == Context.UnknownAnyTy) {
12656     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12657     if (Result.isInvalid()) {
12658       VDecl->setInvalidDecl();
12659       return;
12660     }
12661     Init = Result.get();
12662   }
12663 
12664   // Perform the initialization.
12665   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12666   if (!VDecl->isInvalidDecl()) {
12667     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12668     InitializationKind Kind = InitializationKind::CreateForInit(
12669         VDecl->getLocation(), DirectInit, Init);
12670 
12671     MultiExprArg Args = Init;
12672     if (CXXDirectInit)
12673       Args = MultiExprArg(CXXDirectInit->getExprs(),
12674                           CXXDirectInit->getNumExprs());
12675 
12676     // Try to correct any TypoExprs in the initialization arguments.
12677     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12678       ExprResult Res = CorrectDelayedTyposInExpr(
12679           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12680           [this, Entity, Kind](Expr *E) {
12681             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12682             return Init.Failed() ? ExprError() : E;
12683           });
12684       if (Res.isInvalid()) {
12685         VDecl->setInvalidDecl();
12686       } else if (Res.get() != Args[Idx]) {
12687         Args[Idx] = Res.get();
12688       }
12689     }
12690     if (VDecl->isInvalidDecl())
12691       return;
12692 
12693     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12694                                    /*TopLevelOfInitList=*/false,
12695                                    /*TreatUnavailableAsInvalid=*/false);
12696     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12697     if (Result.isInvalid()) {
12698       // If the provided initializer fails to initialize the var decl,
12699       // we attach a recovery expr for better recovery.
12700       auto RecoveryExpr =
12701           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12702       if (RecoveryExpr.get())
12703         VDecl->setInit(RecoveryExpr.get());
12704       return;
12705     }
12706 
12707     Init = Result.getAs<Expr>();
12708   }
12709 
12710   // Check for self-references within variable initializers.
12711   // Variables declared within a function/method body (except for references)
12712   // are handled by a dataflow analysis.
12713   // This is undefined behavior in C++, but valid in C.
12714   if (getLangOpts().CPlusPlus)
12715     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12716         VDecl->getType()->isReferenceType())
12717       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12718 
12719   // If the type changed, it means we had an incomplete type that was
12720   // completed by the initializer. For example:
12721   //   int ary[] = { 1, 3, 5 };
12722   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12723   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12724     VDecl->setType(DclT);
12725 
12726   if (!VDecl->isInvalidDecl()) {
12727     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12728 
12729     if (VDecl->hasAttr<BlocksAttr>())
12730       checkRetainCycles(VDecl, Init);
12731 
12732     // It is safe to assign a weak reference into a strong variable.
12733     // Although this code can still have problems:
12734     //   id x = self.weakProp;
12735     //   id y = self.weakProp;
12736     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12737     // paths through the function. This should be revisited if
12738     // -Wrepeated-use-of-weak is made flow-sensitive.
12739     if (FunctionScopeInfo *FSI = getCurFunction())
12740       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12741            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12742           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12743                            Init->getBeginLoc()))
12744         FSI->markSafeWeakUse(Init);
12745   }
12746 
12747   // The initialization is usually a full-expression.
12748   //
12749   // FIXME: If this is a braced initialization of an aggregate, it is not
12750   // an expression, and each individual field initializer is a separate
12751   // full-expression. For instance, in:
12752   //
12753   //   struct Temp { ~Temp(); };
12754   //   struct S { S(Temp); };
12755   //   struct T { S a, b; } t = { Temp(), Temp() }
12756   //
12757   // we should destroy the first Temp before constructing the second.
12758   ExprResult Result =
12759       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12760                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12761   if (Result.isInvalid()) {
12762     VDecl->setInvalidDecl();
12763     return;
12764   }
12765   Init = Result.get();
12766 
12767   // Attach the initializer to the decl.
12768   VDecl->setInit(Init);
12769 
12770   if (VDecl->isLocalVarDecl()) {
12771     // Don't check the initializer if the declaration is malformed.
12772     if (VDecl->isInvalidDecl()) {
12773       // do nothing
12774 
12775     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12776     // This is true even in C++ for OpenCL.
12777     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12778       CheckForConstantInitializer(Init, DclT);
12779 
12780     // Otherwise, C++ does not restrict the initializer.
12781     } else if (getLangOpts().CPlusPlus) {
12782       // do nothing
12783 
12784     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12785     // static storage duration shall be constant expressions or string literals.
12786     } else if (VDecl->getStorageClass() == SC_Static) {
12787       CheckForConstantInitializer(Init, DclT);
12788 
12789     // C89 is stricter than C99 for aggregate initializers.
12790     // C89 6.5.7p3: All the expressions [...] in an initializer list
12791     // for an object that has aggregate or union type shall be
12792     // constant expressions.
12793     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12794                isa<InitListExpr>(Init)) {
12795       const Expr *Culprit;
12796       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12797         Diag(Culprit->getExprLoc(),
12798              diag::ext_aggregate_init_not_constant)
12799           << Culprit->getSourceRange();
12800       }
12801     }
12802 
12803     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12804       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12805         if (VDecl->hasLocalStorage())
12806           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12807   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12808              VDecl->getLexicalDeclContext()->isRecord()) {
12809     // This is an in-class initialization for a static data member, e.g.,
12810     //
12811     // struct S {
12812     //   static const int value = 17;
12813     // };
12814 
12815     // C++ [class.mem]p4:
12816     //   A member-declarator can contain a constant-initializer only
12817     //   if it declares a static member (9.4) of const integral or
12818     //   const enumeration type, see 9.4.2.
12819     //
12820     // C++11 [class.static.data]p3:
12821     //   If a non-volatile non-inline const static data member is of integral
12822     //   or enumeration type, its declaration in the class definition can
12823     //   specify a brace-or-equal-initializer in which every initializer-clause
12824     //   that is an assignment-expression is a constant expression. A static
12825     //   data member of literal type can be declared in the class definition
12826     //   with the constexpr specifier; if so, its declaration shall specify a
12827     //   brace-or-equal-initializer in which every initializer-clause that is
12828     //   an assignment-expression is a constant expression.
12829 
12830     // Do nothing on dependent types.
12831     if (DclT->isDependentType()) {
12832 
12833     // Allow any 'static constexpr' members, whether or not they are of literal
12834     // type. We separately check that every constexpr variable is of literal
12835     // type.
12836     } else if (VDecl->isConstexpr()) {
12837 
12838     // Require constness.
12839     } else if (!DclT.isConstQualified()) {
12840       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12841         << Init->getSourceRange();
12842       VDecl->setInvalidDecl();
12843 
12844     // We allow integer constant expressions in all cases.
12845     } else if (DclT->isIntegralOrEnumerationType()) {
12846       // Check whether the expression is a constant expression.
12847       SourceLocation Loc;
12848       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12849         // In C++11, a non-constexpr const static data member with an
12850         // in-class initializer cannot be volatile.
12851         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12852       else if (Init->isValueDependent())
12853         ; // Nothing to check.
12854       else if (Init->isIntegerConstantExpr(Context, &Loc))
12855         ; // Ok, it's an ICE!
12856       else if (Init->getType()->isScopedEnumeralType() &&
12857                Init->isCXX11ConstantExpr(Context))
12858         ; // Ok, it is a scoped-enum constant expression.
12859       else if (Init->isEvaluatable(Context)) {
12860         // If we can constant fold the initializer through heroics, accept it,
12861         // but report this as a use of an extension for -pedantic.
12862         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12863           << Init->getSourceRange();
12864       } else {
12865         // Otherwise, this is some crazy unknown case.  Report the issue at the
12866         // location provided by the isIntegerConstantExpr failed check.
12867         Diag(Loc, diag::err_in_class_initializer_non_constant)
12868           << Init->getSourceRange();
12869         VDecl->setInvalidDecl();
12870       }
12871 
12872     // We allow foldable floating-point constants as an extension.
12873     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12874       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12875       // it anyway and provide a fixit to add the 'constexpr'.
12876       if (getLangOpts().CPlusPlus11) {
12877         Diag(VDecl->getLocation(),
12878              diag::ext_in_class_initializer_float_type_cxx11)
12879             << DclT << Init->getSourceRange();
12880         Diag(VDecl->getBeginLoc(),
12881              diag::note_in_class_initializer_float_type_cxx11)
12882             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12883       } else {
12884         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12885           << DclT << Init->getSourceRange();
12886 
12887         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12888           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12889             << Init->getSourceRange();
12890           VDecl->setInvalidDecl();
12891         }
12892       }
12893 
12894     // Suggest adding 'constexpr' in C++11 for literal types.
12895     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12896       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12897           << DclT << Init->getSourceRange()
12898           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12899       VDecl->setConstexpr(true);
12900 
12901     } else {
12902       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12903         << DclT << Init->getSourceRange();
12904       VDecl->setInvalidDecl();
12905     }
12906   } else if (VDecl->isFileVarDecl()) {
12907     // In C, extern is typically used to avoid tentative definitions when
12908     // declaring variables in headers, but adding an intializer makes it a
12909     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12910     // In C++, extern is often used to give implictly static const variables
12911     // external linkage, so don't warn in that case. If selectany is present,
12912     // this might be header code intended for C and C++ inclusion, so apply the
12913     // C++ rules.
12914     if (VDecl->getStorageClass() == SC_Extern &&
12915         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12916          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12917         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12918         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12919       Diag(VDecl->getLocation(), diag::warn_extern_init);
12920 
12921     // In Microsoft C++ mode, a const variable defined in namespace scope has
12922     // external linkage by default if the variable is declared with
12923     // __declspec(dllexport).
12924     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12925         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12926         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12927       VDecl->setStorageClass(SC_Extern);
12928 
12929     // C99 6.7.8p4. All file scoped initializers need to be constant.
12930     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12931       CheckForConstantInitializer(Init, DclT);
12932   }
12933 
12934   QualType InitType = Init->getType();
12935   if (!InitType.isNull() &&
12936       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12937        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12938     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12939 
12940   // We will represent direct-initialization similarly to copy-initialization:
12941   //    int x(1);  -as-> int x = 1;
12942   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12943   //
12944   // Clients that want to distinguish between the two forms, can check for
12945   // direct initializer using VarDecl::getInitStyle().
12946   // A major benefit is that clients that don't particularly care about which
12947   // exactly form was it (like the CodeGen) can handle both cases without
12948   // special case code.
12949 
12950   // C++ 8.5p11:
12951   // The form of initialization (using parentheses or '=') is generally
12952   // insignificant, but does matter when the entity being initialized has a
12953   // class type.
12954   if (CXXDirectInit) {
12955     assert(DirectInit && "Call-style initializer must be direct init.");
12956     VDecl->setInitStyle(VarDecl::CallInit);
12957   } else if (DirectInit) {
12958     // This must be list-initialization. No other way is direct-initialization.
12959     VDecl->setInitStyle(VarDecl::ListInit);
12960   }
12961 
12962   if (LangOpts.OpenMP &&
12963       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12964       VDecl->isFileVarDecl())
12965     DeclsToCheckForDeferredDiags.insert(VDecl);
12966   CheckCompleteVariableDeclaration(VDecl);
12967 }
12968 
12969 /// ActOnInitializerError - Given that there was an error parsing an
12970 /// initializer for the given declaration, try to at least re-establish
12971 /// invariants such as whether a variable's type is either dependent or
12972 /// complete.
12973 void Sema::ActOnInitializerError(Decl *D) {
12974   // Our main concern here is re-establishing invariants like "a
12975   // variable's type is either dependent or complete".
12976   if (!D || D->isInvalidDecl()) return;
12977 
12978   VarDecl *VD = dyn_cast<VarDecl>(D);
12979   if (!VD) return;
12980 
12981   // Bindings are not usable if we can't make sense of the initializer.
12982   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12983     for (auto *BD : DD->bindings())
12984       BD->setInvalidDecl();
12985 
12986   // Auto types are meaningless if we can't make sense of the initializer.
12987   if (VD->getType()->isUndeducedType()) {
12988     D->setInvalidDecl();
12989     return;
12990   }
12991 
12992   QualType Ty = VD->getType();
12993   if (Ty->isDependentType()) return;
12994 
12995   // Require a complete type.
12996   if (RequireCompleteType(VD->getLocation(),
12997                           Context.getBaseElementType(Ty),
12998                           diag::err_typecheck_decl_incomplete_type)) {
12999     VD->setInvalidDecl();
13000     return;
13001   }
13002 
13003   // Require a non-abstract type.
13004   if (RequireNonAbstractType(VD->getLocation(), Ty,
13005                              diag::err_abstract_type_in_decl,
13006                              AbstractVariableType)) {
13007     VD->setInvalidDecl();
13008     return;
13009   }
13010 
13011   // Don't bother complaining about constructors or destructors,
13012   // though.
13013 }
13014 
13015 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13016   // If there is no declaration, there was an error parsing it. Just ignore it.
13017   if (!RealDecl)
13018     return;
13019 
13020   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13021     QualType Type = Var->getType();
13022 
13023     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13024     if (isa<DecompositionDecl>(RealDecl)) {
13025       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13026       Var->setInvalidDecl();
13027       return;
13028     }
13029 
13030     if (Type->isUndeducedType() &&
13031         DeduceVariableDeclarationType(Var, false, nullptr))
13032       return;
13033 
13034     // C++11 [class.static.data]p3: A static data member can be declared with
13035     // the constexpr specifier; if so, its declaration shall specify
13036     // a brace-or-equal-initializer.
13037     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13038     // the definition of a variable [...] or the declaration of a static data
13039     // member.
13040     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13041         !Var->isThisDeclarationADemotedDefinition()) {
13042       if (Var->isStaticDataMember()) {
13043         // C++1z removes the relevant rule; the in-class declaration is always
13044         // a definition there.
13045         if (!getLangOpts().CPlusPlus17 &&
13046             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13047           Diag(Var->getLocation(),
13048                diag::err_constexpr_static_mem_var_requires_init)
13049               << Var;
13050           Var->setInvalidDecl();
13051           return;
13052         }
13053       } else {
13054         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13055         Var->setInvalidDecl();
13056         return;
13057       }
13058     }
13059 
13060     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13061     // be initialized.
13062     if (!Var->isInvalidDecl() &&
13063         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13064         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13065       bool HasConstExprDefaultConstructor = false;
13066       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13067         for (auto *Ctor : RD->ctors()) {
13068           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13069               Ctor->getMethodQualifiers().getAddressSpace() ==
13070                   LangAS::opencl_constant) {
13071             HasConstExprDefaultConstructor = true;
13072           }
13073         }
13074       }
13075       if (!HasConstExprDefaultConstructor) {
13076         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13077         Var->setInvalidDecl();
13078         return;
13079       }
13080     }
13081 
13082     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13083       if (Var->getStorageClass() == SC_Extern) {
13084         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13085             << Var;
13086         Var->setInvalidDecl();
13087         return;
13088       }
13089       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13090                               diag::err_typecheck_decl_incomplete_type)) {
13091         Var->setInvalidDecl();
13092         return;
13093       }
13094       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13095         if (!RD->hasTrivialDefaultConstructor()) {
13096           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13097           Var->setInvalidDecl();
13098           return;
13099         }
13100       }
13101       // The declaration is unitialized, no need for further checks.
13102       return;
13103     }
13104 
13105     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13106     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13107         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13108       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13109                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13110 
13111 
13112     switch (DefKind) {
13113     case VarDecl::Definition:
13114       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13115         break;
13116 
13117       // We have an out-of-line definition of a static data member
13118       // that has an in-class initializer, so we type-check this like
13119       // a declaration.
13120       //
13121       LLVM_FALLTHROUGH;
13122 
13123     case VarDecl::DeclarationOnly:
13124       // It's only a declaration.
13125 
13126       // Block scope. C99 6.7p7: If an identifier for an object is
13127       // declared with no linkage (C99 6.2.2p6), the type for the
13128       // object shall be complete.
13129       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13130           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13131           RequireCompleteType(Var->getLocation(), Type,
13132                               diag::err_typecheck_decl_incomplete_type))
13133         Var->setInvalidDecl();
13134 
13135       // Make sure that the type is not abstract.
13136       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13137           RequireNonAbstractType(Var->getLocation(), Type,
13138                                  diag::err_abstract_type_in_decl,
13139                                  AbstractVariableType))
13140         Var->setInvalidDecl();
13141       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13142           Var->getStorageClass() == SC_PrivateExtern) {
13143         Diag(Var->getLocation(), diag::warn_private_extern);
13144         Diag(Var->getLocation(), diag::note_private_extern);
13145       }
13146 
13147       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13148           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13149         ExternalDeclarations.push_back(Var);
13150 
13151       return;
13152 
13153     case VarDecl::TentativeDefinition:
13154       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13155       // object that has file scope without an initializer, and without a
13156       // storage-class specifier or with the storage-class specifier "static",
13157       // constitutes a tentative definition. Note: A tentative definition with
13158       // external linkage is valid (C99 6.2.2p5).
13159       if (!Var->isInvalidDecl()) {
13160         if (const IncompleteArrayType *ArrayT
13161                                     = Context.getAsIncompleteArrayType(Type)) {
13162           if (RequireCompleteSizedType(
13163                   Var->getLocation(), ArrayT->getElementType(),
13164                   diag::err_array_incomplete_or_sizeless_type))
13165             Var->setInvalidDecl();
13166         } else if (Var->getStorageClass() == SC_Static) {
13167           // C99 6.9.2p3: If the declaration of an identifier for an object is
13168           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13169           // declared type shall not be an incomplete type.
13170           // NOTE: code such as the following
13171           //     static struct s;
13172           //     struct s { int a; };
13173           // is accepted by gcc. Hence here we issue a warning instead of
13174           // an error and we do not invalidate the static declaration.
13175           // NOTE: to avoid multiple warnings, only check the first declaration.
13176           if (Var->isFirstDecl())
13177             RequireCompleteType(Var->getLocation(), Type,
13178                                 diag::ext_typecheck_decl_incomplete_type);
13179         }
13180       }
13181 
13182       // Record the tentative definition; we're done.
13183       if (!Var->isInvalidDecl())
13184         TentativeDefinitions.push_back(Var);
13185       return;
13186     }
13187 
13188     // Provide a specific diagnostic for uninitialized variable
13189     // definitions with incomplete array type.
13190     if (Type->isIncompleteArrayType()) {
13191       Diag(Var->getLocation(),
13192            diag::err_typecheck_incomplete_array_needs_initializer);
13193       Var->setInvalidDecl();
13194       return;
13195     }
13196 
13197     // Provide a specific diagnostic for uninitialized variable
13198     // definitions with reference type.
13199     if (Type->isReferenceType()) {
13200       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13201           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13202       return;
13203     }
13204 
13205     // Do not attempt to type-check the default initializer for a
13206     // variable with dependent type.
13207     if (Type->isDependentType())
13208       return;
13209 
13210     if (Var->isInvalidDecl())
13211       return;
13212 
13213     if (!Var->hasAttr<AliasAttr>()) {
13214       if (RequireCompleteType(Var->getLocation(),
13215                               Context.getBaseElementType(Type),
13216                               diag::err_typecheck_decl_incomplete_type)) {
13217         Var->setInvalidDecl();
13218         return;
13219       }
13220     } else {
13221       return;
13222     }
13223 
13224     // The variable can not have an abstract class type.
13225     if (RequireNonAbstractType(Var->getLocation(), Type,
13226                                diag::err_abstract_type_in_decl,
13227                                AbstractVariableType)) {
13228       Var->setInvalidDecl();
13229       return;
13230     }
13231 
13232     // Check for jumps past the implicit initializer.  C++0x
13233     // clarifies that this applies to a "variable with automatic
13234     // storage duration", not a "local variable".
13235     // C++11 [stmt.dcl]p3
13236     //   A program that jumps from a point where a variable with automatic
13237     //   storage duration is not in scope to a point where it is in scope is
13238     //   ill-formed unless the variable has scalar type, class type with a
13239     //   trivial default constructor and a trivial destructor, a cv-qualified
13240     //   version of one of these types, or an array of one of the preceding
13241     //   types and is declared without an initializer.
13242     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13243       if (const RecordType *Record
13244             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13245         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13246         // Mark the function (if we're in one) for further checking even if the
13247         // looser rules of C++11 do not require such checks, so that we can
13248         // diagnose incompatibilities with C++98.
13249         if (!CXXRecord->isPOD())
13250           setFunctionHasBranchProtectedScope();
13251       }
13252     }
13253     // In OpenCL, we can't initialize objects in the __local address space,
13254     // even implicitly, so don't synthesize an implicit initializer.
13255     if (getLangOpts().OpenCL &&
13256         Var->getType().getAddressSpace() == LangAS::opencl_local)
13257       return;
13258     // C++03 [dcl.init]p9:
13259     //   If no initializer is specified for an object, and the
13260     //   object is of (possibly cv-qualified) non-POD class type (or
13261     //   array thereof), the object shall be default-initialized; if
13262     //   the object is of const-qualified type, the underlying class
13263     //   type shall have a user-declared default
13264     //   constructor. Otherwise, if no initializer is specified for
13265     //   a non- static object, the object and its subobjects, if
13266     //   any, have an indeterminate initial value); if the object
13267     //   or any of its subobjects are of const-qualified type, the
13268     //   program is ill-formed.
13269     // C++0x [dcl.init]p11:
13270     //   If no initializer is specified for an object, the object is
13271     //   default-initialized; [...].
13272     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13273     InitializationKind Kind
13274       = InitializationKind::CreateDefault(Var->getLocation());
13275 
13276     InitializationSequence InitSeq(*this, Entity, Kind, None);
13277     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13278 
13279     if (Init.get()) {
13280       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13281       // This is important for template substitution.
13282       Var->setInitStyle(VarDecl::CallInit);
13283     } else if (Init.isInvalid()) {
13284       // If default-init fails, attach a recovery-expr initializer to track
13285       // that initialization was attempted and failed.
13286       auto RecoveryExpr =
13287           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13288       if (RecoveryExpr.get())
13289         Var->setInit(RecoveryExpr.get());
13290     }
13291 
13292     CheckCompleteVariableDeclaration(Var);
13293   }
13294 }
13295 
13296 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13297   // If there is no declaration, there was an error parsing it. Ignore it.
13298   if (!D)
13299     return;
13300 
13301   VarDecl *VD = dyn_cast<VarDecl>(D);
13302   if (!VD) {
13303     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13304     D->setInvalidDecl();
13305     return;
13306   }
13307 
13308   VD->setCXXForRangeDecl(true);
13309 
13310   // for-range-declaration cannot be given a storage class specifier.
13311   int Error = -1;
13312   switch (VD->getStorageClass()) {
13313   case SC_None:
13314     break;
13315   case SC_Extern:
13316     Error = 0;
13317     break;
13318   case SC_Static:
13319     Error = 1;
13320     break;
13321   case SC_PrivateExtern:
13322     Error = 2;
13323     break;
13324   case SC_Auto:
13325     Error = 3;
13326     break;
13327   case SC_Register:
13328     Error = 4;
13329     break;
13330   }
13331 
13332   // for-range-declaration cannot be given a storage class specifier con't.
13333   switch (VD->getTSCSpec()) {
13334   case TSCS_thread_local:
13335     Error = 6;
13336     break;
13337   case TSCS___thread:
13338   case TSCS__Thread_local:
13339   case TSCS_unspecified:
13340     break;
13341   }
13342 
13343   if (Error != -1) {
13344     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13345         << VD << Error;
13346     D->setInvalidDecl();
13347   }
13348 }
13349 
13350 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13351                                             IdentifierInfo *Ident,
13352                                             ParsedAttributes &Attrs) {
13353   // C++1y [stmt.iter]p1:
13354   //   A range-based for statement of the form
13355   //      for ( for-range-identifier : for-range-initializer ) statement
13356   //   is equivalent to
13357   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13358   DeclSpec DS(Attrs.getPool().getFactory());
13359 
13360   const char *PrevSpec;
13361   unsigned DiagID;
13362   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13363                      getPrintingPolicy());
13364 
13365   Declarator D(DS, DeclaratorContext::ForInit);
13366   D.SetIdentifier(Ident, IdentLoc);
13367   D.takeAttributes(Attrs);
13368 
13369   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13370                 IdentLoc);
13371   Decl *Var = ActOnDeclarator(S, D);
13372   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13373   FinalizeDeclaration(Var);
13374   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13375                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13376                                                       : IdentLoc);
13377 }
13378 
13379 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13380   if (var->isInvalidDecl()) return;
13381 
13382   MaybeAddCUDAConstantAttr(var);
13383 
13384   if (getLangOpts().OpenCL) {
13385     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13386     // initialiser
13387     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13388         !var->hasInit()) {
13389       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13390           << 1 /*Init*/;
13391       var->setInvalidDecl();
13392       return;
13393     }
13394   }
13395 
13396   // In Objective-C, don't allow jumps past the implicit initialization of a
13397   // local retaining variable.
13398   if (getLangOpts().ObjC &&
13399       var->hasLocalStorage()) {
13400     switch (var->getType().getObjCLifetime()) {
13401     case Qualifiers::OCL_None:
13402     case Qualifiers::OCL_ExplicitNone:
13403     case Qualifiers::OCL_Autoreleasing:
13404       break;
13405 
13406     case Qualifiers::OCL_Weak:
13407     case Qualifiers::OCL_Strong:
13408       setFunctionHasBranchProtectedScope();
13409       break;
13410     }
13411   }
13412 
13413   if (var->hasLocalStorage() &&
13414       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13415     setFunctionHasBranchProtectedScope();
13416 
13417   // Warn about externally-visible variables being defined without a
13418   // prior declaration.  We only want to do this for global
13419   // declarations, but we also specifically need to avoid doing it for
13420   // class members because the linkage of an anonymous class can
13421   // change if it's later given a typedef name.
13422   if (var->isThisDeclarationADefinition() &&
13423       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13424       var->isExternallyVisible() && var->hasLinkage() &&
13425       !var->isInline() && !var->getDescribedVarTemplate() &&
13426       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13427       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13428       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13429                                   var->getLocation())) {
13430     // Find a previous declaration that's not a definition.
13431     VarDecl *prev = var->getPreviousDecl();
13432     while (prev && prev->isThisDeclarationADefinition())
13433       prev = prev->getPreviousDecl();
13434 
13435     if (!prev) {
13436       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13437       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13438           << /* variable */ 0;
13439     }
13440   }
13441 
13442   // Cache the result of checking for constant initialization.
13443   Optional<bool> CacheHasConstInit;
13444   const Expr *CacheCulprit = nullptr;
13445   auto checkConstInit = [&]() mutable {
13446     if (!CacheHasConstInit)
13447       CacheHasConstInit = var->getInit()->isConstantInitializer(
13448             Context, var->getType()->isReferenceType(), &CacheCulprit);
13449     return *CacheHasConstInit;
13450   };
13451 
13452   if (var->getTLSKind() == VarDecl::TLS_Static) {
13453     if (var->getType().isDestructedType()) {
13454       // GNU C++98 edits for __thread, [basic.start.term]p3:
13455       //   The type of an object with thread storage duration shall not
13456       //   have a non-trivial destructor.
13457       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13458       if (getLangOpts().CPlusPlus11)
13459         Diag(var->getLocation(), diag::note_use_thread_local);
13460     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13461       if (!checkConstInit()) {
13462         // GNU C++98 edits for __thread, [basic.start.init]p4:
13463         //   An object of thread storage duration shall not require dynamic
13464         //   initialization.
13465         // FIXME: Need strict checking here.
13466         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13467           << CacheCulprit->getSourceRange();
13468         if (getLangOpts().CPlusPlus11)
13469           Diag(var->getLocation(), diag::note_use_thread_local);
13470       }
13471     }
13472   }
13473 
13474 
13475   if (!var->getType()->isStructureType() && var->hasInit() &&
13476       isa<InitListExpr>(var->getInit())) {
13477     const auto *ILE = cast<InitListExpr>(var->getInit());
13478     unsigned NumInits = ILE->getNumInits();
13479     if (NumInits > 2)
13480       for (unsigned I = 0; I < NumInits; ++I) {
13481         const auto *Init = ILE->getInit(I);
13482         if (!Init)
13483           break;
13484         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13485         if (!SL)
13486           break;
13487 
13488         unsigned NumConcat = SL->getNumConcatenated();
13489         // Diagnose missing comma in string array initialization.
13490         // Do not warn when all the elements in the initializer are concatenated
13491         // together. Do not warn for macros too.
13492         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13493           bool OnlyOneMissingComma = true;
13494           for (unsigned J = I + 1; J < NumInits; ++J) {
13495             const auto *Init = ILE->getInit(J);
13496             if (!Init)
13497               break;
13498             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13499             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13500               OnlyOneMissingComma = false;
13501               break;
13502             }
13503           }
13504 
13505           if (OnlyOneMissingComma) {
13506             SmallVector<FixItHint, 1> Hints;
13507             for (unsigned i = 0; i < NumConcat - 1; ++i)
13508               Hints.push_back(FixItHint::CreateInsertion(
13509                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13510 
13511             Diag(SL->getStrTokenLoc(1),
13512                  diag::warn_concatenated_literal_array_init)
13513                 << Hints;
13514             Diag(SL->getBeginLoc(),
13515                  diag::note_concatenated_string_literal_silence);
13516           }
13517           // In any case, stop now.
13518           break;
13519         }
13520       }
13521   }
13522 
13523 
13524   QualType type = var->getType();
13525 
13526   if (var->hasAttr<BlocksAttr>())
13527     getCurFunction()->addByrefBlockVar(var);
13528 
13529   Expr *Init = var->getInit();
13530   bool GlobalStorage = var->hasGlobalStorage();
13531   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13532   QualType baseType = Context.getBaseElementType(type);
13533   bool HasConstInit = true;
13534 
13535   // Check whether the initializer is sufficiently constant.
13536   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13537       !Init->isValueDependent() &&
13538       (GlobalStorage || var->isConstexpr() ||
13539        var->mightBeUsableInConstantExpressions(Context))) {
13540     // If this variable might have a constant initializer or might be usable in
13541     // constant expressions, check whether or not it actually is now.  We can't
13542     // do this lazily, because the result might depend on things that change
13543     // later, such as which constexpr functions happen to be defined.
13544     SmallVector<PartialDiagnosticAt, 8> Notes;
13545     if (!getLangOpts().CPlusPlus11) {
13546       // Prior to C++11, in contexts where a constant initializer is required,
13547       // the set of valid constant initializers is described by syntactic rules
13548       // in [expr.const]p2-6.
13549       // FIXME: Stricter checking for these rules would be useful for constinit /
13550       // -Wglobal-constructors.
13551       HasConstInit = checkConstInit();
13552 
13553       // Compute and cache the constant value, and remember that we have a
13554       // constant initializer.
13555       if (HasConstInit) {
13556         (void)var->checkForConstantInitialization(Notes);
13557         Notes.clear();
13558       } else if (CacheCulprit) {
13559         Notes.emplace_back(CacheCulprit->getExprLoc(),
13560                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13561         Notes.back().second << CacheCulprit->getSourceRange();
13562       }
13563     } else {
13564       // Evaluate the initializer to see if it's a constant initializer.
13565       HasConstInit = var->checkForConstantInitialization(Notes);
13566     }
13567 
13568     if (HasConstInit) {
13569       // FIXME: Consider replacing the initializer with a ConstantExpr.
13570     } else if (var->isConstexpr()) {
13571       SourceLocation DiagLoc = var->getLocation();
13572       // If the note doesn't add any useful information other than a source
13573       // location, fold it into the primary diagnostic.
13574       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13575                                    diag::note_invalid_subexpr_in_const_expr) {
13576         DiagLoc = Notes[0].first;
13577         Notes.clear();
13578       }
13579       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13580           << var << Init->getSourceRange();
13581       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13582         Diag(Notes[I].first, Notes[I].second);
13583     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13584       auto *Attr = var->getAttr<ConstInitAttr>();
13585       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13586           << Init->getSourceRange();
13587       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13588           << Attr->getRange() << Attr->isConstinit();
13589       for (auto &it : Notes)
13590         Diag(it.first, it.second);
13591     } else if (IsGlobal &&
13592                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13593                                            var->getLocation())) {
13594       // Warn about globals which don't have a constant initializer.  Don't
13595       // warn about globals with a non-trivial destructor because we already
13596       // warned about them.
13597       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13598       if (!(RD && !RD->hasTrivialDestructor())) {
13599         // checkConstInit() here permits trivial default initialization even in
13600         // C++11 onwards, where such an initializer is not a constant initializer
13601         // but nonetheless doesn't require a global constructor.
13602         if (!checkConstInit())
13603           Diag(var->getLocation(), diag::warn_global_constructor)
13604               << Init->getSourceRange();
13605       }
13606     }
13607   }
13608 
13609   // Apply section attributes and pragmas to global variables.
13610   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13611       !inTemplateInstantiation()) {
13612     PragmaStack<StringLiteral *> *Stack = nullptr;
13613     int SectionFlags = ASTContext::PSF_Read;
13614     if (var->getType().isConstQualified()) {
13615       if (HasConstInit)
13616         Stack = &ConstSegStack;
13617       else {
13618         Stack = &BSSSegStack;
13619         SectionFlags |= ASTContext::PSF_Write;
13620       }
13621     } else if (var->hasInit() && HasConstInit) {
13622       Stack = &DataSegStack;
13623       SectionFlags |= ASTContext::PSF_Write;
13624     } else {
13625       Stack = &BSSSegStack;
13626       SectionFlags |= ASTContext::PSF_Write;
13627     }
13628     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13629       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13630         SectionFlags |= ASTContext::PSF_Implicit;
13631       UnifySection(SA->getName(), SectionFlags, var);
13632     } else if (Stack->CurrentValue) {
13633       SectionFlags |= ASTContext::PSF_Implicit;
13634       auto SectionName = Stack->CurrentValue->getString();
13635       var->addAttr(SectionAttr::CreateImplicit(
13636           Context, SectionName, Stack->CurrentPragmaLocation,
13637           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13638       if (UnifySection(SectionName, SectionFlags, var))
13639         var->dropAttr<SectionAttr>();
13640     }
13641 
13642     // Apply the init_seg attribute if this has an initializer.  If the
13643     // initializer turns out to not be dynamic, we'll end up ignoring this
13644     // attribute.
13645     if (CurInitSeg && var->getInit())
13646       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13647                                                CurInitSegLoc,
13648                                                AttributeCommonInfo::AS_Pragma));
13649   }
13650 
13651   // All the following checks are C++ only.
13652   if (!getLangOpts().CPlusPlus) {
13653     // If this variable must be emitted, add it as an initializer for the
13654     // current module.
13655     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13656       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13657     return;
13658   }
13659 
13660   // Require the destructor.
13661   if (!type->isDependentType())
13662     if (const RecordType *recordType = baseType->getAs<RecordType>())
13663       FinalizeVarWithDestructor(var, recordType);
13664 
13665   // If this variable must be emitted, add it as an initializer for the current
13666   // module.
13667   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13668     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13669 
13670   // Build the bindings if this is a structured binding declaration.
13671   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13672     CheckCompleteDecompositionDeclaration(DD);
13673 }
13674 
13675 /// Check if VD needs to be dllexport/dllimport due to being in a
13676 /// dllexport/import function.
13677 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13678   assert(VD->isStaticLocal());
13679 
13680   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13681 
13682   // Find outermost function when VD is in lambda function.
13683   while (FD && !getDLLAttr(FD) &&
13684          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13685          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13686     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13687   }
13688 
13689   if (!FD)
13690     return;
13691 
13692   // Static locals inherit dll attributes from their function.
13693   if (Attr *A = getDLLAttr(FD)) {
13694     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13695     NewAttr->setInherited(true);
13696     VD->addAttr(NewAttr);
13697   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13698     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13699     NewAttr->setInherited(true);
13700     VD->addAttr(NewAttr);
13701 
13702     // Export this function to enforce exporting this static variable even
13703     // if it is not used in this compilation unit.
13704     if (!FD->hasAttr<DLLExportAttr>())
13705       FD->addAttr(NewAttr);
13706 
13707   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13708     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13709     NewAttr->setInherited(true);
13710     VD->addAttr(NewAttr);
13711   }
13712 }
13713 
13714 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13715 /// any semantic actions necessary after any initializer has been attached.
13716 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13717   // Note that we are no longer parsing the initializer for this declaration.
13718   ParsingInitForAutoVars.erase(ThisDecl);
13719 
13720   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13721   if (!VD)
13722     return;
13723 
13724   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13725   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13726       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13727     if (PragmaClangBSSSection.Valid)
13728       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13729           Context, PragmaClangBSSSection.SectionName,
13730           PragmaClangBSSSection.PragmaLocation,
13731           AttributeCommonInfo::AS_Pragma));
13732     if (PragmaClangDataSection.Valid)
13733       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13734           Context, PragmaClangDataSection.SectionName,
13735           PragmaClangDataSection.PragmaLocation,
13736           AttributeCommonInfo::AS_Pragma));
13737     if (PragmaClangRodataSection.Valid)
13738       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13739           Context, PragmaClangRodataSection.SectionName,
13740           PragmaClangRodataSection.PragmaLocation,
13741           AttributeCommonInfo::AS_Pragma));
13742     if (PragmaClangRelroSection.Valid)
13743       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13744           Context, PragmaClangRelroSection.SectionName,
13745           PragmaClangRelroSection.PragmaLocation,
13746           AttributeCommonInfo::AS_Pragma));
13747   }
13748 
13749   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13750     for (auto *BD : DD->bindings()) {
13751       FinalizeDeclaration(BD);
13752     }
13753   }
13754 
13755   checkAttributesAfterMerging(*this, *VD);
13756 
13757   // Perform TLS alignment check here after attributes attached to the variable
13758   // which may affect the alignment have been processed. Only perform the check
13759   // if the target has a maximum TLS alignment (zero means no constraints).
13760   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13761     // Protect the check so that it's not performed on dependent types and
13762     // dependent alignments (we can't determine the alignment in that case).
13763     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13764       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13765       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13766         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13767           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13768           << (unsigned)MaxAlignChars.getQuantity();
13769       }
13770     }
13771   }
13772 
13773   if (VD->isStaticLocal())
13774     CheckStaticLocalForDllExport(VD);
13775 
13776   // Perform check for initializers of device-side global variables.
13777   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13778   // 7.5). We must also apply the same checks to all __shared__
13779   // variables whether they are local or not. CUDA also allows
13780   // constant initializers for __constant__ and __device__ variables.
13781   if (getLangOpts().CUDA)
13782     checkAllowedCUDAInitializer(VD);
13783 
13784   // Grab the dllimport or dllexport attribute off of the VarDecl.
13785   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13786 
13787   // Imported static data members cannot be defined out-of-line.
13788   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13789     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13790         VD->isThisDeclarationADefinition()) {
13791       // We allow definitions of dllimport class template static data members
13792       // with a warning.
13793       CXXRecordDecl *Context =
13794         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13795       bool IsClassTemplateMember =
13796           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13797           Context->getDescribedClassTemplate();
13798 
13799       Diag(VD->getLocation(),
13800            IsClassTemplateMember
13801                ? diag::warn_attribute_dllimport_static_field_definition
13802                : diag::err_attribute_dllimport_static_field_definition);
13803       Diag(IA->getLocation(), diag::note_attribute);
13804       if (!IsClassTemplateMember)
13805         VD->setInvalidDecl();
13806     }
13807   }
13808 
13809   // dllimport/dllexport variables cannot be thread local, their TLS index
13810   // isn't exported with the variable.
13811   if (DLLAttr && VD->getTLSKind()) {
13812     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13813     if (F && getDLLAttr(F)) {
13814       assert(VD->isStaticLocal());
13815       // But if this is a static local in a dlimport/dllexport function, the
13816       // function will never be inlined, which means the var would never be
13817       // imported, so having it marked import/export is safe.
13818     } else {
13819       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13820                                                                     << DLLAttr;
13821       VD->setInvalidDecl();
13822     }
13823   }
13824 
13825   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13826     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13827       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13828           << Attr;
13829       VD->dropAttr<UsedAttr>();
13830     }
13831   }
13832   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13833     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13834       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13835           << Attr;
13836       VD->dropAttr<RetainAttr>();
13837     }
13838   }
13839 
13840   const DeclContext *DC = VD->getDeclContext();
13841   // If there's a #pragma GCC visibility in scope, and this isn't a class
13842   // member, set the visibility of this variable.
13843   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13844     AddPushedVisibilityAttribute(VD);
13845 
13846   // FIXME: Warn on unused var template partial specializations.
13847   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13848     MarkUnusedFileScopedDecl(VD);
13849 
13850   // Now we have parsed the initializer and can update the table of magic
13851   // tag values.
13852   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13853       !VD->getType()->isIntegralOrEnumerationType())
13854     return;
13855 
13856   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13857     const Expr *MagicValueExpr = VD->getInit();
13858     if (!MagicValueExpr) {
13859       continue;
13860     }
13861     Optional<llvm::APSInt> MagicValueInt;
13862     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13863       Diag(I->getRange().getBegin(),
13864            diag::err_type_tag_for_datatype_not_ice)
13865         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13866       continue;
13867     }
13868     if (MagicValueInt->getActiveBits() > 64) {
13869       Diag(I->getRange().getBegin(),
13870            diag::err_type_tag_for_datatype_too_large)
13871         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13872       continue;
13873     }
13874     uint64_t MagicValue = MagicValueInt->getZExtValue();
13875     RegisterTypeTagForDatatype(I->getArgumentKind(),
13876                                MagicValue,
13877                                I->getMatchingCType(),
13878                                I->getLayoutCompatible(),
13879                                I->getMustBeNull());
13880   }
13881 }
13882 
13883 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13884   auto *VD = dyn_cast<VarDecl>(DD);
13885   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13886 }
13887 
13888 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13889                                                    ArrayRef<Decl *> Group) {
13890   SmallVector<Decl*, 8> Decls;
13891 
13892   if (DS.isTypeSpecOwned())
13893     Decls.push_back(DS.getRepAsDecl());
13894 
13895   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13896   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13897   bool DiagnosedMultipleDecomps = false;
13898   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13899   bool DiagnosedNonDeducedAuto = false;
13900 
13901   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13902     if (Decl *D = Group[i]) {
13903       // For declarators, there are some additional syntactic-ish checks we need
13904       // to perform.
13905       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13906         if (!FirstDeclaratorInGroup)
13907           FirstDeclaratorInGroup = DD;
13908         if (!FirstDecompDeclaratorInGroup)
13909           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13910         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13911             !hasDeducedAuto(DD))
13912           FirstNonDeducedAutoInGroup = DD;
13913 
13914         if (FirstDeclaratorInGroup != DD) {
13915           // A decomposition declaration cannot be combined with any other
13916           // declaration in the same group.
13917           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13918             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13919                  diag::err_decomp_decl_not_alone)
13920                 << FirstDeclaratorInGroup->getSourceRange()
13921                 << DD->getSourceRange();
13922             DiagnosedMultipleDecomps = true;
13923           }
13924 
13925           // A declarator that uses 'auto' in any way other than to declare a
13926           // variable with a deduced type cannot be combined with any other
13927           // declarator in the same group.
13928           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13929             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13930                  diag::err_auto_non_deduced_not_alone)
13931                 << FirstNonDeducedAutoInGroup->getType()
13932                        ->hasAutoForTrailingReturnType()
13933                 << FirstDeclaratorInGroup->getSourceRange()
13934                 << DD->getSourceRange();
13935             DiagnosedNonDeducedAuto = true;
13936           }
13937         }
13938       }
13939 
13940       Decls.push_back(D);
13941     }
13942   }
13943 
13944   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13945     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13946       handleTagNumbering(Tag, S);
13947       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13948           getLangOpts().CPlusPlus)
13949         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13950     }
13951   }
13952 
13953   return BuildDeclaratorGroup(Decls);
13954 }
13955 
13956 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13957 /// group, performing any necessary semantic checking.
13958 Sema::DeclGroupPtrTy
13959 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13960   // C++14 [dcl.spec.auto]p7: (DR1347)
13961   //   If the type that replaces the placeholder type is not the same in each
13962   //   deduction, the program is ill-formed.
13963   if (Group.size() > 1) {
13964     QualType Deduced;
13965     VarDecl *DeducedDecl = nullptr;
13966     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13967       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13968       if (!D || D->isInvalidDecl())
13969         break;
13970       DeducedType *DT = D->getType()->getContainedDeducedType();
13971       if (!DT || DT->getDeducedType().isNull())
13972         continue;
13973       if (Deduced.isNull()) {
13974         Deduced = DT->getDeducedType();
13975         DeducedDecl = D;
13976       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13977         auto *AT = dyn_cast<AutoType>(DT);
13978         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13979                         diag::err_auto_different_deductions)
13980                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13981                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13982                    << D->getDeclName();
13983         if (DeducedDecl->hasInit())
13984           Dia << DeducedDecl->getInit()->getSourceRange();
13985         if (D->getInit())
13986           Dia << D->getInit()->getSourceRange();
13987         D->setInvalidDecl();
13988         break;
13989       }
13990     }
13991   }
13992 
13993   ActOnDocumentableDecls(Group);
13994 
13995   return DeclGroupPtrTy::make(
13996       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13997 }
13998 
13999 void Sema::ActOnDocumentableDecl(Decl *D) {
14000   ActOnDocumentableDecls(D);
14001 }
14002 
14003 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14004   // Don't parse the comment if Doxygen diagnostics are ignored.
14005   if (Group.empty() || !Group[0])
14006     return;
14007 
14008   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14009                       Group[0]->getLocation()) &&
14010       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14011                       Group[0]->getLocation()))
14012     return;
14013 
14014   if (Group.size() >= 2) {
14015     // This is a decl group.  Normally it will contain only declarations
14016     // produced from declarator list.  But in case we have any definitions or
14017     // additional declaration references:
14018     //   'typedef struct S {} S;'
14019     //   'typedef struct S *S;'
14020     //   'struct S *pS;'
14021     // FinalizeDeclaratorGroup adds these as separate declarations.
14022     Decl *MaybeTagDecl = Group[0];
14023     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14024       Group = Group.slice(1);
14025     }
14026   }
14027 
14028   // FIMXE: We assume every Decl in the group is in the same file.
14029   // This is false when preprocessor constructs the group from decls in
14030   // different files (e. g. macros or #include).
14031   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14032 }
14033 
14034 /// Common checks for a parameter-declaration that should apply to both function
14035 /// parameters and non-type template parameters.
14036 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14037   // Check that there are no default arguments inside the type of this
14038   // parameter.
14039   if (getLangOpts().CPlusPlus)
14040     CheckExtraCXXDefaultArguments(D);
14041 
14042   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14043   if (D.getCXXScopeSpec().isSet()) {
14044     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14045       << D.getCXXScopeSpec().getRange();
14046   }
14047 
14048   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14049   // simple identifier except [...irrelevant cases...].
14050   switch (D.getName().getKind()) {
14051   case UnqualifiedIdKind::IK_Identifier:
14052     break;
14053 
14054   case UnqualifiedIdKind::IK_OperatorFunctionId:
14055   case UnqualifiedIdKind::IK_ConversionFunctionId:
14056   case UnqualifiedIdKind::IK_LiteralOperatorId:
14057   case UnqualifiedIdKind::IK_ConstructorName:
14058   case UnqualifiedIdKind::IK_DestructorName:
14059   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14060   case UnqualifiedIdKind::IK_DeductionGuideName:
14061     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14062       << GetNameForDeclarator(D).getName();
14063     break;
14064 
14065   case UnqualifiedIdKind::IK_TemplateId:
14066   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14067     // GetNameForDeclarator would not produce a useful name in this case.
14068     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14069     break;
14070   }
14071 }
14072 
14073 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14074 /// to introduce parameters into function prototype scope.
14075 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14076   const DeclSpec &DS = D.getDeclSpec();
14077 
14078   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14079 
14080   // C++03 [dcl.stc]p2 also permits 'auto'.
14081   StorageClass SC = SC_None;
14082   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14083     SC = SC_Register;
14084     // In C++11, the 'register' storage class specifier is deprecated.
14085     // In C++17, it is not allowed, but we tolerate it as an extension.
14086     if (getLangOpts().CPlusPlus11) {
14087       Diag(DS.getStorageClassSpecLoc(),
14088            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14089                                      : diag::warn_deprecated_register)
14090         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14091     }
14092   } else if (getLangOpts().CPlusPlus &&
14093              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14094     SC = SC_Auto;
14095   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14096     Diag(DS.getStorageClassSpecLoc(),
14097          diag::err_invalid_storage_class_in_func_decl);
14098     D.getMutableDeclSpec().ClearStorageClassSpecs();
14099   }
14100 
14101   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14102     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14103       << DeclSpec::getSpecifierName(TSCS);
14104   if (DS.isInlineSpecified())
14105     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14106         << getLangOpts().CPlusPlus17;
14107   if (DS.hasConstexprSpecifier())
14108     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14109         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14110 
14111   DiagnoseFunctionSpecifiers(DS);
14112 
14113   CheckFunctionOrTemplateParamDeclarator(S, D);
14114 
14115   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14116   QualType parmDeclType = TInfo->getType();
14117 
14118   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14119   IdentifierInfo *II = D.getIdentifier();
14120   if (II) {
14121     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14122                    ForVisibleRedeclaration);
14123     LookupName(R, S);
14124     if (R.isSingleResult()) {
14125       NamedDecl *PrevDecl = R.getFoundDecl();
14126       if (PrevDecl->isTemplateParameter()) {
14127         // Maybe we will complain about the shadowed template parameter.
14128         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14129         // Just pretend that we didn't see the previous declaration.
14130         PrevDecl = nullptr;
14131       } else if (S->isDeclScope(PrevDecl)) {
14132         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14133         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14134 
14135         // Recover by removing the name
14136         II = nullptr;
14137         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14138         D.setInvalidType(true);
14139       }
14140     }
14141   }
14142 
14143   // Temporarily put parameter variables in the translation unit, not
14144   // the enclosing context.  This prevents them from accidentally
14145   // looking like class members in C++.
14146   ParmVarDecl *New =
14147       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14148                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14149 
14150   if (D.isInvalidType())
14151     New->setInvalidDecl();
14152 
14153   assert(S->isFunctionPrototypeScope());
14154   assert(S->getFunctionPrototypeDepth() >= 1);
14155   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14156                     S->getNextFunctionPrototypeIndex());
14157 
14158   // Add the parameter declaration into this scope.
14159   S->AddDecl(New);
14160   if (II)
14161     IdResolver.AddDecl(New);
14162 
14163   ProcessDeclAttributes(S, New, D);
14164 
14165   if (D.getDeclSpec().isModulePrivateSpecified())
14166     Diag(New->getLocation(), diag::err_module_private_local)
14167         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14168         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14169 
14170   if (New->hasAttr<BlocksAttr>()) {
14171     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14172   }
14173 
14174   if (getLangOpts().OpenCL)
14175     deduceOpenCLAddressSpace(New);
14176 
14177   return New;
14178 }
14179 
14180 /// Synthesizes a variable for a parameter arising from a
14181 /// typedef.
14182 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14183                                               SourceLocation Loc,
14184                                               QualType T) {
14185   /* FIXME: setting StartLoc == Loc.
14186      Would it be worth to modify callers so as to provide proper source
14187      location for the unnamed parameters, embedding the parameter's type? */
14188   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14189                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14190                                            SC_None, nullptr);
14191   Param->setImplicit();
14192   return Param;
14193 }
14194 
14195 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14196   // Don't diagnose unused-parameter errors in template instantiations; we
14197   // will already have done so in the template itself.
14198   if (inTemplateInstantiation())
14199     return;
14200 
14201   for (const ParmVarDecl *Parameter : Parameters) {
14202     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14203         !Parameter->hasAttr<UnusedAttr>()) {
14204       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14205         << Parameter->getDeclName();
14206     }
14207   }
14208 }
14209 
14210 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14211     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14212   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14213     return;
14214 
14215   // Warn if the return value is pass-by-value and larger than the specified
14216   // threshold.
14217   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14218     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14219     if (Size > LangOpts.NumLargeByValueCopy)
14220       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14221   }
14222 
14223   // Warn if any parameter is pass-by-value and larger than the specified
14224   // threshold.
14225   for (const ParmVarDecl *Parameter : Parameters) {
14226     QualType T = Parameter->getType();
14227     if (T->isDependentType() || !T.isPODType(Context))
14228       continue;
14229     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14230     if (Size > LangOpts.NumLargeByValueCopy)
14231       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14232           << Parameter << Size;
14233   }
14234 }
14235 
14236 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14237                                   SourceLocation NameLoc, IdentifierInfo *Name,
14238                                   QualType T, TypeSourceInfo *TSInfo,
14239                                   StorageClass SC) {
14240   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14241   if (getLangOpts().ObjCAutoRefCount &&
14242       T.getObjCLifetime() == Qualifiers::OCL_None &&
14243       T->isObjCLifetimeType()) {
14244 
14245     Qualifiers::ObjCLifetime lifetime;
14246 
14247     // Special cases for arrays:
14248     //   - if it's const, use __unsafe_unretained
14249     //   - otherwise, it's an error
14250     if (T->isArrayType()) {
14251       if (!T.isConstQualified()) {
14252         if (DelayedDiagnostics.shouldDelayDiagnostics())
14253           DelayedDiagnostics.add(
14254               sema::DelayedDiagnostic::makeForbiddenType(
14255               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14256         else
14257           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14258               << TSInfo->getTypeLoc().getSourceRange();
14259       }
14260       lifetime = Qualifiers::OCL_ExplicitNone;
14261     } else {
14262       lifetime = T->getObjCARCImplicitLifetime();
14263     }
14264     T = Context.getLifetimeQualifiedType(T, lifetime);
14265   }
14266 
14267   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14268                                          Context.getAdjustedParameterType(T),
14269                                          TSInfo, SC, nullptr);
14270 
14271   // Make a note if we created a new pack in the scope of a lambda, so that
14272   // we know that references to that pack must also be expanded within the
14273   // lambda scope.
14274   if (New->isParameterPack())
14275     if (auto *LSI = getEnclosingLambda())
14276       LSI->LocalPacks.push_back(New);
14277 
14278   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14279       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14280     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14281                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14282 
14283   // Parameters can not be abstract class types.
14284   // For record types, this is done by the AbstractClassUsageDiagnoser once
14285   // the class has been completely parsed.
14286   if (!CurContext->isRecord() &&
14287       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14288                              AbstractParamType))
14289     New->setInvalidDecl();
14290 
14291   // Parameter declarators cannot be interface types. All ObjC objects are
14292   // passed by reference.
14293   if (T->isObjCObjectType()) {
14294     SourceLocation TypeEndLoc =
14295         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14296     Diag(NameLoc,
14297          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14298       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14299     T = Context.getObjCObjectPointerType(T);
14300     New->setType(T);
14301   }
14302 
14303   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14304   // duration shall not be qualified by an address-space qualifier."
14305   // Since all parameters have automatic store duration, they can not have
14306   // an address space.
14307   if (T.getAddressSpace() != LangAS::Default &&
14308       // OpenCL allows function arguments declared to be an array of a type
14309       // to be qualified with an address space.
14310       !(getLangOpts().OpenCL &&
14311         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14312     Diag(NameLoc, diag::err_arg_with_address_space);
14313     New->setInvalidDecl();
14314   }
14315 
14316   // PPC MMA non-pointer types are not allowed as function argument types.
14317   if (Context.getTargetInfo().getTriple().isPPC64() &&
14318       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14319     New->setInvalidDecl();
14320   }
14321 
14322   return New;
14323 }
14324 
14325 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14326                                            SourceLocation LocAfterDecls) {
14327   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14328 
14329   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14330   // in the declaration list shall have at least one declarator, those
14331   // declarators shall only declare identifiers from the identifier list, and
14332   // every identifier in the identifier list shall be declared.
14333   //
14334   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14335   // identifiers it names shall be declared in the declaration list."
14336   //
14337   // This is why we only diagnose in C99 and later. Note, the other conditions
14338   // listed are checked elsewhere.
14339   if (!FTI.hasPrototype) {
14340     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14341       --i;
14342       if (FTI.Params[i].Param == nullptr) {
14343         if (getLangOpts().C99) {
14344           SmallString<256> Code;
14345           llvm::raw_svector_ostream(Code)
14346               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14347           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14348               << FTI.Params[i].Ident
14349               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14350         }
14351 
14352         // Implicitly declare the argument as type 'int' for lack of a better
14353         // type.
14354         AttributeFactory attrs;
14355         DeclSpec DS(attrs);
14356         const char* PrevSpec; // unused
14357         unsigned DiagID; // unused
14358         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14359                            DiagID, Context.getPrintingPolicy());
14360         // Use the identifier location for the type source range.
14361         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14362         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14363         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14364         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14365         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14366       }
14367     }
14368   }
14369 }
14370 
14371 Decl *
14372 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14373                               MultiTemplateParamsArg TemplateParameterLists,
14374                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14375   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14376   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14377   Scope *ParentScope = FnBodyScope->getParent();
14378 
14379   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14380   // we define a non-templated function definition, we will create a declaration
14381   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14382   // The base function declaration will have the equivalent of an `omp declare
14383   // variant` annotation which specifies the mangled definition as a
14384   // specialization function under the OpenMP context defined as part of the
14385   // `omp begin declare variant`.
14386   SmallVector<FunctionDecl *, 4> Bases;
14387   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14388     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14389         ParentScope, D, TemplateParameterLists, Bases);
14390 
14391   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14392   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14393   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14394 
14395   if (!Bases.empty())
14396     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14397 
14398   return Dcl;
14399 }
14400 
14401 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14402   Consumer.HandleInlineFunctionDefinition(D);
14403 }
14404 
14405 static bool
14406 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14407                                 const FunctionDecl *&PossiblePrototype) {
14408   // Don't warn about invalid declarations.
14409   if (FD->isInvalidDecl())
14410     return false;
14411 
14412   // Or declarations that aren't global.
14413   if (!FD->isGlobal())
14414     return false;
14415 
14416   // Don't warn about C++ member functions.
14417   if (isa<CXXMethodDecl>(FD))
14418     return false;
14419 
14420   // Don't warn about 'main'.
14421   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14422     if (IdentifierInfo *II = FD->getIdentifier())
14423       if (II->isStr("main") || II->isStr("efi_main"))
14424         return false;
14425 
14426   // Don't warn about inline functions.
14427   if (FD->isInlined())
14428     return false;
14429 
14430   // Don't warn about function templates.
14431   if (FD->getDescribedFunctionTemplate())
14432     return false;
14433 
14434   // Don't warn about function template specializations.
14435   if (FD->isFunctionTemplateSpecialization())
14436     return false;
14437 
14438   // Don't warn for OpenCL kernels.
14439   if (FD->hasAttr<OpenCLKernelAttr>())
14440     return false;
14441 
14442   // Don't warn on explicitly deleted functions.
14443   if (FD->isDeleted())
14444     return false;
14445 
14446   // Don't warn on implicitly local functions (such as having local-typed
14447   // parameters).
14448   if (!FD->isExternallyVisible())
14449     return false;
14450 
14451   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14452        Prev; Prev = Prev->getPreviousDecl()) {
14453     // Ignore any declarations that occur in function or method
14454     // scope, because they aren't visible from the header.
14455     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14456       continue;
14457 
14458     PossiblePrototype = Prev;
14459     return Prev->getType()->isFunctionNoProtoType();
14460   }
14461 
14462   return true;
14463 }
14464 
14465 void
14466 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14467                                    const FunctionDecl *EffectiveDefinition,
14468                                    SkipBodyInfo *SkipBody) {
14469   const FunctionDecl *Definition = EffectiveDefinition;
14470   if (!Definition &&
14471       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14472     return;
14473 
14474   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14475     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14476       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14477         // A merged copy of the same function, instantiated as a member of
14478         // the same class, is OK.
14479         if (declaresSameEntity(OrigFD, OrigDef) &&
14480             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14481                                cast<Decl>(FD->getLexicalDeclContext())))
14482           return;
14483       }
14484     }
14485   }
14486 
14487   if (canRedefineFunction(Definition, getLangOpts()))
14488     return;
14489 
14490   // Don't emit an error when this is redefinition of a typo-corrected
14491   // definition.
14492   if (TypoCorrectedFunctionDefinitions.count(Definition))
14493     return;
14494 
14495   // If we don't have a visible definition of the function, and it's inline or
14496   // a template, skip the new definition.
14497   if (SkipBody && !hasVisibleDefinition(Definition) &&
14498       (Definition->getFormalLinkage() == InternalLinkage ||
14499        Definition->isInlined() ||
14500        Definition->getDescribedFunctionTemplate() ||
14501        Definition->getNumTemplateParameterLists())) {
14502     SkipBody->ShouldSkip = true;
14503     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14504     if (auto *TD = Definition->getDescribedFunctionTemplate())
14505       makeMergedDefinitionVisible(TD);
14506     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14507     return;
14508   }
14509 
14510   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14511       Definition->getStorageClass() == SC_Extern)
14512     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14513         << FD << getLangOpts().CPlusPlus;
14514   else
14515     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14516 
14517   Diag(Definition->getLocation(), diag::note_previous_definition);
14518   FD->setInvalidDecl();
14519 }
14520 
14521 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14522                                    Sema &S) {
14523   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14524 
14525   LambdaScopeInfo *LSI = S.PushLambdaScope();
14526   LSI->CallOperator = CallOperator;
14527   LSI->Lambda = LambdaClass;
14528   LSI->ReturnType = CallOperator->getReturnType();
14529   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14530 
14531   if (LCD == LCD_None)
14532     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14533   else if (LCD == LCD_ByCopy)
14534     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14535   else if (LCD == LCD_ByRef)
14536     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14537   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14538 
14539   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14540   LSI->Mutable = !CallOperator->isConst();
14541 
14542   // Add the captures to the LSI so they can be noted as already
14543   // captured within tryCaptureVar.
14544   auto I = LambdaClass->field_begin();
14545   for (const auto &C : LambdaClass->captures()) {
14546     if (C.capturesVariable()) {
14547       VarDecl *VD = C.getCapturedVar();
14548       if (VD->isInitCapture())
14549         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14550       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14551       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14552           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14553           /*EllipsisLoc*/C.isPackExpansion()
14554                          ? C.getEllipsisLoc() : SourceLocation(),
14555           I->getType(), /*Invalid*/false);
14556 
14557     } else if (C.capturesThis()) {
14558       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14559                           C.getCaptureKind() == LCK_StarThis);
14560     } else {
14561       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14562                              I->getType());
14563     }
14564     ++I;
14565   }
14566 }
14567 
14568 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14569                                     SkipBodyInfo *SkipBody,
14570                                     FnBodyKind BodyKind) {
14571   if (!D) {
14572     // Parsing the function declaration failed in some way. Push on a fake scope
14573     // anyway so we can try to parse the function body.
14574     PushFunctionScope();
14575     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14576     return D;
14577   }
14578 
14579   FunctionDecl *FD = nullptr;
14580 
14581   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14582     FD = FunTmpl->getTemplatedDecl();
14583   else
14584     FD = cast<FunctionDecl>(D);
14585 
14586   // Do not push if it is a lambda because one is already pushed when building
14587   // the lambda in ActOnStartOfLambdaDefinition().
14588   if (!isLambdaCallOperator(FD))
14589     PushExpressionEvaluationContext(
14590         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14591                           : ExprEvalContexts.back().Context);
14592 
14593   // Check for defining attributes before the check for redefinition.
14594   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14595     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14596     FD->dropAttr<AliasAttr>();
14597     FD->setInvalidDecl();
14598   }
14599   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14600     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14601     FD->dropAttr<IFuncAttr>();
14602     FD->setInvalidDecl();
14603   }
14604 
14605   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14606     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14607         Ctor->isDefaultConstructor() &&
14608         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14609       // If this is an MS ABI dllexport default constructor, instantiate any
14610       // default arguments.
14611       InstantiateDefaultCtorDefaultArgs(Ctor);
14612     }
14613   }
14614 
14615   // See if this is a redefinition. If 'will have body' (or similar) is already
14616   // set, then these checks were already performed when it was set.
14617   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14618       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14619     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14620 
14621     // If we're skipping the body, we're done. Don't enter the scope.
14622     if (SkipBody && SkipBody->ShouldSkip)
14623       return D;
14624   }
14625 
14626   // Mark this function as "will have a body eventually".  This lets users to
14627   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14628   // this function.
14629   FD->setWillHaveBody();
14630 
14631   // If we are instantiating a generic lambda call operator, push
14632   // a LambdaScopeInfo onto the function stack.  But use the information
14633   // that's already been calculated (ActOnLambdaExpr) to prime the current
14634   // LambdaScopeInfo.
14635   // When the template operator is being specialized, the LambdaScopeInfo,
14636   // has to be properly restored so that tryCaptureVariable doesn't try
14637   // and capture any new variables. In addition when calculating potential
14638   // captures during transformation of nested lambdas, it is necessary to
14639   // have the LSI properly restored.
14640   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14641     assert(inTemplateInstantiation() &&
14642            "There should be an active template instantiation on the stack "
14643            "when instantiating a generic lambda!");
14644     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14645   } else {
14646     // Enter a new function scope
14647     PushFunctionScope();
14648   }
14649 
14650   // Builtin functions cannot be defined.
14651   if (unsigned BuiltinID = FD->getBuiltinID()) {
14652     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14653         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14654       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14655       FD->setInvalidDecl();
14656     }
14657   }
14658 
14659   // The return type of a function definition must be complete (C99 6.9.1p3),
14660   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14661   QualType ResultType = FD->getReturnType();
14662   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14663       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14664       RequireCompleteType(FD->getLocation(), ResultType,
14665                           diag::err_func_def_incomplete_result))
14666     FD->setInvalidDecl();
14667 
14668   if (FnBodyScope)
14669     PushDeclContext(FnBodyScope, FD);
14670 
14671   // Check the validity of our function parameters
14672   if (BodyKind != FnBodyKind::Delete)
14673     CheckParmsForFunctionDef(FD->parameters(),
14674                              /*CheckParameterNames=*/true);
14675 
14676   // Add non-parameter declarations already in the function to the current
14677   // scope.
14678   if (FnBodyScope) {
14679     for (Decl *NPD : FD->decls()) {
14680       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14681       if (!NonParmDecl)
14682         continue;
14683       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14684              "parameters should not be in newly created FD yet");
14685 
14686       // If the decl has a name, make it accessible in the current scope.
14687       if (NonParmDecl->getDeclName())
14688         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14689 
14690       // Similarly, dive into enums and fish their constants out, making them
14691       // accessible in this scope.
14692       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14693         for (auto *EI : ED->enumerators())
14694           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14695       }
14696     }
14697   }
14698 
14699   // Introduce our parameters into the function scope
14700   for (auto Param : FD->parameters()) {
14701     Param->setOwningFunction(FD);
14702 
14703     // If this has an identifier, add it to the scope stack.
14704     if (Param->getIdentifier() && FnBodyScope) {
14705       CheckShadow(FnBodyScope, Param);
14706 
14707       PushOnScopeChains(Param, FnBodyScope);
14708     }
14709   }
14710 
14711   // Ensure that the function's exception specification is instantiated.
14712   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14713     ResolveExceptionSpec(D->getLocation(), FPT);
14714 
14715   // dllimport cannot be applied to non-inline function definitions.
14716   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14717       !FD->isTemplateInstantiation()) {
14718     assert(!FD->hasAttr<DLLExportAttr>());
14719     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14720     FD->setInvalidDecl();
14721     return D;
14722   }
14723   // We want to attach documentation to original Decl (which might be
14724   // a function template).
14725   ActOnDocumentableDecl(D);
14726   if (getCurLexicalContext()->isObjCContainer() &&
14727       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14728       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14729     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14730 
14731   return D;
14732 }
14733 
14734 /// Given the set of return statements within a function body,
14735 /// compute the variables that are subject to the named return value
14736 /// optimization.
14737 ///
14738 /// Each of the variables that is subject to the named return value
14739 /// optimization will be marked as NRVO variables in the AST, and any
14740 /// return statement that has a marked NRVO variable as its NRVO candidate can
14741 /// use the named return value optimization.
14742 ///
14743 /// This function applies a very simplistic algorithm for NRVO: if every return
14744 /// statement in the scope of a variable has the same NRVO candidate, that
14745 /// candidate is an NRVO variable.
14746 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14747   ReturnStmt **Returns = Scope->Returns.data();
14748 
14749   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14750     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14751       if (!NRVOCandidate->isNRVOVariable())
14752         Returns[I]->setNRVOCandidate(nullptr);
14753     }
14754   }
14755 }
14756 
14757 bool Sema::canDelayFunctionBody(const Declarator &D) {
14758   // We can't delay parsing the body of a constexpr function template (yet).
14759   if (D.getDeclSpec().hasConstexprSpecifier())
14760     return false;
14761 
14762   // We can't delay parsing the body of a function template with a deduced
14763   // return type (yet).
14764   if (D.getDeclSpec().hasAutoTypeSpec()) {
14765     // If the placeholder introduces a non-deduced trailing return type,
14766     // we can still delay parsing it.
14767     if (D.getNumTypeObjects()) {
14768       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14769       if (Outer.Kind == DeclaratorChunk::Function &&
14770           Outer.Fun.hasTrailingReturnType()) {
14771         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14772         return Ty.isNull() || !Ty->isUndeducedType();
14773       }
14774     }
14775     return false;
14776   }
14777 
14778   return true;
14779 }
14780 
14781 bool Sema::canSkipFunctionBody(Decl *D) {
14782   // We cannot skip the body of a function (or function template) which is
14783   // constexpr, since we may need to evaluate its body in order to parse the
14784   // rest of the file.
14785   // We cannot skip the body of a function with an undeduced return type,
14786   // because any callers of that function need to know the type.
14787   if (const FunctionDecl *FD = D->getAsFunction()) {
14788     if (FD->isConstexpr())
14789       return false;
14790     // We can't simply call Type::isUndeducedType here, because inside template
14791     // auto can be deduced to a dependent type, which is not considered
14792     // "undeduced".
14793     if (FD->getReturnType()->getContainedDeducedType())
14794       return false;
14795   }
14796   return Consumer.shouldSkipFunctionBody(D);
14797 }
14798 
14799 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14800   if (!Decl)
14801     return nullptr;
14802   if (FunctionDecl *FD = Decl->getAsFunction())
14803     FD->setHasSkippedBody();
14804   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14805     MD->setHasSkippedBody();
14806   return Decl;
14807 }
14808 
14809 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14810   return ActOnFinishFunctionBody(D, BodyArg, false);
14811 }
14812 
14813 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14814 /// body.
14815 class ExitFunctionBodyRAII {
14816 public:
14817   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14818   ~ExitFunctionBodyRAII() {
14819     if (!IsLambda)
14820       S.PopExpressionEvaluationContext();
14821   }
14822 
14823 private:
14824   Sema &S;
14825   bool IsLambda = false;
14826 };
14827 
14828 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14829   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14830 
14831   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14832     if (EscapeInfo.count(BD))
14833       return EscapeInfo[BD];
14834 
14835     bool R = false;
14836     const BlockDecl *CurBD = BD;
14837 
14838     do {
14839       R = !CurBD->doesNotEscape();
14840       if (R)
14841         break;
14842       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14843     } while (CurBD);
14844 
14845     return EscapeInfo[BD] = R;
14846   };
14847 
14848   // If the location where 'self' is implicitly retained is inside a escaping
14849   // block, emit a diagnostic.
14850   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14851        S.ImplicitlyRetainedSelfLocs)
14852     if (IsOrNestedInEscapingBlock(P.second))
14853       S.Diag(P.first, diag::warn_implicitly_retains_self)
14854           << FixItHint::CreateInsertion(P.first, "self->");
14855 }
14856 
14857 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14858                                     bool IsInstantiation) {
14859   FunctionScopeInfo *FSI = getCurFunction();
14860   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14861 
14862   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14863     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14864 
14865   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14866   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14867 
14868   if (getLangOpts().Coroutines && FSI->isCoroutine())
14869     CheckCompletedCoroutineBody(FD, Body);
14870 
14871   {
14872     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14873     // one is already popped when finishing the lambda in BuildLambdaExpr().
14874     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14875     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14876 
14877     if (FD) {
14878       FD->setBody(Body);
14879       FD->setWillHaveBody(false);
14880 
14881       if (getLangOpts().CPlusPlus14) {
14882         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14883             FD->getReturnType()->isUndeducedType()) {
14884           // For a function with a deduced result type to return void,
14885           // the result type as written must be 'auto' or 'decltype(auto)',
14886           // possibly cv-qualified or constrained, but not ref-qualified.
14887           if (!FD->getReturnType()->getAs<AutoType>()) {
14888             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14889                 << FD->getReturnType();
14890             FD->setInvalidDecl();
14891           } else {
14892             // Falling off the end of the function is the same as 'return;'.
14893             Expr *Dummy = nullptr;
14894             if (DeduceFunctionTypeFromReturnExpr(
14895                     FD, dcl->getLocation(), Dummy,
14896                     FD->getReturnType()->getAs<AutoType>()))
14897               FD->setInvalidDecl();
14898           }
14899         }
14900       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14901         // In C++11, we don't use 'auto' deduction rules for lambda call
14902         // operators because we don't support return type deduction.
14903         auto *LSI = getCurLambda();
14904         if (LSI->HasImplicitReturnType) {
14905           deduceClosureReturnType(*LSI);
14906 
14907           // C++11 [expr.prim.lambda]p4:
14908           //   [...] if there are no return statements in the compound-statement
14909           //   [the deduced type is] the type void
14910           QualType RetType =
14911               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14912 
14913           // Update the return type to the deduced type.
14914           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14915           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14916                                               Proto->getExtProtoInfo()));
14917         }
14918       }
14919 
14920       // If the function implicitly returns zero (like 'main') or is naked,
14921       // don't complain about missing return statements.
14922       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14923         WP.disableCheckFallThrough();
14924 
14925       // MSVC permits the use of pure specifier (=0) on function definition,
14926       // defined at class scope, warn about this non-standard construct.
14927       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14928         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14929 
14930       if (!FD->isInvalidDecl()) {
14931         // Don't diagnose unused parameters of defaulted, deleted or naked
14932         // functions.
14933         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14934             !FD->hasAttr<NakedAttr>())
14935           DiagnoseUnusedParameters(FD->parameters());
14936         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14937                                                FD->getReturnType(), FD);
14938 
14939         // If this is a structor, we need a vtable.
14940         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14941           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14942         else if (CXXDestructorDecl *Destructor =
14943                      dyn_cast<CXXDestructorDecl>(FD))
14944           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14945 
14946         // Try to apply the named return value optimization. We have to check
14947         // if we can do this here because lambdas keep return statements around
14948         // to deduce an implicit return type.
14949         if (FD->getReturnType()->isRecordType() &&
14950             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14951           computeNRVO(Body, FSI);
14952       }
14953 
14954       // GNU warning -Wmissing-prototypes:
14955       //   Warn if a global function is defined without a previous
14956       //   prototype declaration. This warning is issued even if the
14957       //   definition itself provides a prototype. The aim is to detect
14958       //   global functions that fail to be declared in header files.
14959       const FunctionDecl *PossiblePrototype = nullptr;
14960       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14961         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14962 
14963         if (PossiblePrototype) {
14964           // We found a declaration that is not a prototype,
14965           // but that could be a zero-parameter prototype
14966           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14967             TypeLoc TL = TI->getTypeLoc();
14968             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14969               Diag(PossiblePrototype->getLocation(),
14970                    diag::note_declaration_not_a_prototype)
14971                   << (FD->getNumParams() != 0)
14972                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14973                                                     FTL.getRParenLoc(), "void")
14974                                               : FixItHint{});
14975           }
14976         } else {
14977           // Returns true if the token beginning at this Loc is `const`.
14978           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14979                                   const LangOptions &LangOpts) {
14980             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14981             if (LocInfo.first.isInvalid())
14982               return false;
14983 
14984             bool Invalid = false;
14985             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14986             if (Invalid)
14987               return false;
14988 
14989             if (LocInfo.second > Buffer.size())
14990               return false;
14991 
14992             const char *LexStart = Buffer.data() + LocInfo.second;
14993             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14994 
14995             return StartTok.consume_front("const") &&
14996                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14997                     StartTok.startswith("/*") || StartTok.startswith("//"));
14998           };
14999 
15000           auto findBeginLoc = [&]() {
15001             // If the return type has `const` qualifier, we want to insert
15002             // `static` before `const` (and not before the typename).
15003             if ((FD->getReturnType()->isAnyPointerType() &&
15004                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15005                 FD->getReturnType().isConstQualified()) {
15006               // But only do this if we can determine where the `const` is.
15007 
15008               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15009                                getLangOpts()))
15010 
15011                 return FD->getBeginLoc();
15012             }
15013             return FD->getTypeSpecStartLoc();
15014           };
15015           Diag(FD->getTypeSpecStartLoc(),
15016                diag::note_static_for_internal_linkage)
15017               << /* function */ 1
15018               << (FD->getStorageClass() == SC_None
15019                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15020                       : FixItHint{});
15021         }
15022       }
15023 
15024       // If the function being defined does not have a prototype, then we may
15025       // need to diagnose it as changing behavior in C2x because we now know
15026       // whether the function accepts arguments or not. This only handles the
15027       // case where the definition has no prototype but does have parameters
15028       // and either there is no previous potential prototype, or the previous
15029       // potential prototype also has no actual prototype. This handles cases
15030       // like:
15031       //   void f(); void f(a) int a; {}
15032       //   void g(a) int a; {}
15033       // See MergeFunctionDecl() for other cases of the behavior change
15034       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15035       // type without a prototype.
15036       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15037           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15038                                   !PossiblePrototype->isImplicit()))) {
15039         // The function definition has parameters, so this will change behavior
15040         // in C2x. If there is a possible prototype, it comes before the
15041         // function definition.
15042         // FIXME: The declaration may have already been diagnosed as being
15043         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15044         // there's no way to test for the "changes behavior" condition in
15045         // SemaType.cpp when forming the declaration's function type. So, we do
15046         // this awkward dance instead.
15047         //
15048         // If we have a possible prototype and it declares a function with a
15049         // prototype, we don't want to diagnose it; if we have a possible
15050         // prototype and it has no prototype, it may have already been
15051         // diagnosed in SemaType.cpp as deprecated depending on whether
15052         // -Wstrict-prototypes is enabled. If we already warned about it being
15053         // deprecated, add a note that it also changes behavior. If we didn't
15054         // warn about it being deprecated (because the diagnostic is not
15055         // enabled), warn now that it is deprecated and changes behavior.
15056         bool AddNote = false;
15057         if (PossiblePrototype) {
15058           if (Diags.isIgnored(diag::warn_strict_prototypes,
15059                               PossiblePrototype->getLocation())) {
15060 
15061             PartialDiagnostic PD =
15062                 PDiag(diag::warn_non_prototype_changes_behavior);
15063             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
15064               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
15065                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
15066             }
15067             Diag(PossiblePrototype->getLocation(), PD);
15068           } else {
15069             AddNote = true;
15070           }
15071         }
15072 
15073         // Because this function definition has no prototype and it has
15074         // parameters, it will definitely change behavior in C2x.
15075         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
15076         if (AddNote)
15077           Diag(PossiblePrototype->getLocation(),
15078                diag::note_func_decl_changes_behavior);
15079       }
15080 
15081       // Warn on CPUDispatch with an actual body.
15082       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15083         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15084           if (!CmpndBody->body_empty())
15085             Diag(CmpndBody->body_front()->getBeginLoc(),
15086                  diag::warn_dispatch_body_ignored);
15087 
15088       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15089         const CXXMethodDecl *KeyFunction;
15090         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15091             MD->isVirtual() &&
15092             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15093             MD == KeyFunction->getCanonicalDecl()) {
15094           // Update the key-function state if necessary for this ABI.
15095           if (FD->isInlined() &&
15096               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15097             Context.setNonKeyFunction(MD);
15098 
15099             // If the newly-chosen key function is already defined, then we
15100             // need to mark the vtable as used retroactively.
15101             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15102             const FunctionDecl *Definition;
15103             if (KeyFunction && KeyFunction->isDefined(Definition))
15104               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15105           } else {
15106             // We just defined they key function; mark the vtable as used.
15107             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15108           }
15109         }
15110       }
15111 
15112       assert(
15113           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15114           "Function parsing confused");
15115     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15116       assert(MD == getCurMethodDecl() && "Method parsing confused");
15117       MD->setBody(Body);
15118       if (!MD->isInvalidDecl()) {
15119         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15120                                                MD->getReturnType(), MD);
15121 
15122         if (Body)
15123           computeNRVO(Body, FSI);
15124       }
15125       if (FSI->ObjCShouldCallSuper) {
15126         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15127             << MD->getSelector().getAsString();
15128         FSI->ObjCShouldCallSuper = false;
15129       }
15130       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15131         const ObjCMethodDecl *InitMethod = nullptr;
15132         bool isDesignated =
15133             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15134         assert(isDesignated && InitMethod);
15135         (void)isDesignated;
15136 
15137         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15138           auto IFace = MD->getClassInterface();
15139           if (!IFace)
15140             return false;
15141           auto SuperD = IFace->getSuperClass();
15142           if (!SuperD)
15143             return false;
15144           return SuperD->getIdentifier() ==
15145                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15146         };
15147         // Don't issue this warning for unavailable inits or direct subclasses
15148         // of NSObject.
15149         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15150           Diag(MD->getLocation(),
15151                diag::warn_objc_designated_init_missing_super_call);
15152           Diag(InitMethod->getLocation(),
15153                diag::note_objc_designated_init_marked_here);
15154         }
15155         FSI->ObjCWarnForNoDesignatedInitChain = false;
15156       }
15157       if (FSI->ObjCWarnForNoInitDelegation) {
15158         // Don't issue this warning for unavaialable inits.
15159         if (!MD->isUnavailable())
15160           Diag(MD->getLocation(),
15161                diag::warn_objc_secondary_init_missing_init_call);
15162         FSI->ObjCWarnForNoInitDelegation = false;
15163       }
15164 
15165       diagnoseImplicitlyRetainedSelf(*this);
15166     } else {
15167       // Parsing the function declaration failed in some way. Pop the fake scope
15168       // we pushed on.
15169       PopFunctionScopeInfo(ActivePolicy, dcl);
15170       return nullptr;
15171     }
15172 
15173     if (Body && FSI->HasPotentialAvailabilityViolations)
15174       DiagnoseUnguardedAvailabilityViolations(dcl);
15175 
15176     assert(!FSI->ObjCShouldCallSuper &&
15177            "This should only be set for ObjC methods, which should have been "
15178            "handled in the block above.");
15179 
15180     // Verify and clean out per-function state.
15181     if (Body && (!FD || !FD->isDefaulted())) {
15182       // C++ constructors that have function-try-blocks can't have return
15183       // statements in the handlers of that block. (C++ [except.handle]p14)
15184       // Verify this.
15185       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15186         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15187 
15188       // Verify that gotos and switch cases don't jump into scopes illegally.
15189       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15190         DiagnoseInvalidJumps(Body);
15191 
15192       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15193         if (!Destructor->getParent()->isDependentType())
15194           CheckDestructor(Destructor);
15195 
15196         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15197                                                Destructor->getParent());
15198       }
15199 
15200       // If any errors have occurred, clear out any temporaries that may have
15201       // been leftover. This ensures that these temporaries won't be picked up
15202       // for deletion in some later function.
15203       if (hasUncompilableErrorOccurred() ||
15204           getDiagnostics().getSuppressAllDiagnostics()) {
15205         DiscardCleanupsInEvaluationContext();
15206       }
15207       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15208         // Since the body is valid, issue any analysis-based warnings that are
15209         // enabled.
15210         ActivePolicy = &WP;
15211       }
15212 
15213       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15214           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15215         FD->setInvalidDecl();
15216 
15217       if (FD && FD->hasAttr<NakedAttr>()) {
15218         for (const Stmt *S : Body->children()) {
15219           // Allow local register variables without initializer as they don't
15220           // require prologue.
15221           bool RegisterVariables = false;
15222           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15223             for (const auto *Decl : DS->decls()) {
15224               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15225                 RegisterVariables =
15226                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15227                 if (!RegisterVariables)
15228                   break;
15229               }
15230             }
15231           }
15232           if (RegisterVariables)
15233             continue;
15234           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15235             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15236             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15237             FD->setInvalidDecl();
15238             break;
15239           }
15240         }
15241       }
15242 
15243       assert(ExprCleanupObjects.size() ==
15244                  ExprEvalContexts.back().NumCleanupObjects &&
15245              "Leftover temporaries in function");
15246       assert(!Cleanup.exprNeedsCleanups() &&
15247              "Unaccounted cleanups in function");
15248       assert(MaybeODRUseExprs.empty() &&
15249              "Leftover expressions for odr-use checking");
15250     }
15251   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15252     // the declaration context below. Otherwise, we're unable to transform
15253     // 'this' expressions when transforming immediate context functions.
15254 
15255   if (!IsInstantiation)
15256     PopDeclContext();
15257 
15258   PopFunctionScopeInfo(ActivePolicy, dcl);
15259   // If any errors have occurred, clear out any temporaries that may have
15260   // been leftover. This ensures that these temporaries won't be picked up for
15261   // deletion in some later function.
15262   if (hasUncompilableErrorOccurred()) {
15263     DiscardCleanupsInEvaluationContext();
15264   }
15265 
15266   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15267                                   !LangOpts.OMPTargetTriples.empty())) ||
15268              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15269     auto ES = getEmissionStatus(FD);
15270     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15271         ES == Sema::FunctionEmissionStatus::Unknown)
15272       DeclsToCheckForDeferredDiags.insert(FD);
15273   }
15274 
15275   if (FD && !FD->isDeleted())
15276     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15277 
15278   return dcl;
15279 }
15280 
15281 /// When we finish delayed parsing of an attribute, we must attach it to the
15282 /// relevant Decl.
15283 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15284                                        ParsedAttributes &Attrs) {
15285   // Always attach attributes to the underlying decl.
15286   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15287     D = TD->getTemplatedDecl();
15288   ProcessDeclAttributeList(S, D, Attrs);
15289 
15290   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15291     if (Method->isStatic())
15292       checkThisInStaticMemberFunctionAttributes(Method);
15293 }
15294 
15295 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15296 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15297 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15298                                           IdentifierInfo &II, Scope *S) {
15299   // It is not valid to implicitly define a function in C2x.
15300   assert(LangOpts.implicitFunctionsAllowed() &&
15301          "Implicit function declarations aren't allowed in this language mode");
15302 
15303   // Find the scope in which the identifier is injected and the corresponding
15304   // DeclContext.
15305   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15306   // In that case, we inject the declaration into the translation unit scope
15307   // instead.
15308   Scope *BlockScope = S;
15309   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15310     BlockScope = BlockScope->getParent();
15311 
15312   Scope *ContextScope = BlockScope;
15313   while (!ContextScope->getEntity())
15314     ContextScope = ContextScope->getParent();
15315   ContextRAII SavedContext(*this, ContextScope->getEntity());
15316 
15317   // Before we produce a declaration for an implicitly defined
15318   // function, see whether there was a locally-scoped declaration of
15319   // this name as a function or variable. If so, use that
15320   // (non-visible) declaration, and complain about it.
15321   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15322   if (ExternCPrev) {
15323     // We still need to inject the function into the enclosing block scope so
15324     // that later (non-call) uses can see it.
15325     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15326 
15327     // C89 footnote 38:
15328     //   If in fact it is not defined as having type "function returning int",
15329     //   the behavior is undefined.
15330     if (!isa<FunctionDecl>(ExternCPrev) ||
15331         !Context.typesAreCompatible(
15332             cast<FunctionDecl>(ExternCPrev)->getType(),
15333             Context.getFunctionNoProtoType(Context.IntTy))) {
15334       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15335           << ExternCPrev << !getLangOpts().C99;
15336       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15337       return ExternCPrev;
15338     }
15339   }
15340 
15341   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15342   unsigned diag_id;
15343   if (II.getName().startswith("__builtin_"))
15344     diag_id = diag::warn_builtin_unknown;
15345   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15346   else if (getLangOpts().C99)
15347     diag_id = diag::ext_implicit_function_decl_c99;
15348   else
15349     diag_id = diag::warn_implicit_function_decl;
15350 
15351   TypoCorrection Corrected;
15352   // Because typo correction is expensive, only do it if the implicit
15353   // function declaration is going to be treated as an error.
15354   //
15355   // Perform the corection before issuing the main diagnostic, as some consumers
15356   // use typo-correction callbacks to enhance the main diagnostic.
15357   if (S && !ExternCPrev &&
15358       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15359     DeclFilterCCC<FunctionDecl> CCC{};
15360     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15361                             S, nullptr, CCC, CTK_NonError);
15362   }
15363 
15364   Diag(Loc, diag_id) << &II;
15365   if (Corrected) {
15366     // If the correction is going to suggest an implicitly defined function,
15367     // skip the correction as not being a particularly good idea.
15368     bool Diagnose = true;
15369     if (const auto *D = Corrected.getCorrectionDecl())
15370       Diagnose = !D->isImplicit();
15371     if (Diagnose)
15372       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15373                    /*ErrorRecovery*/ false);
15374   }
15375 
15376   // If we found a prior declaration of this function, don't bother building
15377   // another one. We've already pushed that one into scope, so there's nothing
15378   // more to do.
15379   if (ExternCPrev)
15380     return ExternCPrev;
15381 
15382   // Set a Declarator for the implicit definition: int foo();
15383   const char *Dummy;
15384   AttributeFactory attrFactory;
15385   DeclSpec DS(attrFactory);
15386   unsigned DiagID;
15387   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15388                                   Context.getPrintingPolicy());
15389   (void)Error; // Silence warning.
15390   assert(!Error && "Error setting up implicit decl!");
15391   SourceLocation NoLoc;
15392   Declarator D(DS, DeclaratorContext::Block);
15393   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15394                                              /*IsAmbiguous=*/false,
15395                                              /*LParenLoc=*/NoLoc,
15396                                              /*Params=*/nullptr,
15397                                              /*NumParams=*/0,
15398                                              /*EllipsisLoc=*/NoLoc,
15399                                              /*RParenLoc=*/NoLoc,
15400                                              /*RefQualifierIsLvalueRef=*/true,
15401                                              /*RefQualifierLoc=*/NoLoc,
15402                                              /*MutableLoc=*/NoLoc, EST_None,
15403                                              /*ESpecRange=*/SourceRange(),
15404                                              /*Exceptions=*/nullptr,
15405                                              /*ExceptionRanges=*/nullptr,
15406                                              /*NumExceptions=*/0,
15407                                              /*NoexceptExpr=*/nullptr,
15408                                              /*ExceptionSpecTokens=*/nullptr,
15409                                              /*DeclsInPrototype=*/None, Loc,
15410                                              Loc, D),
15411                 std::move(DS.getAttributes()), SourceLocation());
15412   D.SetIdentifier(&II, Loc);
15413 
15414   // Insert this function into the enclosing block scope.
15415   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15416   FD->setImplicit();
15417 
15418   AddKnownFunctionAttributes(FD);
15419 
15420   return FD;
15421 }
15422 
15423 /// If this function is a C++ replaceable global allocation function
15424 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15425 /// adds any function attributes that we know a priori based on the standard.
15426 ///
15427 /// We need to check for duplicate attributes both here and where user-written
15428 /// attributes are applied to declarations.
15429 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15430     FunctionDecl *FD) {
15431   if (FD->isInvalidDecl())
15432     return;
15433 
15434   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15435       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15436     return;
15437 
15438   Optional<unsigned> AlignmentParam;
15439   bool IsNothrow = false;
15440   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15441     return;
15442 
15443   // C++2a [basic.stc.dynamic.allocation]p4:
15444   //   An allocation function that has a non-throwing exception specification
15445   //   indicates failure by returning a null pointer value. Any other allocation
15446   //   function never returns a null pointer value and indicates failure only by
15447   //   throwing an exception [...]
15448   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15449     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15450 
15451   // C++2a [basic.stc.dynamic.allocation]p2:
15452   //   An allocation function attempts to allocate the requested amount of
15453   //   storage. [...] If the request succeeds, the value returned by a
15454   //   replaceable allocation function is a [...] pointer value p0 different
15455   //   from any previously returned value p1 [...]
15456   //
15457   // However, this particular information is being added in codegen,
15458   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15459 
15460   // C++2a [basic.stc.dynamic.allocation]p2:
15461   //   An allocation function attempts to allocate the requested amount of
15462   //   storage. If it is successful, it returns the address of the start of a
15463   //   block of storage whose length in bytes is at least as large as the
15464   //   requested size.
15465   if (!FD->hasAttr<AllocSizeAttr>()) {
15466     FD->addAttr(AllocSizeAttr::CreateImplicit(
15467         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15468         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15469   }
15470 
15471   // C++2a [basic.stc.dynamic.allocation]p3:
15472   //   For an allocation function [...], the pointer returned on a successful
15473   //   call shall represent the address of storage that is aligned as follows:
15474   //   (3.1) If the allocation function takes an argument of type
15475   //         std​::​align_­val_­t, the storage will have the alignment
15476   //         specified by the value of this argument.
15477   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15478     FD->addAttr(AllocAlignAttr::CreateImplicit(
15479         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15480   }
15481 
15482   // FIXME:
15483   // C++2a [basic.stc.dynamic.allocation]p3:
15484   //   For an allocation function [...], the pointer returned on a successful
15485   //   call shall represent the address of storage that is aligned as follows:
15486   //   (3.2) Otherwise, if the allocation function is named operator new[],
15487   //         the storage is aligned for any object that does not have
15488   //         new-extended alignment ([basic.align]) and is no larger than the
15489   //         requested size.
15490   //   (3.3) Otherwise, the storage is aligned for any object that does not
15491   //         have new-extended alignment and is of the requested size.
15492 }
15493 
15494 /// Adds any function attributes that we know a priori based on
15495 /// the declaration of this function.
15496 ///
15497 /// These attributes can apply both to implicitly-declared builtins
15498 /// (like __builtin___printf_chk) or to library-declared functions
15499 /// like NSLog or printf.
15500 ///
15501 /// We need to check for duplicate attributes both here and where user-written
15502 /// attributes are applied to declarations.
15503 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15504   if (FD->isInvalidDecl())
15505     return;
15506 
15507   // If this is a built-in function, map its builtin attributes to
15508   // actual attributes.
15509   if (unsigned BuiltinID = FD->getBuiltinID()) {
15510     // Handle printf-formatting attributes.
15511     unsigned FormatIdx;
15512     bool HasVAListArg;
15513     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15514       if (!FD->hasAttr<FormatAttr>()) {
15515         const char *fmt = "printf";
15516         unsigned int NumParams = FD->getNumParams();
15517         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15518             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15519           fmt = "NSString";
15520         FD->addAttr(FormatAttr::CreateImplicit(Context,
15521                                                &Context.Idents.get(fmt),
15522                                                FormatIdx+1,
15523                                                HasVAListArg ? 0 : FormatIdx+2,
15524                                                FD->getLocation()));
15525       }
15526     }
15527     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15528                                              HasVAListArg)) {
15529      if (!FD->hasAttr<FormatAttr>())
15530        FD->addAttr(FormatAttr::CreateImplicit(Context,
15531                                               &Context.Idents.get("scanf"),
15532                                               FormatIdx+1,
15533                                               HasVAListArg ? 0 : FormatIdx+2,
15534                                               FD->getLocation()));
15535     }
15536 
15537     // Handle automatically recognized callbacks.
15538     SmallVector<int, 4> Encoding;
15539     if (!FD->hasAttr<CallbackAttr>() &&
15540         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15541       FD->addAttr(CallbackAttr::CreateImplicit(
15542           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15543 
15544     // Mark const if we don't care about errno and that is the only thing
15545     // preventing the function from being const. This allows IRgen to use LLVM
15546     // intrinsics for such functions.
15547     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15548         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15549       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15550 
15551     // We make "fma" on GNU or Windows const because we know it does not set
15552     // errno in those environments even though it could set errno based on the
15553     // C standard.
15554     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15555     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15556         !FD->hasAttr<ConstAttr>()) {
15557       switch (BuiltinID) {
15558       case Builtin::BI__builtin_fma:
15559       case Builtin::BI__builtin_fmaf:
15560       case Builtin::BI__builtin_fmal:
15561       case Builtin::BIfma:
15562       case Builtin::BIfmaf:
15563       case Builtin::BIfmal:
15564         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15565         break;
15566       default:
15567         break;
15568       }
15569     }
15570 
15571     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15572         !FD->hasAttr<ReturnsTwiceAttr>())
15573       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15574                                          FD->getLocation()));
15575     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15576       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15577     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15578       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15579     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15580       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15581     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15582         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15583       // Add the appropriate attribute, depending on the CUDA compilation mode
15584       // and which target the builtin belongs to. For example, during host
15585       // compilation, aux builtins are __device__, while the rest are __host__.
15586       if (getLangOpts().CUDAIsDevice !=
15587           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15588         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15589       else
15590         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15591     }
15592 
15593     // Add known guaranteed alignment for allocation functions.
15594     switch (BuiltinID) {
15595     case Builtin::BImemalign:
15596     case Builtin::BIaligned_alloc:
15597       if (!FD->hasAttr<AllocAlignAttr>())
15598         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15599                                                    FD->getLocation()));
15600       break;
15601     default:
15602       break;
15603     }
15604 
15605     // Add allocsize attribute for allocation functions.
15606     switch (BuiltinID) {
15607     case Builtin::BIcalloc:
15608       FD->addAttr(AllocSizeAttr::CreateImplicit(
15609           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15610       break;
15611     case Builtin::BImemalign:
15612     case Builtin::BIaligned_alloc:
15613     case Builtin::BIrealloc:
15614       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15615                                                 ParamIdx(), FD->getLocation()));
15616       break;
15617     case Builtin::BImalloc:
15618       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15619                                                 ParamIdx(), FD->getLocation()));
15620       break;
15621     default:
15622       break;
15623     }
15624   }
15625 
15626   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15627 
15628   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15629   // throw, add an implicit nothrow attribute to any extern "C" function we come
15630   // across.
15631   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15632       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15633     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15634     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15635       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15636   }
15637 
15638   IdentifierInfo *Name = FD->getIdentifier();
15639   if (!Name)
15640     return;
15641   if ((!getLangOpts().CPlusPlus &&
15642        FD->getDeclContext()->isTranslationUnit()) ||
15643       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15644        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15645        LinkageSpecDecl::lang_c)) {
15646     // Okay: this could be a libc/libm/Objective-C function we know
15647     // about.
15648   } else
15649     return;
15650 
15651   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15652     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15653     // target-specific builtins, perhaps?
15654     if (!FD->hasAttr<FormatAttr>())
15655       FD->addAttr(FormatAttr::CreateImplicit(Context,
15656                                              &Context.Idents.get("printf"), 2,
15657                                              Name->isStr("vasprintf") ? 0 : 3,
15658                                              FD->getLocation()));
15659   }
15660 
15661   if (Name->isStr("__CFStringMakeConstantString")) {
15662     // We already have a __builtin___CFStringMakeConstantString,
15663     // but builds that use -fno-constant-cfstrings don't go through that.
15664     if (!FD->hasAttr<FormatArgAttr>())
15665       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15666                                                 FD->getLocation()));
15667   }
15668 }
15669 
15670 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15671                                     TypeSourceInfo *TInfo) {
15672   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15673   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15674 
15675   if (!TInfo) {
15676     assert(D.isInvalidType() && "no declarator info for valid type");
15677     TInfo = Context.getTrivialTypeSourceInfo(T);
15678   }
15679 
15680   // Scope manipulation handled by caller.
15681   TypedefDecl *NewTD =
15682       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15683                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15684 
15685   // Bail out immediately if we have an invalid declaration.
15686   if (D.isInvalidType()) {
15687     NewTD->setInvalidDecl();
15688     return NewTD;
15689   }
15690 
15691   if (D.getDeclSpec().isModulePrivateSpecified()) {
15692     if (CurContext->isFunctionOrMethod())
15693       Diag(NewTD->getLocation(), diag::err_module_private_local)
15694           << 2 << NewTD
15695           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15696           << FixItHint::CreateRemoval(
15697                  D.getDeclSpec().getModulePrivateSpecLoc());
15698     else
15699       NewTD->setModulePrivate();
15700   }
15701 
15702   // C++ [dcl.typedef]p8:
15703   //   If the typedef declaration defines an unnamed class (or
15704   //   enum), the first typedef-name declared by the declaration
15705   //   to be that class type (or enum type) is used to denote the
15706   //   class type (or enum type) for linkage purposes only.
15707   // We need to check whether the type was declared in the declaration.
15708   switch (D.getDeclSpec().getTypeSpecType()) {
15709   case TST_enum:
15710   case TST_struct:
15711   case TST_interface:
15712   case TST_union:
15713   case TST_class: {
15714     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15715     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15716     break;
15717   }
15718 
15719   default:
15720     break;
15721   }
15722 
15723   return NewTD;
15724 }
15725 
15726 /// Check that this is a valid underlying type for an enum declaration.
15727 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15728   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15729   QualType T = TI->getType();
15730 
15731   if (T->isDependentType())
15732     return false;
15733 
15734   // This doesn't use 'isIntegralType' despite the error message mentioning
15735   // integral type because isIntegralType would also allow enum types in C.
15736   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15737     if (BT->isInteger())
15738       return false;
15739 
15740   if (T->isBitIntType())
15741     return false;
15742 
15743   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15744 }
15745 
15746 /// Check whether this is a valid redeclaration of a previous enumeration.
15747 /// \return true if the redeclaration was invalid.
15748 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15749                                   QualType EnumUnderlyingTy, bool IsFixed,
15750                                   const EnumDecl *Prev) {
15751   if (IsScoped != Prev->isScoped()) {
15752     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15753       << Prev->isScoped();
15754     Diag(Prev->getLocation(), diag::note_previous_declaration);
15755     return true;
15756   }
15757 
15758   if (IsFixed && Prev->isFixed()) {
15759     if (!EnumUnderlyingTy->isDependentType() &&
15760         !Prev->getIntegerType()->isDependentType() &&
15761         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15762                                         Prev->getIntegerType())) {
15763       // TODO: Highlight the underlying type of the redeclaration.
15764       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15765         << EnumUnderlyingTy << Prev->getIntegerType();
15766       Diag(Prev->getLocation(), diag::note_previous_declaration)
15767           << Prev->getIntegerTypeRange();
15768       return true;
15769     }
15770   } else if (IsFixed != Prev->isFixed()) {
15771     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15772       << Prev->isFixed();
15773     Diag(Prev->getLocation(), diag::note_previous_declaration);
15774     return true;
15775   }
15776 
15777   return false;
15778 }
15779 
15780 /// Get diagnostic %select index for tag kind for
15781 /// redeclaration diagnostic message.
15782 /// WARNING: Indexes apply to particular diagnostics only!
15783 ///
15784 /// \returns diagnostic %select index.
15785 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15786   switch (Tag) {
15787   case TTK_Struct: return 0;
15788   case TTK_Interface: return 1;
15789   case TTK_Class:  return 2;
15790   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15791   }
15792 }
15793 
15794 /// Determine if tag kind is a class-key compatible with
15795 /// class for redeclaration (class, struct, or __interface).
15796 ///
15797 /// \returns true iff the tag kind is compatible.
15798 static bool isClassCompatTagKind(TagTypeKind Tag)
15799 {
15800   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15801 }
15802 
15803 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15804                                              TagTypeKind TTK) {
15805   if (isa<TypedefDecl>(PrevDecl))
15806     return NTK_Typedef;
15807   else if (isa<TypeAliasDecl>(PrevDecl))
15808     return NTK_TypeAlias;
15809   else if (isa<ClassTemplateDecl>(PrevDecl))
15810     return NTK_Template;
15811   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15812     return NTK_TypeAliasTemplate;
15813   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15814     return NTK_TemplateTemplateArgument;
15815   switch (TTK) {
15816   case TTK_Struct:
15817   case TTK_Interface:
15818   case TTK_Class:
15819     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15820   case TTK_Union:
15821     return NTK_NonUnion;
15822   case TTK_Enum:
15823     return NTK_NonEnum;
15824   }
15825   llvm_unreachable("invalid TTK");
15826 }
15827 
15828 /// Determine whether a tag with a given kind is acceptable
15829 /// as a redeclaration of the given tag declaration.
15830 ///
15831 /// \returns true if the new tag kind is acceptable, false otherwise.
15832 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15833                                         TagTypeKind NewTag, bool isDefinition,
15834                                         SourceLocation NewTagLoc,
15835                                         const IdentifierInfo *Name) {
15836   // C++ [dcl.type.elab]p3:
15837   //   The class-key or enum keyword present in the
15838   //   elaborated-type-specifier shall agree in kind with the
15839   //   declaration to which the name in the elaborated-type-specifier
15840   //   refers. This rule also applies to the form of
15841   //   elaborated-type-specifier that declares a class-name or
15842   //   friend class since it can be construed as referring to the
15843   //   definition of the class. Thus, in any
15844   //   elaborated-type-specifier, the enum keyword shall be used to
15845   //   refer to an enumeration (7.2), the union class-key shall be
15846   //   used to refer to a union (clause 9), and either the class or
15847   //   struct class-key shall be used to refer to a class (clause 9)
15848   //   declared using the class or struct class-key.
15849   TagTypeKind OldTag = Previous->getTagKind();
15850   if (OldTag != NewTag &&
15851       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15852     return false;
15853 
15854   // Tags are compatible, but we might still want to warn on mismatched tags.
15855   // Non-class tags can't be mismatched at this point.
15856   if (!isClassCompatTagKind(NewTag))
15857     return true;
15858 
15859   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15860   // by our warning analysis. We don't want to warn about mismatches with (eg)
15861   // declarations in system headers that are designed to be specialized, but if
15862   // a user asks us to warn, we should warn if their code contains mismatched
15863   // declarations.
15864   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15865     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15866                                       Loc);
15867   };
15868   if (IsIgnoredLoc(NewTagLoc))
15869     return true;
15870 
15871   auto IsIgnored = [&](const TagDecl *Tag) {
15872     return IsIgnoredLoc(Tag->getLocation());
15873   };
15874   while (IsIgnored(Previous)) {
15875     Previous = Previous->getPreviousDecl();
15876     if (!Previous)
15877       return true;
15878     OldTag = Previous->getTagKind();
15879   }
15880 
15881   bool isTemplate = false;
15882   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15883     isTemplate = Record->getDescribedClassTemplate();
15884 
15885   if (inTemplateInstantiation()) {
15886     if (OldTag != NewTag) {
15887       // In a template instantiation, do not offer fix-its for tag mismatches
15888       // since they usually mess up the template instead of fixing the problem.
15889       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15890         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15891         << getRedeclDiagFromTagKind(OldTag);
15892       // FIXME: Note previous location?
15893     }
15894     return true;
15895   }
15896 
15897   if (isDefinition) {
15898     // On definitions, check all previous tags and issue a fix-it for each
15899     // one that doesn't match the current tag.
15900     if (Previous->getDefinition()) {
15901       // Don't suggest fix-its for redefinitions.
15902       return true;
15903     }
15904 
15905     bool previousMismatch = false;
15906     for (const TagDecl *I : Previous->redecls()) {
15907       if (I->getTagKind() != NewTag) {
15908         // Ignore previous declarations for which the warning was disabled.
15909         if (IsIgnored(I))
15910           continue;
15911 
15912         if (!previousMismatch) {
15913           previousMismatch = true;
15914           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15915             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15916             << getRedeclDiagFromTagKind(I->getTagKind());
15917         }
15918         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15919           << getRedeclDiagFromTagKind(NewTag)
15920           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15921                TypeWithKeyword::getTagTypeKindName(NewTag));
15922       }
15923     }
15924     return true;
15925   }
15926 
15927   // Identify the prevailing tag kind: this is the kind of the definition (if
15928   // there is a non-ignored definition), or otherwise the kind of the prior
15929   // (non-ignored) declaration.
15930   const TagDecl *PrevDef = Previous->getDefinition();
15931   if (PrevDef && IsIgnored(PrevDef))
15932     PrevDef = nullptr;
15933   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15934   if (Redecl->getTagKind() != NewTag) {
15935     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15936       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15937       << getRedeclDiagFromTagKind(OldTag);
15938     Diag(Redecl->getLocation(), diag::note_previous_use);
15939 
15940     // If there is a previous definition, suggest a fix-it.
15941     if (PrevDef) {
15942       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15943         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15944         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15945              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15946     }
15947   }
15948 
15949   return true;
15950 }
15951 
15952 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15953 /// from an outer enclosing namespace or file scope inside a friend declaration.
15954 /// This should provide the commented out code in the following snippet:
15955 ///   namespace N {
15956 ///     struct X;
15957 ///     namespace M {
15958 ///       struct Y { friend struct /*N::*/ X; };
15959 ///     }
15960 ///   }
15961 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15962                                          SourceLocation NameLoc) {
15963   // While the decl is in a namespace, do repeated lookup of that name and see
15964   // if we get the same namespace back.  If we do not, continue until
15965   // translation unit scope, at which point we have a fully qualified NNS.
15966   SmallVector<IdentifierInfo *, 4> Namespaces;
15967   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15968   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15969     // This tag should be declared in a namespace, which can only be enclosed by
15970     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15971     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15972     if (!Namespace || Namespace->isAnonymousNamespace())
15973       return FixItHint();
15974     IdentifierInfo *II = Namespace->getIdentifier();
15975     Namespaces.push_back(II);
15976     NamedDecl *Lookup = SemaRef.LookupSingleName(
15977         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15978     if (Lookup == Namespace)
15979       break;
15980   }
15981 
15982   // Once we have all the namespaces, reverse them to go outermost first, and
15983   // build an NNS.
15984   SmallString<64> Insertion;
15985   llvm::raw_svector_ostream OS(Insertion);
15986   if (DC->isTranslationUnit())
15987     OS << "::";
15988   std::reverse(Namespaces.begin(), Namespaces.end());
15989   for (auto *II : Namespaces)
15990     OS << II->getName() << "::";
15991   return FixItHint::CreateInsertion(NameLoc, Insertion);
15992 }
15993 
15994 /// Determine whether a tag originally declared in context \p OldDC can
15995 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15996 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15997 /// using-declaration).
15998 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15999                                          DeclContext *NewDC) {
16000   OldDC = OldDC->getRedeclContext();
16001   NewDC = NewDC->getRedeclContext();
16002 
16003   if (OldDC->Equals(NewDC))
16004     return true;
16005 
16006   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16007   // encloses the other).
16008   if (S.getLangOpts().MSVCCompat &&
16009       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16010     return true;
16011 
16012   return false;
16013 }
16014 
16015 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16016 /// former case, Name will be non-null.  In the later case, Name will be null.
16017 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16018 /// reference/declaration/definition of a tag.
16019 ///
16020 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16021 /// trailing-type-specifier) other than one in an alias-declaration.
16022 ///
16023 /// \param SkipBody If non-null, will be set to indicate if the caller should
16024 /// skip the definition of this tag and treat it as if it were a declaration.
16025 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16026                      SourceLocation KWLoc, CXXScopeSpec &SS,
16027                      IdentifierInfo *Name, SourceLocation NameLoc,
16028                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16029                      SourceLocation ModulePrivateLoc,
16030                      MultiTemplateParamsArg TemplateParameterLists,
16031                      bool &OwnedDecl, bool &IsDependent,
16032                      SourceLocation ScopedEnumKWLoc,
16033                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16034                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16035                      SkipBodyInfo *SkipBody) {
16036   // If this is not a definition, it must have a name.
16037   IdentifierInfo *OrigName = Name;
16038   assert((Name != nullptr || TUK == TUK_Definition) &&
16039          "Nameless record must be a definition!");
16040   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16041 
16042   OwnedDecl = false;
16043   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16044   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16045 
16046   // FIXME: Check member specializations more carefully.
16047   bool isMemberSpecialization = false;
16048   bool Invalid = false;
16049 
16050   // We only need to do this matching if we have template parameters
16051   // or a scope specifier, which also conveniently avoids this work
16052   // for non-C++ cases.
16053   if (TemplateParameterLists.size() > 0 ||
16054       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16055     if (TemplateParameterList *TemplateParams =
16056             MatchTemplateParametersToScopeSpecifier(
16057                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16058                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16059       if (Kind == TTK_Enum) {
16060         Diag(KWLoc, diag::err_enum_template);
16061         return nullptr;
16062       }
16063 
16064       if (TemplateParams->size() > 0) {
16065         // This is a declaration or definition of a class template (which may
16066         // be a member of another template).
16067 
16068         if (Invalid)
16069           return nullptr;
16070 
16071         OwnedDecl = false;
16072         DeclResult Result = CheckClassTemplate(
16073             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16074             AS, ModulePrivateLoc,
16075             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16076             TemplateParameterLists.data(), SkipBody);
16077         return Result.get();
16078       } else {
16079         // The "template<>" header is extraneous.
16080         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16081           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16082         isMemberSpecialization = true;
16083       }
16084     }
16085 
16086     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16087         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16088       return nullptr;
16089   }
16090 
16091   // Figure out the underlying type if this a enum declaration. We need to do
16092   // this early, because it's needed to detect if this is an incompatible
16093   // redeclaration.
16094   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16095   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16096 
16097   if (Kind == TTK_Enum) {
16098     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16099       // No underlying type explicitly specified, or we failed to parse the
16100       // type, default to int.
16101       EnumUnderlying = Context.IntTy.getTypePtr();
16102     } else if (UnderlyingType.get()) {
16103       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16104       // integral type; any cv-qualification is ignored.
16105       TypeSourceInfo *TI = nullptr;
16106       GetTypeFromParser(UnderlyingType.get(), &TI);
16107       EnumUnderlying = TI;
16108 
16109       if (CheckEnumUnderlyingType(TI))
16110         // Recover by falling back to int.
16111         EnumUnderlying = Context.IntTy.getTypePtr();
16112 
16113       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16114                                           UPPC_FixedUnderlyingType))
16115         EnumUnderlying = Context.IntTy.getTypePtr();
16116 
16117     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16118       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16119       // of 'int'. However, if this is an unfixed forward declaration, don't set
16120       // the underlying type unless the user enables -fms-compatibility. This
16121       // makes unfixed forward declared enums incomplete and is more conforming.
16122       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16123         EnumUnderlying = Context.IntTy.getTypePtr();
16124     }
16125   }
16126 
16127   DeclContext *SearchDC = CurContext;
16128   DeclContext *DC = CurContext;
16129   bool isStdBadAlloc = false;
16130   bool isStdAlignValT = false;
16131 
16132   RedeclarationKind Redecl = forRedeclarationInCurContext();
16133   if (TUK == TUK_Friend || TUK == TUK_Reference)
16134     Redecl = NotForRedeclaration;
16135 
16136   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16137   /// implemented asks for structural equivalence checking, the returned decl
16138   /// here is passed back to the parser, allowing the tag body to be parsed.
16139   auto createTagFromNewDecl = [&]() -> TagDecl * {
16140     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16141     // If there is an identifier, use the location of the identifier as the
16142     // location of the decl, otherwise use the location of the struct/union
16143     // keyword.
16144     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16145     TagDecl *New = nullptr;
16146 
16147     if (Kind == TTK_Enum) {
16148       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16149                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16150       // If this is an undefined enum, bail.
16151       if (TUK != TUK_Definition && !Invalid)
16152         return nullptr;
16153       if (EnumUnderlying) {
16154         EnumDecl *ED = cast<EnumDecl>(New);
16155         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16156           ED->setIntegerTypeSourceInfo(TI);
16157         else
16158           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16159         ED->setPromotionType(ED->getIntegerType());
16160       }
16161     } else { // struct/union
16162       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16163                                nullptr);
16164     }
16165 
16166     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16167       // Add alignment attributes if necessary; these attributes are checked
16168       // when the ASTContext lays out the structure.
16169       //
16170       // It is important for implementing the correct semantics that this
16171       // happen here (in ActOnTag). The #pragma pack stack is
16172       // maintained as a result of parser callbacks which can occur at
16173       // many points during the parsing of a struct declaration (because
16174       // the #pragma tokens are effectively skipped over during the
16175       // parsing of the struct).
16176       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16177         AddAlignmentAttributesForRecord(RD);
16178         AddMsStructLayoutForRecord(RD);
16179       }
16180     }
16181     New->setLexicalDeclContext(CurContext);
16182     return New;
16183   };
16184 
16185   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16186   if (Name && SS.isNotEmpty()) {
16187     // We have a nested-name tag ('struct foo::bar').
16188 
16189     // Check for invalid 'foo::'.
16190     if (SS.isInvalid()) {
16191       Name = nullptr;
16192       goto CreateNewDecl;
16193     }
16194 
16195     // If this is a friend or a reference to a class in a dependent
16196     // context, don't try to make a decl for it.
16197     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16198       DC = computeDeclContext(SS, false);
16199       if (!DC) {
16200         IsDependent = true;
16201         return nullptr;
16202       }
16203     } else {
16204       DC = computeDeclContext(SS, true);
16205       if (!DC) {
16206         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16207           << SS.getRange();
16208         return nullptr;
16209       }
16210     }
16211 
16212     if (RequireCompleteDeclContext(SS, DC))
16213       return nullptr;
16214 
16215     SearchDC = DC;
16216     // Look-up name inside 'foo::'.
16217     LookupQualifiedName(Previous, DC);
16218 
16219     if (Previous.isAmbiguous())
16220       return nullptr;
16221 
16222     if (Previous.empty()) {
16223       // Name lookup did not find anything. However, if the
16224       // nested-name-specifier refers to the current instantiation,
16225       // and that current instantiation has any dependent base
16226       // classes, we might find something at instantiation time: treat
16227       // this as a dependent elaborated-type-specifier.
16228       // But this only makes any sense for reference-like lookups.
16229       if (Previous.wasNotFoundInCurrentInstantiation() &&
16230           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16231         IsDependent = true;
16232         return nullptr;
16233       }
16234 
16235       // A tag 'foo::bar' must already exist.
16236       Diag(NameLoc, diag::err_not_tag_in_scope)
16237         << Kind << Name << DC << SS.getRange();
16238       Name = nullptr;
16239       Invalid = true;
16240       goto CreateNewDecl;
16241     }
16242   } else if (Name) {
16243     // C++14 [class.mem]p14:
16244     //   If T is the name of a class, then each of the following shall have a
16245     //   name different from T:
16246     //    -- every member of class T that is itself a type
16247     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16248         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16249       return nullptr;
16250 
16251     // If this is a named struct, check to see if there was a previous forward
16252     // declaration or definition.
16253     // FIXME: We're looking into outer scopes here, even when we
16254     // shouldn't be. Doing so can result in ambiguities that we
16255     // shouldn't be diagnosing.
16256     LookupName(Previous, S);
16257 
16258     // When declaring or defining a tag, ignore ambiguities introduced
16259     // by types using'ed into this scope.
16260     if (Previous.isAmbiguous() &&
16261         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16262       LookupResult::Filter F = Previous.makeFilter();
16263       while (F.hasNext()) {
16264         NamedDecl *ND = F.next();
16265         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16266                 SearchDC->getRedeclContext()))
16267           F.erase();
16268       }
16269       F.done();
16270     }
16271 
16272     // C++11 [namespace.memdef]p3:
16273     //   If the name in a friend declaration is neither qualified nor
16274     //   a template-id and the declaration is a function or an
16275     //   elaborated-type-specifier, the lookup to determine whether
16276     //   the entity has been previously declared shall not consider
16277     //   any scopes outside the innermost enclosing namespace.
16278     //
16279     // MSVC doesn't implement the above rule for types, so a friend tag
16280     // declaration may be a redeclaration of a type declared in an enclosing
16281     // scope.  They do implement this rule for friend functions.
16282     //
16283     // Does it matter that this should be by scope instead of by
16284     // semantic context?
16285     if (!Previous.empty() && TUK == TUK_Friend) {
16286       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16287       LookupResult::Filter F = Previous.makeFilter();
16288       bool FriendSawTagOutsideEnclosingNamespace = false;
16289       while (F.hasNext()) {
16290         NamedDecl *ND = F.next();
16291         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16292         if (DC->isFileContext() &&
16293             !EnclosingNS->Encloses(ND->getDeclContext())) {
16294           if (getLangOpts().MSVCCompat)
16295             FriendSawTagOutsideEnclosingNamespace = true;
16296           else
16297             F.erase();
16298         }
16299       }
16300       F.done();
16301 
16302       // Diagnose this MSVC extension in the easy case where lookup would have
16303       // unambiguously found something outside the enclosing namespace.
16304       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16305         NamedDecl *ND = Previous.getFoundDecl();
16306         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16307             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16308       }
16309     }
16310 
16311     // Note:  there used to be some attempt at recovery here.
16312     if (Previous.isAmbiguous())
16313       return nullptr;
16314 
16315     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16316       // FIXME: This makes sure that we ignore the contexts associated
16317       // with C structs, unions, and enums when looking for a matching
16318       // tag declaration or definition. See the similar lookup tweak
16319       // in Sema::LookupName; is there a better way to deal with this?
16320       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16321         SearchDC = SearchDC->getParent();
16322     } else if (getLangOpts().CPlusPlus) {
16323       // Inside ObjCContainer want to keep it as a lexical decl context but go
16324       // past it (most often to TranslationUnit) to find the semantic decl
16325       // context.
16326       while (isa<ObjCContainerDecl>(SearchDC))
16327         SearchDC = SearchDC->getParent();
16328     }
16329   } else if (getLangOpts().CPlusPlus) {
16330     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16331     // TagDecl the same way as we skip it for named TagDecl.
16332     while (isa<ObjCContainerDecl>(SearchDC))
16333       SearchDC = SearchDC->getParent();
16334   }
16335 
16336   if (Previous.isSingleResult() &&
16337       Previous.getFoundDecl()->isTemplateParameter()) {
16338     // Maybe we will complain about the shadowed template parameter.
16339     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16340     // Just pretend that we didn't see the previous declaration.
16341     Previous.clear();
16342   }
16343 
16344   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16345       DC->Equals(getStdNamespace())) {
16346     if (Name->isStr("bad_alloc")) {
16347       // This is a declaration of or a reference to "std::bad_alloc".
16348       isStdBadAlloc = true;
16349 
16350       // If std::bad_alloc has been implicitly declared (but made invisible to
16351       // name lookup), fill in this implicit declaration as the previous
16352       // declaration, so that the declarations get chained appropriately.
16353       if (Previous.empty() && StdBadAlloc)
16354         Previous.addDecl(getStdBadAlloc());
16355     } else if (Name->isStr("align_val_t")) {
16356       isStdAlignValT = true;
16357       if (Previous.empty() && StdAlignValT)
16358         Previous.addDecl(getStdAlignValT());
16359     }
16360   }
16361 
16362   // If we didn't find a previous declaration, and this is a reference
16363   // (or friend reference), move to the correct scope.  In C++, we
16364   // also need to do a redeclaration lookup there, just in case
16365   // there's a shadow friend decl.
16366   if (Name && Previous.empty() &&
16367       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16368     if (Invalid) goto CreateNewDecl;
16369     assert(SS.isEmpty());
16370 
16371     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16372       // C++ [basic.scope.pdecl]p5:
16373       //   -- for an elaborated-type-specifier of the form
16374       //
16375       //          class-key identifier
16376       //
16377       //      if the elaborated-type-specifier is used in the
16378       //      decl-specifier-seq or parameter-declaration-clause of a
16379       //      function defined in namespace scope, the identifier is
16380       //      declared as a class-name in the namespace that contains
16381       //      the declaration; otherwise, except as a friend
16382       //      declaration, the identifier is declared in the smallest
16383       //      non-class, non-function-prototype scope that contains the
16384       //      declaration.
16385       //
16386       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16387       // C structs and unions.
16388       //
16389       // It is an error in C++ to declare (rather than define) an enum
16390       // type, including via an elaborated type specifier.  We'll
16391       // diagnose that later; for now, declare the enum in the same
16392       // scope as we would have picked for any other tag type.
16393       //
16394       // GNU C also supports this behavior as part of its incomplete
16395       // enum types extension, while GNU C++ does not.
16396       //
16397       // Find the context where we'll be declaring the tag.
16398       // FIXME: We would like to maintain the current DeclContext as the
16399       // lexical context,
16400       SearchDC = getTagInjectionContext(SearchDC);
16401 
16402       // Find the scope where we'll be declaring the tag.
16403       S = getTagInjectionScope(S, getLangOpts());
16404     } else {
16405       assert(TUK == TUK_Friend);
16406       // C++ [namespace.memdef]p3:
16407       //   If a friend declaration in a non-local class first declares a
16408       //   class or function, the friend class or function is a member of
16409       //   the innermost enclosing namespace.
16410       SearchDC = SearchDC->getEnclosingNamespaceContext();
16411     }
16412 
16413     // In C++, we need to do a redeclaration lookup to properly
16414     // diagnose some problems.
16415     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16416     // hidden declaration so that we don't get ambiguity errors when using a
16417     // type declared by an elaborated-type-specifier.  In C that is not correct
16418     // and we should instead merge compatible types found by lookup.
16419     if (getLangOpts().CPlusPlus) {
16420       // FIXME: This can perform qualified lookups into function contexts,
16421       // which are meaningless.
16422       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16423       LookupQualifiedName(Previous, SearchDC);
16424     } else {
16425       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16426       LookupName(Previous, S);
16427     }
16428   }
16429 
16430   // If we have a known previous declaration to use, then use it.
16431   if (Previous.empty() && SkipBody && SkipBody->Previous)
16432     Previous.addDecl(SkipBody->Previous);
16433 
16434   if (!Previous.empty()) {
16435     NamedDecl *PrevDecl = Previous.getFoundDecl();
16436     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16437 
16438     // It's okay to have a tag decl in the same scope as a typedef
16439     // which hides a tag decl in the same scope.  Finding this
16440     // with a redeclaration lookup can only actually happen in C++.
16441     //
16442     // This is also okay for elaborated-type-specifiers, which is
16443     // technically forbidden by the current standard but which is
16444     // okay according to the likely resolution of an open issue;
16445     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16446     if (getLangOpts().CPlusPlus) {
16447       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16448         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16449           TagDecl *Tag = TT->getDecl();
16450           if (Tag->getDeclName() == Name &&
16451               Tag->getDeclContext()->getRedeclContext()
16452                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16453             PrevDecl = Tag;
16454             Previous.clear();
16455             Previous.addDecl(Tag);
16456             Previous.resolveKind();
16457           }
16458         }
16459       }
16460     }
16461 
16462     // If this is a redeclaration of a using shadow declaration, it must
16463     // declare a tag in the same context. In MSVC mode, we allow a
16464     // redefinition if either context is within the other.
16465     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16466       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16467       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16468           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16469           !(OldTag && isAcceptableTagRedeclContext(
16470                           *this, OldTag->getDeclContext(), SearchDC))) {
16471         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16472         Diag(Shadow->getTargetDecl()->getLocation(),
16473              diag::note_using_decl_target);
16474         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16475             << 0;
16476         // Recover by ignoring the old declaration.
16477         Previous.clear();
16478         goto CreateNewDecl;
16479       }
16480     }
16481 
16482     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16483       // If this is a use of a previous tag, or if the tag is already declared
16484       // in the same scope (so that the definition/declaration completes or
16485       // rementions the tag), reuse the decl.
16486       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16487           isDeclInScope(DirectPrevDecl, SearchDC, S,
16488                         SS.isNotEmpty() || isMemberSpecialization)) {
16489         // Make sure that this wasn't declared as an enum and now used as a
16490         // struct or something similar.
16491         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16492                                           TUK == TUK_Definition, KWLoc,
16493                                           Name)) {
16494           bool SafeToContinue
16495             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16496                Kind != TTK_Enum);
16497           if (SafeToContinue)
16498             Diag(KWLoc, diag::err_use_with_wrong_tag)
16499               << Name
16500               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16501                                               PrevTagDecl->getKindName());
16502           else
16503             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16504           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16505 
16506           if (SafeToContinue)
16507             Kind = PrevTagDecl->getTagKind();
16508           else {
16509             // Recover by making this an anonymous redefinition.
16510             Name = nullptr;
16511             Previous.clear();
16512             Invalid = true;
16513           }
16514         }
16515 
16516         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16517           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16518           if (TUK == TUK_Reference || TUK == TUK_Friend)
16519             return PrevTagDecl;
16520 
16521           QualType EnumUnderlyingTy;
16522           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16523             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16524           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16525             EnumUnderlyingTy = QualType(T, 0);
16526 
16527           // All conflicts with previous declarations are recovered by
16528           // returning the previous declaration, unless this is a definition,
16529           // in which case we want the caller to bail out.
16530           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16531                                      ScopedEnum, EnumUnderlyingTy,
16532                                      IsFixed, PrevEnum))
16533             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16534         }
16535 
16536         // C++11 [class.mem]p1:
16537         //   A member shall not be declared twice in the member-specification,
16538         //   except that a nested class or member class template can be declared
16539         //   and then later defined.
16540         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16541             S->isDeclScope(PrevDecl)) {
16542           Diag(NameLoc, diag::ext_member_redeclared);
16543           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16544         }
16545 
16546         if (!Invalid) {
16547           // If this is a use, just return the declaration we found, unless
16548           // we have attributes.
16549           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16550             if (!Attrs.empty()) {
16551               // FIXME: Diagnose these attributes. For now, we create a new
16552               // declaration to hold them.
16553             } else if (TUK == TUK_Reference &&
16554                        (PrevTagDecl->getFriendObjectKind() ==
16555                             Decl::FOK_Undeclared ||
16556                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16557                        SS.isEmpty()) {
16558               // This declaration is a reference to an existing entity, but
16559               // has different visibility from that entity: it either makes
16560               // a friend visible or it makes a type visible in a new module.
16561               // In either case, create a new declaration. We only do this if
16562               // the declaration would have meant the same thing if no prior
16563               // declaration were found, that is, if it was found in the same
16564               // scope where we would have injected a declaration.
16565               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16566                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16567                 return PrevTagDecl;
16568               // This is in the injected scope, create a new declaration in
16569               // that scope.
16570               S = getTagInjectionScope(S, getLangOpts());
16571             } else {
16572               return PrevTagDecl;
16573             }
16574           }
16575 
16576           // Diagnose attempts to redefine a tag.
16577           if (TUK == TUK_Definition) {
16578             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16579               // If we're defining a specialization and the previous definition
16580               // is from an implicit instantiation, don't emit an error
16581               // here; we'll catch this in the general case below.
16582               bool IsExplicitSpecializationAfterInstantiation = false;
16583               if (isMemberSpecialization) {
16584                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16585                   IsExplicitSpecializationAfterInstantiation =
16586                     RD->getTemplateSpecializationKind() !=
16587                     TSK_ExplicitSpecialization;
16588                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16589                   IsExplicitSpecializationAfterInstantiation =
16590                     ED->getTemplateSpecializationKind() !=
16591                     TSK_ExplicitSpecialization;
16592               }
16593 
16594               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16595               // not keep more that one definition around (merge them). However,
16596               // ensure the decl passes the structural compatibility check in
16597               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16598               NamedDecl *Hidden = nullptr;
16599               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16600                 // There is a definition of this tag, but it is not visible. We
16601                 // explicitly make use of C++'s one definition rule here, and
16602                 // assume that this definition is identical to the hidden one
16603                 // we already have. Make the existing definition visible and
16604                 // use it in place of this one.
16605                 if (!getLangOpts().CPlusPlus) {
16606                   // Postpone making the old definition visible until after we
16607                   // complete parsing the new one and do the structural
16608                   // comparison.
16609                   SkipBody->CheckSameAsPrevious = true;
16610                   SkipBody->New = createTagFromNewDecl();
16611                   SkipBody->Previous = Def;
16612                   return Def;
16613                 } else {
16614                   SkipBody->ShouldSkip = true;
16615                   SkipBody->Previous = Def;
16616                   makeMergedDefinitionVisible(Hidden);
16617                   // Carry on and handle it like a normal definition. We'll
16618                   // skip starting the definitiion later.
16619                 }
16620               } else if (!IsExplicitSpecializationAfterInstantiation) {
16621                 // A redeclaration in function prototype scope in C isn't
16622                 // visible elsewhere, so merely issue a warning.
16623                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16624                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16625                 else
16626                   Diag(NameLoc, diag::err_redefinition) << Name;
16627                 notePreviousDefinition(Def,
16628                                        NameLoc.isValid() ? NameLoc : KWLoc);
16629                 // If this is a redefinition, recover by making this
16630                 // struct be anonymous, which will make any later
16631                 // references get the previous definition.
16632                 Name = nullptr;
16633                 Previous.clear();
16634                 Invalid = true;
16635               }
16636             } else {
16637               // If the type is currently being defined, complain
16638               // about a nested redefinition.
16639               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16640               if (TD->isBeingDefined()) {
16641                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16642                 Diag(PrevTagDecl->getLocation(),
16643                      diag::note_previous_definition);
16644                 Name = nullptr;
16645                 Previous.clear();
16646                 Invalid = true;
16647               }
16648             }
16649 
16650             // Okay, this is definition of a previously declared or referenced
16651             // tag. We're going to create a new Decl for it.
16652           }
16653 
16654           // Okay, we're going to make a redeclaration.  If this is some kind
16655           // of reference, make sure we build the redeclaration in the same DC
16656           // as the original, and ignore the current access specifier.
16657           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16658             SearchDC = PrevTagDecl->getDeclContext();
16659             AS = AS_none;
16660           }
16661         }
16662         // If we get here we have (another) forward declaration or we
16663         // have a definition.  Just create a new decl.
16664 
16665       } else {
16666         // If we get here, this is a definition of a new tag type in a nested
16667         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16668         // new decl/type.  We set PrevDecl to NULL so that the entities
16669         // have distinct types.
16670         Previous.clear();
16671       }
16672       // If we get here, we're going to create a new Decl. If PrevDecl
16673       // is non-NULL, it's a definition of the tag declared by
16674       // PrevDecl. If it's NULL, we have a new definition.
16675 
16676     // Otherwise, PrevDecl is not a tag, but was found with tag
16677     // lookup.  This is only actually possible in C++, where a few
16678     // things like templates still live in the tag namespace.
16679     } else {
16680       // Use a better diagnostic if an elaborated-type-specifier
16681       // found the wrong kind of type on the first
16682       // (non-redeclaration) lookup.
16683       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16684           !Previous.isForRedeclaration()) {
16685         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16686         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16687                                                        << Kind;
16688         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16689         Invalid = true;
16690 
16691       // Otherwise, only diagnose if the declaration is in scope.
16692       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16693                                 SS.isNotEmpty() || isMemberSpecialization)) {
16694         // do nothing
16695 
16696       // Diagnose implicit declarations introduced by elaborated types.
16697       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16698         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16699         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16700         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16701         Invalid = true;
16702 
16703       // Otherwise it's a declaration.  Call out a particularly common
16704       // case here.
16705       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16706         unsigned Kind = 0;
16707         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16708         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16709           << Name << Kind << TND->getUnderlyingType();
16710         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16711         Invalid = true;
16712 
16713       // Otherwise, diagnose.
16714       } else {
16715         // The tag name clashes with something else in the target scope,
16716         // issue an error and recover by making this tag be anonymous.
16717         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16718         notePreviousDefinition(PrevDecl, NameLoc);
16719         Name = nullptr;
16720         Invalid = true;
16721       }
16722 
16723       // The existing declaration isn't relevant to us; we're in a
16724       // new scope, so clear out the previous declaration.
16725       Previous.clear();
16726     }
16727   }
16728 
16729 CreateNewDecl:
16730 
16731   TagDecl *PrevDecl = nullptr;
16732   if (Previous.isSingleResult())
16733     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16734 
16735   // If there is an identifier, use the location of the identifier as the
16736   // location of the decl, otherwise use the location of the struct/union
16737   // keyword.
16738   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16739 
16740   // Otherwise, create a new declaration. If there is a previous
16741   // declaration of the same entity, the two will be linked via
16742   // PrevDecl.
16743   TagDecl *New;
16744 
16745   if (Kind == TTK_Enum) {
16746     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16747     // enum X { A, B, C } D;    D should chain to X.
16748     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16749                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16750                            ScopedEnumUsesClassTag, IsFixed);
16751 
16752     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16753       StdAlignValT = cast<EnumDecl>(New);
16754 
16755     // If this is an undefined enum, warn.
16756     if (TUK != TUK_Definition && !Invalid) {
16757       TagDecl *Def;
16758       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16759         // C++0x: 7.2p2: opaque-enum-declaration.
16760         // Conflicts are diagnosed above. Do nothing.
16761       }
16762       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16763         Diag(Loc, diag::ext_forward_ref_enum_def)
16764           << New;
16765         Diag(Def->getLocation(), diag::note_previous_definition);
16766       } else {
16767         unsigned DiagID = diag::ext_forward_ref_enum;
16768         if (getLangOpts().MSVCCompat)
16769           DiagID = diag::ext_ms_forward_ref_enum;
16770         else if (getLangOpts().CPlusPlus)
16771           DiagID = diag::err_forward_ref_enum;
16772         Diag(Loc, DiagID);
16773       }
16774     }
16775 
16776     if (EnumUnderlying) {
16777       EnumDecl *ED = cast<EnumDecl>(New);
16778       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16779         ED->setIntegerTypeSourceInfo(TI);
16780       else
16781         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16782       ED->setPromotionType(ED->getIntegerType());
16783       assert(ED->isComplete() && "enum with type should be complete");
16784     }
16785   } else {
16786     // struct/union/class
16787 
16788     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16789     // struct X { int A; } D;    D should chain to X.
16790     if (getLangOpts().CPlusPlus) {
16791       // FIXME: Look for a way to use RecordDecl for simple structs.
16792       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16793                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16794 
16795       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16796         StdBadAlloc = cast<CXXRecordDecl>(New);
16797     } else
16798       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16799                                cast_or_null<RecordDecl>(PrevDecl));
16800   }
16801 
16802   // C++11 [dcl.type]p3:
16803   //   A type-specifier-seq shall not define a class or enumeration [...].
16804   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16805       TUK == TUK_Definition) {
16806     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16807       << Context.getTagDeclType(New);
16808     Invalid = true;
16809   }
16810 
16811   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16812       DC->getDeclKind() == Decl::Enum) {
16813     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16814       << Context.getTagDeclType(New);
16815     Invalid = true;
16816   }
16817 
16818   // Maybe add qualifier info.
16819   if (SS.isNotEmpty()) {
16820     if (SS.isSet()) {
16821       // If this is either a declaration or a definition, check the
16822       // nested-name-specifier against the current context.
16823       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16824           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16825                                        isMemberSpecialization))
16826         Invalid = true;
16827 
16828       New->setQualifierInfo(SS.getWithLocInContext(Context));
16829       if (TemplateParameterLists.size() > 0) {
16830         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16831       }
16832     }
16833     else
16834       Invalid = true;
16835   }
16836 
16837   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16838     // Add alignment attributes if necessary; these attributes are checked when
16839     // the ASTContext lays out the structure.
16840     //
16841     // It is important for implementing the correct semantics that this
16842     // happen here (in ActOnTag). The #pragma pack stack is
16843     // maintained as a result of parser callbacks which can occur at
16844     // many points during the parsing of a struct declaration (because
16845     // the #pragma tokens are effectively skipped over during the
16846     // parsing of the struct).
16847     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16848       AddAlignmentAttributesForRecord(RD);
16849       AddMsStructLayoutForRecord(RD);
16850     }
16851   }
16852 
16853   if (ModulePrivateLoc.isValid()) {
16854     if (isMemberSpecialization)
16855       Diag(New->getLocation(), diag::err_module_private_specialization)
16856         << 2
16857         << FixItHint::CreateRemoval(ModulePrivateLoc);
16858     // __module_private__ does not apply to local classes. However, we only
16859     // diagnose this as an error when the declaration specifiers are
16860     // freestanding. Here, we just ignore the __module_private__.
16861     else if (!SearchDC->isFunctionOrMethod())
16862       New->setModulePrivate();
16863   }
16864 
16865   // If this is a specialization of a member class (of a class template),
16866   // check the specialization.
16867   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16868     Invalid = true;
16869 
16870   // If we're declaring or defining a tag in function prototype scope in C,
16871   // note that this type can only be used within the function and add it to
16872   // the list of decls to inject into the function definition scope.
16873   if ((Name || Kind == TTK_Enum) &&
16874       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16875     if (getLangOpts().CPlusPlus) {
16876       // C++ [dcl.fct]p6:
16877       //   Types shall not be defined in return or parameter types.
16878       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16879         Diag(Loc, diag::err_type_defined_in_param_type)
16880             << Name;
16881         Invalid = true;
16882       }
16883     } else if (!PrevDecl) {
16884       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16885     }
16886   }
16887 
16888   if (Invalid)
16889     New->setInvalidDecl();
16890 
16891   // Set the lexical context. If the tag has a C++ scope specifier, the
16892   // lexical context will be different from the semantic context.
16893   New->setLexicalDeclContext(CurContext);
16894 
16895   // Mark this as a friend decl if applicable.
16896   // In Microsoft mode, a friend declaration also acts as a forward
16897   // declaration so we always pass true to setObjectOfFriendDecl to make
16898   // the tag name visible.
16899   if (TUK == TUK_Friend)
16900     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16901 
16902   // Set the access specifier.
16903   if (!Invalid && SearchDC->isRecord())
16904     SetMemberAccessSpecifier(New, PrevDecl, AS);
16905 
16906   if (PrevDecl)
16907     CheckRedeclarationInModule(New, PrevDecl);
16908 
16909   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16910     New->startDefinition();
16911 
16912   ProcessDeclAttributeList(S, New, Attrs);
16913   AddPragmaAttributes(S, New);
16914 
16915   // If this has an identifier, add it to the scope stack.
16916   if (TUK == TUK_Friend) {
16917     // We might be replacing an existing declaration in the lookup tables;
16918     // if so, borrow its access specifier.
16919     if (PrevDecl)
16920       New->setAccess(PrevDecl->getAccess());
16921 
16922     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16923     DC->makeDeclVisibleInContext(New);
16924     if (Name) // can be null along some error paths
16925       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16926         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16927   } else if (Name) {
16928     S = getNonFieldDeclScope(S);
16929     PushOnScopeChains(New, S, true);
16930   } else {
16931     CurContext->addDecl(New);
16932   }
16933 
16934   // If this is the C FILE type, notify the AST context.
16935   if (IdentifierInfo *II = New->getIdentifier())
16936     if (!New->isInvalidDecl() &&
16937         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16938         II->isStr("FILE"))
16939       Context.setFILEDecl(New);
16940 
16941   if (PrevDecl)
16942     mergeDeclAttributes(New, PrevDecl);
16943 
16944   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16945     inferGslOwnerPointerAttribute(CXXRD);
16946 
16947   // If there's a #pragma GCC visibility in scope, set the visibility of this
16948   // record.
16949   AddPushedVisibilityAttribute(New);
16950 
16951   if (isMemberSpecialization && !New->isInvalidDecl())
16952     CompleteMemberSpecialization(New, Previous);
16953 
16954   OwnedDecl = true;
16955   // In C++, don't return an invalid declaration. We can't recover well from
16956   // the cases where we make the type anonymous.
16957   if (Invalid && getLangOpts().CPlusPlus) {
16958     if (New->isBeingDefined())
16959       if (auto RD = dyn_cast<RecordDecl>(New))
16960         RD->completeDefinition();
16961     return nullptr;
16962   } else if (SkipBody && SkipBody->ShouldSkip) {
16963     return SkipBody->Previous;
16964   } else {
16965     return New;
16966   }
16967 }
16968 
16969 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16970   AdjustDeclIfTemplate(TagD);
16971   TagDecl *Tag = cast<TagDecl>(TagD);
16972 
16973   // Enter the tag context.
16974   PushDeclContext(S, Tag);
16975 
16976   ActOnDocumentableDecl(TagD);
16977 
16978   // If there's a #pragma GCC visibility in scope, set the visibility of this
16979   // record.
16980   AddPushedVisibilityAttribute(Tag);
16981 }
16982 
16983 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16984   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16985     return false;
16986 
16987   // Make the previous decl visible.
16988   makeMergedDefinitionVisible(SkipBody.Previous);
16989   return true;
16990 }
16991 
16992 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
16993   assert(IDecl->getLexicalParent() == CurContext &&
16994       "The next DeclContext should be lexically contained in the current one.");
16995   CurContext = IDecl;
16996 }
16997 
16998 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16999                                            SourceLocation FinalLoc,
17000                                            bool IsFinalSpelledSealed,
17001                                            bool IsAbstract,
17002                                            SourceLocation LBraceLoc) {
17003   AdjustDeclIfTemplate(TagD);
17004   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17005 
17006   FieldCollector->StartClass();
17007 
17008   if (!Record->getIdentifier())
17009     return;
17010 
17011   if (IsAbstract)
17012     Record->markAbstract();
17013 
17014   if (FinalLoc.isValid()) {
17015     Record->addAttr(FinalAttr::Create(
17016         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17017         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17018   }
17019   // C++ [class]p2:
17020   //   [...] The class-name is also inserted into the scope of the
17021   //   class itself; this is known as the injected-class-name. For
17022   //   purposes of access checking, the injected-class-name is treated
17023   //   as if it were a public member name.
17024   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17025       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17026       Record->getLocation(), Record->getIdentifier(),
17027       /*PrevDecl=*/nullptr,
17028       /*DelayTypeCreation=*/true);
17029   Context.getTypeDeclType(InjectedClassName, Record);
17030   InjectedClassName->setImplicit();
17031   InjectedClassName->setAccess(AS_public);
17032   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17033       InjectedClassName->setDescribedClassTemplate(Template);
17034   PushOnScopeChains(InjectedClassName, S);
17035   assert(InjectedClassName->isInjectedClassName() &&
17036          "Broken injected-class-name");
17037 }
17038 
17039 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17040                                     SourceRange BraceRange) {
17041   AdjustDeclIfTemplate(TagD);
17042   TagDecl *Tag = cast<TagDecl>(TagD);
17043   Tag->setBraceRange(BraceRange);
17044 
17045   // Make sure we "complete" the definition even it is invalid.
17046   if (Tag->isBeingDefined()) {
17047     assert(Tag->isInvalidDecl() && "We should already have completed it");
17048     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17049       RD->completeDefinition();
17050   }
17051 
17052   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17053     FieldCollector->FinishClass();
17054     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17055       auto *Def = RD->getDefinition();
17056       assert(Def && "The record is expected to have a completed definition");
17057       unsigned NumInitMethods = 0;
17058       for (auto *Method : Def->methods()) {
17059         if (!Method->getIdentifier())
17060             continue;
17061         if (Method->getName() == "__init")
17062           NumInitMethods++;
17063       }
17064       if (NumInitMethods > 1 || !Def->hasInitMethod())
17065         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17066     }
17067   }
17068 
17069   // Exit this scope of this tag's definition.
17070   PopDeclContext();
17071 
17072   if (getCurLexicalContext()->isObjCContainer() &&
17073       Tag->getDeclContext()->isFileContext())
17074     Tag->setTopLevelDeclInObjCContainer();
17075 
17076   // Notify the consumer that we've defined a tag.
17077   if (!Tag->isInvalidDecl())
17078     Consumer.HandleTagDeclDefinition(Tag);
17079 
17080   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17081   // from XLs and instead matches the XL #pragma pack(1) behavior.
17082   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17083       AlignPackStack.hasValue()) {
17084     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17085     // Only diagnose #pragma align(packed).
17086     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17087       return;
17088     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17089     if (!RD)
17090       return;
17091     // Only warn if there is at least 1 bitfield member.
17092     if (llvm::any_of(RD->fields(),
17093                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17094       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17095   }
17096 }
17097 
17098 void Sema::ActOnObjCContainerFinishDefinition() {
17099   // Exit this scope of this interface definition.
17100   PopDeclContext();
17101 }
17102 
17103 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17104   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17105   OriginalLexicalContext = ObjCCtx;
17106   ActOnObjCContainerFinishDefinition();
17107 }
17108 
17109 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17110   ActOnObjCContainerStartDefinition(ObjCCtx);
17111   OriginalLexicalContext = nullptr;
17112 }
17113 
17114 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17115   AdjustDeclIfTemplate(TagD);
17116   TagDecl *Tag = cast<TagDecl>(TagD);
17117   Tag->setInvalidDecl();
17118 
17119   // Make sure we "complete" the definition even it is invalid.
17120   if (Tag->isBeingDefined()) {
17121     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17122       RD->completeDefinition();
17123   }
17124 
17125   // We're undoing ActOnTagStartDefinition here, not
17126   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17127   // the FieldCollector.
17128 
17129   PopDeclContext();
17130 }
17131 
17132 // Note that FieldName may be null for anonymous bitfields.
17133 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17134                                 IdentifierInfo *FieldName,
17135                                 QualType FieldTy, bool IsMsStruct,
17136                                 Expr *BitWidth, bool *ZeroWidth) {
17137   assert(BitWidth);
17138   if (BitWidth->containsErrors())
17139     return ExprError();
17140 
17141   // Default to true; that shouldn't confuse checks for emptiness
17142   if (ZeroWidth)
17143     *ZeroWidth = true;
17144 
17145   // C99 6.7.2.1p4 - verify the field type.
17146   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17147   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17148     // Handle incomplete and sizeless types with a specific error.
17149     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17150                                  diag::err_field_incomplete_or_sizeless))
17151       return ExprError();
17152     if (FieldName)
17153       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17154         << FieldName << FieldTy << BitWidth->getSourceRange();
17155     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17156       << FieldTy << BitWidth->getSourceRange();
17157   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17158                                              UPPC_BitFieldWidth))
17159     return ExprError();
17160 
17161   // If the bit-width is type- or value-dependent, don't try to check
17162   // it now.
17163   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17164     return BitWidth;
17165 
17166   llvm::APSInt Value;
17167   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17168   if (ICE.isInvalid())
17169     return ICE;
17170   BitWidth = ICE.get();
17171 
17172   if (Value != 0 && ZeroWidth)
17173     *ZeroWidth = false;
17174 
17175   // Zero-width bitfield is ok for anonymous field.
17176   if (Value == 0 && FieldName)
17177     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17178 
17179   if (Value.isSigned() && Value.isNegative()) {
17180     if (FieldName)
17181       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17182                << FieldName << toString(Value, 10);
17183     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17184       << toString(Value, 10);
17185   }
17186 
17187   // The size of the bit-field must not exceed our maximum permitted object
17188   // size.
17189   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17190     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17191            << !FieldName << FieldName << toString(Value, 10);
17192   }
17193 
17194   if (!FieldTy->isDependentType()) {
17195     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17196     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17197     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17198 
17199     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17200     // ABI.
17201     bool CStdConstraintViolation =
17202         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17203     bool MSBitfieldViolation =
17204         Value.ugt(TypeStorageSize) &&
17205         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17206     if (CStdConstraintViolation || MSBitfieldViolation) {
17207       unsigned DiagWidth =
17208           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17209       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17210              << (bool)FieldName << FieldName << toString(Value, 10)
17211              << !CStdConstraintViolation << DiagWidth;
17212     }
17213 
17214     // Warn on types where the user might conceivably expect to get all
17215     // specified bits as value bits: that's all integral types other than
17216     // 'bool'.
17217     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17218       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17219           << FieldName << toString(Value, 10)
17220           << (unsigned)TypeWidth;
17221     }
17222   }
17223 
17224   return BitWidth;
17225 }
17226 
17227 /// ActOnField - Each field of a C struct/union is passed into this in order
17228 /// to create a FieldDecl object for it.
17229 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17230                        Declarator &D, Expr *BitfieldWidth) {
17231   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17232                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17233                                /*InitStyle=*/ICIS_NoInit, AS_public);
17234   return Res;
17235 }
17236 
17237 /// HandleField - Analyze a field of a C struct or a C++ data member.
17238 ///
17239 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17240                              SourceLocation DeclStart,
17241                              Declarator &D, Expr *BitWidth,
17242                              InClassInitStyle InitStyle,
17243                              AccessSpecifier AS) {
17244   if (D.isDecompositionDeclarator()) {
17245     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17246     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17247       << Decomp.getSourceRange();
17248     return nullptr;
17249   }
17250 
17251   IdentifierInfo *II = D.getIdentifier();
17252   SourceLocation Loc = DeclStart;
17253   if (II) Loc = D.getIdentifierLoc();
17254 
17255   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17256   QualType T = TInfo->getType();
17257   if (getLangOpts().CPlusPlus) {
17258     CheckExtraCXXDefaultArguments(D);
17259 
17260     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17261                                         UPPC_DataMemberType)) {
17262       D.setInvalidType();
17263       T = Context.IntTy;
17264       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17265     }
17266   }
17267 
17268   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17269 
17270   if (D.getDeclSpec().isInlineSpecified())
17271     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17272         << getLangOpts().CPlusPlus17;
17273   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17274     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17275          diag::err_invalid_thread)
17276       << DeclSpec::getSpecifierName(TSCS);
17277 
17278   // Check to see if this name was declared as a member previously
17279   NamedDecl *PrevDecl = nullptr;
17280   LookupResult Previous(*this, II, Loc, LookupMemberName,
17281                         ForVisibleRedeclaration);
17282   LookupName(Previous, S);
17283   switch (Previous.getResultKind()) {
17284     case LookupResult::Found:
17285     case LookupResult::FoundUnresolvedValue:
17286       PrevDecl = Previous.getAsSingle<NamedDecl>();
17287       break;
17288 
17289     case LookupResult::FoundOverloaded:
17290       PrevDecl = Previous.getRepresentativeDecl();
17291       break;
17292 
17293     case LookupResult::NotFound:
17294     case LookupResult::NotFoundInCurrentInstantiation:
17295     case LookupResult::Ambiguous:
17296       break;
17297   }
17298   Previous.suppressDiagnostics();
17299 
17300   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17301     // Maybe we will complain about the shadowed template parameter.
17302     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17303     // Just pretend that we didn't see the previous declaration.
17304     PrevDecl = nullptr;
17305   }
17306 
17307   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17308     PrevDecl = nullptr;
17309 
17310   bool Mutable
17311     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17312   SourceLocation TSSL = D.getBeginLoc();
17313   FieldDecl *NewFD
17314     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17315                      TSSL, AS, PrevDecl, &D);
17316 
17317   if (NewFD->isInvalidDecl())
17318     Record->setInvalidDecl();
17319 
17320   if (D.getDeclSpec().isModulePrivateSpecified())
17321     NewFD->setModulePrivate();
17322 
17323   if (NewFD->isInvalidDecl() && PrevDecl) {
17324     // Don't introduce NewFD into scope; there's already something
17325     // with the same name in the same scope.
17326   } else if (II) {
17327     PushOnScopeChains(NewFD, S);
17328   } else
17329     Record->addDecl(NewFD);
17330 
17331   return NewFD;
17332 }
17333 
17334 /// Build a new FieldDecl and check its well-formedness.
17335 ///
17336 /// This routine builds a new FieldDecl given the fields name, type,
17337 /// record, etc. \p PrevDecl should refer to any previous declaration
17338 /// with the same name and in the same scope as the field to be
17339 /// created.
17340 ///
17341 /// \returns a new FieldDecl.
17342 ///
17343 /// \todo The Declarator argument is a hack. It will be removed once
17344 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17345                                 TypeSourceInfo *TInfo,
17346                                 RecordDecl *Record, SourceLocation Loc,
17347                                 bool Mutable, Expr *BitWidth,
17348                                 InClassInitStyle InitStyle,
17349                                 SourceLocation TSSL,
17350                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17351                                 Declarator *D) {
17352   IdentifierInfo *II = Name.getAsIdentifierInfo();
17353   bool InvalidDecl = false;
17354   if (D) InvalidDecl = D->isInvalidType();
17355 
17356   // If we receive a broken type, recover by assuming 'int' and
17357   // marking this declaration as invalid.
17358   if (T.isNull() || T->containsErrors()) {
17359     InvalidDecl = true;
17360     T = Context.IntTy;
17361   }
17362 
17363   QualType EltTy = Context.getBaseElementType(T);
17364   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17365     if (RequireCompleteSizedType(Loc, EltTy,
17366                                  diag::err_field_incomplete_or_sizeless)) {
17367       // Fields of incomplete type force their record to be invalid.
17368       Record->setInvalidDecl();
17369       InvalidDecl = true;
17370     } else {
17371       NamedDecl *Def;
17372       EltTy->isIncompleteType(&Def);
17373       if (Def && Def->isInvalidDecl()) {
17374         Record->setInvalidDecl();
17375         InvalidDecl = true;
17376       }
17377     }
17378   }
17379 
17380   // TR 18037 does not allow fields to be declared with address space
17381   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17382       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17383     Diag(Loc, diag::err_field_with_address_space);
17384     Record->setInvalidDecl();
17385     InvalidDecl = true;
17386   }
17387 
17388   if (LangOpts.OpenCL) {
17389     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17390     // used as structure or union field: image, sampler, event or block types.
17391     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17392         T->isBlockPointerType()) {
17393       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17394       Record->setInvalidDecl();
17395       InvalidDecl = true;
17396     }
17397     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17398     // is enabled.
17399     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17400                         "__cl_clang_bitfields", LangOpts)) {
17401       Diag(Loc, diag::err_opencl_bitfields);
17402       InvalidDecl = true;
17403     }
17404   }
17405 
17406   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17407   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17408       T.hasQualifiers()) {
17409     InvalidDecl = true;
17410     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17411   }
17412 
17413   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17414   // than a variably modified type.
17415   if (!InvalidDecl && T->isVariablyModifiedType()) {
17416     if (!tryToFixVariablyModifiedVarType(
17417             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17418       InvalidDecl = true;
17419   }
17420 
17421   // Fields can not have abstract class types
17422   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17423                                              diag::err_abstract_type_in_decl,
17424                                              AbstractFieldType))
17425     InvalidDecl = true;
17426 
17427   bool ZeroWidth = false;
17428   if (InvalidDecl)
17429     BitWidth = nullptr;
17430   // If this is declared as a bit-field, check the bit-field.
17431   if (BitWidth) {
17432     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17433                               &ZeroWidth).get();
17434     if (!BitWidth) {
17435       InvalidDecl = true;
17436       BitWidth = nullptr;
17437       ZeroWidth = false;
17438     }
17439   }
17440 
17441   // Check that 'mutable' is consistent with the type of the declaration.
17442   if (!InvalidDecl && Mutable) {
17443     unsigned DiagID = 0;
17444     if (T->isReferenceType())
17445       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17446                                         : diag::err_mutable_reference;
17447     else if (T.isConstQualified())
17448       DiagID = diag::err_mutable_const;
17449 
17450     if (DiagID) {
17451       SourceLocation ErrLoc = Loc;
17452       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17453         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17454       Diag(ErrLoc, DiagID);
17455       if (DiagID != diag::ext_mutable_reference) {
17456         Mutable = false;
17457         InvalidDecl = true;
17458       }
17459     }
17460   }
17461 
17462   // C++11 [class.union]p8 (DR1460):
17463   //   At most one variant member of a union may have a
17464   //   brace-or-equal-initializer.
17465   if (InitStyle != ICIS_NoInit)
17466     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17467 
17468   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17469                                        BitWidth, Mutable, InitStyle);
17470   if (InvalidDecl)
17471     NewFD->setInvalidDecl();
17472 
17473   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17474     Diag(Loc, diag::err_duplicate_member) << II;
17475     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17476     NewFD->setInvalidDecl();
17477   }
17478 
17479   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17480     if (Record->isUnion()) {
17481       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17482         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17483         if (RDecl->getDefinition()) {
17484           // C++ [class.union]p1: An object of a class with a non-trivial
17485           // constructor, a non-trivial copy constructor, a non-trivial
17486           // destructor, or a non-trivial copy assignment operator
17487           // cannot be a member of a union, nor can an array of such
17488           // objects.
17489           if (CheckNontrivialField(NewFD))
17490             NewFD->setInvalidDecl();
17491         }
17492       }
17493 
17494       // C++ [class.union]p1: If a union contains a member of reference type,
17495       // the program is ill-formed, except when compiling with MSVC extensions
17496       // enabled.
17497       if (EltTy->isReferenceType()) {
17498         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17499                                     diag::ext_union_member_of_reference_type :
17500                                     diag::err_union_member_of_reference_type)
17501           << NewFD->getDeclName() << EltTy;
17502         if (!getLangOpts().MicrosoftExt)
17503           NewFD->setInvalidDecl();
17504       }
17505     }
17506   }
17507 
17508   // FIXME: We need to pass in the attributes given an AST
17509   // representation, not a parser representation.
17510   if (D) {
17511     // FIXME: The current scope is almost... but not entirely... correct here.
17512     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17513 
17514     if (NewFD->hasAttrs())
17515       CheckAlignasUnderalignment(NewFD);
17516   }
17517 
17518   // In auto-retain/release, infer strong retension for fields of
17519   // retainable type.
17520   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17521     NewFD->setInvalidDecl();
17522 
17523   if (T.isObjCGCWeak())
17524     Diag(Loc, diag::warn_attribute_weak_on_field);
17525 
17526   // PPC MMA non-pointer types are not allowed as field types.
17527   if (Context.getTargetInfo().getTriple().isPPC64() &&
17528       CheckPPCMMAType(T, NewFD->getLocation()))
17529     NewFD->setInvalidDecl();
17530 
17531   NewFD->setAccess(AS);
17532   return NewFD;
17533 }
17534 
17535 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17536   assert(FD);
17537   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17538 
17539   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17540     return false;
17541 
17542   QualType EltTy = Context.getBaseElementType(FD->getType());
17543   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17544     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17545     if (RDecl->getDefinition()) {
17546       // We check for copy constructors before constructors
17547       // because otherwise we'll never get complaints about
17548       // copy constructors.
17549 
17550       CXXSpecialMember member = CXXInvalid;
17551       // We're required to check for any non-trivial constructors. Since the
17552       // implicit default constructor is suppressed if there are any
17553       // user-declared constructors, we just need to check that there is a
17554       // trivial default constructor and a trivial copy constructor. (We don't
17555       // worry about move constructors here, since this is a C++98 check.)
17556       if (RDecl->hasNonTrivialCopyConstructor())
17557         member = CXXCopyConstructor;
17558       else if (!RDecl->hasTrivialDefaultConstructor())
17559         member = CXXDefaultConstructor;
17560       else if (RDecl->hasNonTrivialCopyAssignment())
17561         member = CXXCopyAssignment;
17562       else if (RDecl->hasNonTrivialDestructor())
17563         member = CXXDestructor;
17564 
17565       if (member != CXXInvalid) {
17566         if (!getLangOpts().CPlusPlus11 &&
17567             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17568           // Objective-C++ ARC: it is an error to have a non-trivial field of
17569           // a union. However, system headers in Objective-C programs
17570           // occasionally have Objective-C lifetime objects within unions,
17571           // and rather than cause the program to fail, we make those
17572           // members unavailable.
17573           SourceLocation Loc = FD->getLocation();
17574           if (getSourceManager().isInSystemHeader(Loc)) {
17575             if (!FD->hasAttr<UnavailableAttr>())
17576               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17577                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17578             return false;
17579           }
17580         }
17581 
17582         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17583                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17584                diag::err_illegal_union_or_anon_struct_member)
17585           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17586         DiagnoseNontrivial(RDecl, member);
17587         return !getLangOpts().CPlusPlus11;
17588       }
17589     }
17590   }
17591 
17592   return false;
17593 }
17594 
17595 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17596 ///  AST enum value.
17597 static ObjCIvarDecl::AccessControl
17598 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17599   switch (ivarVisibility) {
17600   default: llvm_unreachable("Unknown visitibility kind");
17601   case tok::objc_private: return ObjCIvarDecl::Private;
17602   case tok::objc_public: return ObjCIvarDecl::Public;
17603   case tok::objc_protected: return ObjCIvarDecl::Protected;
17604   case tok::objc_package: return ObjCIvarDecl::Package;
17605   }
17606 }
17607 
17608 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17609 /// in order to create an IvarDecl object for it.
17610 Decl *Sema::ActOnIvar(Scope *S,
17611                                 SourceLocation DeclStart,
17612                                 Declarator &D, Expr *BitfieldWidth,
17613                                 tok::ObjCKeywordKind Visibility) {
17614 
17615   IdentifierInfo *II = D.getIdentifier();
17616   Expr *BitWidth = (Expr*)BitfieldWidth;
17617   SourceLocation Loc = DeclStart;
17618   if (II) Loc = D.getIdentifierLoc();
17619 
17620   // FIXME: Unnamed fields can be handled in various different ways, for
17621   // example, unnamed unions inject all members into the struct namespace!
17622 
17623   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17624   QualType T = TInfo->getType();
17625 
17626   if (BitWidth) {
17627     // 6.7.2.1p3, 6.7.2.1p4
17628     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17629     if (!BitWidth)
17630       D.setInvalidType();
17631   } else {
17632     // Not a bitfield.
17633 
17634     // validate II.
17635 
17636   }
17637   if (T->isReferenceType()) {
17638     Diag(Loc, diag::err_ivar_reference_type);
17639     D.setInvalidType();
17640   }
17641   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17642   // than a variably modified type.
17643   else if (T->isVariablyModifiedType()) {
17644     if (!tryToFixVariablyModifiedVarType(
17645             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17646       D.setInvalidType();
17647   }
17648 
17649   // Get the visibility (access control) for this ivar.
17650   ObjCIvarDecl::AccessControl ac =
17651     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17652                                         : ObjCIvarDecl::None;
17653   // Must set ivar's DeclContext to its enclosing interface.
17654   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17655   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17656     return nullptr;
17657   ObjCContainerDecl *EnclosingContext;
17658   if (ObjCImplementationDecl *IMPDecl =
17659       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17660     if (LangOpts.ObjCRuntime.isFragile()) {
17661     // Case of ivar declared in an implementation. Context is that of its class.
17662       EnclosingContext = IMPDecl->getClassInterface();
17663       assert(EnclosingContext && "Implementation has no class interface!");
17664     }
17665     else
17666       EnclosingContext = EnclosingDecl;
17667   } else {
17668     if (ObjCCategoryDecl *CDecl =
17669         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17670       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17671         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17672         return nullptr;
17673       }
17674     }
17675     EnclosingContext = EnclosingDecl;
17676   }
17677 
17678   // Construct the decl.
17679   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17680                                              DeclStart, Loc, II, T,
17681                                              TInfo, ac, (Expr *)BitfieldWidth);
17682 
17683   if (II) {
17684     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17685                                            ForVisibleRedeclaration);
17686     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17687         && !isa<TagDecl>(PrevDecl)) {
17688       Diag(Loc, diag::err_duplicate_member) << II;
17689       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17690       NewID->setInvalidDecl();
17691     }
17692   }
17693 
17694   // Process attributes attached to the ivar.
17695   ProcessDeclAttributes(S, NewID, D);
17696 
17697   if (D.isInvalidType())
17698     NewID->setInvalidDecl();
17699 
17700   // In ARC, infer 'retaining' for ivars of retainable type.
17701   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17702     NewID->setInvalidDecl();
17703 
17704   if (D.getDeclSpec().isModulePrivateSpecified())
17705     NewID->setModulePrivate();
17706 
17707   if (II) {
17708     // FIXME: When interfaces are DeclContexts, we'll need to add
17709     // these to the interface.
17710     S->AddDecl(NewID);
17711     IdResolver.AddDecl(NewID);
17712   }
17713 
17714   if (LangOpts.ObjCRuntime.isNonFragile() &&
17715       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17716     Diag(Loc, diag::warn_ivars_in_interface);
17717 
17718   return NewID;
17719 }
17720 
17721 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17722 /// class and class extensions. For every class \@interface and class
17723 /// extension \@interface, if the last ivar is a bitfield of any type,
17724 /// then add an implicit `char :0` ivar to the end of that interface.
17725 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17726                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17727   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17728     return;
17729 
17730   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17731   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17732 
17733   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17734     return;
17735   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17736   if (!ID) {
17737     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17738       if (!CD->IsClassExtension())
17739         return;
17740     }
17741     // No need to add this to end of @implementation.
17742     else
17743       return;
17744   }
17745   // All conditions are met. Add a new bitfield to the tail end of ivars.
17746   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17747   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17748 
17749   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17750                               DeclLoc, DeclLoc, nullptr,
17751                               Context.CharTy,
17752                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17753                                                                DeclLoc),
17754                               ObjCIvarDecl::Private, BW,
17755                               true);
17756   AllIvarDecls.push_back(Ivar);
17757 }
17758 
17759 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17760                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17761                        SourceLocation RBrac,
17762                        const ParsedAttributesView &Attrs) {
17763   assert(EnclosingDecl && "missing record or interface decl");
17764 
17765   // If this is an Objective-C @implementation or category and we have
17766   // new fields here we should reset the layout of the interface since
17767   // it will now change.
17768   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17769     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17770     switch (DC->getKind()) {
17771     default: break;
17772     case Decl::ObjCCategory:
17773       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17774       break;
17775     case Decl::ObjCImplementation:
17776       Context.
17777         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17778       break;
17779     }
17780   }
17781 
17782   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17783   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17784 
17785   // Start counting up the number of named members; make sure to include
17786   // members of anonymous structs and unions in the total.
17787   unsigned NumNamedMembers = 0;
17788   if (Record) {
17789     for (const auto *I : Record->decls()) {
17790       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17791         if (IFD->getDeclName())
17792           ++NumNamedMembers;
17793     }
17794   }
17795 
17796   // Verify that all the fields are okay.
17797   SmallVector<FieldDecl*, 32> RecFields;
17798 
17799   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17800        i != end; ++i) {
17801     FieldDecl *FD = cast<FieldDecl>(*i);
17802 
17803     // Get the type for the field.
17804     const Type *FDTy = FD->getType().getTypePtr();
17805 
17806     if (!FD->isAnonymousStructOrUnion()) {
17807       // Remember all fields written by the user.
17808       RecFields.push_back(FD);
17809     }
17810 
17811     // If the field is already invalid for some reason, don't emit more
17812     // diagnostics about it.
17813     if (FD->isInvalidDecl()) {
17814       EnclosingDecl->setInvalidDecl();
17815       continue;
17816     }
17817 
17818     // C99 6.7.2.1p2:
17819     //   A structure or union shall not contain a member with
17820     //   incomplete or function type (hence, a structure shall not
17821     //   contain an instance of itself, but may contain a pointer to
17822     //   an instance of itself), except that the last member of a
17823     //   structure with more than one named member may have incomplete
17824     //   array type; such a structure (and any union containing,
17825     //   possibly recursively, a member that is such a structure)
17826     //   shall not be a member of a structure or an element of an
17827     //   array.
17828     bool IsLastField = (i + 1 == Fields.end());
17829     if (FDTy->isFunctionType()) {
17830       // Field declared as a function.
17831       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17832         << FD->getDeclName();
17833       FD->setInvalidDecl();
17834       EnclosingDecl->setInvalidDecl();
17835       continue;
17836     } else if (FDTy->isIncompleteArrayType() &&
17837                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17838       if (Record) {
17839         // Flexible array member.
17840         // Microsoft and g++ is more permissive regarding flexible array.
17841         // It will accept flexible array in union and also
17842         // as the sole element of a struct/class.
17843         unsigned DiagID = 0;
17844         if (!Record->isUnion() && !IsLastField) {
17845           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17846             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17847           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17848           FD->setInvalidDecl();
17849           EnclosingDecl->setInvalidDecl();
17850           continue;
17851         } else if (Record->isUnion())
17852           DiagID = getLangOpts().MicrosoftExt
17853                        ? diag::ext_flexible_array_union_ms
17854                        : getLangOpts().CPlusPlus
17855                              ? diag::ext_flexible_array_union_gnu
17856                              : diag::err_flexible_array_union;
17857         else if (NumNamedMembers < 1)
17858           DiagID = getLangOpts().MicrosoftExt
17859                        ? diag::ext_flexible_array_empty_aggregate_ms
17860                        : getLangOpts().CPlusPlus
17861                              ? diag::ext_flexible_array_empty_aggregate_gnu
17862                              : diag::err_flexible_array_empty_aggregate;
17863 
17864         if (DiagID)
17865           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17866                                           << Record->getTagKind();
17867         // While the layout of types that contain virtual bases is not specified
17868         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17869         // virtual bases after the derived members.  This would make a flexible
17870         // array member declared at the end of an object not adjacent to the end
17871         // of the type.
17872         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17873           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17874               << FD->getDeclName() << Record->getTagKind();
17875         if (!getLangOpts().C99)
17876           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17877             << FD->getDeclName() << Record->getTagKind();
17878 
17879         // If the element type has a non-trivial destructor, we would not
17880         // implicitly destroy the elements, so disallow it for now.
17881         //
17882         // FIXME: GCC allows this. We should probably either implicitly delete
17883         // the destructor of the containing class, or just allow this.
17884         QualType BaseElem = Context.getBaseElementType(FD->getType());
17885         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17886           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17887             << FD->getDeclName() << FD->getType();
17888           FD->setInvalidDecl();
17889           EnclosingDecl->setInvalidDecl();
17890           continue;
17891         }
17892         // Okay, we have a legal flexible array member at the end of the struct.
17893         Record->setHasFlexibleArrayMember(true);
17894       } else {
17895         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17896         // unless they are followed by another ivar. That check is done
17897         // elsewhere, after synthesized ivars are known.
17898       }
17899     } else if (!FDTy->isDependentType() &&
17900                RequireCompleteSizedType(
17901                    FD->getLocation(), FD->getType(),
17902                    diag::err_field_incomplete_or_sizeless)) {
17903       // Incomplete type
17904       FD->setInvalidDecl();
17905       EnclosingDecl->setInvalidDecl();
17906       continue;
17907     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17908       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17909         // A type which contains a flexible array member is considered to be a
17910         // flexible array member.
17911         Record->setHasFlexibleArrayMember(true);
17912         if (!Record->isUnion()) {
17913           // If this is a struct/class and this is not the last element, reject
17914           // it.  Note that GCC supports variable sized arrays in the middle of
17915           // structures.
17916           if (!IsLastField)
17917             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17918               << FD->getDeclName() << FD->getType();
17919           else {
17920             // We support flexible arrays at the end of structs in
17921             // other structs as an extension.
17922             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17923               << FD->getDeclName();
17924           }
17925         }
17926       }
17927       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17928           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17929                                  diag::err_abstract_type_in_decl,
17930                                  AbstractIvarType)) {
17931         // Ivars can not have abstract class types
17932         FD->setInvalidDecl();
17933       }
17934       if (Record && FDTTy->getDecl()->hasObjectMember())
17935         Record->setHasObjectMember(true);
17936       if (Record && FDTTy->getDecl()->hasVolatileMember())
17937         Record->setHasVolatileMember(true);
17938     } else if (FDTy->isObjCObjectType()) {
17939       /// A field cannot be an Objective-c object
17940       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17941         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17942       QualType T = Context.getObjCObjectPointerType(FD->getType());
17943       FD->setType(T);
17944     } else if (Record && Record->isUnion() &&
17945                FD->getType().hasNonTrivialObjCLifetime() &&
17946                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17947                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17948                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17949                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17950       // For backward compatibility, fields of C unions declared in system
17951       // headers that have non-trivial ObjC ownership qualifications are marked
17952       // as unavailable unless the qualifier is explicit and __strong. This can
17953       // break ABI compatibility between programs compiled with ARC and MRR, but
17954       // is a better option than rejecting programs using those unions under
17955       // ARC.
17956       FD->addAttr(UnavailableAttr::CreateImplicit(
17957           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17958           FD->getLocation()));
17959     } else if (getLangOpts().ObjC &&
17960                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17961                !Record->hasObjectMember()) {
17962       if (FD->getType()->isObjCObjectPointerType() ||
17963           FD->getType().isObjCGCStrong())
17964         Record->setHasObjectMember(true);
17965       else if (Context.getAsArrayType(FD->getType())) {
17966         QualType BaseType = Context.getBaseElementType(FD->getType());
17967         if (BaseType->isRecordType() &&
17968             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17969           Record->setHasObjectMember(true);
17970         else if (BaseType->isObjCObjectPointerType() ||
17971                  BaseType.isObjCGCStrong())
17972                Record->setHasObjectMember(true);
17973       }
17974     }
17975 
17976     if (Record && !getLangOpts().CPlusPlus &&
17977         !shouldIgnoreForRecordTriviality(FD)) {
17978       QualType FT = FD->getType();
17979       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17980         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17981         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17982             Record->isUnion())
17983           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17984       }
17985       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17986       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17987         Record->setNonTrivialToPrimitiveCopy(true);
17988         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17989           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17990       }
17991       if (FT.isDestructedType()) {
17992         Record->setNonTrivialToPrimitiveDestroy(true);
17993         Record->setParamDestroyedInCallee(true);
17994         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17995           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17996       }
17997 
17998       if (const auto *RT = FT->getAs<RecordType>()) {
17999         if (RT->getDecl()->getArgPassingRestrictions() ==
18000             RecordDecl::APK_CanNeverPassInRegs)
18001           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18002       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18003         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18004     }
18005 
18006     if (Record && FD->getType().isVolatileQualified())
18007       Record->setHasVolatileMember(true);
18008     // Keep track of the number of named members.
18009     if (FD->getIdentifier())
18010       ++NumNamedMembers;
18011   }
18012 
18013   // Okay, we successfully defined 'Record'.
18014   if (Record) {
18015     bool Completed = false;
18016     if (CXXRecord) {
18017       if (!CXXRecord->isInvalidDecl()) {
18018         // Set access bits correctly on the directly-declared conversions.
18019         for (CXXRecordDecl::conversion_iterator
18020                I = CXXRecord->conversion_begin(),
18021                E = CXXRecord->conversion_end(); I != E; ++I)
18022           I.setAccess((*I)->getAccess());
18023       }
18024 
18025       // Add any implicitly-declared members to this class.
18026       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18027 
18028       if (!CXXRecord->isDependentType()) {
18029         if (!CXXRecord->isInvalidDecl()) {
18030           // If we have virtual base classes, we may end up finding multiple
18031           // final overriders for a given virtual function. Check for this
18032           // problem now.
18033           if (CXXRecord->getNumVBases()) {
18034             CXXFinalOverriderMap FinalOverriders;
18035             CXXRecord->getFinalOverriders(FinalOverriders);
18036 
18037             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18038                                              MEnd = FinalOverriders.end();
18039                  M != MEnd; ++M) {
18040               for (OverridingMethods::iterator SO = M->second.begin(),
18041                                             SOEnd = M->second.end();
18042                    SO != SOEnd; ++SO) {
18043                 assert(SO->second.size() > 0 &&
18044                        "Virtual function without overriding functions?");
18045                 if (SO->second.size() == 1)
18046                   continue;
18047 
18048                 // C++ [class.virtual]p2:
18049                 //   In a derived class, if a virtual member function of a base
18050                 //   class subobject has more than one final overrider the
18051                 //   program is ill-formed.
18052                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18053                   << (const NamedDecl *)M->first << Record;
18054                 Diag(M->first->getLocation(),
18055                      diag::note_overridden_virtual_function);
18056                 for (OverridingMethods::overriding_iterator
18057                           OM = SO->second.begin(),
18058                        OMEnd = SO->second.end();
18059                      OM != OMEnd; ++OM)
18060                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18061                     << (const NamedDecl *)M->first << OM->Method->getParent();
18062 
18063                 Record->setInvalidDecl();
18064               }
18065             }
18066             CXXRecord->completeDefinition(&FinalOverriders);
18067             Completed = true;
18068           }
18069         }
18070       }
18071     }
18072 
18073     if (!Completed)
18074       Record->completeDefinition();
18075 
18076     // Handle attributes before checking the layout.
18077     ProcessDeclAttributeList(S, Record, Attrs);
18078 
18079     // Check to see if a FieldDecl is a pointer to a function.
18080     auto IsFunctionPointer = [&](const Decl *D) {
18081       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18082       if (!FD)
18083         return false;
18084       QualType FieldType = FD->getType().getDesugaredType(Context);
18085       if (isa<PointerType>(FieldType)) {
18086         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18087         return PointeeType.getDesugaredType(Context)->isFunctionType();
18088       }
18089       return false;
18090     };
18091 
18092     // Maybe randomize the record's decls. We automatically randomize a record
18093     // of function pointers, unless it has the "no_randomize_layout" attribute.
18094     if (!getLangOpts().CPlusPlus &&
18095         (Record->hasAttr<RandomizeLayoutAttr>() ||
18096          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18097           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18098         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18099         !Record->isRandomized()) {
18100       SmallVector<Decl *, 32> NewDeclOrdering;
18101       if (randstruct::randomizeStructureLayout(Context, Record,
18102                                                NewDeclOrdering))
18103         Record->reorderDecls(NewDeclOrdering);
18104     }
18105 
18106     // We may have deferred checking for a deleted destructor. Check now.
18107     if (CXXRecord) {
18108       auto *Dtor = CXXRecord->getDestructor();
18109       if (Dtor && Dtor->isImplicit() &&
18110           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18111         CXXRecord->setImplicitDestructorIsDeleted();
18112         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18113       }
18114     }
18115 
18116     if (Record->hasAttrs()) {
18117       CheckAlignasUnderalignment(Record);
18118 
18119       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18120         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18121                                            IA->getRange(), IA->getBestCase(),
18122                                            IA->getInheritanceModel());
18123     }
18124 
18125     // Check if the structure/union declaration is a type that can have zero
18126     // size in C. For C this is a language extension, for C++ it may cause
18127     // compatibility problems.
18128     bool CheckForZeroSize;
18129     if (!getLangOpts().CPlusPlus) {
18130       CheckForZeroSize = true;
18131     } else {
18132       // For C++ filter out types that cannot be referenced in C code.
18133       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18134       CheckForZeroSize =
18135           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18136           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18137           CXXRecord->isCLike();
18138     }
18139     if (CheckForZeroSize) {
18140       bool ZeroSize = true;
18141       bool IsEmpty = true;
18142       unsigned NonBitFields = 0;
18143       for (RecordDecl::field_iterator I = Record->field_begin(),
18144                                       E = Record->field_end();
18145            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18146         IsEmpty = false;
18147         if (I->isUnnamedBitfield()) {
18148           if (!I->isZeroLengthBitField(Context))
18149             ZeroSize = false;
18150         } else {
18151           ++NonBitFields;
18152           QualType FieldType = I->getType();
18153           if (FieldType->isIncompleteType() ||
18154               !Context.getTypeSizeInChars(FieldType).isZero())
18155             ZeroSize = false;
18156         }
18157       }
18158 
18159       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18160       // allowed in C++, but warn if its declaration is inside
18161       // extern "C" block.
18162       if (ZeroSize) {
18163         Diag(RecLoc, getLangOpts().CPlusPlus ?
18164                          diag::warn_zero_size_struct_union_in_extern_c :
18165                          diag::warn_zero_size_struct_union_compat)
18166           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18167       }
18168 
18169       // Structs without named members are extension in C (C99 6.7.2.1p7),
18170       // but are accepted by GCC.
18171       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18172         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18173                                diag::ext_no_named_members_in_struct_union)
18174           << Record->isUnion();
18175       }
18176     }
18177   } else {
18178     ObjCIvarDecl **ClsFields =
18179       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18180     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18181       ID->setEndOfDefinitionLoc(RBrac);
18182       // Add ivar's to class's DeclContext.
18183       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18184         ClsFields[i]->setLexicalDeclContext(ID);
18185         ID->addDecl(ClsFields[i]);
18186       }
18187       // Must enforce the rule that ivars in the base classes may not be
18188       // duplicates.
18189       if (ID->getSuperClass())
18190         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18191     } else if (ObjCImplementationDecl *IMPDecl =
18192                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18193       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18194       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18195         // Ivar declared in @implementation never belongs to the implementation.
18196         // Only it is in implementation's lexical context.
18197         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18198       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18199       IMPDecl->setIvarLBraceLoc(LBrac);
18200       IMPDecl->setIvarRBraceLoc(RBrac);
18201     } else if (ObjCCategoryDecl *CDecl =
18202                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18203       // case of ivars in class extension; all other cases have been
18204       // reported as errors elsewhere.
18205       // FIXME. Class extension does not have a LocEnd field.
18206       // CDecl->setLocEnd(RBrac);
18207       // Add ivar's to class extension's DeclContext.
18208       // Diagnose redeclaration of private ivars.
18209       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18210       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18211         if (IDecl) {
18212           if (const ObjCIvarDecl *ClsIvar =
18213               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18214             Diag(ClsFields[i]->getLocation(),
18215                  diag::err_duplicate_ivar_declaration);
18216             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18217             continue;
18218           }
18219           for (const auto *Ext : IDecl->known_extensions()) {
18220             if (const ObjCIvarDecl *ClsExtIvar
18221                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18222               Diag(ClsFields[i]->getLocation(),
18223                    diag::err_duplicate_ivar_declaration);
18224               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18225               continue;
18226             }
18227           }
18228         }
18229         ClsFields[i]->setLexicalDeclContext(CDecl);
18230         CDecl->addDecl(ClsFields[i]);
18231       }
18232       CDecl->setIvarLBraceLoc(LBrac);
18233       CDecl->setIvarRBraceLoc(RBrac);
18234     }
18235   }
18236 }
18237 
18238 /// Determine whether the given integral value is representable within
18239 /// the given type T.
18240 static bool isRepresentableIntegerValue(ASTContext &Context,
18241                                         llvm::APSInt &Value,
18242                                         QualType T) {
18243   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18244          "Integral type required!");
18245   unsigned BitWidth = Context.getIntWidth(T);
18246 
18247   if (Value.isUnsigned() || Value.isNonNegative()) {
18248     if (T->isSignedIntegerOrEnumerationType())
18249       --BitWidth;
18250     return Value.getActiveBits() <= BitWidth;
18251   }
18252   return Value.getMinSignedBits() <= BitWidth;
18253 }
18254 
18255 // Given an integral type, return the next larger integral type
18256 // (or a NULL type of no such type exists).
18257 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18258   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18259   // enum checking below.
18260   assert((T->isIntegralType(Context) ||
18261          T->isEnumeralType()) && "Integral type required!");
18262   const unsigned NumTypes = 4;
18263   QualType SignedIntegralTypes[NumTypes] = {
18264     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18265   };
18266   QualType UnsignedIntegralTypes[NumTypes] = {
18267     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18268     Context.UnsignedLongLongTy
18269   };
18270 
18271   unsigned BitWidth = Context.getTypeSize(T);
18272   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18273                                                         : UnsignedIntegralTypes;
18274   for (unsigned I = 0; I != NumTypes; ++I)
18275     if (Context.getTypeSize(Types[I]) > BitWidth)
18276       return Types[I];
18277 
18278   return QualType();
18279 }
18280 
18281 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18282                                           EnumConstantDecl *LastEnumConst,
18283                                           SourceLocation IdLoc,
18284                                           IdentifierInfo *Id,
18285                                           Expr *Val) {
18286   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18287   llvm::APSInt EnumVal(IntWidth);
18288   QualType EltTy;
18289 
18290   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18291     Val = nullptr;
18292 
18293   if (Val)
18294     Val = DefaultLvalueConversion(Val).get();
18295 
18296   if (Val) {
18297     if (Enum->isDependentType() || Val->isTypeDependent() ||
18298         Val->containsErrors())
18299       EltTy = Context.DependentTy;
18300     else {
18301       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18302       // underlying type, but do allow it in all other contexts.
18303       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18304         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18305         // constant-expression in the enumerator-definition shall be a converted
18306         // constant expression of the underlying type.
18307         EltTy = Enum->getIntegerType();
18308         ExprResult Converted =
18309           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18310                                            CCEK_Enumerator);
18311         if (Converted.isInvalid())
18312           Val = nullptr;
18313         else
18314           Val = Converted.get();
18315       } else if (!Val->isValueDependent() &&
18316                  !(Val =
18317                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18318                            .get())) {
18319         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18320       } else {
18321         if (Enum->isComplete()) {
18322           EltTy = Enum->getIntegerType();
18323 
18324           // In Obj-C and Microsoft mode, require the enumeration value to be
18325           // representable in the underlying type of the enumeration. In C++11,
18326           // we perform a non-narrowing conversion as part of converted constant
18327           // expression checking.
18328           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18329             if (Context.getTargetInfo()
18330                     .getTriple()
18331                     .isWindowsMSVCEnvironment()) {
18332               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18333             } else {
18334               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18335             }
18336           }
18337 
18338           // Cast to the underlying type.
18339           Val = ImpCastExprToType(Val, EltTy,
18340                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18341                                                          : CK_IntegralCast)
18342                     .get();
18343         } else if (getLangOpts().CPlusPlus) {
18344           // C++11 [dcl.enum]p5:
18345           //   If the underlying type is not fixed, the type of each enumerator
18346           //   is the type of its initializing value:
18347           //     - If an initializer is specified for an enumerator, the
18348           //       initializing value has the same type as the expression.
18349           EltTy = Val->getType();
18350         } else {
18351           // C99 6.7.2.2p2:
18352           //   The expression that defines the value of an enumeration constant
18353           //   shall be an integer constant expression that has a value
18354           //   representable as an int.
18355 
18356           // Complain if the value is not representable in an int.
18357           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18358             Diag(IdLoc, diag::ext_enum_value_not_int)
18359               << toString(EnumVal, 10) << Val->getSourceRange()
18360               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18361           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18362             // Force the type of the expression to 'int'.
18363             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18364           }
18365           EltTy = Val->getType();
18366         }
18367       }
18368     }
18369   }
18370 
18371   if (!Val) {
18372     if (Enum->isDependentType())
18373       EltTy = Context.DependentTy;
18374     else if (!LastEnumConst) {
18375       // C++0x [dcl.enum]p5:
18376       //   If the underlying type is not fixed, the type of each enumerator
18377       //   is the type of its initializing value:
18378       //     - If no initializer is specified for the first enumerator, the
18379       //       initializing value has an unspecified integral type.
18380       //
18381       // GCC uses 'int' for its unspecified integral type, as does
18382       // C99 6.7.2.2p3.
18383       if (Enum->isFixed()) {
18384         EltTy = Enum->getIntegerType();
18385       }
18386       else {
18387         EltTy = Context.IntTy;
18388       }
18389     } else {
18390       // Assign the last value + 1.
18391       EnumVal = LastEnumConst->getInitVal();
18392       ++EnumVal;
18393       EltTy = LastEnumConst->getType();
18394 
18395       // Check for overflow on increment.
18396       if (EnumVal < LastEnumConst->getInitVal()) {
18397         // C++0x [dcl.enum]p5:
18398         //   If the underlying type is not fixed, the type of each enumerator
18399         //   is the type of its initializing value:
18400         //
18401         //     - Otherwise the type of the initializing value is the same as
18402         //       the type of the initializing value of the preceding enumerator
18403         //       unless the incremented value is not representable in that type,
18404         //       in which case the type is an unspecified integral type
18405         //       sufficient to contain the incremented value. If no such type
18406         //       exists, the program is ill-formed.
18407         QualType T = getNextLargerIntegralType(Context, EltTy);
18408         if (T.isNull() || Enum->isFixed()) {
18409           // There is no integral type larger enough to represent this
18410           // value. Complain, then allow the value to wrap around.
18411           EnumVal = LastEnumConst->getInitVal();
18412           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18413           ++EnumVal;
18414           if (Enum->isFixed())
18415             // When the underlying type is fixed, this is ill-formed.
18416             Diag(IdLoc, diag::err_enumerator_wrapped)
18417               << toString(EnumVal, 10)
18418               << EltTy;
18419           else
18420             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18421               << toString(EnumVal, 10);
18422         } else {
18423           EltTy = T;
18424         }
18425 
18426         // Retrieve the last enumerator's value, extent that type to the
18427         // type that is supposed to be large enough to represent the incremented
18428         // value, then increment.
18429         EnumVal = LastEnumConst->getInitVal();
18430         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18431         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18432         ++EnumVal;
18433 
18434         // If we're not in C++, diagnose the overflow of enumerator values,
18435         // which in C99 means that the enumerator value is not representable in
18436         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18437         // permits enumerator values that are representable in some larger
18438         // integral type.
18439         if (!getLangOpts().CPlusPlus && !T.isNull())
18440           Diag(IdLoc, diag::warn_enum_value_overflow);
18441       } else if (!getLangOpts().CPlusPlus &&
18442                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18443         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18444         Diag(IdLoc, diag::ext_enum_value_not_int)
18445           << toString(EnumVal, 10) << 1;
18446       }
18447     }
18448   }
18449 
18450   if (!EltTy->isDependentType()) {
18451     // Make the enumerator value match the signedness and size of the
18452     // enumerator's type.
18453     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18454     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18455   }
18456 
18457   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18458                                   Val, EnumVal);
18459 }
18460 
18461 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18462                                                 SourceLocation IILoc) {
18463   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18464       !getLangOpts().CPlusPlus)
18465     return SkipBodyInfo();
18466 
18467   // We have an anonymous enum definition. Look up the first enumerator to
18468   // determine if we should merge the definition with an existing one and
18469   // skip the body.
18470   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18471                                          forRedeclarationInCurContext());
18472   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18473   if (!PrevECD)
18474     return SkipBodyInfo();
18475 
18476   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18477   NamedDecl *Hidden;
18478   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18479     SkipBodyInfo Skip;
18480     Skip.Previous = Hidden;
18481     return Skip;
18482   }
18483 
18484   return SkipBodyInfo();
18485 }
18486 
18487 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18488                               SourceLocation IdLoc, IdentifierInfo *Id,
18489                               const ParsedAttributesView &Attrs,
18490                               SourceLocation EqualLoc, Expr *Val) {
18491   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18492   EnumConstantDecl *LastEnumConst =
18493     cast_or_null<EnumConstantDecl>(lastEnumConst);
18494 
18495   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18496   // we find one that is.
18497   S = getNonFieldDeclScope(S);
18498 
18499   // Verify that there isn't already something declared with this name in this
18500   // scope.
18501   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18502   LookupName(R, S);
18503   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18504 
18505   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18506     // Maybe we will complain about the shadowed template parameter.
18507     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18508     // Just pretend that we didn't see the previous declaration.
18509     PrevDecl = nullptr;
18510   }
18511 
18512   // C++ [class.mem]p15:
18513   // If T is the name of a class, then each of the following shall have a name
18514   // different from T:
18515   // - every enumerator of every member of class T that is an unscoped
18516   // enumerated type
18517   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18518     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18519                             DeclarationNameInfo(Id, IdLoc));
18520 
18521   EnumConstantDecl *New =
18522     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18523   if (!New)
18524     return nullptr;
18525 
18526   if (PrevDecl) {
18527     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18528       // Check for other kinds of shadowing not already handled.
18529       CheckShadow(New, PrevDecl, R);
18530     }
18531 
18532     // When in C++, we may get a TagDecl with the same name; in this case the
18533     // enum constant will 'hide' the tag.
18534     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18535            "Received TagDecl when not in C++!");
18536     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18537       if (isa<EnumConstantDecl>(PrevDecl))
18538         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18539       else
18540         Diag(IdLoc, diag::err_redefinition) << Id;
18541       notePreviousDefinition(PrevDecl, IdLoc);
18542       return nullptr;
18543     }
18544   }
18545 
18546   // Process attributes.
18547   ProcessDeclAttributeList(S, New, Attrs);
18548   AddPragmaAttributes(S, New);
18549 
18550   // Register this decl in the current scope stack.
18551   New->setAccess(TheEnumDecl->getAccess());
18552   PushOnScopeChains(New, S);
18553 
18554   ActOnDocumentableDecl(New);
18555 
18556   return New;
18557 }
18558 
18559 // Returns true when the enum initial expression does not trigger the
18560 // duplicate enum warning.  A few common cases are exempted as follows:
18561 // Element2 = Element1
18562 // Element2 = Element1 + 1
18563 // Element2 = Element1 - 1
18564 // Where Element2 and Element1 are from the same enum.
18565 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18566   Expr *InitExpr = ECD->getInitExpr();
18567   if (!InitExpr)
18568     return true;
18569   InitExpr = InitExpr->IgnoreImpCasts();
18570 
18571   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18572     if (!BO->isAdditiveOp())
18573       return true;
18574     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18575     if (!IL)
18576       return true;
18577     if (IL->getValue() != 1)
18578       return true;
18579 
18580     InitExpr = BO->getLHS();
18581   }
18582 
18583   // This checks if the elements are from the same enum.
18584   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18585   if (!DRE)
18586     return true;
18587 
18588   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18589   if (!EnumConstant)
18590     return true;
18591 
18592   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18593       Enum)
18594     return true;
18595 
18596   return false;
18597 }
18598 
18599 // Emits a warning when an element is implicitly set a value that
18600 // a previous element has already been set to.
18601 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18602                                         EnumDecl *Enum, QualType EnumType) {
18603   // Avoid anonymous enums
18604   if (!Enum->getIdentifier())
18605     return;
18606 
18607   // Only check for small enums.
18608   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18609     return;
18610 
18611   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18612     return;
18613 
18614   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18615   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18616 
18617   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18618 
18619   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18620   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18621 
18622   // Use int64_t as a key to avoid needing special handling for map keys.
18623   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18624     llvm::APSInt Val = D->getInitVal();
18625     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18626   };
18627 
18628   DuplicatesVector DupVector;
18629   ValueToVectorMap EnumMap;
18630 
18631   // Populate the EnumMap with all values represented by enum constants without
18632   // an initializer.
18633   for (auto *Element : Elements) {
18634     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18635 
18636     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18637     // this constant.  Skip this enum since it may be ill-formed.
18638     if (!ECD) {
18639       return;
18640     }
18641 
18642     // Constants with initalizers are handled in the next loop.
18643     if (ECD->getInitExpr())
18644       continue;
18645 
18646     // Duplicate values are handled in the next loop.
18647     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18648   }
18649 
18650   if (EnumMap.size() == 0)
18651     return;
18652 
18653   // Create vectors for any values that has duplicates.
18654   for (auto *Element : Elements) {
18655     // The last loop returned if any constant was null.
18656     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18657     if (!ValidDuplicateEnum(ECD, Enum))
18658       continue;
18659 
18660     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18661     if (Iter == EnumMap.end())
18662       continue;
18663 
18664     DeclOrVector& Entry = Iter->second;
18665     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18666       // Ensure constants are different.
18667       if (D == ECD)
18668         continue;
18669 
18670       // Create new vector and push values onto it.
18671       auto Vec = std::make_unique<ECDVector>();
18672       Vec->push_back(D);
18673       Vec->push_back(ECD);
18674 
18675       // Update entry to point to the duplicates vector.
18676       Entry = Vec.get();
18677 
18678       // Store the vector somewhere we can consult later for quick emission of
18679       // diagnostics.
18680       DupVector.emplace_back(std::move(Vec));
18681       continue;
18682     }
18683 
18684     ECDVector *Vec = Entry.get<ECDVector*>();
18685     // Make sure constants are not added more than once.
18686     if (*Vec->begin() == ECD)
18687       continue;
18688 
18689     Vec->push_back(ECD);
18690   }
18691 
18692   // Emit diagnostics.
18693   for (const auto &Vec : DupVector) {
18694     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18695 
18696     // Emit warning for one enum constant.
18697     auto *FirstECD = Vec->front();
18698     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18699       << FirstECD << toString(FirstECD->getInitVal(), 10)
18700       << FirstECD->getSourceRange();
18701 
18702     // Emit one note for each of the remaining enum constants with
18703     // the same value.
18704     for (auto *ECD : llvm::drop_begin(*Vec))
18705       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18706         << ECD << toString(ECD->getInitVal(), 10)
18707         << ECD->getSourceRange();
18708   }
18709 }
18710 
18711 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18712                              bool AllowMask) const {
18713   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18714   assert(ED->isCompleteDefinition() && "expected enum definition");
18715 
18716   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18717   llvm::APInt &FlagBits = R.first->second;
18718 
18719   if (R.second) {
18720     for (auto *E : ED->enumerators()) {
18721       const auto &EVal = E->getInitVal();
18722       // Only single-bit enumerators introduce new flag values.
18723       if (EVal.isPowerOf2())
18724         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18725     }
18726   }
18727 
18728   // A value is in a flag enum if either its bits are a subset of the enum's
18729   // flag bits (the first condition) or we are allowing masks and the same is
18730   // true of its complement (the second condition). When masks are allowed, we
18731   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18732   //
18733   // While it's true that any value could be used as a mask, the assumption is
18734   // that a mask will have all of the insignificant bits set. Anything else is
18735   // likely a logic error.
18736   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18737   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18738 }
18739 
18740 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18741                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18742                          const ParsedAttributesView &Attrs) {
18743   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18744   QualType EnumType = Context.getTypeDeclType(Enum);
18745 
18746   ProcessDeclAttributeList(S, Enum, Attrs);
18747 
18748   if (Enum->isDependentType()) {
18749     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18750       EnumConstantDecl *ECD =
18751         cast_or_null<EnumConstantDecl>(Elements[i]);
18752       if (!ECD) continue;
18753 
18754       ECD->setType(EnumType);
18755     }
18756 
18757     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18758     return;
18759   }
18760 
18761   // TODO: If the result value doesn't fit in an int, it must be a long or long
18762   // long value.  ISO C does not support this, but GCC does as an extension,
18763   // emit a warning.
18764   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18765   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18766   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18767 
18768   // Verify that all the values are okay, compute the size of the values, and
18769   // reverse the list.
18770   unsigned NumNegativeBits = 0;
18771   unsigned NumPositiveBits = 0;
18772 
18773   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18774     EnumConstantDecl *ECD =
18775       cast_or_null<EnumConstantDecl>(Elements[i]);
18776     if (!ECD) continue;  // Already issued a diagnostic.
18777 
18778     const llvm::APSInt &InitVal = ECD->getInitVal();
18779 
18780     // Keep track of the size of positive and negative values.
18781     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18782       NumPositiveBits = std::max(NumPositiveBits,
18783                                  (unsigned)InitVal.getActiveBits());
18784     else
18785       NumNegativeBits = std::max(NumNegativeBits,
18786                                  (unsigned)InitVal.getMinSignedBits());
18787   }
18788 
18789   // Figure out the type that should be used for this enum.
18790   QualType BestType;
18791   unsigned BestWidth;
18792 
18793   // C++0x N3000 [conv.prom]p3:
18794   //   An rvalue of an unscoped enumeration type whose underlying
18795   //   type is not fixed can be converted to an rvalue of the first
18796   //   of the following types that can represent all the values of
18797   //   the enumeration: int, unsigned int, long int, unsigned long
18798   //   int, long long int, or unsigned long long int.
18799   // C99 6.4.4.3p2:
18800   //   An identifier declared as an enumeration constant has type int.
18801   // The C99 rule is modified by a gcc extension
18802   QualType BestPromotionType;
18803 
18804   bool Packed = Enum->hasAttr<PackedAttr>();
18805   // -fshort-enums is the equivalent to specifying the packed attribute on all
18806   // enum definitions.
18807   if (LangOpts.ShortEnums)
18808     Packed = true;
18809 
18810   // If the enum already has a type because it is fixed or dictated by the
18811   // target, promote that type instead of analyzing the enumerators.
18812   if (Enum->isComplete()) {
18813     BestType = Enum->getIntegerType();
18814     if (BestType->isPromotableIntegerType())
18815       BestPromotionType = Context.getPromotedIntegerType(BestType);
18816     else
18817       BestPromotionType = BestType;
18818 
18819     BestWidth = Context.getIntWidth(BestType);
18820   }
18821   else if (NumNegativeBits) {
18822     // If there is a negative value, figure out the smallest integer type (of
18823     // int/long/longlong) that fits.
18824     // If it's packed, check also if it fits a char or a short.
18825     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18826       BestType = Context.SignedCharTy;
18827       BestWidth = CharWidth;
18828     } else if (Packed && NumNegativeBits <= ShortWidth &&
18829                NumPositiveBits < ShortWidth) {
18830       BestType = Context.ShortTy;
18831       BestWidth = ShortWidth;
18832     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18833       BestType = Context.IntTy;
18834       BestWidth = IntWidth;
18835     } else {
18836       BestWidth = Context.getTargetInfo().getLongWidth();
18837 
18838       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18839         BestType = Context.LongTy;
18840       } else {
18841         BestWidth = Context.getTargetInfo().getLongLongWidth();
18842 
18843         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18844           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18845         BestType = Context.LongLongTy;
18846       }
18847     }
18848     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18849   } else {
18850     // If there is no negative value, figure out the smallest type that fits
18851     // all of the enumerator values.
18852     // If it's packed, check also if it fits a char or a short.
18853     if (Packed && NumPositiveBits <= CharWidth) {
18854       BestType = Context.UnsignedCharTy;
18855       BestPromotionType = Context.IntTy;
18856       BestWidth = CharWidth;
18857     } else if (Packed && NumPositiveBits <= ShortWidth) {
18858       BestType = Context.UnsignedShortTy;
18859       BestPromotionType = Context.IntTy;
18860       BestWidth = ShortWidth;
18861     } else if (NumPositiveBits <= IntWidth) {
18862       BestType = Context.UnsignedIntTy;
18863       BestWidth = IntWidth;
18864       BestPromotionType
18865         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18866                            ? Context.UnsignedIntTy : Context.IntTy;
18867     } else if (NumPositiveBits <=
18868                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18869       BestType = Context.UnsignedLongTy;
18870       BestPromotionType
18871         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18872                            ? Context.UnsignedLongTy : Context.LongTy;
18873     } else {
18874       BestWidth = Context.getTargetInfo().getLongLongWidth();
18875       assert(NumPositiveBits <= BestWidth &&
18876              "How could an initializer get larger than ULL?");
18877       BestType = Context.UnsignedLongLongTy;
18878       BestPromotionType
18879         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18880                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18881     }
18882   }
18883 
18884   // Loop over all of the enumerator constants, changing their types to match
18885   // the type of the enum if needed.
18886   for (auto *D : Elements) {
18887     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18888     if (!ECD) continue;  // Already issued a diagnostic.
18889 
18890     // Standard C says the enumerators have int type, but we allow, as an
18891     // extension, the enumerators to be larger than int size.  If each
18892     // enumerator value fits in an int, type it as an int, otherwise type it the
18893     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18894     // that X has type 'int', not 'unsigned'.
18895 
18896     // Determine whether the value fits into an int.
18897     llvm::APSInt InitVal = ECD->getInitVal();
18898 
18899     // If it fits into an integer type, force it.  Otherwise force it to match
18900     // the enum decl type.
18901     QualType NewTy;
18902     unsigned NewWidth;
18903     bool NewSign;
18904     if (!getLangOpts().CPlusPlus &&
18905         !Enum->isFixed() &&
18906         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18907       NewTy = Context.IntTy;
18908       NewWidth = IntWidth;
18909       NewSign = true;
18910     } else if (ECD->getType() == BestType) {
18911       // Already the right type!
18912       if (getLangOpts().CPlusPlus)
18913         // C++ [dcl.enum]p4: Following the closing brace of an
18914         // enum-specifier, each enumerator has the type of its
18915         // enumeration.
18916         ECD->setType(EnumType);
18917       continue;
18918     } else {
18919       NewTy = BestType;
18920       NewWidth = BestWidth;
18921       NewSign = BestType->isSignedIntegerOrEnumerationType();
18922     }
18923 
18924     // Adjust the APSInt value.
18925     InitVal = InitVal.extOrTrunc(NewWidth);
18926     InitVal.setIsSigned(NewSign);
18927     ECD->setInitVal(InitVal);
18928 
18929     // Adjust the Expr initializer and type.
18930     if (ECD->getInitExpr() &&
18931         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18932       ECD->setInitExpr(ImplicitCastExpr::Create(
18933           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18934           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18935     if (getLangOpts().CPlusPlus)
18936       // C++ [dcl.enum]p4: Following the closing brace of an
18937       // enum-specifier, each enumerator has the type of its
18938       // enumeration.
18939       ECD->setType(EnumType);
18940     else
18941       ECD->setType(NewTy);
18942   }
18943 
18944   Enum->completeDefinition(BestType, BestPromotionType,
18945                            NumPositiveBits, NumNegativeBits);
18946 
18947   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18948 
18949   if (Enum->isClosedFlag()) {
18950     for (Decl *D : Elements) {
18951       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18952       if (!ECD) continue;  // Already issued a diagnostic.
18953 
18954       llvm::APSInt InitVal = ECD->getInitVal();
18955       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18956           !IsValueInFlagEnum(Enum, InitVal, true))
18957         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18958           << ECD << Enum;
18959     }
18960   }
18961 
18962   // Now that the enum type is defined, ensure it's not been underaligned.
18963   if (Enum->hasAttrs())
18964     CheckAlignasUnderalignment(Enum);
18965 }
18966 
18967 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18968                                   SourceLocation StartLoc,
18969                                   SourceLocation EndLoc) {
18970   StringLiteral *AsmString = cast<StringLiteral>(expr);
18971 
18972   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18973                                                    AsmString, StartLoc,
18974                                                    EndLoc);
18975   CurContext->addDecl(New);
18976   return New;
18977 }
18978 
18979 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18980                                       IdentifierInfo* AliasName,
18981                                       SourceLocation PragmaLoc,
18982                                       SourceLocation NameLoc,
18983                                       SourceLocation AliasNameLoc) {
18984   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18985                                          LookupOrdinaryName);
18986   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18987                            AttributeCommonInfo::AS_Pragma);
18988   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18989       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18990 
18991   // If a declaration that:
18992   // 1) declares a function or a variable
18993   // 2) has external linkage
18994   // already exists, add a label attribute to it.
18995   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18996     if (isDeclExternC(PrevDecl))
18997       PrevDecl->addAttr(Attr);
18998     else
18999       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19000           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19001   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19002   } else
19003     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19004 }
19005 
19006 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19007                              SourceLocation PragmaLoc,
19008                              SourceLocation NameLoc) {
19009   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19010 
19011   if (PrevDecl) {
19012     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19013   } else {
19014     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19015   }
19016 }
19017 
19018 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19019                                 IdentifierInfo* AliasName,
19020                                 SourceLocation PragmaLoc,
19021                                 SourceLocation NameLoc,
19022                                 SourceLocation AliasNameLoc) {
19023   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19024                                     LookupOrdinaryName);
19025   WeakInfo W = WeakInfo(Name, NameLoc);
19026 
19027   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19028     if (!PrevDecl->hasAttr<AliasAttr>())
19029       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19030         DeclApplyPragmaWeak(TUScope, ND, W);
19031   } else {
19032     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19033   }
19034 }
19035 
19036 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19037   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19038 }
19039 
19040 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19041                                                      bool Final) {
19042   assert(FD && "Expected non-null FunctionDecl");
19043 
19044   // SYCL functions can be template, so we check if they have appropriate
19045   // attribute prior to checking if it is a template.
19046   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19047     return FunctionEmissionStatus::Emitted;
19048 
19049   // Templates are emitted when they're instantiated.
19050   if (FD->isDependentContext())
19051     return FunctionEmissionStatus::TemplateDiscarded;
19052 
19053   // Check whether this function is an externally visible definition.
19054   auto IsEmittedForExternalSymbol = [this, FD]() {
19055     // We have to check the GVA linkage of the function's *definition* -- if we
19056     // only have a declaration, we don't know whether or not the function will
19057     // be emitted, because (say) the definition could include "inline".
19058     FunctionDecl *Def = FD->getDefinition();
19059 
19060     return Def && !isDiscardableGVALinkage(
19061                       getASTContext().GetGVALinkageForFunction(Def));
19062   };
19063 
19064   if (LangOpts.OpenMPIsDevice) {
19065     // In OpenMP device mode we will not emit host only functions, or functions
19066     // we don't need due to their linkage.
19067     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19068         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19069     // DevTy may be changed later by
19070     //  #pragma omp declare target to(*) device_type(*).
19071     // Therefore DevTy having no value does not imply host. The emission status
19072     // will be checked again at the end of compilation unit with Final = true.
19073     if (DevTy.hasValue())
19074       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19075         return FunctionEmissionStatus::OMPDiscarded;
19076     // If we have an explicit value for the device type, or we are in a target
19077     // declare context, we need to emit all extern and used symbols.
19078     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
19079       if (IsEmittedForExternalSymbol())
19080         return FunctionEmissionStatus::Emitted;
19081     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19082     // we'll omit it.
19083     if (Final)
19084       return FunctionEmissionStatus::OMPDiscarded;
19085   } else if (LangOpts.OpenMP > 45) {
19086     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19087     // function. In 5.0, no_host was introduced which might cause a function to
19088     // be ommitted.
19089     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19090         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19091     if (DevTy.hasValue())
19092       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19093         return FunctionEmissionStatus::OMPDiscarded;
19094   }
19095 
19096   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19097     return FunctionEmissionStatus::Emitted;
19098 
19099   if (LangOpts.CUDA) {
19100     // When compiling for device, host functions are never emitted.  Similarly,
19101     // when compiling for host, device and global functions are never emitted.
19102     // (Technically, we do emit a host-side stub for global functions, but this
19103     // doesn't count for our purposes here.)
19104     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19105     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19106       return FunctionEmissionStatus::CUDADiscarded;
19107     if (!LangOpts.CUDAIsDevice &&
19108         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19109       return FunctionEmissionStatus::CUDADiscarded;
19110 
19111     if (IsEmittedForExternalSymbol())
19112       return FunctionEmissionStatus::Emitted;
19113   }
19114 
19115   // Otherwise, the function is known-emitted if it's in our set of
19116   // known-emitted functions.
19117   return FunctionEmissionStatus::Unknown;
19118 }
19119 
19120 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19121   // Host-side references to a __global__ function refer to the stub, so the
19122   // function itself is never emitted and therefore should not be marked.
19123   // If we have host fn calls kernel fn calls host+device, the HD function
19124   // does not get instantiated on the host. We model this by omitting at the
19125   // call to the kernel from the callgraph. This ensures that, when compiling
19126   // for host, only HD functions actually called from the host get marked as
19127   // known-emitted.
19128   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19129          IdentifyCUDATarget(Callee) == CFT_Global;
19130 }
19131