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.
937       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
938         return NameClassification::NonType(D);
939     }
940 
941     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
942       // In C++20 onwards, this could be an ADL-only call to a function
943       // template, and we're required to assume that this is a template name.
944       //
945       // FIXME: Find a way to still do typo correction in this case.
946       TemplateName Template =
947           Context.getAssumedTemplateName(NameInfo.getName());
948       return NameClassification::UndeclaredTemplate(Template);
949     }
950 
951     // In C, we first see whether there is a tag type by the same name, in
952     // which case it's likely that the user just forgot to write "enum",
953     // "struct", or "union".
954     if (!getLangOpts().CPlusPlus && !SecondTry &&
955         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
956       break;
957     }
958 
959     // Perform typo correction to determine if there is another name that is
960     // close to this name.
961     if (!SecondTry && CCC) {
962       SecondTry = true;
963       if (TypoCorrection Corrected =
964               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
965                           &SS, *CCC, CTK_ErrorRecovery)) {
966         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
967         unsigned QualifiedDiag = diag::err_no_member_suggest;
968 
969         NamedDecl *FirstDecl = Corrected.getFoundDecl();
970         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
971         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
972             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
973           UnqualifiedDiag = diag::err_no_template_suggest;
974           QualifiedDiag = diag::err_no_member_template_suggest;
975         } else if (UnderlyingFirstDecl &&
976                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
977                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
978                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
979           UnqualifiedDiag = diag::err_unknown_typename_suggest;
980           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
981         }
982 
983         if (SS.isEmpty()) {
984           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
985         } else {// FIXME: is this even reachable? Test it.
986           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
987           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
988                                   Name->getName().equals(CorrectedStr);
989           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
990                                     << Name << computeDeclContext(SS, false)
991                                     << DroppedSpecifier << SS.getRange());
992         }
993 
994         // Update the name, so that the caller has the new name.
995         Name = Corrected.getCorrectionAsIdentifierInfo();
996 
997         // Typo correction corrected to a keyword.
998         if (Corrected.isKeyword())
999           return Name;
1000 
1001         // Also update the LookupResult...
1002         // FIXME: This should probably go away at some point
1003         Result.clear();
1004         Result.setLookupName(Corrected.getCorrection());
1005         if (FirstDecl)
1006           Result.addDecl(FirstDecl);
1007 
1008         // If we found an Objective-C instance variable, let
1009         // LookupInObjCMethod build the appropriate expression to
1010         // reference the ivar.
1011         // FIXME: This is a gross hack.
1012         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1013           DeclResult R =
1014               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1015           if (R.isInvalid())
1016             return NameClassification::Error();
1017           if (R.isUsable())
1018             return NameClassification::NonType(Ivar);
1019         }
1020 
1021         goto Corrected;
1022       }
1023     }
1024 
1025     // We failed to correct; just fall through and let the parser deal with it.
1026     Result.suppressDiagnostics();
1027     return NameClassification::Unknown();
1028 
1029   case LookupResult::NotFoundInCurrentInstantiation: {
1030     // We performed name lookup into the current instantiation, and there were
1031     // dependent bases, so we treat this result the same way as any other
1032     // dependent nested-name-specifier.
1033 
1034     // C++ [temp.res]p2:
1035     //   A name used in a template declaration or definition and that is
1036     //   dependent on a template-parameter is assumed not to name a type
1037     //   unless the applicable name lookup finds a type name or the name is
1038     //   qualified by the keyword typename.
1039     //
1040     // FIXME: If the next token is '<', we might want to ask the parser to
1041     // perform some heroics to see if we actually have a
1042     // template-argument-list, which would indicate a missing 'template'
1043     // keyword here.
1044     return NameClassification::DependentNonType();
1045   }
1046 
1047   case LookupResult::Found:
1048   case LookupResult::FoundOverloaded:
1049   case LookupResult::FoundUnresolvedValue:
1050     break;
1051 
1052   case LookupResult::Ambiguous:
1053     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1054         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1055                                       /*AllowDependent=*/false)) {
1056       // C++ [temp.local]p3:
1057       //   A lookup that finds an injected-class-name (10.2) can result in an
1058       //   ambiguity in certain cases (for example, if it is found in more than
1059       //   one base class). If all of the injected-class-names that are found
1060       //   refer to specializations of the same class template, and if the name
1061       //   is followed by a template-argument-list, the reference refers to the
1062       //   class template itself and not a specialization thereof, and is not
1063       //   ambiguous.
1064       //
1065       // This filtering can make an ambiguous result into an unambiguous one,
1066       // so try again after filtering out template names.
1067       FilterAcceptableTemplateNames(Result);
1068       if (!Result.isAmbiguous()) {
1069         IsFilteredTemplateName = true;
1070         break;
1071       }
1072     }
1073 
1074     // Diagnose the ambiguity and return an error.
1075     return NameClassification::Error();
1076   }
1077 
1078   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1079       (IsFilteredTemplateName ||
1080        hasAnyAcceptableTemplateNames(
1081            Result, /*AllowFunctionTemplates=*/true,
1082            /*AllowDependent=*/false,
1083            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1084                getLangOpts().CPlusPlus20))) {
1085     // C++ [temp.names]p3:
1086     //   After name lookup (3.4) finds that a name is a template-name or that
1087     //   an operator-function-id or a literal- operator-id refers to a set of
1088     //   overloaded functions any member of which is a function template if
1089     //   this is followed by a <, the < is always taken as the delimiter of a
1090     //   template-argument-list and never as the less-than operator.
1091     // C++2a [temp.names]p2:
1092     //   A name is also considered to refer to a template if it is an
1093     //   unqualified-id followed by a < and name lookup finds either one
1094     //   or more functions or finds nothing.
1095     if (!IsFilteredTemplateName)
1096       FilterAcceptableTemplateNames(Result);
1097 
1098     bool IsFunctionTemplate;
1099     bool IsVarTemplate;
1100     TemplateName Template;
1101     if (Result.end() - Result.begin() > 1) {
1102       IsFunctionTemplate = true;
1103       Template = Context.getOverloadedTemplateName(Result.begin(),
1104                                                    Result.end());
1105     } else if (!Result.empty()) {
1106       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1107           *Result.begin(), /*AllowFunctionTemplates=*/true,
1108           /*AllowDependent=*/false));
1109       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1110       IsVarTemplate = isa<VarTemplateDecl>(TD);
1111 
1112       UsingShadowDecl *FoundUsingShadow =
1113           dyn_cast<UsingShadowDecl>(*Result.begin());
1114 
1115       if (SS.isNotEmpty()) {
1116         // FIXME: support using shadow-declaration in qualified template name.
1117         Template =
1118             Context.getQualifiedTemplateName(SS.getScopeRep(),
1119                                              /*TemplateKeyword=*/false, TD);
1120       } else {
1121         assert(!FoundUsingShadow ||
1122                TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1123         Template = FoundUsingShadow ? TemplateName(FoundUsingShadow)
1124                                     : TemplateName(TD);
1125       }
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, diag::ext_implicit_lib_function_decl)
2306         << Context.BuiltinInfo.getName(ID) << R;
2307     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2308       Diag(Loc, diag::note_include_header_or_declare)
2309           << Header << Context.BuiltinInfo.getName(ID);
2310   }
2311 
2312   if (R.isNull())
2313     return nullptr;
2314 
2315   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2316   RegisterLocallyScopedExternCDecl(New, S);
2317 
2318   // TUScope is the translation-unit scope to insert this function into.
2319   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2320   // relate Scopes to DeclContexts, and probably eliminate CurContext
2321   // entirely, but we're not there yet.
2322   DeclContext *SavedContext = CurContext;
2323   CurContext = New->getDeclContext();
2324   PushOnScopeChains(New, TUScope);
2325   CurContext = SavedContext;
2326   return New;
2327 }
2328 
2329 /// Typedef declarations don't have linkage, but they still denote the same
2330 /// entity if their types are the same.
2331 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2332 /// isSameEntity.
2333 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2334                                                      TypedefNameDecl *Decl,
2335                                                      LookupResult &Previous) {
2336   // This is only interesting when modules are enabled.
2337   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2338     return;
2339 
2340   // Empty sets are uninteresting.
2341   if (Previous.empty())
2342     return;
2343 
2344   LookupResult::Filter Filter = Previous.makeFilter();
2345   while (Filter.hasNext()) {
2346     NamedDecl *Old = Filter.next();
2347 
2348     // Non-hidden declarations are never ignored.
2349     if (S.isVisible(Old))
2350       continue;
2351 
2352     // Declarations of the same entity are not ignored, even if they have
2353     // different linkages.
2354     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2355       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2356                                 Decl->getUnderlyingType()))
2357         continue;
2358 
2359       // If both declarations give a tag declaration a typedef name for linkage
2360       // purposes, then they declare the same entity.
2361       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2362           Decl->getAnonDeclWithTypedefName())
2363         continue;
2364     }
2365 
2366     Filter.erase();
2367   }
2368 
2369   Filter.done();
2370 }
2371 
2372 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2373   QualType OldType;
2374   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2375     OldType = OldTypedef->getUnderlyingType();
2376   else
2377     OldType = Context.getTypeDeclType(Old);
2378   QualType NewType = New->getUnderlyingType();
2379 
2380   if (NewType->isVariablyModifiedType()) {
2381     // Must not redefine a typedef with a variably-modified type.
2382     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2383     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2384       << Kind << NewType;
2385     if (Old->getLocation().isValid())
2386       notePreviousDefinition(Old, New->getLocation());
2387     New->setInvalidDecl();
2388     return true;
2389   }
2390 
2391   if (OldType != NewType &&
2392       !OldType->isDependentType() &&
2393       !NewType->isDependentType() &&
2394       !Context.hasSameType(OldType, NewType)) {
2395     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2396     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2397       << Kind << NewType << OldType;
2398     if (Old->getLocation().isValid())
2399       notePreviousDefinition(Old, New->getLocation());
2400     New->setInvalidDecl();
2401     return true;
2402   }
2403   return false;
2404 }
2405 
2406 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2407 /// same name and scope as a previous declaration 'Old'.  Figure out
2408 /// how to resolve this situation, merging decls or emitting
2409 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2410 ///
2411 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2412                                 LookupResult &OldDecls) {
2413   // If the new decl is known invalid already, don't bother doing any
2414   // merging checks.
2415   if (New->isInvalidDecl()) return;
2416 
2417   // Allow multiple definitions for ObjC built-in typedefs.
2418   // FIXME: Verify the underlying types are equivalent!
2419   if (getLangOpts().ObjC) {
2420     const IdentifierInfo *TypeID = New->getIdentifier();
2421     switch (TypeID->getLength()) {
2422     default: break;
2423     case 2:
2424       {
2425         if (!TypeID->isStr("id"))
2426           break;
2427         QualType T = New->getUnderlyingType();
2428         if (!T->isPointerType())
2429           break;
2430         if (!T->isVoidPointerType()) {
2431           QualType PT = T->castAs<PointerType>()->getPointeeType();
2432           if (!PT->isStructureType())
2433             break;
2434         }
2435         Context.setObjCIdRedefinitionType(T);
2436         // Install the built-in type for 'id', ignoring the current definition.
2437         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2438         return;
2439       }
2440     case 5:
2441       if (!TypeID->isStr("Class"))
2442         break;
2443       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2444       // Install the built-in type for 'Class', ignoring the current definition.
2445       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2446       return;
2447     case 3:
2448       if (!TypeID->isStr("SEL"))
2449         break;
2450       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2451       // Install the built-in type for 'SEL', ignoring the current definition.
2452       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2453       return;
2454     }
2455     // Fall through - the typedef name was not a builtin type.
2456   }
2457 
2458   // Verify the old decl was also a type.
2459   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2460   if (!Old) {
2461     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2462       << New->getDeclName();
2463 
2464     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2465     if (OldD->getLocation().isValid())
2466       notePreviousDefinition(OldD, New->getLocation());
2467 
2468     return New->setInvalidDecl();
2469   }
2470 
2471   // If the old declaration is invalid, just give up here.
2472   if (Old->isInvalidDecl())
2473     return New->setInvalidDecl();
2474 
2475   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2476     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2477     auto *NewTag = New->getAnonDeclWithTypedefName();
2478     NamedDecl *Hidden = nullptr;
2479     if (OldTag && NewTag &&
2480         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2481         !hasVisibleDefinition(OldTag, &Hidden)) {
2482       // There is a definition of this tag, but it is not visible. Use it
2483       // instead of our tag.
2484       New->setTypeForDecl(OldTD->getTypeForDecl());
2485       if (OldTD->isModed())
2486         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2487                                     OldTD->getUnderlyingType());
2488       else
2489         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2490 
2491       // Make the old tag definition visible.
2492       makeMergedDefinitionVisible(Hidden);
2493 
2494       // If this was an unscoped enumeration, yank all of its enumerators
2495       // out of the scope.
2496       if (isa<EnumDecl>(NewTag)) {
2497         Scope *EnumScope = getNonFieldDeclScope(S);
2498         for (auto *D : NewTag->decls()) {
2499           auto *ED = cast<EnumConstantDecl>(D);
2500           assert(EnumScope->isDeclScope(ED));
2501           EnumScope->RemoveDecl(ED);
2502           IdResolver.RemoveDecl(ED);
2503           ED->getLexicalDeclContext()->removeDecl(ED);
2504         }
2505       }
2506     }
2507   }
2508 
2509   // If the typedef types are not identical, reject them in all languages and
2510   // with any extensions enabled.
2511   if (isIncompatibleTypedef(Old, New))
2512     return;
2513 
2514   // The types match.  Link up the redeclaration chain and merge attributes if
2515   // the old declaration was a typedef.
2516   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2517     New->setPreviousDecl(Typedef);
2518     mergeDeclAttributes(New, Old);
2519   }
2520 
2521   if (getLangOpts().MicrosoftExt)
2522     return;
2523 
2524   if (getLangOpts().CPlusPlus) {
2525     // C++ [dcl.typedef]p2:
2526     //   In a given non-class scope, a typedef specifier can be used to
2527     //   redefine the name of any type declared in that scope to refer
2528     //   to the type to which it already refers.
2529     if (!isa<CXXRecordDecl>(CurContext))
2530       return;
2531 
2532     // C++0x [dcl.typedef]p4:
2533     //   In a given class scope, a typedef specifier can be used to redefine
2534     //   any class-name declared in that scope that is not also a typedef-name
2535     //   to refer to the type to which it already refers.
2536     //
2537     // This wording came in via DR424, which was a correction to the
2538     // wording in DR56, which accidentally banned code like:
2539     //
2540     //   struct S {
2541     //     typedef struct A { } A;
2542     //   };
2543     //
2544     // in the C++03 standard. We implement the C++0x semantics, which
2545     // allow the above but disallow
2546     //
2547     //   struct S {
2548     //     typedef int I;
2549     //     typedef int I;
2550     //   };
2551     //
2552     // since that was the intent of DR56.
2553     if (!isa<TypedefNameDecl>(Old))
2554       return;
2555 
2556     Diag(New->getLocation(), diag::err_redefinition)
2557       << New->getDeclName();
2558     notePreviousDefinition(Old, New->getLocation());
2559     return New->setInvalidDecl();
2560   }
2561 
2562   // Modules always permit redefinition of typedefs, as does C11.
2563   if (getLangOpts().Modules || getLangOpts().C11)
2564     return;
2565 
2566   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2567   // is normally mapped to an error, but can be controlled with
2568   // -Wtypedef-redefinition.  If either the original or the redefinition is
2569   // in a system header, don't emit this for compatibility with GCC.
2570   if (getDiagnostics().getSuppressSystemWarnings() &&
2571       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2572       (Old->isImplicit() ||
2573        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2574        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2575     return;
2576 
2577   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2578     << New->getDeclName();
2579   notePreviousDefinition(Old, New->getLocation());
2580 }
2581 
2582 /// DeclhasAttr - returns true if decl Declaration already has the target
2583 /// attribute.
2584 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2585   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2586   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2587   for (const auto *i : D->attrs())
2588     if (i->getKind() == A->getKind()) {
2589       if (Ann) {
2590         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2591           return true;
2592         continue;
2593       }
2594       // FIXME: Don't hardcode this check
2595       if (OA && isa<OwnershipAttr>(i))
2596         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2597       return true;
2598     }
2599 
2600   return false;
2601 }
2602 
2603 static bool isAttributeTargetADefinition(Decl *D) {
2604   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2605     return VD->isThisDeclarationADefinition();
2606   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2607     return TD->isCompleteDefinition() || TD->isBeingDefined();
2608   return true;
2609 }
2610 
2611 /// Merge alignment attributes from \p Old to \p New, taking into account the
2612 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2613 ///
2614 /// \return \c true if any attributes were added to \p New.
2615 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2616   // Look for alignas attributes on Old, and pick out whichever attribute
2617   // specifies the strictest alignment requirement.
2618   AlignedAttr *OldAlignasAttr = nullptr;
2619   AlignedAttr *OldStrictestAlignAttr = nullptr;
2620   unsigned OldAlign = 0;
2621   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2622     // FIXME: We have no way of representing inherited dependent alignments
2623     // in a case like:
2624     //   template<int A, int B> struct alignas(A) X;
2625     //   template<int A, int B> struct alignas(B) X {};
2626     // For now, we just ignore any alignas attributes which are not on the
2627     // definition in such a case.
2628     if (I->isAlignmentDependent())
2629       return false;
2630 
2631     if (I->isAlignas())
2632       OldAlignasAttr = I;
2633 
2634     unsigned Align = I->getAlignment(S.Context);
2635     if (Align > OldAlign) {
2636       OldAlign = Align;
2637       OldStrictestAlignAttr = I;
2638     }
2639   }
2640 
2641   // Look for alignas attributes on New.
2642   AlignedAttr *NewAlignasAttr = nullptr;
2643   unsigned NewAlign = 0;
2644   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2645     if (I->isAlignmentDependent())
2646       return false;
2647 
2648     if (I->isAlignas())
2649       NewAlignasAttr = I;
2650 
2651     unsigned Align = I->getAlignment(S.Context);
2652     if (Align > NewAlign)
2653       NewAlign = Align;
2654   }
2655 
2656   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2657     // Both declarations have 'alignas' attributes. We require them to match.
2658     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2659     // fall short. (If two declarations both have alignas, they must both match
2660     // every definition, and so must match each other if there is a definition.)
2661 
2662     // If either declaration only contains 'alignas(0)' specifiers, then it
2663     // specifies the natural alignment for the type.
2664     if (OldAlign == 0 || NewAlign == 0) {
2665       QualType Ty;
2666       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2667         Ty = VD->getType();
2668       else
2669         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2670 
2671       if (OldAlign == 0)
2672         OldAlign = S.Context.getTypeAlign(Ty);
2673       if (NewAlign == 0)
2674         NewAlign = S.Context.getTypeAlign(Ty);
2675     }
2676 
2677     if (OldAlign != NewAlign) {
2678       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2679         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2680         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2681       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2682     }
2683   }
2684 
2685   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2686     // C++11 [dcl.align]p6:
2687     //   if any declaration of an entity has an alignment-specifier,
2688     //   every defining declaration of that entity shall specify an
2689     //   equivalent alignment.
2690     // C11 6.7.5/7:
2691     //   If the definition of an object does not have an alignment
2692     //   specifier, any other declaration of that object shall also
2693     //   have no alignment specifier.
2694     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2695       << OldAlignasAttr;
2696     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2697       << OldAlignasAttr;
2698   }
2699 
2700   bool AnyAdded = false;
2701 
2702   // Ensure we have an attribute representing the strictest alignment.
2703   if (OldAlign > NewAlign) {
2704     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2705     Clone->setInherited(true);
2706     New->addAttr(Clone);
2707     AnyAdded = true;
2708   }
2709 
2710   // Ensure we have an alignas attribute if the old declaration had one.
2711   if (OldAlignasAttr && !NewAlignasAttr &&
2712       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2713     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2714     Clone->setInherited(true);
2715     New->addAttr(Clone);
2716     AnyAdded = true;
2717   }
2718 
2719   return AnyAdded;
2720 }
2721 
2722 #define WANT_DECL_MERGE_LOGIC
2723 #include "clang/Sema/AttrParsedAttrImpl.inc"
2724 #undef WANT_DECL_MERGE_LOGIC
2725 
2726 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2727                                const InheritableAttr *Attr,
2728                                Sema::AvailabilityMergeKind AMK) {
2729   // Diagnose any mutual exclusions between the attribute that we want to add
2730   // and attributes that already exist on the declaration.
2731   if (!DiagnoseMutualExclusions(S, D, Attr))
2732     return false;
2733 
2734   // This function copies an attribute Attr from a previous declaration to the
2735   // new declaration D if the new declaration doesn't itself have that attribute
2736   // yet or if that attribute allows duplicates.
2737   // If you're adding a new attribute that requires logic different from
2738   // "use explicit attribute on decl if present, else use attribute from
2739   // previous decl", for example if the attribute needs to be consistent
2740   // between redeclarations, you need to call a custom merge function here.
2741   InheritableAttr *NewAttr = nullptr;
2742   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2743     NewAttr = S.mergeAvailabilityAttr(
2744         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2745         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2746         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2747         AA->getPriority());
2748   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2749     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2750   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2751     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2752   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2753     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2754   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2755     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2756   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2757     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2758   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2759     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2760                                 FA->getFirstArg());
2761   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2762     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2763   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2764     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2765   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2766     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2767                                        IA->getInheritanceModel());
2768   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2769     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2770                                       &S.Context.Idents.get(AA->getSpelling()));
2771   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2772            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2773             isa<CUDAGlobalAttr>(Attr))) {
2774     // CUDA target attributes are part of function signature for
2775     // overloading purposes and must not be merged.
2776     return false;
2777   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2778     NewAttr = S.mergeMinSizeAttr(D, *MA);
2779   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2780     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2781   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2782     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2783   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2784     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2785   else if (isa<AlignedAttr>(Attr))
2786     // AlignedAttrs are handled separately, because we need to handle all
2787     // such attributes on a declaration at the same time.
2788     NewAttr = nullptr;
2789   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2790            (AMK == Sema::AMK_Override ||
2791             AMK == Sema::AMK_ProtocolImplementation ||
2792             AMK == Sema::AMK_OptionalProtocolImplementation))
2793     NewAttr = nullptr;
2794   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2795     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2796   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2797     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2798   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2799     NewAttr = S.mergeImportNameAttr(D, *INA);
2800   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2801     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2802   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2803     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2804   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2805     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2806   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2807     NewAttr =
2808         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2809   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2810     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2811 
2812   if (NewAttr) {
2813     NewAttr->setInherited(true);
2814     D->addAttr(NewAttr);
2815     if (isa<MSInheritanceAttr>(NewAttr))
2816       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2817     return true;
2818   }
2819 
2820   return false;
2821 }
2822 
2823 static const NamedDecl *getDefinition(const Decl *D) {
2824   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2825     return TD->getDefinition();
2826   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2827     const VarDecl *Def = VD->getDefinition();
2828     if (Def)
2829       return Def;
2830     return VD->getActingDefinition();
2831   }
2832   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2833     const FunctionDecl *Def = nullptr;
2834     if (FD->isDefined(Def, true))
2835       return Def;
2836   }
2837   return nullptr;
2838 }
2839 
2840 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2841   for (const auto *Attribute : D->attrs())
2842     if (Attribute->getKind() == Kind)
2843       return true;
2844   return false;
2845 }
2846 
2847 /// checkNewAttributesAfterDef - If we already have a definition, check that
2848 /// there are no new attributes in this declaration.
2849 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2850   if (!New->hasAttrs())
2851     return;
2852 
2853   const NamedDecl *Def = getDefinition(Old);
2854   if (!Def || Def == New)
2855     return;
2856 
2857   AttrVec &NewAttributes = New->getAttrs();
2858   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2859     const Attr *NewAttribute = NewAttributes[I];
2860 
2861     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2862       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2863         Sema::SkipBodyInfo SkipBody;
2864         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2865 
2866         // If we're skipping this definition, drop the "alias" attribute.
2867         if (SkipBody.ShouldSkip) {
2868           NewAttributes.erase(NewAttributes.begin() + I);
2869           --E;
2870           continue;
2871         }
2872       } else {
2873         VarDecl *VD = cast<VarDecl>(New);
2874         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2875                                 VarDecl::TentativeDefinition
2876                             ? diag::err_alias_after_tentative
2877                             : diag::err_redefinition;
2878         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2879         if (Diag == diag::err_redefinition)
2880           S.notePreviousDefinition(Def, VD->getLocation());
2881         else
2882           S.Diag(Def->getLocation(), diag::note_previous_definition);
2883         VD->setInvalidDecl();
2884       }
2885       ++I;
2886       continue;
2887     }
2888 
2889     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2890       // Tentative definitions are only interesting for the alias check above.
2891       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2892         ++I;
2893         continue;
2894       }
2895     }
2896 
2897     if (hasAttribute(Def, NewAttribute->getKind())) {
2898       ++I;
2899       continue; // regular attr merging will take care of validating this.
2900     }
2901 
2902     if (isa<C11NoReturnAttr>(NewAttribute)) {
2903       // C's _Noreturn is allowed to be added to a function after it is defined.
2904       ++I;
2905       continue;
2906     } else if (isa<UuidAttr>(NewAttribute)) {
2907       // msvc will allow a subsequent definition to add an uuid to a class
2908       ++I;
2909       continue;
2910     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2911       if (AA->isAlignas()) {
2912         // C++11 [dcl.align]p6:
2913         //   if any declaration of an entity has an alignment-specifier,
2914         //   every defining declaration of that entity shall specify an
2915         //   equivalent alignment.
2916         // C11 6.7.5/7:
2917         //   If the definition of an object does not have an alignment
2918         //   specifier, any other declaration of that object shall also
2919         //   have no alignment specifier.
2920         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2921           << AA;
2922         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2923           << AA;
2924         NewAttributes.erase(NewAttributes.begin() + I);
2925         --E;
2926         continue;
2927       }
2928     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2929       // If there is a C definition followed by a redeclaration with this
2930       // attribute then there are two different definitions. In C++, prefer the
2931       // standard diagnostics.
2932       if (!S.getLangOpts().CPlusPlus) {
2933         S.Diag(NewAttribute->getLocation(),
2934                diag::err_loader_uninitialized_redeclaration);
2935         S.Diag(Def->getLocation(), diag::note_previous_definition);
2936         NewAttributes.erase(NewAttributes.begin() + I);
2937         --E;
2938         continue;
2939       }
2940     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2941                cast<VarDecl>(New)->isInline() &&
2942                !cast<VarDecl>(New)->isInlineSpecified()) {
2943       // Don't warn about applying selectany to implicitly inline variables.
2944       // Older compilers and language modes would require the use of selectany
2945       // to make such variables inline, and it would have no effect if we
2946       // honored it.
2947       ++I;
2948       continue;
2949     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2950       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2951       // declarations after defintions.
2952       ++I;
2953       continue;
2954     }
2955 
2956     S.Diag(NewAttribute->getLocation(),
2957            diag::warn_attribute_precede_definition);
2958     S.Diag(Def->getLocation(), diag::note_previous_definition);
2959     NewAttributes.erase(NewAttributes.begin() + I);
2960     --E;
2961   }
2962 }
2963 
2964 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2965                                      const ConstInitAttr *CIAttr,
2966                                      bool AttrBeforeInit) {
2967   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2968 
2969   // Figure out a good way to write this specifier on the old declaration.
2970   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2971   // enough of the attribute list spelling information to extract that without
2972   // heroics.
2973   std::string SuitableSpelling;
2974   if (S.getLangOpts().CPlusPlus20)
2975     SuitableSpelling = std::string(
2976         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2977   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2978     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2979         InsertLoc, {tok::l_square, tok::l_square,
2980                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2981                     S.PP.getIdentifierInfo("require_constant_initialization"),
2982                     tok::r_square, tok::r_square}));
2983   if (SuitableSpelling.empty())
2984     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2985         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2986                     S.PP.getIdentifierInfo("require_constant_initialization"),
2987                     tok::r_paren, tok::r_paren}));
2988   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2989     SuitableSpelling = "constinit";
2990   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2991     SuitableSpelling = "[[clang::require_constant_initialization]]";
2992   if (SuitableSpelling.empty())
2993     SuitableSpelling = "__attribute__((require_constant_initialization))";
2994   SuitableSpelling += " ";
2995 
2996   if (AttrBeforeInit) {
2997     // extern constinit int a;
2998     // int a = 0; // error (missing 'constinit'), accepted as extension
2999     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3000     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3001         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3002     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3003   } else {
3004     // int a = 0;
3005     // constinit extern int a; // error (missing 'constinit')
3006     S.Diag(CIAttr->getLocation(),
3007            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3008                                  : diag::warn_require_const_init_added_too_late)
3009         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3010     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3011         << CIAttr->isConstinit()
3012         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3013   }
3014 }
3015 
3016 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3017 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3018                                AvailabilityMergeKind AMK) {
3019   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3020     UsedAttr *NewAttr = OldAttr->clone(Context);
3021     NewAttr->setInherited(true);
3022     New->addAttr(NewAttr);
3023   }
3024   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3025     RetainAttr *NewAttr = OldAttr->clone(Context);
3026     NewAttr->setInherited(true);
3027     New->addAttr(NewAttr);
3028   }
3029 
3030   if (!Old->hasAttrs() && !New->hasAttrs())
3031     return;
3032 
3033   // [dcl.constinit]p1:
3034   //   If the [constinit] specifier is applied to any declaration of a
3035   //   variable, it shall be applied to the initializing declaration.
3036   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3037   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3038   if (bool(OldConstInit) != bool(NewConstInit)) {
3039     const auto *OldVD = cast<VarDecl>(Old);
3040     auto *NewVD = cast<VarDecl>(New);
3041 
3042     // Find the initializing declaration. Note that we might not have linked
3043     // the new declaration into the redeclaration chain yet.
3044     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3045     if (!InitDecl &&
3046         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3047       InitDecl = NewVD;
3048 
3049     if (InitDecl == NewVD) {
3050       // This is the initializing declaration. If it would inherit 'constinit',
3051       // that's ill-formed. (Note that we do not apply this to the attribute
3052       // form).
3053       if (OldConstInit && OldConstInit->isConstinit())
3054         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3055                                  /*AttrBeforeInit=*/true);
3056     } else if (NewConstInit) {
3057       // This is the first time we've been told that this declaration should
3058       // have a constant initializer. If we already saw the initializing
3059       // declaration, this is too late.
3060       if (InitDecl && InitDecl != NewVD) {
3061         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3062                                  /*AttrBeforeInit=*/false);
3063         NewVD->dropAttr<ConstInitAttr>();
3064       }
3065     }
3066   }
3067 
3068   // Attributes declared post-definition are currently ignored.
3069   checkNewAttributesAfterDef(*this, New, Old);
3070 
3071   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3072     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3073       if (!OldA->isEquivalent(NewA)) {
3074         // This redeclaration changes __asm__ label.
3075         Diag(New->getLocation(), diag::err_different_asm_label);
3076         Diag(OldA->getLocation(), diag::note_previous_declaration);
3077       }
3078     } else if (Old->isUsed()) {
3079       // This redeclaration adds an __asm__ label to a declaration that has
3080       // already been ODR-used.
3081       Diag(New->getLocation(), diag::err_late_asm_label_name)
3082         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3083     }
3084   }
3085 
3086   // Re-declaration cannot add abi_tag's.
3087   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3088     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3089       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3090         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3091           Diag(NewAbiTagAttr->getLocation(),
3092                diag::err_new_abi_tag_on_redeclaration)
3093               << NewTag;
3094           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3095         }
3096       }
3097     } else {
3098       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3099       Diag(Old->getLocation(), diag::note_previous_declaration);
3100     }
3101   }
3102 
3103   // This redeclaration adds a section attribute.
3104   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3105     if (auto *VD = dyn_cast<VarDecl>(New)) {
3106       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3107         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3108         Diag(Old->getLocation(), diag::note_previous_declaration);
3109       }
3110     }
3111   }
3112 
3113   // Redeclaration adds code-seg attribute.
3114   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3115   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3116       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3117     Diag(New->getLocation(), diag::warn_mismatched_section)
3118          << 0 /*codeseg*/;
3119     Diag(Old->getLocation(), diag::note_previous_declaration);
3120   }
3121 
3122   if (!Old->hasAttrs())
3123     return;
3124 
3125   bool foundAny = New->hasAttrs();
3126 
3127   // Ensure that any moving of objects within the allocated map is done before
3128   // we process them.
3129   if (!foundAny) New->setAttrs(AttrVec());
3130 
3131   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3132     // Ignore deprecated/unavailable/availability attributes if requested.
3133     AvailabilityMergeKind LocalAMK = AMK_None;
3134     if (isa<DeprecatedAttr>(I) ||
3135         isa<UnavailableAttr>(I) ||
3136         isa<AvailabilityAttr>(I)) {
3137       switch (AMK) {
3138       case AMK_None:
3139         continue;
3140 
3141       case AMK_Redeclaration:
3142       case AMK_Override:
3143       case AMK_ProtocolImplementation:
3144       case AMK_OptionalProtocolImplementation:
3145         LocalAMK = AMK;
3146         break;
3147       }
3148     }
3149 
3150     // Already handled.
3151     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3152       continue;
3153 
3154     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3155       foundAny = true;
3156   }
3157 
3158   if (mergeAlignedAttrs(*this, New, Old))
3159     foundAny = true;
3160 
3161   if (!foundAny) New->dropAttrs();
3162 }
3163 
3164 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3165 /// to the new one.
3166 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3167                                      const ParmVarDecl *oldDecl,
3168                                      Sema &S) {
3169   // C++11 [dcl.attr.depend]p2:
3170   //   The first declaration of a function shall specify the
3171   //   carries_dependency attribute for its declarator-id if any declaration
3172   //   of the function specifies the carries_dependency attribute.
3173   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3174   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3175     S.Diag(CDA->getLocation(),
3176            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3177     // Find the first declaration of the parameter.
3178     // FIXME: Should we build redeclaration chains for function parameters?
3179     const FunctionDecl *FirstFD =
3180       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3181     const ParmVarDecl *FirstVD =
3182       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3183     S.Diag(FirstVD->getLocation(),
3184            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3185   }
3186 
3187   if (!oldDecl->hasAttrs())
3188     return;
3189 
3190   bool foundAny = newDecl->hasAttrs();
3191 
3192   // Ensure that any moving of objects within the allocated map is
3193   // done before we process them.
3194   if (!foundAny) newDecl->setAttrs(AttrVec());
3195 
3196   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3197     if (!DeclHasAttr(newDecl, I)) {
3198       InheritableAttr *newAttr =
3199         cast<InheritableParamAttr>(I->clone(S.Context));
3200       newAttr->setInherited(true);
3201       newDecl->addAttr(newAttr);
3202       foundAny = true;
3203     }
3204   }
3205 
3206   if (!foundAny) newDecl->dropAttrs();
3207 }
3208 
3209 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3210                                 const ParmVarDecl *OldParam,
3211                                 Sema &S) {
3212   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3213     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3214       if (*Oldnullability != *Newnullability) {
3215         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3216           << DiagNullabilityKind(
3217                *Newnullability,
3218                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3219                 != 0))
3220           << DiagNullabilityKind(
3221                *Oldnullability,
3222                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3223                 != 0));
3224         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3225       }
3226     } else {
3227       QualType NewT = NewParam->getType();
3228       NewT = S.Context.getAttributedType(
3229                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3230                          NewT, NewT);
3231       NewParam->setType(NewT);
3232     }
3233   }
3234 }
3235 
3236 namespace {
3237 
3238 /// Used in MergeFunctionDecl to keep track of function parameters in
3239 /// C.
3240 struct GNUCompatibleParamWarning {
3241   ParmVarDecl *OldParm;
3242   ParmVarDecl *NewParm;
3243   QualType PromotedType;
3244 };
3245 
3246 } // end anonymous namespace
3247 
3248 // Determine whether the previous declaration was a definition, implicit
3249 // declaration, or a declaration.
3250 template <typename T>
3251 static std::pair<diag::kind, SourceLocation>
3252 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3253   diag::kind PrevDiag;
3254   SourceLocation OldLocation = Old->getLocation();
3255   if (Old->isThisDeclarationADefinition())
3256     PrevDiag = diag::note_previous_definition;
3257   else if (Old->isImplicit()) {
3258     PrevDiag = diag::note_previous_implicit_declaration;
3259     if (OldLocation.isInvalid())
3260       OldLocation = New->getLocation();
3261   } else
3262     PrevDiag = diag::note_previous_declaration;
3263   return std::make_pair(PrevDiag, OldLocation);
3264 }
3265 
3266 /// canRedefineFunction - checks if a function can be redefined. Currently,
3267 /// only extern inline functions can be redefined, and even then only in
3268 /// GNU89 mode.
3269 static bool canRedefineFunction(const FunctionDecl *FD,
3270                                 const LangOptions& LangOpts) {
3271   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3272           !LangOpts.CPlusPlus &&
3273           FD->isInlineSpecified() &&
3274           FD->getStorageClass() == SC_Extern);
3275 }
3276 
3277 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3278   const AttributedType *AT = T->getAs<AttributedType>();
3279   while (AT && !AT->isCallingConv())
3280     AT = AT->getModifiedType()->getAs<AttributedType>();
3281   return AT;
3282 }
3283 
3284 template <typename T>
3285 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3286   const DeclContext *DC = Old->getDeclContext();
3287   if (DC->isRecord())
3288     return false;
3289 
3290   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3291   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3292     return true;
3293   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3294     return true;
3295   return false;
3296 }
3297 
3298 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3299 static bool isExternC(VarTemplateDecl *) { return false; }
3300 static bool isExternC(FunctionTemplateDecl *) { return false; }
3301 
3302 /// Check whether a redeclaration of an entity introduced by a
3303 /// using-declaration is valid, given that we know it's not an overload
3304 /// (nor a hidden tag declaration).
3305 template<typename ExpectedDecl>
3306 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3307                                    ExpectedDecl *New) {
3308   // C++11 [basic.scope.declarative]p4:
3309   //   Given a set of declarations in a single declarative region, each of
3310   //   which specifies the same unqualified name,
3311   //   -- they shall all refer to the same entity, or all refer to functions
3312   //      and function templates; or
3313   //   -- exactly one declaration shall declare a class name or enumeration
3314   //      name that is not a typedef name and the other declarations shall all
3315   //      refer to the same variable or enumerator, or all refer to functions
3316   //      and function templates; in this case the class name or enumeration
3317   //      name is hidden (3.3.10).
3318 
3319   // C++11 [namespace.udecl]p14:
3320   //   If a function declaration in namespace scope or block scope has the
3321   //   same name and the same parameter-type-list as a function introduced
3322   //   by a using-declaration, and the declarations do not declare the same
3323   //   function, the program is ill-formed.
3324 
3325   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3326   if (Old &&
3327       !Old->getDeclContext()->getRedeclContext()->Equals(
3328           New->getDeclContext()->getRedeclContext()) &&
3329       !(isExternC(Old) && isExternC(New)))
3330     Old = nullptr;
3331 
3332   if (!Old) {
3333     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3334     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3335     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3336     return true;
3337   }
3338   return false;
3339 }
3340 
3341 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3342                                             const FunctionDecl *B) {
3343   assert(A->getNumParams() == B->getNumParams());
3344 
3345   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3346     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3347     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3348     if (AttrA == AttrB)
3349       return true;
3350     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3351            AttrA->isDynamic() == AttrB->isDynamic();
3352   };
3353 
3354   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3355 }
3356 
3357 /// If necessary, adjust the semantic declaration context for a qualified
3358 /// declaration to name the correct inline namespace within the qualifier.
3359 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3360                                                DeclaratorDecl *OldD) {
3361   // The only case where we need to update the DeclContext is when
3362   // redeclaration lookup for a qualified name finds a declaration
3363   // in an inline namespace within the context named by the qualifier:
3364   //
3365   //   inline namespace N { int f(); }
3366   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3367   //
3368   // For unqualified declarations, the semantic context *can* change
3369   // along the redeclaration chain (for local extern declarations,
3370   // extern "C" declarations, and friend declarations in particular).
3371   if (!NewD->getQualifier())
3372     return;
3373 
3374   // NewD is probably already in the right context.
3375   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3376   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3377   if (NamedDC->Equals(SemaDC))
3378     return;
3379 
3380   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3381           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3382          "unexpected context for redeclaration");
3383 
3384   auto *LexDC = NewD->getLexicalDeclContext();
3385   auto FixSemaDC = [=](NamedDecl *D) {
3386     if (!D)
3387       return;
3388     D->setDeclContext(SemaDC);
3389     D->setLexicalDeclContext(LexDC);
3390   };
3391 
3392   FixSemaDC(NewD);
3393   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3394     FixSemaDC(FD->getDescribedFunctionTemplate());
3395   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3396     FixSemaDC(VD->getDescribedVarTemplate());
3397 }
3398 
3399 /// MergeFunctionDecl - We just parsed a function 'New' from
3400 /// declarator D which has the same name and scope as a previous
3401 /// declaration 'Old'.  Figure out how to resolve this situation,
3402 /// merging decls or emitting diagnostics as appropriate.
3403 ///
3404 /// In C++, New and Old must be declarations that are not
3405 /// overloaded. Use IsOverload to determine whether New and Old are
3406 /// overloaded, and to select the Old declaration that New should be
3407 /// merged with.
3408 ///
3409 /// Returns true if there was an error, false otherwise.
3410 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3411                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3412   // Verify the old decl was also a function.
3413   FunctionDecl *Old = OldD->getAsFunction();
3414   if (!Old) {
3415     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3416       if (New->getFriendObjectKind()) {
3417         Diag(New->getLocation(), diag::err_using_decl_friend);
3418         Diag(Shadow->getTargetDecl()->getLocation(),
3419              diag::note_using_decl_target);
3420         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3421             << 0;
3422         return true;
3423       }
3424 
3425       // Check whether the two declarations might declare the same function or
3426       // function template.
3427       if (FunctionTemplateDecl *NewTemplate =
3428               New->getDescribedFunctionTemplate()) {
3429         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3430                                                          NewTemplate))
3431           return true;
3432         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3433                          ->getAsFunction();
3434       } else {
3435         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3436           return true;
3437         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3438       }
3439     } else {
3440       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3441         << New->getDeclName();
3442       notePreviousDefinition(OldD, New->getLocation());
3443       return true;
3444     }
3445   }
3446 
3447   // If the old declaration was found in an inline namespace and the new
3448   // declaration was qualified, update the DeclContext to match.
3449   adjustDeclContextForDeclaratorDecl(New, Old);
3450 
3451   // If the old declaration is invalid, just give up here.
3452   if (Old->isInvalidDecl())
3453     return true;
3454 
3455   // Disallow redeclaration of some builtins.
3456   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3457     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3458     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3459         << Old << Old->getType();
3460     return true;
3461   }
3462 
3463   diag::kind PrevDiag;
3464   SourceLocation OldLocation;
3465   std::tie(PrevDiag, OldLocation) =
3466       getNoteDiagForInvalidRedeclaration(Old, New);
3467 
3468   // Don't complain about this if we're in GNU89 mode and the old function
3469   // is an extern inline function.
3470   // Don't complain about specializations. They are not supposed to have
3471   // storage classes.
3472   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3473       New->getStorageClass() == SC_Static &&
3474       Old->hasExternalFormalLinkage() &&
3475       !New->getTemplateSpecializationInfo() &&
3476       !canRedefineFunction(Old, getLangOpts())) {
3477     if (getLangOpts().MicrosoftExt) {
3478       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3479       Diag(OldLocation, PrevDiag);
3480     } else {
3481       Diag(New->getLocation(), diag::err_static_non_static) << New;
3482       Diag(OldLocation, PrevDiag);
3483       return true;
3484     }
3485   }
3486 
3487   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3488     if (!Old->hasAttr<InternalLinkageAttr>()) {
3489       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3490           << ILA;
3491       Diag(Old->getLocation(), diag::note_previous_declaration);
3492       New->dropAttr<InternalLinkageAttr>();
3493     }
3494 
3495   if (auto *EA = New->getAttr<ErrorAttr>()) {
3496     if (!Old->hasAttr<ErrorAttr>()) {
3497       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3498       Diag(Old->getLocation(), diag::note_previous_declaration);
3499       New->dropAttr<ErrorAttr>();
3500     }
3501   }
3502 
3503   if (CheckRedeclarationInModule(New, Old))
3504     return true;
3505 
3506   if (!getLangOpts().CPlusPlus) {
3507     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3508     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3509       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3510         << New << OldOvl;
3511 
3512       // Try our best to find a decl that actually has the overloadable
3513       // attribute for the note. In most cases (e.g. programs with only one
3514       // broken declaration/definition), this won't matter.
3515       //
3516       // FIXME: We could do this if we juggled some extra state in
3517       // OverloadableAttr, rather than just removing it.
3518       const Decl *DiagOld = Old;
3519       if (OldOvl) {
3520         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3521           const auto *A = D->getAttr<OverloadableAttr>();
3522           return A && !A->isImplicit();
3523         });
3524         // If we've implicitly added *all* of the overloadable attrs to this
3525         // chain, emitting a "previous redecl" note is pointless.
3526         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3527       }
3528 
3529       if (DiagOld)
3530         Diag(DiagOld->getLocation(),
3531              diag::note_attribute_overloadable_prev_overload)
3532           << OldOvl;
3533 
3534       if (OldOvl)
3535         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3536       else
3537         New->dropAttr<OverloadableAttr>();
3538     }
3539   }
3540 
3541   // If a function is first declared with a calling convention, but is later
3542   // declared or defined without one, all following decls assume the calling
3543   // convention of the first.
3544   //
3545   // It's OK if a function is first declared without a calling convention,
3546   // but is later declared or defined with the default calling convention.
3547   //
3548   // To test if either decl has an explicit calling convention, we look for
3549   // AttributedType sugar nodes on the type as written.  If they are missing or
3550   // were canonicalized away, we assume the calling convention was implicit.
3551   //
3552   // Note also that we DO NOT return at this point, because we still have
3553   // other tests to run.
3554   QualType OldQType = Context.getCanonicalType(Old->getType());
3555   QualType NewQType = Context.getCanonicalType(New->getType());
3556   const FunctionType *OldType = cast<FunctionType>(OldQType);
3557   const FunctionType *NewType = cast<FunctionType>(NewQType);
3558   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3559   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3560   bool RequiresAdjustment = false;
3561 
3562   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3563     FunctionDecl *First = Old->getFirstDecl();
3564     const FunctionType *FT =
3565         First->getType().getCanonicalType()->castAs<FunctionType>();
3566     FunctionType::ExtInfo FI = FT->getExtInfo();
3567     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3568     if (!NewCCExplicit) {
3569       // Inherit the CC from the previous declaration if it was specified
3570       // there but not here.
3571       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3572       RequiresAdjustment = true;
3573     } else if (Old->getBuiltinID()) {
3574       // Builtin attribute isn't propagated to the new one yet at this point,
3575       // so we check if the old one is a builtin.
3576 
3577       // Calling Conventions on a Builtin aren't really useful and setting a
3578       // default calling convention and cdecl'ing some builtin redeclarations is
3579       // common, so warn and ignore the calling convention on the redeclaration.
3580       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3581           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3582           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3583       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3584       RequiresAdjustment = true;
3585     } else {
3586       // Calling conventions aren't compatible, so complain.
3587       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3588       Diag(New->getLocation(), diag::err_cconv_change)
3589         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3590         << !FirstCCExplicit
3591         << (!FirstCCExplicit ? "" :
3592             FunctionType::getNameForCallConv(FI.getCC()));
3593 
3594       // Put the note on the first decl, since it is the one that matters.
3595       Diag(First->getLocation(), diag::note_previous_declaration);
3596       return true;
3597     }
3598   }
3599 
3600   // FIXME: diagnose the other way around?
3601   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3602     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3603     RequiresAdjustment = true;
3604   }
3605 
3606   // Merge regparm attribute.
3607   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3608       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3609     if (NewTypeInfo.getHasRegParm()) {
3610       Diag(New->getLocation(), diag::err_regparm_mismatch)
3611         << NewType->getRegParmType()
3612         << OldType->getRegParmType();
3613       Diag(OldLocation, diag::note_previous_declaration);
3614       return true;
3615     }
3616 
3617     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3618     RequiresAdjustment = true;
3619   }
3620 
3621   // Merge ns_returns_retained attribute.
3622   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3623     if (NewTypeInfo.getProducesResult()) {
3624       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3625           << "'ns_returns_retained'";
3626       Diag(OldLocation, diag::note_previous_declaration);
3627       return true;
3628     }
3629 
3630     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3631     RequiresAdjustment = true;
3632   }
3633 
3634   if (OldTypeInfo.getNoCallerSavedRegs() !=
3635       NewTypeInfo.getNoCallerSavedRegs()) {
3636     if (NewTypeInfo.getNoCallerSavedRegs()) {
3637       AnyX86NoCallerSavedRegistersAttr *Attr =
3638         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3639       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3640       Diag(OldLocation, diag::note_previous_declaration);
3641       return true;
3642     }
3643 
3644     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3645     RequiresAdjustment = true;
3646   }
3647 
3648   if (RequiresAdjustment) {
3649     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3650     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3651     New->setType(QualType(AdjustedType, 0));
3652     NewQType = Context.getCanonicalType(New->getType());
3653   }
3654 
3655   // If this redeclaration makes the function inline, we may need to add it to
3656   // UndefinedButUsed.
3657   if (!Old->isInlined() && New->isInlined() &&
3658       !New->hasAttr<GNUInlineAttr>() &&
3659       !getLangOpts().GNUInline &&
3660       Old->isUsed(false) &&
3661       !Old->isDefined() && !New->isThisDeclarationADefinition())
3662     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3663                                            SourceLocation()));
3664 
3665   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3666   // about it.
3667   if (New->hasAttr<GNUInlineAttr>() &&
3668       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3669     UndefinedButUsed.erase(Old->getCanonicalDecl());
3670   }
3671 
3672   // If pass_object_size params don't match up perfectly, this isn't a valid
3673   // redeclaration.
3674   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3675       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3676     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3677         << New->getDeclName();
3678     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3679     return true;
3680   }
3681 
3682   if (getLangOpts().CPlusPlus) {
3683     // C++1z [over.load]p2
3684     //   Certain function declarations cannot be overloaded:
3685     //     -- Function declarations that differ only in the return type,
3686     //        the exception specification, or both cannot be overloaded.
3687 
3688     // Check the exception specifications match. This may recompute the type of
3689     // both Old and New if it resolved exception specifications, so grab the
3690     // types again after this. Because this updates the type, we do this before
3691     // any of the other checks below, which may update the "de facto" NewQType
3692     // but do not necessarily update the type of New.
3693     if (CheckEquivalentExceptionSpec(Old, New))
3694       return true;
3695     OldQType = Context.getCanonicalType(Old->getType());
3696     NewQType = Context.getCanonicalType(New->getType());
3697 
3698     // Go back to the type source info to compare the declared return types,
3699     // per C++1y [dcl.type.auto]p13:
3700     //   Redeclarations or specializations of a function or function template
3701     //   with a declared return type that uses a placeholder type shall also
3702     //   use that placeholder, not a deduced type.
3703     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3704     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3705     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3706         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3707                                        OldDeclaredReturnType)) {
3708       QualType ResQT;
3709       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3710           OldDeclaredReturnType->isObjCObjectPointerType())
3711         // FIXME: This does the wrong thing for a deduced return type.
3712         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3713       if (ResQT.isNull()) {
3714         if (New->isCXXClassMember() && New->isOutOfLine())
3715           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3716               << New << New->getReturnTypeSourceRange();
3717         else
3718           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3719               << New->getReturnTypeSourceRange();
3720         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3721                                     << Old->getReturnTypeSourceRange();
3722         return true;
3723       }
3724       else
3725         NewQType = ResQT;
3726     }
3727 
3728     QualType OldReturnType = OldType->getReturnType();
3729     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3730     if (OldReturnType != NewReturnType) {
3731       // If this function has a deduced return type and has already been
3732       // defined, copy the deduced value from the old declaration.
3733       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3734       if (OldAT && OldAT->isDeduced()) {
3735         QualType DT = OldAT->getDeducedType();
3736         if (DT.isNull()) {
3737           New->setType(SubstAutoTypeDependent(New->getType()));
3738           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3739         } else {
3740           New->setType(SubstAutoType(New->getType(), DT));
3741           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3742         }
3743       }
3744     }
3745 
3746     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3747     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3748     if (OldMethod && NewMethod) {
3749       // Preserve triviality.
3750       NewMethod->setTrivial(OldMethod->isTrivial());
3751 
3752       // MSVC allows explicit template specialization at class scope:
3753       // 2 CXXMethodDecls referring to the same function will be injected.
3754       // We don't want a redeclaration error.
3755       bool IsClassScopeExplicitSpecialization =
3756                               OldMethod->isFunctionTemplateSpecialization() &&
3757                               NewMethod->isFunctionTemplateSpecialization();
3758       bool isFriend = NewMethod->getFriendObjectKind();
3759 
3760       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3761           !IsClassScopeExplicitSpecialization) {
3762         //    -- Member function declarations with the same name and the
3763         //       same parameter types cannot be overloaded if any of them
3764         //       is a static member function declaration.
3765         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3766           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3767           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3768           return true;
3769         }
3770 
3771         // C++ [class.mem]p1:
3772         //   [...] A member shall not be declared twice in the
3773         //   member-specification, except that a nested class or member
3774         //   class template can be declared and then later defined.
3775         if (!inTemplateInstantiation()) {
3776           unsigned NewDiag;
3777           if (isa<CXXConstructorDecl>(OldMethod))
3778             NewDiag = diag::err_constructor_redeclared;
3779           else if (isa<CXXDestructorDecl>(NewMethod))
3780             NewDiag = diag::err_destructor_redeclared;
3781           else if (isa<CXXConversionDecl>(NewMethod))
3782             NewDiag = diag::err_conv_function_redeclared;
3783           else
3784             NewDiag = diag::err_member_redeclared;
3785 
3786           Diag(New->getLocation(), NewDiag);
3787         } else {
3788           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3789             << New << New->getType();
3790         }
3791         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3792         return true;
3793 
3794       // Complain if this is an explicit declaration of a special
3795       // member that was initially declared implicitly.
3796       //
3797       // As an exception, it's okay to befriend such methods in order
3798       // to permit the implicit constructor/destructor/operator calls.
3799       } else if (OldMethod->isImplicit()) {
3800         if (isFriend) {
3801           NewMethod->setImplicit();
3802         } else {
3803           Diag(NewMethod->getLocation(),
3804                diag::err_definition_of_implicitly_declared_member)
3805             << New << getSpecialMember(OldMethod);
3806           return true;
3807         }
3808       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3809         Diag(NewMethod->getLocation(),
3810              diag::err_definition_of_explicitly_defaulted_member)
3811           << getSpecialMember(OldMethod);
3812         return true;
3813       }
3814     }
3815 
3816     // C++11 [dcl.attr.noreturn]p1:
3817     //   The first declaration of a function shall specify the noreturn
3818     //   attribute if any declaration of that function specifies the noreturn
3819     //   attribute.
3820     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3821       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3822         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3823             << NRA;
3824         Diag(Old->getLocation(), diag::note_previous_declaration);
3825       }
3826 
3827     // C++11 [dcl.attr.depend]p2:
3828     //   The first declaration of a function shall specify the
3829     //   carries_dependency attribute for its declarator-id if any declaration
3830     //   of the function specifies the carries_dependency attribute.
3831     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3832     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3833       Diag(CDA->getLocation(),
3834            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3835       Diag(Old->getFirstDecl()->getLocation(),
3836            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3837     }
3838 
3839     // (C++98 8.3.5p3):
3840     //   All declarations for a function shall agree exactly in both the
3841     //   return type and the parameter-type-list.
3842     // We also want to respect all the extended bits except noreturn.
3843 
3844     // noreturn should now match unless the old type info didn't have it.
3845     QualType OldQTypeForComparison = OldQType;
3846     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3847       auto *OldType = OldQType->castAs<FunctionProtoType>();
3848       const FunctionType *OldTypeForComparison
3849         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3850       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3851       assert(OldQTypeForComparison.isCanonical());
3852     }
3853 
3854     if (haveIncompatibleLanguageLinkages(Old, New)) {
3855       // As a special case, retain the language linkage from previous
3856       // declarations of a friend function as an extension.
3857       //
3858       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3859       // and is useful because there's otherwise no way to specify language
3860       // linkage within class scope.
3861       //
3862       // Check cautiously as the friend object kind isn't yet complete.
3863       if (New->getFriendObjectKind() != Decl::FOK_None) {
3864         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3865         Diag(OldLocation, PrevDiag);
3866       } else {
3867         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3868         Diag(OldLocation, PrevDiag);
3869         return true;
3870       }
3871     }
3872 
3873     // If the function types are compatible, merge the declarations. Ignore the
3874     // exception specifier because it was already checked above in
3875     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3876     // about incompatible types under -fms-compatibility.
3877     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3878                                                          NewQType))
3879       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3880 
3881     // If the types are imprecise (due to dependent constructs in friends or
3882     // local extern declarations), it's OK if they differ. We'll check again
3883     // during instantiation.
3884     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3885       return false;
3886 
3887     // Fall through for conflicting redeclarations and redefinitions.
3888   }
3889 
3890   // C: Function types need to be compatible, not identical. This handles
3891   // duplicate function decls like "void f(int); void f(enum X);" properly.
3892   if (!getLangOpts().CPlusPlus) {
3893     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3894     // type is specified by a function definition that contains a (possibly
3895     // empty) identifier list, both shall agree in the number of parameters
3896     // and the type of each parameter shall be compatible with the type that
3897     // results from the application of default argument promotions to the
3898     // type of the corresponding identifier. ...
3899     // This cannot be handled by ASTContext::typesAreCompatible() because that
3900     // doesn't know whether the function type is for a definition or not when
3901     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3902     // we need to cover here is that the number of arguments agree as the
3903     // default argument promotion rules were already checked by
3904     // ASTContext::typesAreCompatible().
3905     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3906         Old->getNumParams() != New->getNumParams()) {
3907       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3908       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3909       return true;
3910     }
3911 
3912     // If we are merging two functions where only one of them has a prototype,
3913     // we may have enough information to decide to issue a diagnostic that the
3914     // function without a protoype will change behavior in C2x. This handles
3915     // cases like:
3916     //   void i(); void i(int j);
3917     //   void i(int j); void i();
3918     //   void i(); void i(int j) {}
3919     // See ActOnFinishFunctionBody() for other cases of the behavior change
3920     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3921     // type without a prototype.
3922     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3923         !New->isImplicit() && !Old->isImplicit()) {
3924       const FunctionDecl *WithProto, *WithoutProto;
3925       if (New->hasWrittenPrototype()) {
3926         WithProto = New;
3927         WithoutProto = Old;
3928       } else {
3929         WithProto = Old;
3930         WithoutProto = New;
3931       }
3932 
3933       if (WithProto->getNumParams() != 0) {
3934         // The function definition has parameters, so this will change
3935         // behavior in C2x.
3936         //
3937         // If we already warned about about the function without a prototype
3938         // being deprecated, add a note that it also changes behavior. If we
3939         // didn't warn about it being deprecated (because the diagnostic is
3940         // not enabled), warn now that it is deprecated and changes behavior.
3941         bool AddNote = false;
3942         if (Diags.isIgnored(diag::warn_strict_prototypes,
3943                             WithoutProto->getLocation())) {
3944           if (WithoutProto->getBuiltinID() == 0 &&
3945               !WithoutProto->isImplicit() &&
3946               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3947                                                   WithProto->getLocation())) {
3948             PartialDiagnostic PD =
3949                 PDiag(diag::warn_non_prototype_changes_behavior);
3950             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3951               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3952                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3953             }
3954             Diag(WithoutProto->getLocation(), PD);
3955           }
3956         } else {
3957           AddNote = true;
3958         }
3959 
3960         // Because the function with a prototype has parameters but a previous
3961         // declaration had none, the function with the prototype will also
3962         // change behavior in C2x.
3963         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3964           if (SourceMgr.isBeforeInTranslationUnit(
3965                   WithProto->getLocation(), WithoutProto->getLocation())) {
3966             // If the function with the prototype comes before the function
3967             // without the prototype, we only want to diagnose the one without
3968             // the prototype.
3969             Diag(WithoutProto->getLocation(),
3970                  diag::warn_non_prototype_changes_behavior);
3971           } else {
3972             // Otherwise, diagnose the one with the prototype, and potentially
3973             // attach a note to the one without a prototype if needed.
3974             Diag(WithProto->getLocation(),
3975                  diag::warn_non_prototype_changes_behavior);
3976             if (AddNote && WithoutProto->getBuiltinID() == 0)
3977               Diag(WithoutProto->getLocation(),
3978                    diag::note_func_decl_changes_behavior);
3979           }
3980         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3981                    !WithoutProto->isImplicit()) {
3982           // If we were supposed to add a note but the function with a
3983           // prototype is a builtin or was implicitly declared, which means we
3984           // have nothing to attach the note to, so we issue a warning instead.
3985           Diag(WithoutProto->getLocation(),
3986                diag::warn_non_prototype_changes_behavior);
3987         }
3988       }
3989     }
3990 
3991     if (Context.typesAreCompatible(OldQType, NewQType)) {
3992       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3993       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3994       const FunctionProtoType *OldProto = nullptr;
3995       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3996           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3997         // The old declaration provided a function prototype, but the
3998         // new declaration does not. Merge in the prototype.
3999         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4000         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4001         NewQType =
4002             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4003                                     OldProto->getExtProtoInfo());
4004         New->setType(NewQType);
4005         New->setHasInheritedPrototype();
4006 
4007         // Synthesize parameters with the same types.
4008         SmallVector<ParmVarDecl *, 16> Params;
4009         for (const auto &ParamType : OldProto->param_types()) {
4010           ParmVarDecl *Param = ParmVarDecl::Create(
4011               Context, New, SourceLocation(), SourceLocation(), nullptr,
4012               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4013           Param->setScopeInfo(0, Params.size());
4014           Param->setImplicit();
4015           Params.push_back(Param);
4016         }
4017 
4018         New->setParams(Params);
4019       }
4020 
4021       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4022     }
4023   }
4024 
4025   // Check if the function types are compatible when pointer size address
4026   // spaces are ignored.
4027   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4028     return false;
4029 
4030   // GNU C permits a K&R definition to follow a prototype declaration
4031   // if the declared types of the parameters in the K&R definition
4032   // match the types in the prototype declaration, even when the
4033   // promoted types of the parameters from the K&R definition differ
4034   // from the types in the prototype. GCC then keeps the types from
4035   // the prototype.
4036   //
4037   // If a variadic prototype is followed by a non-variadic K&R definition,
4038   // the K&R definition becomes variadic.  This is sort of an edge case, but
4039   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4040   // C99 6.9.1p8.
4041   if (!getLangOpts().CPlusPlus &&
4042       Old->hasPrototype() && !New->hasPrototype() &&
4043       New->getType()->getAs<FunctionProtoType>() &&
4044       Old->getNumParams() == New->getNumParams()) {
4045     SmallVector<QualType, 16> ArgTypes;
4046     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4047     const FunctionProtoType *OldProto
4048       = Old->getType()->getAs<FunctionProtoType>();
4049     const FunctionProtoType *NewProto
4050       = New->getType()->getAs<FunctionProtoType>();
4051 
4052     // Determine whether this is the GNU C extension.
4053     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4054                                                NewProto->getReturnType());
4055     bool LooseCompatible = !MergedReturn.isNull();
4056     for (unsigned Idx = 0, End = Old->getNumParams();
4057          LooseCompatible && Idx != End; ++Idx) {
4058       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4059       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4060       if (Context.typesAreCompatible(OldParm->getType(),
4061                                      NewProto->getParamType(Idx))) {
4062         ArgTypes.push_back(NewParm->getType());
4063       } else if (Context.typesAreCompatible(OldParm->getType(),
4064                                             NewParm->getType(),
4065                                             /*CompareUnqualified=*/true)) {
4066         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4067                                            NewProto->getParamType(Idx) };
4068         Warnings.push_back(Warn);
4069         ArgTypes.push_back(NewParm->getType());
4070       } else
4071         LooseCompatible = false;
4072     }
4073 
4074     if (LooseCompatible) {
4075       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4076         Diag(Warnings[Warn].NewParm->getLocation(),
4077              diag::ext_param_promoted_not_compatible_with_prototype)
4078           << Warnings[Warn].PromotedType
4079           << Warnings[Warn].OldParm->getType();
4080         if (Warnings[Warn].OldParm->getLocation().isValid())
4081           Diag(Warnings[Warn].OldParm->getLocation(),
4082                diag::note_previous_declaration);
4083       }
4084 
4085       if (MergeTypeWithOld)
4086         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4087                                              OldProto->getExtProtoInfo()));
4088       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4089     }
4090 
4091     // Fall through to diagnose conflicting types.
4092   }
4093 
4094   // A function that has already been declared has been redeclared or
4095   // defined with a different type; show an appropriate diagnostic.
4096 
4097   // If the previous declaration was an implicitly-generated builtin
4098   // declaration, then at the very least we should use a specialized note.
4099   unsigned BuiltinID;
4100   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4101     // If it's actually a library-defined builtin function like 'malloc'
4102     // or 'printf', just warn about the incompatible redeclaration.
4103     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4104       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4105       Diag(OldLocation, diag::note_previous_builtin_declaration)
4106         << Old << Old->getType();
4107       return false;
4108     }
4109 
4110     PrevDiag = diag::note_previous_builtin_declaration;
4111   }
4112 
4113   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4114   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4115   return true;
4116 }
4117 
4118 /// Completes the merge of two function declarations that are
4119 /// known to be compatible.
4120 ///
4121 /// This routine handles the merging of attributes and other
4122 /// properties of function declarations from the old declaration to
4123 /// the new declaration, once we know that New is in fact a
4124 /// redeclaration of Old.
4125 ///
4126 /// \returns false
4127 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4128                                         Scope *S, bool MergeTypeWithOld) {
4129   // Merge the attributes
4130   mergeDeclAttributes(New, Old);
4131 
4132   // Merge "pure" flag.
4133   if (Old->isPure())
4134     New->setPure();
4135 
4136   // Merge "used" flag.
4137   if (Old->getMostRecentDecl()->isUsed(false))
4138     New->setIsUsed();
4139 
4140   // Merge attributes from the parameters.  These can mismatch with K&R
4141   // declarations.
4142   if (New->getNumParams() == Old->getNumParams())
4143       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4144         ParmVarDecl *NewParam = New->getParamDecl(i);
4145         ParmVarDecl *OldParam = Old->getParamDecl(i);
4146         mergeParamDeclAttributes(NewParam, OldParam, *this);
4147         mergeParamDeclTypes(NewParam, OldParam, *this);
4148       }
4149 
4150   if (getLangOpts().CPlusPlus)
4151     return MergeCXXFunctionDecl(New, Old, S);
4152 
4153   // Merge the function types so the we get the composite types for the return
4154   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4155   // was visible.
4156   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4157   if (!Merged.isNull() && MergeTypeWithOld)
4158     New->setType(Merged);
4159 
4160   return false;
4161 }
4162 
4163 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4164                                 ObjCMethodDecl *oldMethod) {
4165   // Merge the attributes, including deprecated/unavailable
4166   AvailabilityMergeKind MergeKind =
4167       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4168           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4169                                      : AMK_ProtocolImplementation)
4170           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4171                                                            : AMK_Override;
4172 
4173   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4174 
4175   // Merge attributes from the parameters.
4176   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4177                                        oe = oldMethod->param_end();
4178   for (ObjCMethodDecl::param_iterator
4179          ni = newMethod->param_begin(), ne = newMethod->param_end();
4180        ni != ne && oi != oe; ++ni, ++oi)
4181     mergeParamDeclAttributes(*ni, *oi, *this);
4182 
4183   CheckObjCMethodOverride(newMethod, oldMethod);
4184 }
4185 
4186 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4187   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4188 
4189   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4190          ? diag::err_redefinition_different_type
4191          : diag::err_redeclaration_different_type)
4192     << New->getDeclName() << New->getType() << Old->getType();
4193 
4194   diag::kind PrevDiag;
4195   SourceLocation OldLocation;
4196   std::tie(PrevDiag, OldLocation)
4197     = getNoteDiagForInvalidRedeclaration(Old, New);
4198   S.Diag(OldLocation, PrevDiag);
4199   New->setInvalidDecl();
4200 }
4201 
4202 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4203 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4204 /// emitting diagnostics as appropriate.
4205 ///
4206 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4207 /// to here in AddInitializerToDecl. We can't check them before the initializer
4208 /// is attached.
4209 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4210                              bool MergeTypeWithOld) {
4211   if (New->isInvalidDecl() || Old->isInvalidDecl())
4212     return;
4213 
4214   QualType MergedT;
4215   if (getLangOpts().CPlusPlus) {
4216     if (New->getType()->isUndeducedType()) {
4217       // We don't know what the new type is until the initializer is attached.
4218       return;
4219     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4220       // These could still be something that needs exception specs checked.
4221       return MergeVarDeclExceptionSpecs(New, Old);
4222     }
4223     // C++ [basic.link]p10:
4224     //   [...] the types specified by all declarations referring to a given
4225     //   object or function shall be identical, except that declarations for an
4226     //   array object can specify array types that differ by the presence or
4227     //   absence of a major array bound (8.3.4).
4228     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4229       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4230       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4231 
4232       // We are merging a variable declaration New into Old. If it has an array
4233       // bound, and that bound differs from Old's bound, we should diagnose the
4234       // mismatch.
4235       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4236         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4237              PrevVD = PrevVD->getPreviousDecl()) {
4238           QualType PrevVDTy = PrevVD->getType();
4239           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4240             continue;
4241 
4242           if (!Context.hasSameType(New->getType(), PrevVDTy))
4243             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4244         }
4245       }
4246 
4247       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4248         if (Context.hasSameType(OldArray->getElementType(),
4249                                 NewArray->getElementType()))
4250           MergedT = New->getType();
4251       }
4252       // FIXME: Check visibility. New is hidden but has a complete type. If New
4253       // has no array bound, it should not inherit one from Old, if Old is not
4254       // visible.
4255       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4256         if (Context.hasSameType(OldArray->getElementType(),
4257                                 NewArray->getElementType()))
4258           MergedT = Old->getType();
4259       }
4260     }
4261     else if (New->getType()->isObjCObjectPointerType() &&
4262                Old->getType()->isObjCObjectPointerType()) {
4263       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4264                                               Old->getType());
4265     }
4266   } else {
4267     // C 6.2.7p2:
4268     //   All declarations that refer to the same object or function shall have
4269     //   compatible type.
4270     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4271   }
4272   if (MergedT.isNull()) {
4273     // It's OK if we couldn't merge types if either type is dependent, for a
4274     // block-scope variable. In other cases (static data members of class
4275     // templates, variable templates, ...), we require the types to be
4276     // equivalent.
4277     // FIXME: The C++ standard doesn't say anything about this.
4278     if ((New->getType()->isDependentType() ||
4279          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4280       // If the old type was dependent, we can't merge with it, so the new type
4281       // becomes dependent for now. We'll reproduce the original type when we
4282       // instantiate the TypeSourceInfo for the variable.
4283       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4284         New->setType(Context.DependentTy);
4285       return;
4286     }
4287     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4288   }
4289 
4290   // Don't actually update the type on the new declaration if the old
4291   // declaration was an extern declaration in a different scope.
4292   if (MergeTypeWithOld)
4293     New->setType(MergedT);
4294 }
4295 
4296 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4297                                   LookupResult &Previous) {
4298   // C11 6.2.7p4:
4299   //   For an identifier with internal or external linkage declared
4300   //   in a scope in which a prior declaration of that identifier is
4301   //   visible, if the prior declaration specifies internal or
4302   //   external linkage, the type of the identifier at the later
4303   //   declaration becomes the composite type.
4304   //
4305   // If the variable isn't visible, we do not merge with its type.
4306   if (Previous.isShadowed())
4307     return false;
4308 
4309   if (S.getLangOpts().CPlusPlus) {
4310     // C++11 [dcl.array]p3:
4311     //   If there is a preceding declaration of the entity in the same
4312     //   scope in which the bound was specified, an omitted array bound
4313     //   is taken to be the same as in that earlier declaration.
4314     return NewVD->isPreviousDeclInSameBlockScope() ||
4315            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4316             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4317   } else {
4318     // If the old declaration was function-local, don't merge with its
4319     // type unless we're in the same function.
4320     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4321            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4322   }
4323 }
4324 
4325 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4326 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4327 /// situation, merging decls or emitting diagnostics as appropriate.
4328 ///
4329 /// Tentative definition rules (C99 6.9.2p2) are checked by
4330 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4331 /// definitions here, since the initializer hasn't been attached.
4332 ///
4333 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4334   // If the new decl is already invalid, don't do any other checking.
4335   if (New->isInvalidDecl())
4336     return;
4337 
4338   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4339     return;
4340 
4341   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4342 
4343   // Verify the old decl was also a variable or variable template.
4344   VarDecl *Old = nullptr;
4345   VarTemplateDecl *OldTemplate = nullptr;
4346   if (Previous.isSingleResult()) {
4347     if (NewTemplate) {
4348       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4349       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4350 
4351       if (auto *Shadow =
4352               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4353         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4354           return New->setInvalidDecl();
4355     } else {
4356       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4357 
4358       if (auto *Shadow =
4359               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4360         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4361           return New->setInvalidDecl();
4362     }
4363   }
4364   if (!Old) {
4365     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4366         << New->getDeclName();
4367     notePreviousDefinition(Previous.getRepresentativeDecl(),
4368                            New->getLocation());
4369     return New->setInvalidDecl();
4370   }
4371 
4372   // If the old declaration was found in an inline namespace and the new
4373   // declaration was qualified, update the DeclContext to match.
4374   adjustDeclContextForDeclaratorDecl(New, Old);
4375 
4376   // Ensure the template parameters are compatible.
4377   if (NewTemplate &&
4378       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4379                                       OldTemplate->getTemplateParameters(),
4380                                       /*Complain=*/true, TPL_TemplateMatch))
4381     return New->setInvalidDecl();
4382 
4383   // C++ [class.mem]p1:
4384   //   A member shall not be declared twice in the member-specification [...]
4385   //
4386   // Here, we need only consider static data members.
4387   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4388     Diag(New->getLocation(), diag::err_duplicate_member)
4389       << New->getIdentifier();
4390     Diag(Old->getLocation(), diag::note_previous_declaration);
4391     New->setInvalidDecl();
4392   }
4393 
4394   mergeDeclAttributes(New, Old);
4395   // Warn if an already-declared variable is made a weak_import in a subsequent
4396   // declaration
4397   if (New->hasAttr<WeakImportAttr>() &&
4398       Old->getStorageClass() == SC_None &&
4399       !Old->hasAttr<WeakImportAttr>()) {
4400     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4401     Diag(Old->getLocation(), diag::note_previous_declaration);
4402     // Remove weak_import attribute on new declaration.
4403     New->dropAttr<WeakImportAttr>();
4404   }
4405 
4406   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4407     if (!Old->hasAttr<InternalLinkageAttr>()) {
4408       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4409           << ILA;
4410       Diag(Old->getLocation(), diag::note_previous_declaration);
4411       New->dropAttr<InternalLinkageAttr>();
4412     }
4413 
4414   // Merge the types.
4415   VarDecl *MostRecent = Old->getMostRecentDecl();
4416   if (MostRecent != Old) {
4417     MergeVarDeclTypes(New, MostRecent,
4418                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4419     if (New->isInvalidDecl())
4420       return;
4421   }
4422 
4423   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4424   if (New->isInvalidDecl())
4425     return;
4426 
4427   diag::kind PrevDiag;
4428   SourceLocation OldLocation;
4429   std::tie(PrevDiag, OldLocation) =
4430       getNoteDiagForInvalidRedeclaration(Old, New);
4431 
4432   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4433   if (New->getStorageClass() == SC_Static &&
4434       !New->isStaticDataMember() &&
4435       Old->hasExternalFormalLinkage()) {
4436     if (getLangOpts().MicrosoftExt) {
4437       Diag(New->getLocation(), diag::ext_static_non_static)
4438           << New->getDeclName();
4439       Diag(OldLocation, PrevDiag);
4440     } else {
4441       Diag(New->getLocation(), diag::err_static_non_static)
4442           << New->getDeclName();
4443       Diag(OldLocation, PrevDiag);
4444       return New->setInvalidDecl();
4445     }
4446   }
4447   // C99 6.2.2p4:
4448   //   For an identifier declared with the storage-class specifier
4449   //   extern in a scope in which a prior declaration of that
4450   //   identifier is visible,23) if the prior declaration specifies
4451   //   internal or external linkage, the linkage of the identifier at
4452   //   the later declaration is the same as the linkage specified at
4453   //   the prior declaration. If no prior declaration is visible, or
4454   //   if the prior declaration specifies no linkage, then the
4455   //   identifier has external linkage.
4456   if (New->hasExternalStorage() && Old->hasLinkage())
4457     /* Okay */;
4458   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4459            !New->isStaticDataMember() &&
4460            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4461     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4462     Diag(OldLocation, PrevDiag);
4463     return New->setInvalidDecl();
4464   }
4465 
4466   // Check if extern is followed by non-extern and vice-versa.
4467   if (New->hasExternalStorage() &&
4468       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4469     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4470     Diag(OldLocation, PrevDiag);
4471     return New->setInvalidDecl();
4472   }
4473   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4474       !New->hasExternalStorage()) {
4475     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4476     Diag(OldLocation, PrevDiag);
4477     return New->setInvalidDecl();
4478   }
4479 
4480   if (CheckRedeclarationInModule(New, Old))
4481     return;
4482 
4483   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4484 
4485   // FIXME: The test for external storage here seems wrong? We still
4486   // need to check for mismatches.
4487   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4488       // Don't complain about out-of-line definitions of static members.
4489       !(Old->getLexicalDeclContext()->isRecord() &&
4490         !New->getLexicalDeclContext()->isRecord())) {
4491     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4492     Diag(OldLocation, PrevDiag);
4493     return New->setInvalidDecl();
4494   }
4495 
4496   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4497     if (VarDecl *Def = Old->getDefinition()) {
4498       // C++1z [dcl.fcn.spec]p4:
4499       //   If the definition of a variable appears in a translation unit before
4500       //   its first declaration as inline, the program is ill-formed.
4501       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4502       Diag(Def->getLocation(), diag::note_previous_definition);
4503     }
4504   }
4505 
4506   // If this redeclaration makes the variable inline, we may need to add it to
4507   // UndefinedButUsed.
4508   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4509       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4510     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4511                                            SourceLocation()));
4512 
4513   if (New->getTLSKind() != Old->getTLSKind()) {
4514     if (!Old->getTLSKind()) {
4515       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4516       Diag(OldLocation, PrevDiag);
4517     } else if (!New->getTLSKind()) {
4518       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4519       Diag(OldLocation, PrevDiag);
4520     } else {
4521       // Do not allow redeclaration to change the variable between requiring
4522       // static and dynamic initialization.
4523       // FIXME: GCC allows this, but uses the TLS keyword on the first
4524       // declaration to determine the kind. Do we need to be compatible here?
4525       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4526         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4527       Diag(OldLocation, PrevDiag);
4528     }
4529   }
4530 
4531   // C++ doesn't have tentative definitions, so go right ahead and check here.
4532   if (getLangOpts().CPlusPlus &&
4533       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4534     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4535         Old->getCanonicalDecl()->isConstexpr()) {
4536       // This definition won't be a definition any more once it's been merged.
4537       Diag(New->getLocation(),
4538            diag::warn_deprecated_redundant_constexpr_static_def);
4539     } else if (VarDecl *Def = Old->getDefinition()) {
4540       if (checkVarDeclRedefinition(Def, New))
4541         return;
4542     }
4543   }
4544 
4545   if (haveIncompatibleLanguageLinkages(Old, New)) {
4546     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4547     Diag(OldLocation, PrevDiag);
4548     New->setInvalidDecl();
4549     return;
4550   }
4551 
4552   // Merge "used" flag.
4553   if (Old->getMostRecentDecl()->isUsed(false))
4554     New->setIsUsed();
4555 
4556   // Keep a chain of previous declarations.
4557   New->setPreviousDecl(Old);
4558   if (NewTemplate)
4559     NewTemplate->setPreviousDecl(OldTemplate);
4560 
4561   // Inherit access appropriately.
4562   New->setAccess(Old->getAccess());
4563   if (NewTemplate)
4564     NewTemplate->setAccess(New->getAccess());
4565 
4566   if (Old->isInline())
4567     New->setImplicitlyInline();
4568 }
4569 
4570 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4571   SourceManager &SrcMgr = getSourceManager();
4572   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4573   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4574   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4575   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4576   auto &HSI = PP.getHeaderSearchInfo();
4577   StringRef HdrFilename =
4578       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4579 
4580   auto noteFromModuleOrInclude = [&](Module *Mod,
4581                                      SourceLocation IncLoc) -> bool {
4582     // Redefinition errors with modules are common with non modular mapped
4583     // headers, example: a non-modular header H in module A that also gets
4584     // included directly in a TU. Pointing twice to the same header/definition
4585     // is confusing, try to get better diagnostics when modules is on.
4586     if (IncLoc.isValid()) {
4587       if (Mod) {
4588         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4589             << HdrFilename.str() << Mod->getFullModuleName();
4590         if (!Mod->DefinitionLoc.isInvalid())
4591           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4592               << Mod->getFullModuleName();
4593       } else {
4594         Diag(IncLoc, diag::note_redefinition_include_same_file)
4595             << HdrFilename.str();
4596       }
4597       return true;
4598     }
4599 
4600     return false;
4601   };
4602 
4603   // Is it the same file and same offset? Provide more information on why
4604   // this leads to a redefinition error.
4605   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4606     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4607     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4608     bool EmittedDiag =
4609         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4610     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4611 
4612     // If the header has no guards, emit a note suggesting one.
4613     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4614       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4615 
4616     if (EmittedDiag)
4617       return;
4618   }
4619 
4620   // Redefinition coming from different files or couldn't do better above.
4621   if (Old->getLocation().isValid())
4622     Diag(Old->getLocation(), diag::note_previous_definition);
4623 }
4624 
4625 /// We've just determined that \p Old and \p New both appear to be definitions
4626 /// of the same variable. Either diagnose or fix the problem.
4627 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4628   if (!hasVisibleDefinition(Old) &&
4629       (New->getFormalLinkage() == InternalLinkage ||
4630        New->isInline() ||
4631        New->getDescribedVarTemplate() ||
4632        New->getNumTemplateParameterLists() ||
4633        New->getDeclContext()->isDependentContext())) {
4634     // The previous definition is hidden, and multiple definitions are
4635     // permitted (in separate TUs). Demote this to a declaration.
4636     New->demoteThisDefinitionToDeclaration();
4637 
4638     // Make the canonical definition visible.
4639     if (auto *OldTD = Old->getDescribedVarTemplate())
4640       makeMergedDefinitionVisible(OldTD);
4641     makeMergedDefinitionVisible(Old);
4642     return false;
4643   } else {
4644     Diag(New->getLocation(), diag::err_redefinition) << New;
4645     notePreviousDefinition(Old, New->getLocation());
4646     New->setInvalidDecl();
4647     return true;
4648   }
4649 }
4650 
4651 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4652 /// no declarator (e.g. "struct foo;") is parsed.
4653 Decl *
4654 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4655                                  RecordDecl *&AnonRecord) {
4656   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4657                                     AnonRecord);
4658 }
4659 
4660 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4661 // disambiguate entities defined in different scopes.
4662 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4663 // compatibility.
4664 // We will pick our mangling number depending on which version of MSVC is being
4665 // targeted.
4666 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4667   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4668              ? S->getMSCurManglingNumber()
4669              : S->getMSLastManglingNumber();
4670 }
4671 
4672 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4673   if (!Context.getLangOpts().CPlusPlus)
4674     return;
4675 
4676   if (isa<CXXRecordDecl>(Tag->getParent())) {
4677     // If this tag is the direct child of a class, number it if
4678     // it is anonymous.
4679     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4680       return;
4681     MangleNumberingContext &MCtx =
4682         Context.getManglingNumberContext(Tag->getParent());
4683     Context.setManglingNumber(
4684         Tag, MCtx.getManglingNumber(
4685                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4686     return;
4687   }
4688 
4689   // If this tag isn't a direct child of a class, number it if it is local.
4690   MangleNumberingContext *MCtx;
4691   Decl *ManglingContextDecl;
4692   std::tie(MCtx, ManglingContextDecl) =
4693       getCurrentMangleNumberContext(Tag->getDeclContext());
4694   if (MCtx) {
4695     Context.setManglingNumber(
4696         Tag, MCtx->getManglingNumber(
4697                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4698   }
4699 }
4700 
4701 namespace {
4702 struct NonCLikeKind {
4703   enum {
4704     None,
4705     BaseClass,
4706     DefaultMemberInit,
4707     Lambda,
4708     Friend,
4709     OtherMember,
4710     Invalid,
4711   } Kind = None;
4712   SourceRange Range;
4713 
4714   explicit operator bool() { return Kind != None; }
4715 };
4716 }
4717 
4718 /// Determine whether a class is C-like, according to the rules of C++
4719 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4720 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4721   if (RD->isInvalidDecl())
4722     return {NonCLikeKind::Invalid, {}};
4723 
4724   // C++ [dcl.typedef]p9: [P1766R1]
4725   //   An unnamed class with a typedef name for linkage purposes shall not
4726   //
4727   //    -- have any base classes
4728   if (RD->getNumBases())
4729     return {NonCLikeKind::BaseClass,
4730             SourceRange(RD->bases_begin()->getBeginLoc(),
4731                         RD->bases_end()[-1].getEndLoc())};
4732   bool Invalid = false;
4733   for (Decl *D : RD->decls()) {
4734     // Don't complain about things we already diagnosed.
4735     if (D->isInvalidDecl()) {
4736       Invalid = true;
4737       continue;
4738     }
4739 
4740     //  -- have any [...] default member initializers
4741     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4742       if (FD->hasInClassInitializer()) {
4743         auto *Init = FD->getInClassInitializer();
4744         return {NonCLikeKind::DefaultMemberInit,
4745                 Init ? Init->getSourceRange() : D->getSourceRange()};
4746       }
4747       continue;
4748     }
4749 
4750     // FIXME: We don't allow friend declarations. This violates the wording of
4751     // P1766, but not the intent.
4752     if (isa<FriendDecl>(D))
4753       return {NonCLikeKind::Friend, D->getSourceRange()};
4754 
4755     //  -- declare any members other than non-static data members, member
4756     //     enumerations, or member classes,
4757     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4758         isa<EnumDecl>(D))
4759       continue;
4760     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4761     if (!MemberRD) {
4762       if (D->isImplicit())
4763         continue;
4764       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4765     }
4766 
4767     //  -- contain a lambda-expression,
4768     if (MemberRD->isLambda())
4769       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4770 
4771     //  and all member classes shall also satisfy these requirements
4772     //  (recursively).
4773     if (MemberRD->isThisDeclarationADefinition()) {
4774       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4775         return Kind;
4776     }
4777   }
4778 
4779   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4780 }
4781 
4782 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4783                                         TypedefNameDecl *NewTD) {
4784   if (TagFromDeclSpec->isInvalidDecl())
4785     return;
4786 
4787   // Do nothing if the tag already has a name for linkage purposes.
4788   if (TagFromDeclSpec->hasNameForLinkage())
4789     return;
4790 
4791   // A well-formed anonymous tag must always be a TUK_Definition.
4792   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4793 
4794   // The type must match the tag exactly;  no qualifiers allowed.
4795   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4796                            Context.getTagDeclType(TagFromDeclSpec))) {
4797     if (getLangOpts().CPlusPlus)
4798       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4799     return;
4800   }
4801 
4802   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4803   //   An unnamed class with a typedef name for linkage purposes shall [be
4804   //   C-like].
4805   //
4806   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4807   // shouldn't happen, but there are constructs that the language rule doesn't
4808   // disallow for which we can't reasonably avoid computing linkage early.
4809   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4810   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4811                              : NonCLikeKind();
4812   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4813   if (NonCLike || ChangesLinkage) {
4814     if (NonCLike.Kind == NonCLikeKind::Invalid)
4815       return;
4816 
4817     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4818     if (ChangesLinkage) {
4819       // If the linkage changes, we can't accept this as an extension.
4820       if (NonCLike.Kind == NonCLikeKind::None)
4821         DiagID = diag::err_typedef_changes_linkage;
4822       else
4823         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4824     }
4825 
4826     SourceLocation FixitLoc =
4827         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4828     llvm::SmallString<40> TextToInsert;
4829     TextToInsert += ' ';
4830     TextToInsert += NewTD->getIdentifier()->getName();
4831 
4832     Diag(FixitLoc, DiagID)
4833       << isa<TypeAliasDecl>(NewTD)
4834       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4835     if (NonCLike.Kind != NonCLikeKind::None) {
4836       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4837         << NonCLike.Kind - 1 << NonCLike.Range;
4838     }
4839     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4840       << NewTD << isa<TypeAliasDecl>(NewTD);
4841 
4842     if (ChangesLinkage)
4843       return;
4844   }
4845 
4846   // Otherwise, set this as the anon-decl typedef for the tag.
4847   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4848 }
4849 
4850 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4851   switch (T) {
4852   case DeclSpec::TST_class:
4853     return 0;
4854   case DeclSpec::TST_struct:
4855     return 1;
4856   case DeclSpec::TST_interface:
4857     return 2;
4858   case DeclSpec::TST_union:
4859     return 3;
4860   case DeclSpec::TST_enum:
4861     return 4;
4862   default:
4863     llvm_unreachable("unexpected type specifier");
4864   }
4865 }
4866 
4867 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4868 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4869 /// parameters to cope with template friend declarations.
4870 Decl *
4871 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4872                                  MultiTemplateParamsArg TemplateParams,
4873                                  bool IsExplicitInstantiation,
4874                                  RecordDecl *&AnonRecord) {
4875   Decl *TagD = nullptr;
4876   TagDecl *Tag = nullptr;
4877   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4878       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4879       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4880       DS.getTypeSpecType() == DeclSpec::TST_union ||
4881       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4882     TagD = DS.getRepAsDecl();
4883 
4884     if (!TagD) // We probably had an error
4885       return nullptr;
4886 
4887     // Note that the above type specs guarantee that the
4888     // type rep is a Decl, whereas in many of the others
4889     // it's a Type.
4890     if (isa<TagDecl>(TagD))
4891       Tag = cast<TagDecl>(TagD);
4892     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4893       Tag = CTD->getTemplatedDecl();
4894   }
4895 
4896   if (Tag) {
4897     handleTagNumbering(Tag, S);
4898     Tag->setFreeStanding();
4899     if (Tag->isInvalidDecl())
4900       return Tag;
4901   }
4902 
4903   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4904     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4905     // or incomplete types shall not be restrict-qualified."
4906     if (TypeQuals & DeclSpec::TQ_restrict)
4907       Diag(DS.getRestrictSpecLoc(),
4908            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4909            << DS.getSourceRange();
4910   }
4911 
4912   if (DS.isInlineSpecified())
4913     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4914         << getLangOpts().CPlusPlus17;
4915 
4916   if (DS.hasConstexprSpecifier()) {
4917     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4918     // and definitions of functions and variables.
4919     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4920     // the declaration of a function or function template
4921     if (Tag)
4922       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4923           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4924           << static_cast<int>(DS.getConstexprSpecifier());
4925     else
4926       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4927           << static_cast<int>(DS.getConstexprSpecifier());
4928     // Don't emit warnings after this error.
4929     return TagD;
4930   }
4931 
4932   DiagnoseFunctionSpecifiers(DS);
4933 
4934   if (DS.isFriendSpecified()) {
4935     // If we're dealing with a decl but not a TagDecl, assume that
4936     // whatever routines created it handled the friendship aspect.
4937     if (TagD && !Tag)
4938       return nullptr;
4939     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4940   }
4941 
4942   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4943   bool IsExplicitSpecialization =
4944     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4945   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4946       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4947       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4948     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4949     // nested-name-specifier unless it is an explicit instantiation
4950     // or an explicit specialization.
4951     //
4952     // FIXME: We allow class template partial specializations here too, per the
4953     // obvious intent of DR1819.
4954     //
4955     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4956     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4957         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4958     return nullptr;
4959   }
4960 
4961   // Track whether this decl-specifier declares anything.
4962   bool DeclaresAnything = true;
4963 
4964   // Handle anonymous struct definitions.
4965   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4966     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4967         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4968       if (getLangOpts().CPlusPlus ||
4969           Record->getDeclContext()->isRecord()) {
4970         // If CurContext is a DeclContext that can contain statements,
4971         // RecursiveASTVisitor won't visit the decls that
4972         // BuildAnonymousStructOrUnion() will put into CurContext.
4973         // Also store them here so that they can be part of the
4974         // DeclStmt that gets created in this case.
4975         // FIXME: Also return the IndirectFieldDecls created by
4976         // BuildAnonymousStructOr union, for the same reason?
4977         if (CurContext->isFunctionOrMethod())
4978           AnonRecord = Record;
4979         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4980                                            Context.getPrintingPolicy());
4981       }
4982 
4983       DeclaresAnything = false;
4984     }
4985   }
4986 
4987   // C11 6.7.2.1p2:
4988   //   A struct-declaration that does not declare an anonymous structure or
4989   //   anonymous union shall contain a struct-declarator-list.
4990   //
4991   // This rule also existed in C89 and C99; the grammar for struct-declaration
4992   // did not permit a struct-declaration without a struct-declarator-list.
4993   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4994       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4995     // Check for Microsoft C extension: anonymous struct/union member.
4996     // Handle 2 kinds of anonymous struct/union:
4997     //   struct STRUCT;
4998     //   union UNION;
4999     // and
5000     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5001     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5002     if ((Tag && Tag->getDeclName()) ||
5003         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5004       RecordDecl *Record = nullptr;
5005       if (Tag)
5006         Record = dyn_cast<RecordDecl>(Tag);
5007       else if (const RecordType *RT =
5008                    DS.getRepAsType().get()->getAsStructureType())
5009         Record = RT->getDecl();
5010       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5011         Record = UT->getDecl();
5012 
5013       if (Record && getLangOpts().MicrosoftExt) {
5014         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5015             << Record->isUnion() << DS.getSourceRange();
5016         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5017       }
5018 
5019       DeclaresAnything = false;
5020     }
5021   }
5022 
5023   // Skip all the checks below if we have a type error.
5024   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5025       (TagD && TagD->isInvalidDecl()))
5026     return TagD;
5027 
5028   if (getLangOpts().CPlusPlus &&
5029       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5030     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5031       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5032           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5033         DeclaresAnything = false;
5034 
5035   if (!DS.isMissingDeclaratorOk()) {
5036     // Customize diagnostic for a typedef missing a name.
5037     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5038       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5039           << DS.getSourceRange();
5040     else
5041       DeclaresAnything = false;
5042   }
5043 
5044   if (DS.isModulePrivateSpecified() &&
5045       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5046     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5047       << Tag->getTagKind()
5048       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5049 
5050   ActOnDocumentableDecl(TagD);
5051 
5052   // C 6.7/2:
5053   //   A declaration [...] shall declare at least a declarator [...], a tag,
5054   //   or the members of an enumeration.
5055   // C++ [dcl.dcl]p3:
5056   //   [If there are no declarators], and except for the declaration of an
5057   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5058   //   names into the program, or shall redeclare a name introduced by a
5059   //   previous declaration.
5060   if (!DeclaresAnything) {
5061     // In C, we allow this as a (popular) extension / bug. Don't bother
5062     // producing further diagnostics for redundant qualifiers after this.
5063     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5064                                ? diag::err_no_declarators
5065                                : diag::ext_no_declarators)
5066         << DS.getSourceRange();
5067     return TagD;
5068   }
5069 
5070   // C++ [dcl.stc]p1:
5071   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5072   //   init-declarator-list of the declaration shall not be empty.
5073   // C++ [dcl.fct.spec]p1:
5074   //   If a cv-qualifier appears in a decl-specifier-seq, the
5075   //   init-declarator-list of the declaration shall not be empty.
5076   //
5077   // Spurious qualifiers here appear to be valid in C.
5078   unsigned DiagID = diag::warn_standalone_specifier;
5079   if (getLangOpts().CPlusPlus)
5080     DiagID = diag::ext_standalone_specifier;
5081 
5082   // Note that a linkage-specification sets a storage class, but
5083   // 'extern "C" struct foo;' is actually valid and not theoretically
5084   // useless.
5085   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5086     if (SCS == DeclSpec::SCS_mutable)
5087       // Since mutable is not a viable storage class specifier in C, there is
5088       // no reason to treat it as an extension. Instead, diagnose as an error.
5089       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5090     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5091       Diag(DS.getStorageClassSpecLoc(), DiagID)
5092         << DeclSpec::getSpecifierName(SCS);
5093   }
5094 
5095   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5096     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5097       << DeclSpec::getSpecifierName(TSCS);
5098   if (DS.getTypeQualifiers()) {
5099     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5100       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5101     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5102       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5103     // Restrict is covered above.
5104     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5105       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5106     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5107       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5108   }
5109 
5110   // Warn about ignored type attributes, for example:
5111   // __attribute__((aligned)) struct A;
5112   // Attributes should be placed after tag to apply to type declaration.
5113   if (!DS.getAttributes().empty()) {
5114     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5115     if (TypeSpecType == DeclSpec::TST_class ||
5116         TypeSpecType == DeclSpec::TST_struct ||
5117         TypeSpecType == DeclSpec::TST_interface ||
5118         TypeSpecType == DeclSpec::TST_union ||
5119         TypeSpecType == DeclSpec::TST_enum) {
5120       for (const ParsedAttr &AL : DS.getAttributes())
5121         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5122             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5123     }
5124   }
5125 
5126   return TagD;
5127 }
5128 
5129 /// We are trying to inject an anonymous member into the given scope;
5130 /// check if there's an existing declaration that can't be overloaded.
5131 ///
5132 /// \return true if this is a forbidden redeclaration
5133 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5134                                          Scope *S,
5135                                          DeclContext *Owner,
5136                                          DeclarationName Name,
5137                                          SourceLocation NameLoc,
5138                                          bool IsUnion) {
5139   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5140                  Sema::ForVisibleRedeclaration);
5141   if (!SemaRef.LookupName(R, S)) return false;
5142 
5143   // Pick a representative declaration.
5144   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5145   assert(PrevDecl && "Expected a non-null Decl");
5146 
5147   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5148     return false;
5149 
5150   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5151     << IsUnion << Name;
5152   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5153 
5154   return true;
5155 }
5156 
5157 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5158 /// anonymous struct or union AnonRecord into the owning context Owner
5159 /// and scope S. This routine will be invoked just after we realize
5160 /// that an unnamed union or struct is actually an anonymous union or
5161 /// struct, e.g.,
5162 ///
5163 /// @code
5164 /// union {
5165 ///   int i;
5166 ///   float f;
5167 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5168 ///    // f into the surrounding scope.x
5169 /// @endcode
5170 ///
5171 /// This routine is recursive, injecting the names of nested anonymous
5172 /// structs/unions into the owning context and scope as well.
5173 static bool
5174 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5175                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5176                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5177   bool Invalid = false;
5178 
5179   // Look every FieldDecl and IndirectFieldDecl with a name.
5180   for (auto *D : AnonRecord->decls()) {
5181     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5182         cast<NamedDecl>(D)->getDeclName()) {
5183       ValueDecl *VD = cast<ValueDecl>(D);
5184       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5185                                        VD->getLocation(),
5186                                        AnonRecord->isUnion())) {
5187         // C++ [class.union]p2:
5188         //   The names of the members of an anonymous union shall be
5189         //   distinct from the names of any other entity in the
5190         //   scope in which the anonymous union is declared.
5191         Invalid = true;
5192       } else {
5193         // C++ [class.union]p2:
5194         //   For the purpose of name lookup, after the anonymous union
5195         //   definition, the members of the anonymous union are
5196         //   considered to have been defined in the scope in which the
5197         //   anonymous union is declared.
5198         unsigned OldChainingSize = Chaining.size();
5199         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5200           Chaining.append(IF->chain_begin(), IF->chain_end());
5201         else
5202           Chaining.push_back(VD);
5203 
5204         assert(Chaining.size() >= 2);
5205         NamedDecl **NamedChain =
5206           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5207         for (unsigned i = 0; i < Chaining.size(); i++)
5208           NamedChain[i] = Chaining[i];
5209 
5210         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5211             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5212             VD->getType(), {NamedChain, Chaining.size()});
5213 
5214         for (const auto *Attr : VD->attrs())
5215           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5216 
5217         IndirectField->setAccess(AS);
5218         IndirectField->setImplicit();
5219         SemaRef.PushOnScopeChains(IndirectField, S);
5220 
5221         // That includes picking up the appropriate access specifier.
5222         if (AS != AS_none) IndirectField->setAccess(AS);
5223 
5224         Chaining.resize(OldChainingSize);
5225       }
5226     }
5227   }
5228 
5229   return Invalid;
5230 }
5231 
5232 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5233 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5234 /// illegal input values are mapped to SC_None.
5235 static StorageClass
5236 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5237   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5238   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5239          "Parser allowed 'typedef' as storage class VarDecl.");
5240   switch (StorageClassSpec) {
5241   case DeclSpec::SCS_unspecified:    return SC_None;
5242   case DeclSpec::SCS_extern:
5243     if (DS.isExternInLinkageSpec())
5244       return SC_None;
5245     return SC_Extern;
5246   case DeclSpec::SCS_static:         return SC_Static;
5247   case DeclSpec::SCS_auto:           return SC_Auto;
5248   case DeclSpec::SCS_register:       return SC_Register;
5249   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5250     // Illegal SCSs map to None: error reporting is up to the caller.
5251   case DeclSpec::SCS_mutable:        // Fall through.
5252   case DeclSpec::SCS_typedef:        return SC_None;
5253   }
5254   llvm_unreachable("unknown storage class specifier");
5255 }
5256 
5257 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5258   assert(Record->hasInClassInitializer());
5259 
5260   for (const auto *I : Record->decls()) {
5261     const auto *FD = dyn_cast<FieldDecl>(I);
5262     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5263       FD = IFD->getAnonField();
5264     if (FD && FD->hasInClassInitializer())
5265       return FD->getLocation();
5266   }
5267 
5268   llvm_unreachable("couldn't find in-class initializer");
5269 }
5270 
5271 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5272                                       SourceLocation DefaultInitLoc) {
5273   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5274     return;
5275 
5276   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5277   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5278 }
5279 
5280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5281                                       CXXRecordDecl *AnonUnion) {
5282   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5283     return;
5284 
5285   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5286 }
5287 
5288 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5289 /// anonymous structure or union. Anonymous unions are a C++ feature
5290 /// (C++ [class.union]) and a C11 feature; anonymous structures
5291 /// are a C11 feature and GNU C++ extension.
5292 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5293                                         AccessSpecifier AS,
5294                                         RecordDecl *Record,
5295                                         const PrintingPolicy &Policy) {
5296   DeclContext *Owner = Record->getDeclContext();
5297 
5298   // Diagnose whether this anonymous struct/union is an extension.
5299   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5300     Diag(Record->getLocation(), diag::ext_anonymous_union);
5301   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5302     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5303   else if (!Record->isUnion() && !getLangOpts().C11)
5304     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5305 
5306   // C and C++ require different kinds of checks for anonymous
5307   // structs/unions.
5308   bool Invalid = false;
5309   if (getLangOpts().CPlusPlus) {
5310     const char *PrevSpec = nullptr;
5311     if (Record->isUnion()) {
5312       // C++ [class.union]p6:
5313       // C++17 [class.union.anon]p2:
5314       //   Anonymous unions declared in a named namespace or in the
5315       //   global namespace shall be declared static.
5316       unsigned DiagID;
5317       DeclContext *OwnerScope = Owner->getRedeclContext();
5318       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5319           (OwnerScope->isTranslationUnit() ||
5320            (OwnerScope->isNamespace() &&
5321             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5322         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5323           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5324 
5325         // Recover by adding 'static'.
5326         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5327                                PrevSpec, DiagID, Policy);
5328       }
5329       // C++ [class.union]p6:
5330       //   A storage class is not allowed in a declaration of an
5331       //   anonymous union in a class scope.
5332       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5333                isa<RecordDecl>(Owner)) {
5334         Diag(DS.getStorageClassSpecLoc(),
5335              diag::err_anonymous_union_with_storage_spec)
5336           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5337 
5338         // Recover by removing the storage specifier.
5339         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5340                                SourceLocation(),
5341                                PrevSpec, DiagID, Context.getPrintingPolicy());
5342       }
5343     }
5344 
5345     // Ignore const/volatile/restrict qualifiers.
5346     if (DS.getTypeQualifiers()) {
5347       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5348         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5349           << Record->isUnion() << "const"
5350           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5351       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5352         Diag(DS.getVolatileSpecLoc(),
5353              diag::ext_anonymous_struct_union_qualified)
5354           << Record->isUnion() << "volatile"
5355           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5356       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5357         Diag(DS.getRestrictSpecLoc(),
5358              diag::ext_anonymous_struct_union_qualified)
5359           << Record->isUnion() << "restrict"
5360           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5361       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5362         Diag(DS.getAtomicSpecLoc(),
5363              diag::ext_anonymous_struct_union_qualified)
5364           << Record->isUnion() << "_Atomic"
5365           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5366       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5367         Diag(DS.getUnalignedSpecLoc(),
5368              diag::ext_anonymous_struct_union_qualified)
5369           << Record->isUnion() << "__unaligned"
5370           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5371 
5372       DS.ClearTypeQualifiers();
5373     }
5374 
5375     // C++ [class.union]p2:
5376     //   The member-specification of an anonymous union shall only
5377     //   define non-static data members. [Note: nested types and
5378     //   functions cannot be declared within an anonymous union. ]
5379     for (auto *Mem : Record->decls()) {
5380       // Ignore invalid declarations; we already diagnosed them.
5381       if (Mem->isInvalidDecl())
5382         continue;
5383 
5384       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5385         // C++ [class.union]p3:
5386         //   An anonymous union shall not have private or protected
5387         //   members (clause 11).
5388         assert(FD->getAccess() != AS_none);
5389         if (FD->getAccess() != AS_public) {
5390           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5391             << Record->isUnion() << (FD->getAccess() == AS_protected);
5392           Invalid = true;
5393         }
5394 
5395         // C++ [class.union]p1
5396         //   An object of a class with a non-trivial constructor, a non-trivial
5397         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5398         //   assignment operator cannot be a member of a union, nor can an
5399         //   array of such objects.
5400         if (CheckNontrivialField(FD))
5401           Invalid = true;
5402       } else if (Mem->isImplicit()) {
5403         // Any implicit members are fine.
5404       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5405         // This is a type that showed up in an
5406         // elaborated-type-specifier inside the anonymous struct or
5407         // union, but which actually declares a type outside of the
5408         // anonymous struct or union. It's okay.
5409       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5410         if (!MemRecord->isAnonymousStructOrUnion() &&
5411             MemRecord->getDeclName()) {
5412           // Visual C++ allows type definition in anonymous struct or union.
5413           if (getLangOpts().MicrosoftExt)
5414             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5415               << Record->isUnion();
5416           else {
5417             // This is a nested type declaration.
5418             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5419               << Record->isUnion();
5420             Invalid = true;
5421           }
5422         } else {
5423           // This is an anonymous type definition within another anonymous type.
5424           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5425           // not part of standard C++.
5426           Diag(MemRecord->getLocation(),
5427                diag::ext_anonymous_record_with_anonymous_type)
5428             << Record->isUnion();
5429         }
5430       } else if (isa<AccessSpecDecl>(Mem)) {
5431         // Any access specifier is fine.
5432       } else if (isa<StaticAssertDecl>(Mem)) {
5433         // In C++1z, static_assert declarations are also fine.
5434       } else {
5435         // We have something that isn't a non-static data
5436         // member. Complain about it.
5437         unsigned DK = diag::err_anonymous_record_bad_member;
5438         if (isa<TypeDecl>(Mem))
5439           DK = diag::err_anonymous_record_with_type;
5440         else if (isa<FunctionDecl>(Mem))
5441           DK = diag::err_anonymous_record_with_function;
5442         else if (isa<VarDecl>(Mem))
5443           DK = diag::err_anonymous_record_with_static;
5444 
5445         // Visual C++ allows type definition in anonymous struct or union.
5446         if (getLangOpts().MicrosoftExt &&
5447             DK == diag::err_anonymous_record_with_type)
5448           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5449             << Record->isUnion();
5450         else {
5451           Diag(Mem->getLocation(), DK) << Record->isUnion();
5452           Invalid = true;
5453         }
5454       }
5455     }
5456 
5457     // C++11 [class.union]p8 (DR1460):
5458     //   At most one variant member of a union may have a
5459     //   brace-or-equal-initializer.
5460     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5461         Owner->isRecord())
5462       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5463                                 cast<CXXRecordDecl>(Record));
5464   }
5465 
5466   if (!Record->isUnion() && !Owner->isRecord()) {
5467     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5468       << getLangOpts().CPlusPlus;
5469     Invalid = true;
5470   }
5471 
5472   // C++ [dcl.dcl]p3:
5473   //   [If there are no declarators], and except for the declaration of an
5474   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5475   //   names into the program
5476   // C++ [class.mem]p2:
5477   //   each such member-declaration shall either declare at least one member
5478   //   name of the class or declare at least one unnamed bit-field
5479   //
5480   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5481   if (getLangOpts().CPlusPlus && Record->field_empty())
5482     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5483 
5484   // Mock up a declarator.
5485   Declarator Dc(DS, DeclaratorContext::Member);
5486   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5487   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5488 
5489   // Create a declaration for this anonymous struct/union.
5490   NamedDecl *Anon = nullptr;
5491   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5492     Anon = FieldDecl::Create(
5493         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5494         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5495         /*BitWidth=*/nullptr, /*Mutable=*/false,
5496         /*InitStyle=*/ICIS_NoInit);
5497     Anon->setAccess(AS);
5498     ProcessDeclAttributes(S, Anon, Dc);
5499 
5500     if (getLangOpts().CPlusPlus)
5501       FieldCollector->Add(cast<FieldDecl>(Anon));
5502   } else {
5503     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5504     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5505     if (SCSpec == DeclSpec::SCS_mutable) {
5506       // mutable can only appear on non-static class members, so it's always
5507       // an error here
5508       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5509       Invalid = true;
5510       SC = SC_None;
5511     }
5512 
5513     assert(DS.getAttributes().empty() && "No attribute expected");
5514     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5515                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5516                            Context.getTypeDeclType(Record), TInfo, SC);
5517 
5518     // Default-initialize the implicit variable. This initialization will be
5519     // trivial in almost all cases, except if a union member has an in-class
5520     // initializer:
5521     //   union { int n = 0; };
5522     ActOnUninitializedDecl(Anon);
5523   }
5524   Anon->setImplicit();
5525 
5526   // Mark this as an anonymous struct/union type.
5527   Record->setAnonymousStructOrUnion(true);
5528 
5529   // Add the anonymous struct/union object to the current
5530   // context. We'll be referencing this object when we refer to one of
5531   // its members.
5532   Owner->addDecl(Anon);
5533 
5534   // Inject the members of the anonymous struct/union into the owning
5535   // context and into the identifier resolver chain for name lookup
5536   // purposes.
5537   SmallVector<NamedDecl*, 2> Chain;
5538   Chain.push_back(Anon);
5539 
5540   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5541     Invalid = true;
5542 
5543   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5544     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5545       MangleNumberingContext *MCtx;
5546       Decl *ManglingContextDecl;
5547       std::tie(MCtx, ManglingContextDecl) =
5548           getCurrentMangleNumberContext(NewVD->getDeclContext());
5549       if (MCtx) {
5550         Context.setManglingNumber(
5551             NewVD, MCtx->getManglingNumber(
5552                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5553         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5554       }
5555     }
5556   }
5557 
5558   if (Invalid)
5559     Anon->setInvalidDecl();
5560 
5561   return Anon;
5562 }
5563 
5564 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5565 /// Microsoft C anonymous structure.
5566 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5567 /// Example:
5568 ///
5569 /// struct A { int a; };
5570 /// struct B { struct A; int b; };
5571 ///
5572 /// void foo() {
5573 ///   B var;
5574 ///   var.a = 3;
5575 /// }
5576 ///
5577 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5578                                            RecordDecl *Record) {
5579   assert(Record && "expected a record!");
5580 
5581   // Mock up a declarator.
5582   Declarator Dc(DS, DeclaratorContext::TypeName);
5583   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5584   assert(TInfo && "couldn't build declarator info for anonymous struct");
5585 
5586   auto *ParentDecl = cast<RecordDecl>(CurContext);
5587   QualType RecTy = Context.getTypeDeclType(Record);
5588 
5589   // Create a declaration for this anonymous struct.
5590   NamedDecl *Anon =
5591       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5592                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5593                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5594                         /*InitStyle=*/ICIS_NoInit);
5595   Anon->setImplicit();
5596 
5597   // Add the anonymous struct object to the current context.
5598   CurContext->addDecl(Anon);
5599 
5600   // Inject the members of the anonymous struct into the current
5601   // context and into the identifier resolver chain for name lookup
5602   // purposes.
5603   SmallVector<NamedDecl*, 2> Chain;
5604   Chain.push_back(Anon);
5605 
5606   RecordDecl *RecordDef = Record->getDefinition();
5607   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5608                                diag::err_field_incomplete_or_sizeless) ||
5609       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5610                                           AS_none, Chain)) {
5611     Anon->setInvalidDecl();
5612     ParentDecl->setInvalidDecl();
5613   }
5614 
5615   return Anon;
5616 }
5617 
5618 /// GetNameForDeclarator - Determine the full declaration name for the
5619 /// given Declarator.
5620 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5621   return GetNameFromUnqualifiedId(D.getName());
5622 }
5623 
5624 /// Retrieves the declaration name from a parsed unqualified-id.
5625 DeclarationNameInfo
5626 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5627   DeclarationNameInfo NameInfo;
5628   NameInfo.setLoc(Name.StartLocation);
5629 
5630   switch (Name.getKind()) {
5631 
5632   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5633   case UnqualifiedIdKind::IK_Identifier:
5634     NameInfo.setName(Name.Identifier);
5635     return NameInfo;
5636 
5637   case UnqualifiedIdKind::IK_DeductionGuideName: {
5638     // C++ [temp.deduct.guide]p3:
5639     //   The simple-template-id shall name a class template specialization.
5640     //   The template-name shall be the same identifier as the template-name
5641     //   of the simple-template-id.
5642     // These together intend to imply that the template-name shall name a
5643     // class template.
5644     // FIXME: template<typename T> struct X {};
5645     //        template<typename T> using Y = X<T>;
5646     //        Y(int) -> Y<int>;
5647     //   satisfies these rules but does not name a class template.
5648     TemplateName TN = Name.TemplateName.get().get();
5649     auto *Template = TN.getAsTemplateDecl();
5650     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5651       Diag(Name.StartLocation,
5652            diag::err_deduction_guide_name_not_class_template)
5653         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5654       if (Template)
5655         Diag(Template->getLocation(), diag::note_template_decl_here);
5656       return DeclarationNameInfo();
5657     }
5658 
5659     NameInfo.setName(
5660         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5661     return NameInfo;
5662   }
5663 
5664   case UnqualifiedIdKind::IK_OperatorFunctionId:
5665     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5666                                            Name.OperatorFunctionId.Operator));
5667     NameInfo.setCXXOperatorNameRange(SourceRange(
5668         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5669     return NameInfo;
5670 
5671   case UnqualifiedIdKind::IK_LiteralOperatorId:
5672     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5673                                                            Name.Identifier));
5674     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5675     return NameInfo;
5676 
5677   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5678     TypeSourceInfo *TInfo;
5679     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5680     if (Ty.isNull())
5681       return DeclarationNameInfo();
5682     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5683                                                Context.getCanonicalType(Ty)));
5684     NameInfo.setNamedTypeInfo(TInfo);
5685     return NameInfo;
5686   }
5687 
5688   case UnqualifiedIdKind::IK_ConstructorName: {
5689     TypeSourceInfo *TInfo;
5690     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5691     if (Ty.isNull())
5692       return DeclarationNameInfo();
5693     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5694                                               Context.getCanonicalType(Ty)));
5695     NameInfo.setNamedTypeInfo(TInfo);
5696     return NameInfo;
5697   }
5698 
5699   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5700     // In well-formed code, we can only have a constructor
5701     // template-id that refers to the current context, so go there
5702     // to find the actual type being constructed.
5703     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5704     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5705       return DeclarationNameInfo();
5706 
5707     // Determine the type of the class being constructed.
5708     QualType CurClassType = Context.getTypeDeclType(CurClass);
5709 
5710     // FIXME: Check two things: that the template-id names the same type as
5711     // CurClassType, and that the template-id does not occur when the name
5712     // was qualified.
5713 
5714     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5715                                     Context.getCanonicalType(CurClassType)));
5716     // FIXME: should we retrieve TypeSourceInfo?
5717     NameInfo.setNamedTypeInfo(nullptr);
5718     return NameInfo;
5719   }
5720 
5721   case UnqualifiedIdKind::IK_DestructorName: {
5722     TypeSourceInfo *TInfo;
5723     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5724     if (Ty.isNull())
5725       return DeclarationNameInfo();
5726     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5727                                               Context.getCanonicalType(Ty)));
5728     NameInfo.setNamedTypeInfo(TInfo);
5729     return NameInfo;
5730   }
5731 
5732   case UnqualifiedIdKind::IK_TemplateId: {
5733     TemplateName TName = Name.TemplateId->Template.get();
5734     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5735     return Context.getNameForTemplate(TName, TNameLoc);
5736   }
5737 
5738   } // switch (Name.getKind())
5739 
5740   llvm_unreachable("Unknown name kind");
5741 }
5742 
5743 static QualType getCoreType(QualType Ty) {
5744   do {
5745     if (Ty->isPointerType() || Ty->isReferenceType())
5746       Ty = Ty->getPointeeType();
5747     else if (Ty->isArrayType())
5748       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5749     else
5750       return Ty.withoutLocalFastQualifiers();
5751   } while (true);
5752 }
5753 
5754 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5755 /// and Definition have "nearly" matching parameters. This heuristic is
5756 /// used to improve diagnostics in the case where an out-of-line function
5757 /// definition doesn't match any declaration within the class or namespace.
5758 /// Also sets Params to the list of indices to the parameters that differ
5759 /// between the declaration and the definition. If hasSimilarParameters
5760 /// returns true and Params is empty, then all of the parameters match.
5761 static bool hasSimilarParameters(ASTContext &Context,
5762                                      FunctionDecl *Declaration,
5763                                      FunctionDecl *Definition,
5764                                      SmallVectorImpl<unsigned> &Params) {
5765   Params.clear();
5766   if (Declaration->param_size() != Definition->param_size())
5767     return false;
5768   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5769     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5770     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5771 
5772     // The parameter types are identical
5773     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5774       continue;
5775 
5776     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5777     QualType DefParamBaseTy = getCoreType(DefParamTy);
5778     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5779     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5780 
5781     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5782         (DeclTyName && DeclTyName == DefTyName))
5783       Params.push_back(Idx);
5784     else  // The two parameters aren't even close
5785       return false;
5786   }
5787 
5788   return true;
5789 }
5790 
5791 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5792 /// declarator needs to be rebuilt in the current instantiation.
5793 /// Any bits of declarator which appear before the name are valid for
5794 /// consideration here.  That's specifically the type in the decl spec
5795 /// and the base type in any member-pointer chunks.
5796 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5797                                                     DeclarationName Name) {
5798   // The types we specifically need to rebuild are:
5799   //   - typenames, typeofs, and decltypes
5800   //   - types which will become injected class names
5801   // Of course, we also need to rebuild any type referencing such a
5802   // type.  It's safest to just say "dependent", but we call out a
5803   // few cases here.
5804 
5805   DeclSpec &DS = D.getMutableDeclSpec();
5806   switch (DS.getTypeSpecType()) {
5807   case DeclSpec::TST_typename:
5808   case DeclSpec::TST_typeofType:
5809   case DeclSpec::TST_underlyingType:
5810   case DeclSpec::TST_atomic: {
5811     // Grab the type from the parser.
5812     TypeSourceInfo *TSI = nullptr;
5813     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5814     if (T.isNull() || !T->isInstantiationDependentType()) break;
5815 
5816     // Make sure there's a type source info.  This isn't really much
5817     // of a waste; most dependent types should have type source info
5818     // attached already.
5819     if (!TSI)
5820       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5821 
5822     // Rebuild the type in the current instantiation.
5823     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5824     if (!TSI) return true;
5825 
5826     // Store the new type back in the decl spec.
5827     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5828     DS.UpdateTypeRep(LocType);
5829     break;
5830   }
5831 
5832   case DeclSpec::TST_decltype:
5833   case DeclSpec::TST_typeofExpr: {
5834     Expr *E = DS.getRepAsExpr();
5835     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5836     if (Result.isInvalid()) return true;
5837     DS.UpdateExprRep(Result.get());
5838     break;
5839   }
5840 
5841   default:
5842     // Nothing to do for these decl specs.
5843     break;
5844   }
5845 
5846   // It doesn't matter what order we do this in.
5847   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5848     DeclaratorChunk &Chunk = D.getTypeObject(I);
5849 
5850     // The only type information in the declarator which can come
5851     // before the declaration name is the base type of a member
5852     // pointer.
5853     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5854       continue;
5855 
5856     // Rebuild the scope specifier in-place.
5857     CXXScopeSpec &SS = Chunk.Mem.Scope();
5858     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5859       return true;
5860   }
5861 
5862   return false;
5863 }
5864 
5865 /// Returns true if the declaration is declared in a system header or from a
5866 /// system macro.
5867 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5868   return SM.isInSystemHeader(D->getLocation()) ||
5869          SM.isInSystemMacro(D->getLocation());
5870 }
5871 
5872 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5873   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5874   // of system decl.
5875   if (D->getPreviousDecl() || D->isImplicit())
5876     return;
5877   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5878   if (Status != ReservedIdentifierStatus::NotReserved &&
5879       !isFromSystemHeader(Context.getSourceManager(), D)) {
5880     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5881         << D << static_cast<int>(Status);
5882   }
5883 }
5884 
5885 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5886   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5887   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5888 
5889   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5890       Dcl && Dcl->getDeclContext()->isFileContext())
5891     Dcl->setTopLevelDeclInObjCContainer();
5892 
5893   return Dcl;
5894 }
5895 
5896 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5897 ///   If T is the name of a class, then each of the following shall have a
5898 ///   name different from T:
5899 ///     - every static data member of class T;
5900 ///     - every member function of class T
5901 ///     - every member of class T that is itself a type;
5902 /// \returns true if the declaration name violates these rules.
5903 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5904                                    DeclarationNameInfo NameInfo) {
5905   DeclarationName Name = NameInfo.getName();
5906 
5907   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5908   while (Record && Record->isAnonymousStructOrUnion())
5909     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5910   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5911     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5912     return true;
5913   }
5914 
5915   return false;
5916 }
5917 
5918 /// Diagnose a declaration whose declarator-id has the given
5919 /// nested-name-specifier.
5920 ///
5921 /// \param SS The nested-name-specifier of the declarator-id.
5922 ///
5923 /// \param DC The declaration context to which the nested-name-specifier
5924 /// resolves.
5925 ///
5926 /// \param Name The name of the entity being declared.
5927 ///
5928 /// \param Loc The location of the name of the entity being declared.
5929 ///
5930 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5931 /// we're declaring an explicit / partial specialization / instantiation.
5932 ///
5933 /// \returns true if we cannot safely recover from this error, false otherwise.
5934 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5935                                         DeclarationName Name,
5936                                         SourceLocation Loc, bool IsTemplateId) {
5937   DeclContext *Cur = CurContext;
5938   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5939     Cur = Cur->getParent();
5940 
5941   // If the user provided a superfluous scope specifier that refers back to the
5942   // class in which the entity is already declared, diagnose and ignore it.
5943   //
5944   // class X {
5945   //   void X::f();
5946   // };
5947   //
5948   // Note, it was once ill-formed to give redundant qualification in all
5949   // contexts, but that rule was removed by DR482.
5950   if (Cur->Equals(DC)) {
5951     if (Cur->isRecord()) {
5952       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5953                                       : diag::err_member_extra_qualification)
5954         << Name << FixItHint::CreateRemoval(SS.getRange());
5955       SS.clear();
5956     } else {
5957       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5958     }
5959     return false;
5960   }
5961 
5962   // Check whether the qualifying scope encloses the scope of the original
5963   // declaration. For a template-id, we perform the checks in
5964   // CheckTemplateSpecializationScope.
5965   if (!Cur->Encloses(DC) && !IsTemplateId) {
5966     if (Cur->isRecord())
5967       Diag(Loc, diag::err_member_qualification)
5968         << Name << SS.getRange();
5969     else if (isa<TranslationUnitDecl>(DC))
5970       Diag(Loc, diag::err_invalid_declarator_global_scope)
5971         << Name << SS.getRange();
5972     else if (isa<FunctionDecl>(Cur))
5973       Diag(Loc, diag::err_invalid_declarator_in_function)
5974         << Name << SS.getRange();
5975     else if (isa<BlockDecl>(Cur))
5976       Diag(Loc, diag::err_invalid_declarator_in_block)
5977         << Name << SS.getRange();
5978     else if (isa<ExportDecl>(Cur)) {
5979       if (!isa<NamespaceDecl>(DC))
5980         Diag(Loc, diag::err_export_non_namespace_scope_name)
5981             << Name << SS.getRange();
5982       else
5983         // The cases that DC is not NamespaceDecl should be handled in
5984         // CheckRedeclarationExported.
5985         return false;
5986     } else
5987       Diag(Loc, diag::err_invalid_declarator_scope)
5988       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5989 
5990     return true;
5991   }
5992 
5993   if (Cur->isRecord()) {
5994     // Cannot qualify members within a class.
5995     Diag(Loc, diag::err_member_qualification)
5996       << Name << SS.getRange();
5997     SS.clear();
5998 
5999     // C++ constructors and destructors with incorrect scopes can break
6000     // our AST invariants by having the wrong underlying types. If
6001     // that's the case, then drop this declaration entirely.
6002     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6003          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6004         !Context.hasSameType(Name.getCXXNameType(),
6005                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6006       return true;
6007 
6008     return false;
6009   }
6010 
6011   // C++11 [dcl.meaning]p1:
6012   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6013   //   not begin with a decltype-specifer"
6014   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6015   while (SpecLoc.getPrefix())
6016     SpecLoc = SpecLoc.getPrefix();
6017   if (isa_and_nonnull<DecltypeType>(
6018           SpecLoc.getNestedNameSpecifier()->getAsType()))
6019     Diag(Loc, diag::err_decltype_in_declarator)
6020       << SpecLoc.getTypeLoc().getSourceRange();
6021 
6022   return false;
6023 }
6024 
6025 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6026                                   MultiTemplateParamsArg TemplateParamLists) {
6027   // TODO: consider using NameInfo for diagnostic.
6028   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6029   DeclarationName Name = NameInfo.getName();
6030 
6031   // All of these full declarators require an identifier.  If it doesn't have
6032   // one, the ParsedFreeStandingDeclSpec action should be used.
6033   if (D.isDecompositionDeclarator()) {
6034     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6035   } else if (!Name) {
6036     if (!D.isInvalidType())  // Reject this if we think it is valid.
6037       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6038           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6039     return nullptr;
6040   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6041     return nullptr;
6042 
6043   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6044   // we find one that is.
6045   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6046          (S->getFlags() & Scope::TemplateParamScope) != 0)
6047     S = S->getParent();
6048 
6049   DeclContext *DC = CurContext;
6050   if (D.getCXXScopeSpec().isInvalid())
6051     D.setInvalidType();
6052   else if (D.getCXXScopeSpec().isSet()) {
6053     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6054                                         UPPC_DeclarationQualifier))
6055       return nullptr;
6056 
6057     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6058     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6059     if (!DC || isa<EnumDecl>(DC)) {
6060       // If we could not compute the declaration context, it's because the
6061       // declaration context is dependent but does not refer to a class,
6062       // class template, or class template partial specialization. Complain
6063       // and return early, to avoid the coming semantic disaster.
6064       Diag(D.getIdentifierLoc(),
6065            diag::err_template_qualified_declarator_no_match)
6066         << D.getCXXScopeSpec().getScopeRep()
6067         << D.getCXXScopeSpec().getRange();
6068       return nullptr;
6069     }
6070     bool IsDependentContext = DC->isDependentContext();
6071 
6072     if (!IsDependentContext &&
6073         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6074       return nullptr;
6075 
6076     // If a class is incomplete, do not parse entities inside it.
6077     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6078       Diag(D.getIdentifierLoc(),
6079            diag::err_member_def_undefined_record)
6080         << Name << DC << D.getCXXScopeSpec().getRange();
6081       return nullptr;
6082     }
6083     if (!D.getDeclSpec().isFriendSpecified()) {
6084       if (diagnoseQualifiedDeclaration(
6085               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6086               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6087         if (DC->isRecord())
6088           return nullptr;
6089 
6090         D.setInvalidType();
6091       }
6092     }
6093 
6094     // Check whether we need to rebuild the type of the given
6095     // declaration in the current instantiation.
6096     if (EnteringContext && IsDependentContext &&
6097         TemplateParamLists.size() != 0) {
6098       ContextRAII SavedContext(*this, DC);
6099       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6100         D.setInvalidType();
6101     }
6102   }
6103 
6104   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6105   QualType R = TInfo->getType();
6106 
6107   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6108                                       UPPC_DeclarationType))
6109     D.setInvalidType();
6110 
6111   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6112                         forRedeclarationInCurContext());
6113 
6114   // See if this is a redefinition of a variable in the same scope.
6115   if (!D.getCXXScopeSpec().isSet()) {
6116     bool IsLinkageLookup = false;
6117     bool CreateBuiltins = false;
6118 
6119     // If the declaration we're planning to build will be a function
6120     // or object with linkage, then look for another declaration with
6121     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6122     //
6123     // If the declaration we're planning to build will be declared with
6124     // external linkage in the translation unit, create any builtin with
6125     // the same name.
6126     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6127       /* Do nothing*/;
6128     else if (CurContext->isFunctionOrMethod() &&
6129              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6130               R->isFunctionType())) {
6131       IsLinkageLookup = true;
6132       CreateBuiltins =
6133           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6134     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6135                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6136       CreateBuiltins = true;
6137 
6138     if (IsLinkageLookup) {
6139       Previous.clear(LookupRedeclarationWithLinkage);
6140       Previous.setRedeclarationKind(ForExternalRedeclaration);
6141     }
6142 
6143     LookupName(Previous, S, CreateBuiltins);
6144   } else { // Something like "int foo::x;"
6145     LookupQualifiedName(Previous, DC);
6146 
6147     // C++ [dcl.meaning]p1:
6148     //   When the declarator-id is qualified, the declaration shall refer to a
6149     //  previously declared member of the class or namespace to which the
6150     //  qualifier refers (or, in the case of a namespace, of an element of the
6151     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6152     //  thereof; [...]
6153     //
6154     // Note that we already checked the context above, and that we do not have
6155     // enough information to make sure that Previous contains the declaration
6156     // we want to match. For example, given:
6157     //
6158     //   class X {
6159     //     void f();
6160     //     void f(float);
6161     //   };
6162     //
6163     //   void X::f(int) { } // ill-formed
6164     //
6165     // In this case, Previous will point to the overload set
6166     // containing the two f's declared in X, but neither of them
6167     // matches.
6168 
6169     // C++ [dcl.meaning]p1:
6170     //   [...] the member shall not merely have been introduced by a
6171     //   using-declaration in the scope of the class or namespace nominated by
6172     //   the nested-name-specifier of the declarator-id.
6173     RemoveUsingDecls(Previous);
6174   }
6175 
6176   if (Previous.isSingleResult() &&
6177       Previous.getFoundDecl()->isTemplateParameter()) {
6178     // Maybe we will complain about the shadowed template parameter.
6179     if (!D.isInvalidType())
6180       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6181                                       Previous.getFoundDecl());
6182 
6183     // Just pretend that we didn't see the previous declaration.
6184     Previous.clear();
6185   }
6186 
6187   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6188     // Forget that the previous declaration is the injected-class-name.
6189     Previous.clear();
6190 
6191   // In C++, the previous declaration we find might be a tag type
6192   // (class or enum). In this case, the new declaration will hide the
6193   // tag type. Note that this applies to functions, function templates, and
6194   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6195   if (Previous.isSingleTagDecl() &&
6196       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6197       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6198     Previous.clear();
6199 
6200   // Check that there are no default arguments other than in the parameters
6201   // of a function declaration (C++ only).
6202   if (getLangOpts().CPlusPlus)
6203     CheckExtraCXXDefaultArguments(D);
6204 
6205   NamedDecl *New;
6206 
6207   bool AddToScope = true;
6208   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6209     if (TemplateParamLists.size()) {
6210       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6211       return nullptr;
6212     }
6213 
6214     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6215   } else if (R->isFunctionType()) {
6216     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6217                                   TemplateParamLists,
6218                                   AddToScope);
6219   } else {
6220     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6221                                   AddToScope);
6222   }
6223 
6224   if (!New)
6225     return nullptr;
6226 
6227   // If this has an identifier and is not a function template specialization,
6228   // add it to the scope stack.
6229   if (New->getDeclName() && AddToScope)
6230     PushOnScopeChains(New, S);
6231 
6232   if (isInOpenMPDeclareTargetContext())
6233     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6234 
6235   return New;
6236 }
6237 
6238 /// Helper method to turn variable array types into constant array
6239 /// types in certain situations which would otherwise be errors (for
6240 /// GCC compatibility).
6241 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6242                                                     ASTContext &Context,
6243                                                     bool &SizeIsNegative,
6244                                                     llvm::APSInt &Oversized) {
6245   // This method tries to turn a variable array into a constant
6246   // array even when the size isn't an ICE.  This is necessary
6247   // for compatibility with code that depends on gcc's buggy
6248   // constant expression folding, like struct {char x[(int)(char*)2];}
6249   SizeIsNegative = false;
6250   Oversized = 0;
6251 
6252   if (T->isDependentType())
6253     return QualType();
6254 
6255   QualifierCollector Qs;
6256   const Type *Ty = Qs.strip(T);
6257 
6258   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6259     QualType Pointee = PTy->getPointeeType();
6260     QualType FixedType =
6261         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6262                                             Oversized);
6263     if (FixedType.isNull()) return FixedType;
6264     FixedType = Context.getPointerType(FixedType);
6265     return Qs.apply(Context, FixedType);
6266   }
6267   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6268     QualType Inner = PTy->getInnerType();
6269     QualType FixedType =
6270         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6271                                             Oversized);
6272     if (FixedType.isNull()) return FixedType;
6273     FixedType = Context.getParenType(FixedType);
6274     return Qs.apply(Context, FixedType);
6275   }
6276 
6277   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6278   if (!VLATy)
6279     return QualType();
6280 
6281   QualType ElemTy = VLATy->getElementType();
6282   if (ElemTy->isVariablyModifiedType()) {
6283     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6284                                                  SizeIsNegative, Oversized);
6285     if (ElemTy.isNull())
6286       return QualType();
6287   }
6288 
6289   Expr::EvalResult Result;
6290   if (!VLATy->getSizeExpr() ||
6291       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6292     return QualType();
6293 
6294   llvm::APSInt Res = Result.Val.getInt();
6295 
6296   // Check whether the array size is negative.
6297   if (Res.isSigned() && Res.isNegative()) {
6298     SizeIsNegative = true;
6299     return QualType();
6300   }
6301 
6302   // Check whether the array is too large to be addressed.
6303   unsigned ActiveSizeBits =
6304       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6305        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6306           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6307           : Res.getActiveBits();
6308   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6309     Oversized = Res;
6310     return QualType();
6311   }
6312 
6313   QualType FoldedArrayType = Context.getConstantArrayType(
6314       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6315   return Qs.apply(Context, FoldedArrayType);
6316 }
6317 
6318 static void
6319 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6320   SrcTL = SrcTL.getUnqualifiedLoc();
6321   DstTL = DstTL.getUnqualifiedLoc();
6322   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6323     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6324     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6325                                       DstPTL.getPointeeLoc());
6326     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6327     return;
6328   }
6329   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6330     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6331     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6332                                       DstPTL.getInnerLoc());
6333     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6334     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6335     return;
6336   }
6337   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6338   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6339   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6340   TypeLoc DstElemTL = DstATL.getElementLoc();
6341   if (VariableArrayTypeLoc SrcElemATL =
6342           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6343     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6344     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6345   } else {
6346     DstElemTL.initializeFullCopy(SrcElemTL);
6347   }
6348   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6349   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6350   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6351 }
6352 
6353 /// Helper method to turn variable array types into constant array
6354 /// types in certain situations which would otherwise be errors (for
6355 /// GCC compatibility).
6356 static TypeSourceInfo*
6357 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6358                                               ASTContext &Context,
6359                                               bool &SizeIsNegative,
6360                                               llvm::APSInt &Oversized) {
6361   QualType FixedTy
6362     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6363                                           SizeIsNegative, Oversized);
6364   if (FixedTy.isNull())
6365     return nullptr;
6366   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6367   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6368                                     FixedTInfo->getTypeLoc());
6369   return FixedTInfo;
6370 }
6371 
6372 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6373 /// true if we were successful.
6374 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6375                                            QualType &T, SourceLocation Loc,
6376                                            unsigned FailedFoldDiagID) {
6377   bool SizeIsNegative;
6378   llvm::APSInt Oversized;
6379   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6380       TInfo, Context, SizeIsNegative, Oversized);
6381   if (FixedTInfo) {
6382     Diag(Loc, diag::ext_vla_folded_to_constant);
6383     TInfo = FixedTInfo;
6384     T = FixedTInfo->getType();
6385     return true;
6386   }
6387 
6388   if (SizeIsNegative)
6389     Diag(Loc, diag::err_typecheck_negative_array_size);
6390   else if (Oversized.getBoolValue())
6391     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6392   else if (FailedFoldDiagID)
6393     Diag(Loc, FailedFoldDiagID);
6394   return false;
6395 }
6396 
6397 /// Register the given locally-scoped extern "C" declaration so
6398 /// that it can be found later for redeclarations. We include any extern "C"
6399 /// declaration that is not visible in the translation unit here, not just
6400 /// function-scope declarations.
6401 void
6402 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6403   if (!getLangOpts().CPlusPlus &&
6404       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6405     // Don't need to track declarations in the TU in C.
6406     return;
6407 
6408   // Note that we have a locally-scoped external with this name.
6409   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6410 }
6411 
6412 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6413   // FIXME: We can have multiple results via __attribute__((overloadable)).
6414   auto Result = Context.getExternCContextDecl()->lookup(Name);
6415   return Result.empty() ? nullptr : *Result.begin();
6416 }
6417 
6418 /// Diagnose function specifiers on a declaration of an identifier that
6419 /// does not identify a function.
6420 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6421   // FIXME: We should probably indicate the identifier in question to avoid
6422   // confusion for constructs like "virtual int a(), b;"
6423   if (DS.isVirtualSpecified())
6424     Diag(DS.getVirtualSpecLoc(),
6425          diag::err_virtual_non_function);
6426 
6427   if (DS.hasExplicitSpecifier())
6428     Diag(DS.getExplicitSpecLoc(),
6429          diag::err_explicit_non_function);
6430 
6431   if (DS.isNoreturnSpecified())
6432     Diag(DS.getNoreturnSpecLoc(),
6433          diag::err_noreturn_non_function);
6434 }
6435 
6436 NamedDecl*
6437 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6438                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6439   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6440   if (D.getCXXScopeSpec().isSet()) {
6441     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6442       << D.getCXXScopeSpec().getRange();
6443     D.setInvalidType();
6444     // Pretend we didn't see the scope specifier.
6445     DC = CurContext;
6446     Previous.clear();
6447   }
6448 
6449   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6450 
6451   if (D.getDeclSpec().isInlineSpecified())
6452     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6453         << getLangOpts().CPlusPlus17;
6454   if (D.getDeclSpec().hasConstexprSpecifier())
6455     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6456         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6457 
6458   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6459     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6460       Diag(D.getName().StartLocation,
6461            diag::err_deduction_guide_invalid_specifier)
6462           << "typedef";
6463     else
6464       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6465           << D.getName().getSourceRange();
6466     return nullptr;
6467   }
6468 
6469   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6470   if (!NewTD) return nullptr;
6471 
6472   // Handle attributes prior to checking for duplicates in MergeVarDecl
6473   ProcessDeclAttributes(S, NewTD, D);
6474 
6475   CheckTypedefForVariablyModifiedType(S, NewTD);
6476 
6477   bool Redeclaration = D.isRedeclaration();
6478   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6479   D.setRedeclaration(Redeclaration);
6480   return ND;
6481 }
6482 
6483 void
6484 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6485   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6486   // then it shall have block scope.
6487   // Note that variably modified types must be fixed before merging the decl so
6488   // that redeclarations will match.
6489   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6490   QualType T = TInfo->getType();
6491   if (T->isVariablyModifiedType()) {
6492     setFunctionHasBranchProtectedScope();
6493 
6494     if (S->getFnParent() == nullptr) {
6495       bool SizeIsNegative;
6496       llvm::APSInt Oversized;
6497       TypeSourceInfo *FixedTInfo =
6498         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6499                                                       SizeIsNegative,
6500                                                       Oversized);
6501       if (FixedTInfo) {
6502         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6503         NewTD->setTypeSourceInfo(FixedTInfo);
6504       } else {
6505         if (SizeIsNegative)
6506           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6507         else if (T->isVariableArrayType())
6508           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6509         else if (Oversized.getBoolValue())
6510           Diag(NewTD->getLocation(), diag::err_array_too_large)
6511             << toString(Oversized, 10);
6512         else
6513           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6514         NewTD->setInvalidDecl();
6515       }
6516     }
6517   }
6518 }
6519 
6520 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6521 /// declares a typedef-name, either using the 'typedef' type specifier or via
6522 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6523 NamedDecl*
6524 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6525                            LookupResult &Previous, bool &Redeclaration) {
6526 
6527   // Find the shadowed declaration before filtering for scope.
6528   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6529 
6530   // Merge the decl with the existing one if appropriate. If the decl is
6531   // in an outer scope, it isn't the same thing.
6532   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6533                        /*AllowInlineNamespace*/false);
6534   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6535   if (!Previous.empty()) {
6536     Redeclaration = true;
6537     MergeTypedefNameDecl(S, NewTD, Previous);
6538   } else {
6539     inferGslPointerAttribute(NewTD);
6540   }
6541 
6542   if (ShadowedDecl && !Redeclaration)
6543     CheckShadow(NewTD, ShadowedDecl, Previous);
6544 
6545   // If this is the C FILE type, notify the AST context.
6546   if (IdentifierInfo *II = NewTD->getIdentifier())
6547     if (!NewTD->isInvalidDecl() &&
6548         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6549       if (II->isStr("FILE"))
6550         Context.setFILEDecl(NewTD);
6551       else if (II->isStr("jmp_buf"))
6552         Context.setjmp_bufDecl(NewTD);
6553       else if (II->isStr("sigjmp_buf"))
6554         Context.setsigjmp_bufDecl(NewTD);
6555       else if (II->isStr("ucontext_t"))
6556         Context.setucontext_tDecl(NewTD);
6557     }
6558 
6559   return NewTD;
6560 }
6561 
6562 /// Determines whether the given declaration is an out-of-scope
6563 /// previous declaration.
6564 ///
6565 /// This routine should be invoked when name lookup has found a
6566 /// previous declaration (PrevDecl) that is not in the scope where a
6567 /// new declaration by the same name is being introduced. If the new
6568 /// declaration occurs in a local scope, previous declarations with
6569 /// linkage may still be considered previous declarations (C99
6570 /// 6.2.2p4-5, C++ [basic.link]p6).
6571 ///
6572 /// \param PrevDecl the previous declaration found by name
6573 /// lookup
6574 ///
6575 /// \param DC the context in which the new declaration is being
6576 /// declared.
6577 ///
6578 /// \returns true if PrevDecl is an out-of-scope previous declaration
6579 /// for a new delcaration with the same name.
6580 static bool
6581 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6582                                 ASTContext &Context) {
6583   if (!PrevDecl)
6584     return false;
6585 
6586   if (!PrevDecl->hasLinkage())
6587     return false;
6588 
6589   if (Context.getLangOpts().CPlusPlus) {
6590     // C++ [basic.link]p6:
6591     //   If there is a visible declaration of an entity with linkage
6592     //   having the same name and type, ignoring entities declared
6593     //   outside the innermost enclosing namespace scope, the block
6594     //   scope declaration declares that same entity and receives the
6595     //   linkage of the previous declaration.
6596     DeclContext *OuterContext = DC->getRedeclContext();
6597     if (!OuterContext->isFunctionOrMethod())
6598       // This rule only applies to block-scope declarations.
6599       return false;
6600 
6601     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6602     if (PrevOuterContext->isRecord())
6603       // We found a member function: ignore it.
6604       return false;
6605 
6606     // Find the innermost enclosing namespace for the new and
6607     // previous declarations.
6608     OuterContext = OuterContext->getEnclosingNamespaceContext();
6609     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6610 
6611     // The previous declaration is in a different namespace, so it
6612     // isn't the same function.
6613     if (!OuterContext->Equals(PrevOuterContext))
6614       return false;
6615   }
6616 
6617   return true;
6618 }
6619 
6620 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6621   CXXScopeSpec &SS = D.getCXXScopeSpec();
6622   if (!SS.isSet()) return;
6623   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6624 }
6625 
6626 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6627   QualType type = decl->getType();
6628   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6629   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6630     // Various kinds of declaration aren't allowed to be __autoreleasing.
6631     unsigned kind = -1U;
6632     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6633       if (var->hasAttr<BlocksAttr>())
6634         kind = 0; // __block
6635       else if (!var->hasLocalStorage())
6636         kind = 1; // global
6637     } else if (isa<ObjCIvarDecl>(decl)) {
6638       kind = 3; // ivar
6639     } else if (isa<FieldDecl>(decl)) {
6640       kind = 2; // field
6641     }
6642 
6643     if (kind != -1U) {
6644       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6645         << kind;
6646     }
6647   } else if (lifetime == Qualifiers::OCL_None) {
6648     // Try to infer lifetime.
6649     if (!type->isObjCLifetimeType())
6650       return false;
6651 
6652     lifetime = type->getObjCARCImplicitLifetime();
6653     type = Context.getLifetimeQualifiedType(type, lifetime);
6654     decl->setType(type);
6655   }
6656 
6657   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6658     // Thread-local variables cannot have lifetime.
6659     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6660         var->getTLSKind()) {
6661       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6662         << var->getType();
6663       return true;
6664     }
6665   }
6666 
6667   return false;
6668 }
6669 
6670 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6671   if (Decl->getType().hasAddressSpace())
6672     return;
6673   if (Decl->getType()->isDependentType())
6674     return;
6675   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6676     QualType Type = Var->getType();
6677     if (Type->isSamplerT() || Type->isVoidType())
6678       return;
6679     LangAS ImplAS = LangAS::opencl_private;
6680     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6681     // __opencl_c_program_scope_global_variables feature, the address space
6682     // for a variable at program scope or a static or extern variable inside
6683     // a function are inferred to be __global.
6684     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6685         Var->hasGlobalStorage())
6686       ImplAS = LangAS::opencl_global;
6687     // If the original type from a decayed type is an array type and that array
6688     // type has no address space yet, deduce it now.
6689     if (auto DT = dyn_cast<DecayedType>(Type)) {
6690       auto OrigTy = DT->getOriginalType();
6691       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6692         // Add the address space to the original array type and then propagate
6693         // that to the element type through `getAsArrayType`.
6694         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6695         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6696         // Re-generate the decayed type.
6697         Type = Context.getDecayedType(OrigTy);
6698       }
6699     }
6700     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6701     // Apply any qualifiers (including address space) from the array type to
6702     // the element type. This implements C99 6.7.3p8: "If the specification of
6703     // an array type includes any type qualifiers, the element type is so
6704     // qualified, not the array type."
6705     if (Type->isArrayType())
6706       Type = QualType(Context.getAsArrayType(Type), 0);
6707     Decl->setType(Type);
6708   }
6709 }
6710 
6711 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6712   // Ensure that an auto decl is deduced otherwise the checks below might cache
6713   // the wrong linkage.
6714   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6715 
6716   // 'weak' only applies to declarations with external linkage.
6717   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6718     if (!ND.isExternallyVisible()) {
6719       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6720       ND.dropAttr<WeakAttr>();
6721     }
6722   }
6723   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6724     if (ND.isExternallyVisible()) {
6725       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6726       ND.dropAttr<WeakRefAttr>();
6727       ND.dropAttr<AliasAttr>();
6728     }
6729   }
6730 
6731   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6732     if (VD->hasInit()) {
6733       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6734         assert(VD->isThisDeclarationADefinition() &&
6735                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6736         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6737         VD->dropAttr<AliasAttr>();
6738       }
6739     }
6740   }
6741 
6742   // 'selectany' only applies to externally visible variable declarations.
6743   // It does not apply to functions.
6744   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6745     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6746       S.Diag(Attr->getLocation(),
6747              diag::err_attribute_selectany_non_extern_data);
6748       ND.dropAttr<SelectAnyAttr>();
6749     }
6750   }
6751 
6752   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6753     auto *VD = dyn_cast<VarDecl>(&ND);
6754     bool IsAnonymousNS = false;
6755     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6756     if (VD) {
6757       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6758       while (NS && !IsAnonymousNS) {
6759         IsAnonymousNS = NS->isAnonymousNamespace();
6760         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6761       }
6762     }
6763     // dll attributes require external linkage. Static locals may have external
6764     // linkage but still cannot be explicitly imported or exported.
6765     // In Microsoft mode, a variable defined in anonymous namespace must have
6766     // external linkage in order to be exported.
6767     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6768     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6769         (!AnonNSInMicrosoftMode &&
6770          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6771       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6772         << &ND << Attr;
6773       ND.setInvalidDecl();
6774     }
6775   }
6776 
6777   // Check the attributes on the function type, if any.
6778   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6779     // Don't declare this variable in the second operand of the for-statement;
6780     // GCC miscompiles that by ending its lifetime before evaluating the
6781     // third operand. See gcc.gnu.org/PR86769.
6782     AttributedTypeLoc ATL;
6783     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6784          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6785          TL = ATL.getModifiedLoc()) {
6786       // The [[lifetimebound]] attribute can be applied to the implicit object
6787       // parameter of a non-static member function (other than a ctor or dtor)
6788       // by applying it to the function type.
6789       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6790         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6791         if (!MD || MD->isStatic()) {
6792           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6793               << !MD << A->getRange();
6794         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6795           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6796               << isa<CXXDestructorDecl>(MD) << A->getRange();
6797         }
6798       }
6799     }
6800   }
6801 }
6802 
6803 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6804                                            NamedDecl *NewDecl,
6805                                            bool IsSpecialization,
6806                                            bool IsDefinition) {
6807   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6808     return;
6809 
6810   bool IsTemplate = false;
6811   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6812     OldDecl = OldTD->getTemplatedDecl();
6813     IsTemplate = true;
6814     if (!IsSpecialization)
6815       IsDefinition = false;
6816   }
6817   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6818     NewDecl = NewTD->getTemplatedDecl();
6819     IsTemplate = true;
6820   }
6821 
6822   if (!OldDecl || !NewDecl)
6823     return;
6824 
6825   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6826   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6827   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6828   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6829 
6830   // dllimport and dllexport are inheritable attributes so we have to exclude
6831   // inherited attribute instances.
6832   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6833                     (NewExportAttr && !NewExportAttr->isInherited());
6834 
6835   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6836   // the only exception being explicit specializations.
6837   // Implicitly generated declarations are also excluded for now because there
6838   // is no other way to switch these to use dllimport or dllexport.
6839   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6840 
6841   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6842     // Allow with a warning for free functions and global variables.
6843     bool JustWarn = false;
6844     if (!OldDecl->isCXXClassMember()) {
6845       auto *VD = dyn_cast<VarDecl>(OldDecl);
6846       if (VD && !VD->getDescribedVarTemplate())
6847         JustWarn = true;
6848       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6849       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6850         JustWarn = true;
6851     }
6852 
6853     // We cannot change a declaration that's been used because IR has already
6854     // been emitted. Dllimported functions will still work though (modulo
6855     // address equality) as they can use the thunk.
6856     if (OldDecl->isUsed())
6857       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6858         JustWarn = false;
6859 
6860     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6861                                : diag::err_attribute_dll_redeclaration;
6862     S.Diag(NewDecl->getLocation(), DiagID)
6863         << NewDecl
6864         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6865     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6866     if (!JustWarn) {
6867       NewDecl->setInvalidDecl();
6868       return;
6869     }
6870   }
6871 
6872   // A redeclaration is not allowed to drop a dllimport attribute, the only
6873   // exceptions being inline function definitions (except for function
6874   // templates), local extern declarations, qualified friend declarations or
6875   // special MSVC extension: in the last case, the declaration is treated as if
6876   // it were marked dllexport.
6877   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6878   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6879   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6880     // Ignore static data because out-of-line definitions are diagnosed
6881     // separately.
6882     IsStaticDataMember = VD->isStaticDataMember();
6883     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6884                    VarDecl::DeclarationOnly;
6885   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6886     IsInline = FD->isInlined();
6887     IsQualifiedFriend = FD->getQualifier() &&
6888                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6889   }
6890 
6891   if (OldImportAttr && !HasNewAttr &&
6892       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6893       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6894     if (IsMicrosoftABI && IsDefinition) {
6895       S.Diag(NewDecl->getLocation(),
6896              diag::warn_redeclaration_without_import_attribute)
6897           << NewDecl;
6898       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6899       NewDecl->dropAttr<DLLImportAttr>();
6900       NewDecl->addAttr(
6901           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6902     } else {
6903       S.Diag(NewDecl->getLocation(),
6904              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6905           << NewDecl << OldImportAttr;
6906       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6907       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6908       OldDecl->dropAttr<DLLImportAttr>();
6909       NewDecl->dropAttr<DLLImportAttr>();
6910     }
6911   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6912     // In MinGW, seeing a function declared inline drops the dllimport
6913     // attribute.
6914     OldDecl->dropAttr<DLLImportAttr>();
6915     NewDecl->dropAttr<DLLImportAttr>();
6916     S.Diag(NewDecl->getLocation(),
6917            diag::warn_dllimport_dropped_from_inline_function)
6918         << NewDecl << OldImportAttr;
6919   }
6920 
6921   // A specialization of a class template member function is processed here
6922   // since it's a redeclaration. If the parent class is dllexport, the
6923   // specialization inherits that attribute. This doesn't happen automatically
6924   // since the parent class isn't instantiated until later.
6925   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6926     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6927         !NewImportAttr && !NewExportAttr) {
6928       if (const DLLExportAttr *ParentExportAttr =
6929               MD->getParent()->getAttr<DLLExportAttr>()) {
6930         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6931         NewAttr->setInherited(true);
6932         NewDecl->addAttr(NewAttr);
6933       }
6934     }
6935   }
6936 }
6937 
6938 /// Given that we are within the definition of the given function,
6939 /// will that definition behave like C99's 'inline', where the
6940 /// definition is discarded except for optimization purposes?
6941 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6942   // Try to avoid calling GetGVALinkageForFunction.
6943 
6944   // All cases of this require the 'inline' keyword.
6945   if (!FD->isInlined()) return false;
6946 
6947   // This is only possible in C++ with the gnu_inline attribute.
6948   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6949     return false;
6950 
6951   // Okay, go ahead and call the relatively-more-expensive function.
6952   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6953 }
6954 
6955 /// Determine whether a variable is extern "C" prior to attaching
6956 /// an initializer. We can't just call isExternC() here, because that
6957 /// will also compute and cache whether the declaration is externally
6958 /// visible, which might change when we attach the initializer.
6959 ///
6960 /// This can only be used if the declaration is known to not be a
6961 /// redeclaration of an internal linkage declaration.
6962 ///
6963 /// For instance:
6964 ///
6965 ///   auto x = []{};
6966 ///
6967 /// Attaching the initializer here makes this declaration not externally
6968 /// visible, because its type has internal linkage.
6969 ///
6970 /// FIXME: This is a hack.
6971 template<typename T>
6972 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6973   if (S.getLangOpts().CPlusPlus) {
6974     // In C++, the overloadable attribute negates the effects of extern "C".
6975     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6976       return false;
6977 
6978     // So do CUDA's host/device attributes.
6979     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6980                                  D->template hasAttr<CUDAHostAttr>()))
6981       return false;
6982   }
6983   return D->isExternC();
6984 }
6985 
6986 static bool shouldConsiderLinkage(const VarDecl *VD) {
6987   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6988   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6989       isa<OMPDeclareMapperDecl>(DC))
6990     return VD->hasExternalStorage();
6991   if (DC->isFileContext())
6992     return true;
6993   if (DC->isRecord())
6994     return false;
6995   if (isa<RequiresExprBodyDecl>(DC))
6996     return false;
6997   llvm_unreachable("Unexpected context");
6998 }
6999 
7000 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7001   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7002   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7003       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7004     return true;
7005   if (DC->isRecord())
7006     return false;
7007   llvm_unreachable("Unexpected context");
7008 }
7009 
7010 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7011                           ParsedAttr::Kind Kind) {
7012   // Check decl attributes on the DeclSpec.
7013   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7014     return true;
7015 
7016   // Walk the declarator structure, checking decl attributes that were in a type
7017   // position to the decl itself.
7018   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7019     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7020       return true;
7021   }
7022 
7023   // Finally, check attributes on the decl itself.
7024   return PD.getAttributes().hasAttribute(Kind);
7025 }
7026 
7027 /// Adjust the \c DeclContext for a function or variable that might be a
7028 /// function-local external declaration.
7029 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7030   if (!DC->isFunctionOrMethod())
7031     return false;
7032 
7033   // If this is a local extern function or variable declared within a function
7034   // template, don't add it into the enclosing namespace scope until it is
7035   // instantiated; it might have a dependent type right now.
7036   if (DC->isDependentContext())
7037     return true;
7038 
7039   // C++11 [basic.link]p7:
7040   //   When a block scope declaration of an entity with linkage is not found to
7041   //   refer to some other declaration, then that entity is a member of the
7042   //   innermost enclosing namespace.
7043   //
7044   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7045   // semantically-enclosing namespace, not a lexically-enclosing one.
7046   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7047     DC = DC->getParent();
7048   return true;
7049 }
7050 
7051 /// Returns true if given declaration has external C language linkage.
7052 static bool isDeclExternC(const Decl *D) {
7053   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7054     return FD->isExternC();
7055   if (const auto *VD = dyn_cast<VarDecl>(D))
7056     return VD->isExternC();
7057 
7058   llvm_unreachable("Unknown type of decl!");
7059 }
7060 
7061 /// Returns true if there hasn't been any invalid type diagnosed.
7062 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7063   DeclContext *DC = NewVD->getDeclContext();
7064   QualType R = NewVD->getType();
7065 
7066   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7067   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7068   // argument.
7069   if (R->isImageType() || R->isPipeType()) {
7070     Se.Diag(NewVD->getLocation(),
7071             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7072         << R;
7073     NewVD->setInvalidDecl();
7074     return false;
7075   }
7076 
7077   // OpenCL v1.2 s6.9.r:
7078   // The event type cannot be used to declare a program scope variable.
7079   // OpenCL v2.0 s6.9.q:
7080   // The clk_event_t and reserve_id_t types cannot be declared in program
7081   // scope.
7082   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7083     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7084       Se.Diag(NewVD->getLocation(),
7085               diag::err_invalid_type_for_program_scope_var)
7086           << R;
7087       NewVD->setInvalidDecl();
7088       return false;
7089     }
7090   }
7091 
7092   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7093   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7094                                                Se.getLangOpts())) {
7095     QualType NR = R.getCanonicalType();
7096     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7097            NR->isReferenceType()) {
7098       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7099           NR->isFunctionReferenceType()) {
7100         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7101             << NR->isReferenceType();
7102         NewVD->setInvalidDecl();
7103         return false;
7104       }
7105       NR = NR->getPointeeType();
7106     }
7107   }
7108 
7109   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7110                                                Se.getLangOpts())) {
7111     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7112     // half array type (unless the cl_khr_fp16 extension is enabled).
7113     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7114       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7115       NewVD->setInvalidDecl();
7116       return false;
7117     }
7118   }
7119 
7120   // OpenCL v1.2 s6.9.r:
7121   // The event type cannot be used with the __local, __constant and __global
7122   // address space qualifiers.
7123   if (R->isEventT()) {
7124     if (R.getAddressSpace() != LangAS::opencl_private) {
7125       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7126       NewVD->setInvalidDecl();
7127       return false;
7128     }
7129   }
7130 
7131   if (R->isSamplerT()) {
7132     // OpenCL v1.2 s6.9.b p4:
7133     // The sampler type cannot be used with the __local and __global address
7134     // space qualifiers.
7135     if (R.getAddressSpace() == LangAS::opencl_local ||
7136         R.getAddressSpace() == LangAS::opencl_global) {
7137       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7138       NewVD->setInvalidDecl();
7139     }
7140 
7141     // OpenCL v1.2 s6.12.14.1:
7142     // A global sampler must be declared with either the constant address
7143     // space qualifier or with the const qualifier.
7144     if (DC->isTranslationUnit() &&
7145         !(R.getAddressSpace() == LangAS::opencl_constant ||
7146           R.isConstQualified())) {
7147       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7148       NewVD->setInvalidDecl();
7149     }
7150     if (NewVD->isInvalidDecl())
7151       return false;
7152   }
7153 
7154   return true;
7155 }
7156 
7157 template <typename AttrTy>
7158 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7159   const TypedefNameDecl *TND = TT->getDecl();
7160   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7161     AttrTy *Clone = Attribute->clone(S.Context);
7162     Clone->setInherited(true);
7163     D->addAttr(Clone);
7164   }
7165 }
7166 
7167 NamedDecl *Sema::ActOnVariableDeclarator(
7168     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7169     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7170     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7171   QualType R = TInfo->getType();
7172   DeclarationName Name = GetNameForDeclarator(D).getName();
7173 
7174   IdentifierInfo *II = Name.getAsIdentifierInfo();
7175 
7176   if (D.isDecompositionDeclarator()) {
7177     // Take the name of the first declarator as our name for diagnostic
7178     // purposes.
7179     auto &Decomp = D.getDecompositionDeclarator();
7180     if (!Decomp.bindings().empty()) {
7181       II = Decomp.bindings()[0].Name;
7182       Name = II;
7183     }
7184   } else if (!II) {
7185     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7186     return nullptr;
7187   }
7188 
7189 
7190   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7191   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7192 
7193   // dllimport globals without explicit storage class are treated as extern. We
7194   // have to change the storage class this early to get the right DeclContext.
7195   if (SC == SC_None && !DC->isRecord() &&
7196       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7197       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7198     SC = SC_Extern;
7199 
7200   DeclContext *OriginalDC = DC;
7201   bool IsLocalExternDecl = SC == SC_Extern &&
7202                            adjustContextForLocalExternDecl(DC);
7203 
7204   if (SCSpec == DeclSpec::SCS_mutable) {
7205     // mutable can only appear on non-static class members, so it's always
7206     // an error here
7207     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7208     D.setInvalidType();
7209     SC = SC_None;
7210   }
7211 
7212   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7213       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7214                               D.getDeclSpec().getStorageClassSpecLoc())) {
7215     // In C++11, the 'register' storage class specifier is deprecated.
7216     // Suppress the warning in system macros, it's used in macros in some
7217     // popular C system headers, such as in glibc's htonl() macro.
7218     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7219          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7220                                    : diag::warn_deprecated_register)
7221       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7222   }
7223 
7224   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7225 
7226   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7227     // C99 6.9p2: The storage-class specifiers auto and register shall not
7228     // appear in the declaration specifiers in an external declaration.
7229     // Global Register+Asm is a GNU extension we support.
7230     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7231       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7232       D.setInvalidType();
7233     }
7234   }
7235 
7236   // If this variable has a VLA type and an initializer, try to
7237   // fold to a constant-sized type. This is otherwise invalid.
7238   if (D.hasInitializer() && R->isVariableArrayType())
7239     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7240                                     /*DiagID=*/0);
7241 
7242   bool IsMemberSpecialization = false;
7243   bool IsVariableTemplateSpecialization = false;
7244   bool IsPartialSpecialization = false;
7245   bool IsVariableTemplate = false;
7246   VarDecl *NewVD = nullptr;
7247   VarTemplateDecl *NewTemplate = nullptr;
7248   TemplateParameterList *TemplateParams = nullptr;
7249   if (!getLangOpts().CPlusPlus) {
7250     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7251                             II, R, TInfo, SC);
7252 
7253     if (R->getContainedDeducedType())
7254       ParsingInitForAutoVars.insert(NewVD);
7255 
7256     if (D.isInvalidType())
7257       NewVD->setInvalidDecl();
7258 
7259     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7260         NewVD->hasLocalStorage())
7261       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7262                             NTCUC_AutoVar, NTCUK_Destruct);
7263   } else {
7264     bool Invalid = false;
7265 
7266     if (DC->isRecord() && !CurContext->isRecord()) {
7267       // This is an out-of-line definition of a static data member.
7268       switch (SC) {
7269       case SC_None:
7270         break;
7271       case SC_Static:
7272         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7273              diag::err_static_out_of_line)
7274           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7275         break;
7276       case SC_Auto:
7277       case SC_Register:
7278       case SC_Extern:
7279         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7280         // to names of variables declared in a block or to function parameters.
7281         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7282         // of class members
7283 
7284         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7285              diag::err_storage_class_for_static_member)
7286           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7287         break;
7288       case SC_PrivateExtern:
7289         llvm_unreachable("C storage class in c++!");
7290       }
7291     }
7292 
7293     if (SC == SC_Static && CurContext->isRecord()) {
7294       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7295         // Walk up the enclosing DeclContexts to check for any that are
7296         // incompatible with static data members.
7297         const DeclContext *FunctionOrMethod = nullptr;
7298         const CXXRecordDecl *AnonStruct = nullptr;
7299         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7300           if (Ctxt->isFunctionOrMethod()) {
7301             FunctionOrMethod = Ctxt;
7302             break;
7303           }
7304           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7305           if (ParentDecl && !ParentDecl->getDeclName()) {
7306             AnonStruct = ParentDecl;
7307             break;
7308           }
7309         }
7310         if (FunctionOrMethod) {
7311           // C++ [class.static.data]p5: A local class shall not have static data
7312           // members.
7313           Diag(D.getIdentifierLoc(),
7314                diag::err_static_data_member_not_allowed_in_local_class)
7315             << Name << RD->getDeclName() << RD->getTagKind();
7316         } else if (AnonStruct) {
7317           // C++ [class.static.data]p4: Unnamed classes and classes contained
7318           // directly or indirectly within unnamed classes shall not contain
7319           // static data members.
7320           Diag(D.getIdentifierLoc(),
7321                diag::err_static_data_member_not_allowed_in_anon_struct)
7322             << Name << AnonStruct->getTagKind();
7323           Invalid = true;
7324         } else if (RD->isUnion()) {
7325           // C++98 [class.union]p1: If a union contains a static data member,
7326           // the program is ill-formed. C++11 drops this restriction.
7327           Diag(D.getIdentifierLoc(),
7328                getLangOpts().CPlusPlus11
7329                  ? diag::warn_cxx98_compat_static_data_member_in_union
7330                  : diag::ext_static_data_member_in_union) << Name;
7331         }
7332       }
7333     }
7334 
7335     // Match up the template parameter lists with the scope specifier, then
7336     // determine whether we have a template or a template specialization.
7337     bool InvalidScope = false;
7338     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7339         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7340         D.getCXXScopeSpec(),
7341         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7342             ? D.getName().TemplateId
7343             : nullptr,
7344         TemplateParamLists,
7345         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7346     Invalid |= InvalidScope;
7347 
7348     if (TemplateParams) {
7349       if (!TemplateParams->size() &&
7350           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7351         // There is an extraneous 'template<>' for this variable. Complain
7352         // about it, but allow the declaration of the variable.
7353         Diag(TemplateParams->getTemplateLoc(),
7354              diag::err_template_variable_noparams)
7355           << II
7356           << SourceRange(TemplateParams->getTemplateLoc(),
7357                          TemplateParams->getRAngleLoc());
7358         TemplateParams = nullptr;
7359       } else {
7360         // Check that we can declare a template here.
7361         if (CheckTemplateDeclScope(S, TemplateParams))
7362           return nullptr;
7363 
7364         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7365           // This is an explicit specialization or a partial specialization.
7366           IsVariableTemplateSpecialization = true;
7367           IsPartialSpecialization = TemplateParams->size() > 0;
7368         } else { // if (TemplateParams->size() > 0)
7369           // This is a template declaration.
7370           IsVariableTemplate = true;
7371 
7372           // Only C++1y supports variable templates (N3651).
7373           Diag(D.getIdentifierLoc(),
7374                getLangOpts().CPlusPlus14
7375                    ? diag::warn_cxx11_compat_variable_template
7376                    : diag::ext_variable_template);
7377         }
7378       }
7379     } else {
7380       // Check that we can declare a member specialization here.
7381       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7382           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7383         return nullptr;
7384       assert((Invalid ||
7385               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7386              "should have a 'template<>' for this decl");
7387     }
7388 
7389     if (IsVariableTemplateSpecialization) {
7390       SourceLocation TemplateKWLoc =
7391           TemplateParamLists.size() > 0
7392               ? TemplateParamLists[0]->getTemplateLoc()
7393               : SourceLocation();
7394       DeclResult Res = ActOnVarTemplateSpecialization(
7395           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7396           IsPartialSpecialization);
7397       if (Res.isInvalid())
7398         return nullptr;
7399       NewVD = cast<VarDecl>(Res.get());
7400       AddToScope = false;
7401     } else if (D.isDecompositionDeclarator()) {
7402       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7403                                         D.getIdentifierLoc(), R, TInfo, SC,
7404                                         Bindings);
7405     } else
7406       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7407                               D.getIdentifierLoc(), II, R, TInfo, SC);
7408 
7409     // If this is supposed to be a variable template, create it as such.
7410     if (IsVariableTemplate) {
7411       NewTemplate =
7412           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7413                                   TemplateParams, NewVD);
7414       NewVD->setDescribedVarTemplate(NewTemplate);
7415     }
7416 
7417     // If this decl has an auto type in need of deduction, make a note of the
7418     // Decl so we can diagnose uses of it in its own initializer.
7419     if (R->getContainedDeducedType())
7420       ParsingInitForAutoVars.insert(NewVD);
7421 
7422     if (D.isInvalidType() || Invalid) {
7423       NewVD->setInvalidDecl();
7424       if (NewTemplate)
7425         NewTemplate->setInvalidDecl();
7426     }
7427 
7428     SetNestedNameSpecifier(*this, NewVD, D);
7429 
7430     // If we have any template parameter lists that don't directly belong to
7431     // the variable (matching the scope specifier), store them.
7432     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7433     if (TemplateParamLists.size() > VDTemplateParamLists)
7434       NewVD->setTemplateParameterListsInfo(
7435           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7436   }
7437 
7438   if (D.getDeclSpec().isInlineSpecified()) {
7439     if (!getLangOpts().CPlusPlus) {
7440       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7441           << 0;
7442     } else if (CurContext->isFunctionOrMethod()) {
7443       // 'inline' is not allowed on block scope variable declaration.
7444       Diag(D.getDeclSpec().getInlineSpecLoc(),
7445            diag::err_inline_declaration_block_scope) << Name
7446         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7447     } else {
7448       Diag(D.getDeclSpec().getInlineSpecLoc(),
7449            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7450                                      : diag::ext_inline_variable);
7451       NewVD->setInlineSpecified();
7452     }
7453   }
7454 
7455   // Set the lexical context. If the declarator has a C++ scope specifier, the
7456   // lexical context will be different from the semantic context.
7457   NewVD->setLexicalDeclContext(CurContext);
7458   if (NewTemplate)
7459     NewTemplate->setLexicalDeclContext(CurContext);
7460 
7461   if (IsLocalExternDecl) {
7462     if (D.isDecompositionDeclarator())
7463       for (auto *B : Bindings)
7464         B->setLocalExternDecl();
7465     else
7466       NewVD->setLocalExternDecl();
7467   }
7468 
7469   bool EmitTLSUnsupportedError = false;
7470   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7471     // C++11 [dcl.stc]p4:
7472     //   When thread_local is applied to a variable of block scope the
7473     //   storage-class-specifier static is implied if it does not appear
7474     //   explicitly.
7475     // Core issue: 'static' is not implied if the variable is declared
7476     //   'extern'.
7477     if (NewVD->hasLocalStorage() &&
7478         (SCSpec != DeclSpec::SCS_unspecified ||
7479          TSCS != DeclSpec::TSCS_thread_local ||
7480          !DC->isFunctionOrMethod()))
7481       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7482            diag::err_thread_non_global)
7483         << DeclSpec::getSpecifierName(TSCS);
7484     else if (!Context.getTargetInfo().isTLSSupported()) {
7485       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7486           getLangOpts().SYCLIsDevice) {
7487         // Postpone error emission until we've collected attributes required to
7488         // figure out whether it's a host or device variable and whether the
7489         // error should be ignored.
7490         EmitTLSUnsupportedError = true;
7491         // We still need to mark the variable as TLS so it shows up in AST with
7492         // proper storage class for other tools to use even if we're not going
7493         // to emit any code for it.
7494         NewVD->setTSCSpec(TSCS);
7495       } else
7496         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7497              diag::err_thread_unsupported);
7498     } else
7499       NewVD->setTSCSpec(TSCS);
7500   }
7501 
7502   switch (D.getDeclSpec().getConstexprSpecifier()) {
7503   case ConstexprSpecKind::Unspecified:
7504     break;
7505 
7506   case ConstexprSpecKind::Consteval:
7507     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7508          diag::err_constexpr_wrong_decl_kind)
7509         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7510     LLVM_FALLTHROUGH;
7511 
7512   case ConstexprSpecKind::Constexpr:
7513     NewVD->setConstexpr(true);
7514     // C++1z [dcl.spec.constexpr]p1:
7515     //   A static data member declared with the constexpr specifier is
7516     //   implicitly an inline variable.
7517     if (NewVD->isStaticDataMember() &&
7518         (getLangOpts().CPlusPlus17 ||
7519          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7520       NewVD->setImplicitlyInline();
7521     break;
7522 
7523   case ConstexprSpecKind::Constinit:
7524     if (!NewVD->hasGlobalStorage())
7525       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7526            diag::err_constinit_local_variable);
7527     else
7528       NewVD->addAttr(ConstInitAttr::Create(
7529           Context, D.getDeclSpec().getConstexprSpecLoc(),
7530           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7531     break;
7532   }
7533 
7534   // C99 6.7.4p3
7535   //   An inline definition of a function with external linkage shall
7536   //   not contain a definition of a modifiable object with static or
7537   //   thread storage duration...
7538   // We only apply this when the function is required to be defined
7539   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7540   // that a local variable with thread storage duration still has to
7541   // be marked 'static'.  Also note that it's possible to get these
7542   // semantics in C++ using __attribute__((gnu_inline)).
7543   if (SC == SC_Static && S->getFnParent() != nullptr &&
7544       !NewVD->getType().isConstQualified()) {
7545     FunctionDecl *CurFD = getCurFunctionDecl();
7546     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7547       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7548            diag::warn_static_local_in_extern_inline);
7549       MaybeSuggestAddingStaticToDecl(CurFD);
7550     }
7551   }
7552 
7553   if (D.getDeclSpec().isModulePrivateSpecified()) {
7554     if (IsVariableTemplateSpecialization)
7555       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7556           << (IsPartialSpecialization ? 1 : 0)
7557           << FixItHint::CreateRemoval(
7558                  D.getDeclSpec().getModulePrivateSpecLoc());
7559     else if (IsMemberSpecialization)
7560       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7561         << 2
7562         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7563     else if (NewVD->hasLocalStorage())
7564       Diag(NewVD->getLocation(), diag::err_module_private_local)
7565           << 0 << NewVD
7566           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7567           << FixItHint::CreateRemoval(
7568                  D.getDeclSpec().getModulePrivateSpecLoc());
7569     else {
7570       NewVD->setModulePrivate();
7571       if (NewTemplate)
7572         NewTemplate->setModulePrivate();
7573       for (auto *B : Bindings)
7574         B->setModulePrivate();
7575     }
7576   }
7577 
7578   if (getLangOpts().OpenCL) {
7579     deduceOpenCLAddressSpace(NewVD);
7580 
7581     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7582     if (TSC != TSCS_unspecified) {
7583       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7584            diag::err_opencl_unknown_type_specifier)
7585           << getLangOpts().getOpenCLVersionString()
7586           << DeclSpec::getSpecifierName(TSC) << 1;
7587       NewVD->setInvalidDecl();
7588     }
7589   }
7590 
7591   // Handle attributes prior to checking for duplicates in MergeVarDecl
7592   ProcessDeclAttributes(S, NewVD, D);
7593 
7594   // FIXME: This is probably the wrong location to be doing this and we should
7595   // probably be doing this for more attributes (especially for function
7596   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7597   // the code to copy attributes would be generated by TableGen.
7598   if (R->isFunctionPointerType())
7599     if (const auto *TT = R->getAs<TypedefType>())
7600       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7601 
7602   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7603       getLangOpts().SYCLIsDevice) {
7604     if (EmitTLSUnsupportedError &&
7605         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7606          (getLangOpts().OpenMPIsDevice &&
7607           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7608       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7609            diag::err_thread_unsupported);
7610 
7611     if (EmitTLSUnsupportedError &&
7612         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7613       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7614     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7615     // storage [duration]."
7616     if (SC == SC_None && S->getFnParent() != nullptr &&
7617         (NewVD->hasAttr<CUDASharedAttr>() ||
7618          NewVD->hasAttr<CUDAConstantAttr>())) {
7619       NewVD->setStorageClass(SC_Static);
7620     }
7621   }
7622 
7623   // Ensure that dllimport globals without explicit storage class are treated as
7624   // extern. The storage class is set above using parsed attributes. Now we can
7625   // check the VarDecl itself.
7626   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7627          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7628          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7629 
7630   // In auto-retain/release, infer strong retension for variables of
7631   // retainable type.
7632   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7633     NewVD->setInvalidDecl();
7634 
7635   // Handle GNU asm-label extension (encoded as an attribute).
7636   if (Expr *E = (Expr*)D.getAsmLabel()) {
7637     // The parser guarantees this is a string.
7638     StringLiteral *SE = cast<StringLiteral>(E);
7639     StringRef Label = SE->getString();
7640     if (S->getFnParent() != nullptr) {
7641       switch (SC) {
7642       case SC_None:
7643       case SC_Auto:
7644         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7645         break;
7646       case SC_Register:
7647         // Local Named register
7648         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7649             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7650           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7651         break;
7652       case SC_Static:
7653       case SC_Extern:
7654       case SC_PrivateExtern:
7655         break;
7656       }
7657     } else if (SC == SC_Register) {
7658       // Global Named register
7659       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7660         const auto &TI = Context.getTargetInfo();
7661         bool HasSizeMismatch;
7662 
7663         if (!TI.isValidGCCRegisterName(Label))
7664           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7665         else if (!TI.validateGlobalRegisterVariable(Label,
7666                                                     Context.getTypeSize(R),
7667                                                     HasSizeMismatch))
7668           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7669         else if (HasSizeMismatch)
7670           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7671       }
7672 
7673       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7674         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7675         NewVD->setInvalidDecl(true);
7676       }
7677     }
7678 
7679     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7680                                         /*IsLiteralLabel=*/true,
7681                                         SE->getStrTokenLoc(0)));
7682   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7683     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7684       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7685     if (I != ExtnameUndeclaredIdentifiers.end()) {
7686       if (isDeclExternC(NewVD)) {
7687         NewVD->addAttr(I->second);
7688         ExtnameUndeclaredIdentifiers.erase(I);
7689       } else
7690         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7691             << /*Variable*/1 << NewVD;
7692     }
7693   }
7694 
7695   // Find the shadowed declaration before filtering for scope.
7696   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7697                                 ? getShadowedDeclaration(NewVD, Previous)
7698                                 : nullptr;
7699 
7700   // Don't consider existing declarations that are in a different
7701   // scope and are out-of-semantic-context declarations (if the new
7702   // declaration has linkage).
7703   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7704                        D.getCXXScopeSpec().isNotEmpty() ||
7705                        IsMemberSpecialization ||
7706                        IsVariableTemplateSpecialization);
7707 
7708   // Check whether the previous declaration is in the same block scope. This
7709   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7710   if (getLangOpts().CPlusPlus &&
7711       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7712     NewVD->setPreviousDeclInSameBlockScope(
7713         Previous.isSingleResult() && !Previous.isShadowed() &&
7714         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7715 
7716   if (!getLangOpts().CPlusPlus) {
7717     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7718   } else {
7719     // If this is an explicit specialization of a static data member, check it.
7720     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7721         CheckMemberSpecialization(NewVD, Previous))
7722       NewVD->setInvalidDecl();
7723 
7724     // Merge the decl with the existing one if appropriate.
7725     if (!Previous.empty()) {
7726       if (Previous.isSingleResult() &&
7727           isa<FieldDecl>(Previous.getFoundDecl()) &&
7728           D.getCXXScopeSpec().isSet()) {
7729         // The user tried to define a non-static data member
7730         // out-of-line (C++ [dcl.meaning]p1).
7731         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7732           << D.getCXXScopeSpec().getRange();
7733         Previous.clear();
7734         NewVD->setInvalidDecl();
7735       }
7736     } else if (D.getCXXScopeSpec().isSet()) {
7737       // No previous declaration in the qualifying scope.
7738       Diag(D.getIdentifierLoc(), diag::err_no_member)
7739         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7740         << D.getCXXScopeSpec().getRange();
7741       NewVD->setInvalidDecl();
7742     }
7743 
7744     if (!IsVariableTemplateSpecialization)
7745       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7746 
7747     if (NewTemplate) {
7748       VarTemplateDecl *PrevVarTemplate =
7749           NewVD->getPreviousDecl()
7750               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7751               : nullptr;
7752 
7753       // Check the template parameter list of this declaration, possibly
7754       // merging in the template parameter list from the previous variable
7755       // template declaration.
7756       if (CheckTemplateParameterList(
7757               TemplateParams,
7758               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7759                               : nullptr,
7760               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7761                DC->isDependentContext())
7762                   ? TPC_ClassTemplateMember
7763                   : TPC_VarTemplate))
7764         NewVD->setInvalidDecl();
7765 
7766       // If we are providing an explicit specialization of a static variable
7767       // template, make a note of that.
7768       if (PrevVarTemplate &&
7769           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7770         PrevVarTemplate->setMemberSpecialization();
7771     }
7772   }
7773 
7774   // Diagnose shadowed variables iff this isn't a redeclaration.
7775   if (ShadowedDecl && !D.isRedeclaration())
7776     CheckShadow(NewVD, ShadowedDecl, Previous);
7777 
7778   ProcessPragmaWeak(S, NewVD);
7779 
7780   // If this is the first declaration of an extern C variable, update
7781   // the map of such variables.
7782   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7783       isIncompleteDeclExternC(*this, NewVD))
7784     RegisterLocallyScopedExternCDecl(NewVD, S);
7785 
7786   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7787     MangleNumberingContext *MCtx;
7788     Decl *ManglingContextDecl;
7789     std::tie(MCtx, ManglingContextDecl) =
7790         getCurrentMangleNumberContext(NewVD->getDeclContext());
7791     if (MCtx) {
7792       Context.setManglingNumber(
7793           NewVD, MCtx->getManglingNumber(
7794                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7795       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7796     }
7797   }
7798 
7799   // Special handling of variable named 'main'.
7800   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7801       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7802       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7803 
7804     // C++ [basic.start.main]p3
7805     // A program that declares a variable main at global scope is ill-formed.
7806     if (getLangOpts().CPlusPlus)
7807       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7808 
7809     // In C, and external-linkage variable named main results in undefined
7810     // behavior.
7811     else if (NewVD->hasExternalFormalLinkage())
7812       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7813   }
7814 
7815   if (D.isRedeclaration() && !Previous.empty()) {
7816     NamedDecl *Prev = Previous.getRepresentativeDecl();
7817     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7818                                    D.isFunctionDefinition());
7819   }
7820 
7821   if (NewTemplate) {
7822     if (NewVD->isInvalidDecl())
7823       NewTemplate->setInvalidDecl();
7824     ActOnDocumentableDecl(NewTemplate);
7825     return NewTemplate;
7826   }
7827 
7828   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7829     CompleteMemberSpecialization(NewVD, Previous);
7830 
7831   return NewVD;
7832 }
7833 
7834 /// Enum describing the %select options in diag::warn_decl_shadow.
7835 enum ShadowedDeclKind {
7836   SDK_Local,
7837   SDK_Global,
7838   SDK_StaticMember,
7839   SDK_Field,
7840   SDK_Typedef,
7841   SDK_Using,
7842   SDK_StructuredBinding
7843 };
7844 
7845 /// Determine what kind of declaration we're shadowing.
7846 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7847                                                 const DeclContext *OldDC) {
7848   if (isa<TypeAliasDecl>(ShadowedDecl))
7849     return SDK_Using;
7850   else if (isa<TypedefDecl>(ShadowedDecl))
7851     return SDK_Typedef;
7852   else if (isa<BindingDecl>(ShadowedDecl))
7853     return SDK_StructuredBinding;
7854   else if (isa<RecordDecl>(OldDC))
7855     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7856 
7857   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7858 }
7859 
7860 /// Return the location of the capture if the given lambda captures the given
7861 /// variable \p VD, or an invalid source location otherwise.
7862 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7863                                          const VarDecl *VD) {
7864   for (const Capture &Capture : LSI->Captures) {
7865     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7866       return Capture.getLocation();
7867   }
7868   return SourceLocation();
7869 }
7870 
7871 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7872                                      const LookupResult &R) {
7873   // Only diagnose if we're shadowing an unambiguous field or variable.
7874   if (R.getResultKind() != LookupResult::Found)
7875     return false;
7876 
7877   // Return false if warning is ignored.
7878   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7879 }
7880 
7881 /// Return the declaration shadowed by the given variable \p D, or null
7882 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7883 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7884                                         const LookupResult &R) {
7885   if (!shouldWarnIfShadowedDecl(Diags, R))
7886     return nullptr;
7887 
7888   // Don't diagnose declarations at file scope.
7889   if (D->hasGlobalStorage())
7890     return nullptr;
7891 
7892   NamedDecl *ShadowedDecl = R.getFoundDecl();
7893   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7894                                                             : nullptr;
7895 }
7896 
7897 /// Return the declaration shadowed by the given typedef \p D, or null
7898 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7899 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7900                                         const LookupResult &R) {
7901   // Don't warn if typedef declaration is part of a class
7902   if (D->getDeclContext()->isRecord())
7903     return nullptr;
7904 
7905   if (!shouldWarnIfShadowedDecl(Diags, R))
7906     return nullptr;
7907 
7908   NamedDecl *ShadowedDecl = R.getFoundDecl();
7909   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7910 }
7911 
7912 /// Return the declaration shadowed by the given variable \p D, or null
7913 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7914 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7915                                         const LookupResult &R) {
7916   if (!shouldWarnIfShadowedDecl(Diags, R))
7917     return nullptr;
7918 
7919   NamedDecl *ShadowedDecl = R.getFoundDecl();
7920   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7921                                                             : nullptr;
7922 }
7923 
7924 /// Diagnose variable or built-in function shadowing.  Implements
7925 /// -Wshadow.
7926 ///
7927 /// This method is called whenever a VarDecl is added to a "useful"
7928 /// scope.
7929 ///
7930 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7931 /// \param R the lookup of the name
7932 ///
7933 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7934                        const LookupResult &R) {
7935   DeclContext *NewDC = D->getDeclContext();
7936 
7937   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7938     // Fields are not shadowed by variables in C++ static methods.
7939     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7940       if (MD->isStatic())
7941         return;
7942 
7943     // Fields shadowed by constructor parameters are a special case. Usually
7944     // the constructor initializes the field with the parameter.
7945     if (isa<CXXConstructorDecl>(NewDC))
7946       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7947         // Remember that this was shadowed so we can either warn about its
7948         // modification or its existence depending on warning settings.
7949         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7950         return;
7951       }
7952   }
7953 
7954   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7955     if (shadowedVar->isExternC()) {
7956       // For shadowing external vars, make sure that we point to the global
7957       // declaration, not a locally scoped extern declaration.
7958       for (auto I : shadowedVar->redecls())
7959         if (I->isFileVarDecl()) {
7960           ShadowedDecl = I;
7961           break;
7962         }
7963     }
7964 
7965   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7966 
7967   unsigned WarningDiag = diag::warn_decl_shadow;
7968   SourceLocation CaptureLoc;
7969   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7970       isa<CXXMethodDecl>(NewDC)) {
7971     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7972       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7973         if (RD->getLambdaCaptureDefault() == LCD_None) {
7974           // Try to avoid warnings for lambdas with an explicit capture list.
7975           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7976           // Warn only when the lambda captures the shadowed decl explicitly.
7977           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7978           if (CaptureLoc.isInvalid())
7979             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7980         } else {
7981           // Remember that this was shadowed so we can avoid the warning if the
7982           // shadowed decl isn't captured and the warning settings allow it.
7983           cast<LambdaScopeInfo>(getCurFunction())
7984               ->ShadowingDecls.push_back(
7985                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7986           return;
7987         }
7988       }
7989 
7990       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7991         // A variable can't shadow a local variable in an enclosing scope, if
7992         // they are separated by a non-capturing declaration context.
7993         for (DeclContext *ParentDC = NewDC;
7994              ParentDC && !ParentDC->Equals(OldDC);
7995              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7996           // Only block literals, captured statements, and lambda expressions
7997           // can capture; other scopes don't.
7998           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7999               !isLambdaCallOperator(ParentDC)) {
8000             return;
8001           }
8002         }
8003       }
8004     }
8005   }
8006 
8007   // Only warn about certain kinds of shadowing for class members.
8008   if (NewDC && NewDC->isRecord()) {
8009     // In particular, don't warn about shadowing non-class members.
8010     if (!OldDC->isRecord())
8011       return;
8012 
8013     // TODO: should we warn about static data members shadowing
8014     // static data members from base classes?
8015 
8016     // TODO: don't diagnose for inaccessible shadowed members.
8017     // This is hard to do perfectly because we might friend the
8018     // shadowing context, but that's just a false negative.
8019   }
8020 
8021 
8022   DeclarationName Name = R.getLookupName();
8023 
8024   // Emit warning and note.
8025   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8026   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8027   if (!CaptureLoc.isInvalid())
8028     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8029         << Name << /*explicitly*/ 1;
8030   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8031 }
8032 
8033 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8034 /// when these variables are captured by the lambda.
8035 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8036   for (const auto &Shadow : LSI->ShadowingDecls) {
8037     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8038     // Try to avoid the warning when the shadowed decl isn't captured.
8039     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8040     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8041     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8042                                        ? diag::warn_decl_shadow_uncaptured_local
8043                                        : diag::warn_decl_shadow)
8044         << Shadow.VD->getDeclName()
8045         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8046     if (!CaptureLoc.isInvalid())
8047       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8048           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8049     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8050   }
8051 }
8052 
8053 /// Check -Wshadow without the advantage of a previous lookup.
8054 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8055   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8056     return;
8057 
8058   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8059                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8060   LookupName(R, S);
8061   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8062     CheckShadow(D, ShadowedDecl, R);
8063 }
8064 
8065 /// Check if 'E', which is an expression that is about to be modified, refers
8066 /// to a constructor parameter that shadows a field.
8067 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8068   // Quickly ignore expressions that can't be shadowing ctor parameters.
8069   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8070     return;
8071   E = E->IgnoreParenImpCasts();
8072   auto *DRE = dyn_cast<DeclRefExpr>(E);
8073   if (!DRE)
8074     return;
8075   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8076   auto I = ShadowingDecls.find(D);
8077   if (I == ShadowingDecls.end())
8078     return;
8079   const NamedDecl *ShadowedDecl = I->second;
8080   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8081   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8082   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8083   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8084 
8085   // Avoid issuing multiple warnings about the same decl.
8086   ShadowingDecls.erase(I);
8087 }
8088 
8089 /// Check for conflict between this global or extern "C" declaration and
8090 /// previous global or extern "C" declarations. This is only used in C++.
8091 template<typename T>
8092 static bool checkGlobalOrExternCConflict(
8093     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8094   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8095   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8096 
8097   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8098     // The common case: this global doesn't conflict with any extern "C"
8099     // declaration.
8100     return false;
8101   }
8102 
8103   if (Prev) {
8104     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8105       // Both the old and new declarations have C language linkage. This is a
8106       // redeclaration.
8107       Previous.clear();
8108       Previous.addDecl(Prev);
8109       return true;
8110     }
8111 
8112     // This is a global, non-extern "C" declaration, and there is a previous
8113     // non-global extern "C" declaration. Diagnose if this is a variable
8114     // declaration.
8115     if (!isa<VarDecl>(ND))
8116       return false;
8117   } else {
8118     // The declaration is extern "C". Check for any declaration in the
8119     // translation unit which might conflict.
8120     if (IsGlobal) {
8121       // We have already performed the lookup into the translation unit.
8122       IsGlobal = false;
8123       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8124            I != E; ++I) {
8125         if (isa<VarDecl>(*I)) {
8126           Prev = *I;
8127           break;
8128         }
8129       }
8130     } else {
8131       DeclContext::lookup_result R =
8132           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8133       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8134            I != E; ++I) {
8135         if (isa<VarDecl>(*I)) {
8136           Prev = *I;
8137           break;
8138         }
8139         // FIXME: If we have any other entity with this name in global scope,
8140         // the declaration is ill-formed, but that is a defect: it breaks the
8141         // 'stat' hack, for instance. Only variables can have mangled name
8142         // clashes with extern "C" declarations, so only they deserve a
8143         // diagnostic.
8144       }
8145     }
8146 
8147     if (!Prev)
8148       return false;
8149   }
8150 
8151   // Use the first declaration's location to ensure we point at something which
8152   // is lexically inside an extern "C" linkage-spec.
8153   assert(Prev && "should have found a previous declaration to diagnose");
8154   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8155     Prev = FD->getFirstDecl();
8156   else
8157     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8158 
8159   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8160     << IsGlobal << ND;
8161   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8162     << IsGlobal;
8163   return false;
8164 }
8165 
8166 /// Apply special rules for handling extern "C" declarations. Returns \c true
8167 /// if we have found that this is a redeclaration of some prior entity.
8168 ///
8169 /// Per C++ [dcl.link]p6:
8170 ///   Two declarations [for a function or variable] with C language linkage
8171 ///   with the same name that appear in different scopes refer to the same
8172 ///   [entity]. An entity with C language linkage shall not be declared with
8173 ///   the same name as an entity in global scope.
8174 template<typename T>
8175 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8176                                                   LookupResult &Previous) {
8177   if (!S.getLangOpts().CPlusPlus) {
8178     // In C, when declaring a global variable, look for a corresponding 'extern'
8179     // variable declared in function scope. We don't need this in C++, because
8180     // we find local extern decls in the surrounding file-scope DeclContext.
8181     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8182       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8183         Previous.clear();
8184         Previous.addDecl(Prev);
8185         return true;
8186       }
8187     }
8188     return false;
8189   }
8190 
8191   // A declaration in the translation unit can conflict with an extern "C"
8192   // declaration.
8193   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8194     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8195 
8196   // An extern "C" declaration can conflict with a declaration in the
8197   // translation unit or can be a redeclaration of an extern "C" declaration
8198   // in another scope.
8199   if (isIncompleteDeclExternC(S,ND))
8200     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8201 
8202   // Neither global nor extern "C": nothing to do.
8203   return false;
8204 }
8205 
8206 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8207   // If the decl is already known invalid, don't check it.
8208   if (NewVD->isInvalidDecl())
8209     return;
8210 
8211   QualType T = NewVD->getType();
8212 
8213   // Defer checking an 'auto' type until its initializer is attached.
8214   if (T->isUndeducedType())
8215     return;
8216 
8217   if (NewVD->hasAttrs())
8218     CheckAlignasUnderalignment(NewVD);
8219 
8220   if (T->isObjCObjectType()) {
8221     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8222       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8223     T = Context.getObjCObjectPointerType(T);
8224     NewVD->setType(T);
8225   }
8226 
8227   // Emit an error if an address space was applied to decl with local storage.
8228   // This includes arrays of objects with address space qualifiers, but not
8229   // automatic variables that point to other address spaces.
8230   // ISO/IEC TR 18037 S5.1.2
8231   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8232       T.getAddressSpace() != LangAS::Default) {
8233     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8234     NewVD->setInvalidDecl();
8235     return;
8236   }
8237 
8238   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8239   // scope.
8240   if (getLangOpts().OpenCLVersion == 120 &&
8241       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8242                                             getLangOpts()) &&
8243       NewVD->isStaticLocal()) {
8244     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8245     NewVD->setInvalidDecl();
8246     return;
8247   }
8248 
8249   if (getLangOpts().OpenCL) {
8250     if (!diagnoseOpenCLTypes(*this, NewVD))
8251       return;
8252 
8253     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8254     if (NewVD->hasAttr<BlocksAttr>()) {
8255       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8256       return;
8257     }
8258 
8259     if (T->isBlockPointerType()) {
8260       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8261       // can't use 'extern' storage class.
8262       if (!T.isConstQualified()) {
8263         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8264             << 0 /*const*/;
8265         NewVD->setInvalidDecl();
8266         return;
8267       }
8268       if (NewVD->hasExternalStorage()) {
8269         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8270         NewVD->setInvalidDecl();
8271         return;
8272       }
8273     }
8274 
8275     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8276     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8277         NewVD->hasExternalStorage()) {
8278       if (!T->isSamplerT() && !T->isDependentType() &&
8279           !(T.getAddressSpace() == LangAS::opencl_constant ||
8280             (T.getAddressSpace() == LangAS::opencl_global &&
8281              getOpenCLOptions().areProgramScopeVariablesSupported(
8282                  getLangOpts())))) {
8283         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8284         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8285           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8286               << Scope << "global or constant";
8287         else
8288           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8289               << Scope << "constant";
8290         NewVD->setInvalidDecl();
8291         return;
8292       }
8293     } else {
8294       if (T.getAddressSpace() == LangAS::opencl_global) {
8295         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8296             << 1 /*is any function*/ << "global";
8297         NewVD->setInvalidDecl();
8298         return;
8299       }
8300       if (T.getAddressSpace() == LangAS::opencl_constant ||
8301           T.getAddressSpace() == LangAS::opencl_local) {
8302         FunctionDecl *FD = getCurFunctionDecl();
8303         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8304         // in functions.
8305         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8306           if (T.getAddressSpace() == LangAS::opencl_constant)
8307             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8308                 << 0 /*non-kernel only*/ << "constant";
8309           else
8310             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8311                 << 0 /*non-kernel only*/ << "local";
8312           NewVD->setInvalidDecl();
8313           return;
8314         }
8315         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8316         // in the outermost scope of a kernel function.
8317         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8318           if (!getCurScope()->isFunctionScope()) {
8319             if (T.getAddressSpace() == LangAS::opencl_constant)
8320               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8321                   << "constant";
8322             else
8323               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8324                   << "local";
8325             NewVD->setInvalidDecl();
8326             return;
8327           }
8328         }
8329       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8330                  // If we are parsing a template we didn't deduce an addr
8331                  // space yet.
8332                  T.getAddressSpace() != LangAS::Default) {
8333         // Do not allow other address spaces on automatic variable.
8334         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8335         NewVD->setInvalidDecl();
8336         return;
8337       }
8338     }
8339   }
8340 
8341   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8342       && !NewVD->hasAttr<BlocksAttr>()) {
8343     if (getLangOpts().getGC() != LangOptions::NonGC)
8344       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8345     else {
8346       assert(!getLangOpts().ObjCAutoRefCount);
8347       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8348     }
8349   }
8350 
8351   bool isVM = T->isVariablyModifiedType();
8352   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8353       NewVD->hasAttr<BlocksAttr>())
8354     setFunctionHasBranchProtectedScope();
8355 
8356   if ((isVM && NewVD->hasLinkage()) ||
8357       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8358     bool SizeIsNegative;
8359     llvm::APSInt Oversized;
8360     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8361         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8362     QualType FixedT;
8363     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8364       FixedT = FixedTInfo->getType();
8365     else if (FixedTInfo) {
8366       // Type and type-as-written are canonically different. We need to fix up
8367       // both types separately.
8368       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8369                                                    Oversized);
8370     }
8371     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8372       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8373       // FIXME: This won't give the correct result for
8374       // int a[10][n];
8375       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8376 
8377       if (NewVD->isFileVarDecl())
8378         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8379         << SizeRange;
8380       else if (NewVD->isStaticLocal())
8381         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8382         << SizeRange;
8383       else
8384         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8385         << SizeRange;
8386       NewVD->setInvalidDecl();
8387       return;
8388     }
8389 
8390     if (!FixedTInfo) {
8391       if (NewVD->isFileVarDecl())
8392         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8393       else
8394         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8395       NewVD->setInvalidDecl();
8396       return;
8397     }
8398 
8399     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8400     NewVD->setType(FixedT);
8401     NewVD->setTypeSourceInfo(FixedTInfo);
8402   }
8403 
8404   if (T->isVoidType()) {
8405     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8406     //                    of objects and functions.
8407     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8408       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8409         << T;
8410       NewVD->setInvalidDecl();
8411       return;
8412     }
8413   }
8414 
8415   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8416     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8417     NewVD->setInvalidDecl();
8418     return;
8419   }
8420 
8421   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8422     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8423     NewVD->setInvalidDecl();
8424     return;
8425   }
8426 
8427   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8428     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8429     NewVD->setInvalidDecl();
8430     return;
8431   }
8432 
8433   if (NewVD->isConstexpr() && !T->isDependentType() &&
8434       RequireLiteralType(NewVD->getLocation(), T,
8435                          diag::err_constexpr_var_non_literal)) {
8436     NewVD->setInvalidDecl();
8437     return;
8438   }
8439 
8440   // PPC MMA non-pointer types are not allowed as non-local variable types.
8441   if (Context.getTargetInfo().getTriple().isPPC64() &&
8442       !NewVD->isLocalVarDecl() &&
8443       CheckPPCMMAType(T, NewVD->getLocation())) {
8444     NewVD->setInvalidDecl();
8445     return;
8446   }
8447 }
8448 
8449 /// Perform semantic checking on a newly-created variable
8450 /// declaration.
8451 ///
8452 /// This routine performs all of the type-checking required for a
8453 /// variable declaration once it has been built. It is used both to
8454 /// check variables after they have been parsed and their declarators
8455 /// have been translated into a declaration, and to check variables
8456 /// that have been instantiated from a template.
8457 ///
8458 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8459 ///
8460 /// Returns true if the variable declaration is a redeclaration.
8461 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8462   CheckVariableDeclarationType(NewVD);
8463 
8464   // If the decl is already known invalid, don't check it.
8465   if (NewVD->isInvalidDecl())
8466     return false;
8467 
8468   // If we did not find anything by this name, look for a non-visible
8469   // extern "C" declaration with the same name.
8470   if (Previous.empty() &&
8471       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8472     Previous.setShadowed();
8473 
8474   if (!Previous.empty()) {
8475     MergeVarDecl(NewVD, Previous);
8476     return true;
8477   }
8478   return false;
8479 }
8480 
8481 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8482 /// and if so, check that it's a valid override and remember it.
8483 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8484   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8485 
8486   // Look for methods in base classes that this method might override.
8487   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8488                      /*DetectVirtual=*/false);
8489   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8490     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8491     DeclarationName Name = MD->getDeclName();
8492 
8493     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8494       // We really want to find the base class destructor here.
8495       QualType T = Context.getTypeDeclType(BaseRecord);
8496       CanQualType CT = Context.getCanonicalType(T);
8497       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8498     }
8499 
8500     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8501       CXXMethodDecl *BaseMD =
8502           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8503       if (!BaseMD || !BaseMD->isVirtual() ||
8504           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8505                      /*ConsiderCudaAttrs=*/true,
8506                      // C++2a [class.virtual]p2 does not consider requires
8507                      // clauses when overriding.
8508                      /*ConsiderRequiresClauses=*/false))
8509         continue;
8510 
8511       if (Overridden.insert(BaseMD).second) {
8512         MD->addOverriddenMethod(BaseMD);
8513         CheckOverridingFunctionReturnType(MD, BaseMD);
8514         CheckOverridingFunctionAttributes(MD, BaseMD);
8515         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8516         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8517       }
8518 
8519       // A method can only override one function from each base class. We
8520       // don't track indirectly overridden methods from bases of bases.
8521       return true;
8522     }
8523 
8524     return false;
8525   };
8526 
8527   DC->lookupInBases(VisitBase, Paths);
8528   return !Overridden.empty();
8529 }
8530 
8531 namespace {
8532   // Struct for holding all of the extra arguments needed by
8533   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8534   struct ActOnFDArgs {
8535     Scope *S;
8536     Declarator &D;
8537     MultiTemplateParamsArg TemplateParamLists;
8538     bool AddToScope;
8539   };
8540 } // end anonymous namespace
8541 
8542 namespace {
8543 
8544 // Callback to only accept typo corrections that have a non-zero edit distance.
8545 // Also only accept corrections that have the same parent decl.
8546 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8547  public:
8548   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8549                             CXXRecordDecl *Parent)
8550       : Context(Context), OriginalFD(TypoFD),
8551         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8552 
8553   bool ValidateCandidate(const TypoCorrection &candidate) override {
8554     if (candidate.getEditDistance() == 0)
8555       return false;
8556 
8557     SmallVector<unsigned, 1> MismatchedParams;
8558     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8559                                           CDeclEnd = candidate.end();
8560          CDecl != CDeclEnd; ++CDecl) {
8561       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8562 
8563       if (FD && !FD->hasBody() &&
8564           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8565         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8566           CXXRecordDecl *Parent = MD->getParent();
8567           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8568             return true;
8569         } else if (!ExpectedParent) {
8570           return true;
8571         }
8572       }
8573     }
8574 
8575     return false;
8576   }
8577 
8578   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8579     return std::make_unique<DifferentNameValidatorCCC>(*this);
8580   }
8581 
8582  private:
8583   ASTContext &Context;
8584   FunctionDecl *OriginalFD;
8585   CXXRecordDecl *ExpectedParent;
8586 };
8587 
8588 } // end anonymous namespace
8589 
8590 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8591   TypoCorrectedFunctionDefinitions.insert(F);
8592 }
8593 
8594 /// Generate diagnostics for an invalid function redeclaration.
8595 ///
8596 /// This routine handles generating the diagnostic messages for an invalid
8597 /// function redeclaration, including finding possible similar declarations
8598 /// or performing typo correction if there are no previous declarations with
8599 /// the same name.
8600 ///
8601 /// Returns a NamedDecl iff typo correction was performed and substituting in
8602 /// the new declaration name does not cause new errors.
8603 static NamedDecl *DiagnoseInvalidRedeclaration(
8604     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8605     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8606   DeclarationName Name = NewFD->getDeclName();
8607   DeclContext *NewDC = NewFD->getDeclContext();
8608   SmallVector<unsigned, 1> MismatchedParams;
8609   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8610   TypoCorrection Correction;
8611   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8612   unsigned DiagMsg =
8613     IsLocalFriend ? diag::err_no_matching_local_friend :
8614     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8615     diag::err_member_decl_does_not_match;
8616   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8617                     IsLocalFriend ? Sema::LookupLocalFriendName
8618                                   : Sema::LookupOrdinaryName,
8619                     Sema::ForVisibleRedeclaration);
8620 
8621   NewFD->setInvalidDecl();
8622   if (IsLocalFriend)
8623     SemaRef.LookupName(Prev, S);
8624   else
8625     SemaRef.LookupQualifiedName(Prev, NewDC);
8626   assert(!Prev.isAmbiguous() &&
8627          "Cannot have an ambiguity in previous-declaration lookup");
8628   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8629   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8630                                 MD ? MD->getParent() : nullptr);
8631   if (!Prev.empty()) {
8632     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8633          Func != FuncEnd; ++Func) {
8634       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8635       if (FD &&
8636           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8637         // Add 1 to the index so that 0 can mean the mismatch didn't
8638         // involve a parameter
8639         unsigned ParamNum =
8640             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8641         NearMatches.push_back(std::make_pair(FD, ParamNum));
8642       }
8643     }
8644   // If the qualified name lookup yielded nothing, try typo correction
8645   } else if ((Correction = SemaRef.CorrectTypo(
8646                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8647                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8648                   IsLocalFriend ? nullptr : NewDC))) {
8649     // Set up everything for the call to ActOnFunctionDeclarator
8650     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8651                               ExtraArgs.D.getIdentifierLoc());
8652     Previous.clear();
8653     Previous.setLookupName(Correction.getCorrection());
8654     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8655                                     CDeclEnd = Correction.end();
8656          CDecl != CDeclEnd; ++CDecl) {
8657       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8658       if (FD && !FD->hasBody() &&
8659           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8660         Previous.addDecl(FD);
8661       }
8662     }
8663     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8664 
8665     NamedDecl *Result;
8666     // Retry building the function declaration with the new previous
8667     // declarations, and with errors suppressed.
8668     {
8669       // Trap errors.
8670       Sema::SFINAETrap Trap(SemaRef);
8671 
8672       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8673       // pieces need to verify the typo-corrected C++ declaration and hopefully
8674       // eliminate the need for the parameter pack ExtraArgs.
8675       Result = SemaRef.ActOnFunctionDeclarator(
8676           ExtraArgs.S, ExtraArgs.D,
8677           Correction.getCorrectionDecl()->getDeclContext(),
8678           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8679           ExtraArgs.AddToScope);
8680 
8681       if (Trap.hasErrorOccurred())
8682         Result = nullptr;
8683     }
8684 
8685     if (Result) {
8686       // Determine which correction we picked.
8687       Decl *Canonical = Result->getCanonicalDecl();
8688       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8689            I != E; ++I)
8690         if ((*I)->getCanonicalDecl() == Canonical)
8691           Correction.setCorrectionDecl(*I);
8692 
8693       // Let Sema know about the correction.
8694       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8695       SemaRef.diagnoseTypo(
8696           Correction,
8697           SemaRef.PDiag(IsLocalFriend
8698                           ? diag::err_no_matching_local_friend_suggest
8699                           : diag::err_member_decl_does_not_match_suggest)
8700             << Name << NewDC << IsDefinition);
8701       return Result;
8702     }
8703 
8704     // Pretend the typo correction never occurred
8705     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8706                               ExtraArgs.D.getIdentifierLoc());
8707     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8708     Previous.clear();
8709     Previous.setLookupName(Name);
8710   }
8711 
8712   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8713       << Name << NewDC << IsDefinition << NewFD->getLocation();
8714 
8715   bool NewFDisConst = false;
8716   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8717     NewFDisConst = NewMD->isConst();
8718 
8719   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8720        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8721        NearMatch != NearMatchEnd; ++NearMatch) {
8722     FunctionDecl *FD = NearMatch->first;
8723     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8724     bool FDisConst = MD && MD->isConst();
8725     bool IsMember = MD || !IsLocalFriend;
8726 
8727     // FIXME: These notes are poorly worded for the local friend case.
8728     if (unsigned Idx = NearMatch->second) {
8729       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8730       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8731       if (Loc.isInvalid()) Loc = FD->getLocation();
8732       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8733                                  : diag::note_local_decl_close_param_match)
8734         << Idx << FDParam->getType()
8735         << NewFD->getParamDecl(Idx - 1)->getType();
8736     } else if (FDisConst != NewFDisConst) {
8737       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8738           << NewFDisConst << FD->getSourceRange().getEnd()
8739           << (NewFDisConst
8740                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8741                                                  .getConstQualifierLoc())
8742                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8743                                                    .getRParenLoc()
8744                                                    .getLocWithOffset(1),
8745                                                " const"));
8746     } else
8747       SemaRef.Diag(FD->getLocation(),
8748                    IsMember ? diag::note_member_def_close_match
8749                             : diag::note_local_decl_close_match);
8750   }
8751   return nullptr;
8752 }
8753 
8754 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8755   switch (D.getDeclSpec().getStorageClassSpec()) {
8756   default: llvm_unreachable("Unknown storage class!");
8757   case DeclSpec::SCS_auto:
8758   case DeclSpec::SCS_register:
8759   case DeclSpec::SCS_mutable:
8760     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8761                  diag::err_typecheck_sclass_func);
8762     D.getMutableDeclSpec().ClearStorageClassSpecs();
8763     D.setInvalidType();
8764     break;
8765   case DeclSpec::SCS_unspecified: break;
8766   case DeclSpec::SCS_extern:
8767     if (D.getDeclSpec().isExternInLinkageSpec())
8768       return SC_None;
8769     return SC_Extern;
8770   case DeclSpec::SCS_static: {
8771     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8772       // C99 6.7.1p5:
8773       //   The declaration of an identifier for a function that has
8774       //   block scope shall have no explicit storage-class specifier
8775       //   other than extern
8776       // See also (C++ [dcl.stc]p4).
8777       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8778                    diag::err_static_block_func);
8779       break;
8780     } else
8781       return SC_Static;
8782   }
8783   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8784   }
8785 
8786   // No explicit storage class has already been returned
8787   return SC_None;
8788 }
8789 
8790 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8791                                            DeclContext *DC, QualType &R,
8792                                            TypeSourceInfo *TInfo,
8793                                            StorageClass SC,
8794                                            bool &IsVirtualOkay) {
8795   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8796   DeclarationName Name = NameInfo.getName();
8797 
8798   FunctionDecl *NewFD = nullptr;
8799   bool isInline = D.getDeclSpec().isInlineSpecified();
8800 
8801   if (!SemaRef.getLangOpts().CPlusPlus) {
8802     // Determine whether the function was written with a
8803     // prototype. This true when:
8804     //   - there is a prototype in the declarator, or
8805     //   - the type R of the function is some kind of typedef or other non-
8806     //     attributed reference to a type name (which eventually refers to a
8807     //     function type).
8808     bool HasPrototype =
8809       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8810       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8811 
8812     NewFD = FunctionDecl::Create(
8813         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8814         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8815         ConstexprSpecKind::Unspecified,
8816         /*TrailingRequiresClause=*/nullptr);
8817     if (D.isInvalidType())
8818       NewFD->setInvalidDecl();
8819 
8820     return NewFD;
8821   }
8822 
8823   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8824 
8825   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8826   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8827     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8828                  diag::err_constexpr_wrong_decl_kind)
8829         << static_cast<int>(ConstexprKind);
8830     ConstexprKind = ConstexprSpecKind::Unspecified;
8831     D.getMutableDeclSpec().ClearConstexprSpec();
8832   }
8833   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8834 
8835   // Check that the return type is not an abstract class type.
8836   // For record types, this is done by the AbstractClassUsageDiagnoser once
8837   // the class has been completely parsed.
8838   if (!DC->isRecord() &&
8839       SemaRef.RequireNonAbstractType(
8840           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8841           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8842     D.setInvalidType();
8843 
8844   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8845     // This is a C++ constructor declaration.
8846     assert(DC->isRecord() &&
8847            "Constructors can only be declared in a member context");
8848 
8849     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8850     return CXXConstructorDecl::Create(
8851         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8852         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8853         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8854         InheritedConstructor(), TrailingRequiresClause);
8855 
8856   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8857     // This is a C++ destructor declaration.
8858     if (DC->isRecord()) {
8859       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8860       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8861       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8862           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8863           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8864           /*isImplicitlyDeclared=*/false, ConstexprKind,
8865           TrailingRequiresClause);
8866 
8867       // If the destructor needs an implicit exception specification, set it
8868       // now. FIXME: It'd be nice to be able to create the right type to start
8869       // with, but the type needs to reference the destructor declaration.
8870       if (SemaRef.getLangOpts().CPlusPlus11)
8871         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8872 
8873       IsVirtualOkay = true;
8874       return NewDD;
8875 
8876     } else {
8877       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8878       D.setInvalidType();
8879 
8880       // Create a FunctionDecl to satisfy the function definition parsing
8881       // code path.
8882       return FunctionDecl::Create(
8883           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8884           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8885           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8886     }
8887 
8888   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8889     if (!DC->isRecord()) {
8890       SemaRef.Diag(D.getIdentifierLoc(),
8891            diag::err_conv_function_not_member);
8892       return nullptr;
8893     }
8894 
8895     SemaRef.CheckConversionDeclarator(D, R, SC);
8896     if (D.isInvalidType())
8897       return nullptr;
8898 
8899     IsVirtualOkay = true;
8900     return CXXConversionDecl::Create(
8901         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8902         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8903         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8904         TrailingRequiresClause);
8905 
8906   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8907     if (TrailingRequiresClause)
8908       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8909                    diag::err_trailing_requires_clause_on_deduction_guide)
8910           << TrailingRequiresClause->getSourceRange();
8911     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8912 
8913     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8914                                          ExplicitSpecifier, NameInfo, R, TInfo,
8915                                          D.getEndLoc());
8916   } else if (DC->isRecord()) {
8917     // If the name of the function is the same as the name of the record,
8918     // then this must be an invalid constructor that has a return type.
8919     // (The parser checks for a return type and makes the declarator a
8920     // constructor if it has no return type).
8921     if (Name.getAsIdentifierInfo() &&
8922         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8923       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8924         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8925         << SourceRange(D.getIdentifierLoc());
8926       return nullptr;
8927     }
8928 
8929     // This is a C++ method declaration.
8930     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8931         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8932         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8933         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8934     IsVirtualOkay = !Ret->isStatic();
8935     return Ret;
8936   } else {
8937     bool isFriend =
8938         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8939     if (!isFriend && SemaRef.CurContext->isRecord())
8940       return nullptr;
8941 
8942     // Determine whether the function was written with a
8943     // prototype. This true when:
8944     //   - we're in C++ (where every function has a prototype),
8945     return FunctionDecl::Create(
8946         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8947         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8948         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8949   }
8950 }
8951 
8952 enum OpenCLParamType {
8953   ValidKernelParam,
8954   PtrPtrKernelParam,
8955   PtrKernelParam,
8956   InvalidAddrSpacePtrKernelParam,
8957   InvalidKernelParam,
8958   RecordKernelParam
8959 };
8960 
8961 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8962   // Size dependent types are just typedefs to normal integer types
8963   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8964   // integers other than by their names.
8965   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8966 
8967   // Remove typedefs one by one until we reach a typedef
8968   // for a size dependent type.
8969   QualType DesugaredTy = Ty;
8970   do {
8971     ArrayRef<StringRef> Names(SizeTypeNames);
8972     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8973     if (Names.end() != Match)
8974       return true;
8975 
8976     Ty = DesugaredTy;
8977     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8978   } while (DesugaredTy != Ty);
8979 
8980   return false;
8981 }
8982 
8983 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8984   if (PT->isDependentType())
8985     return InvalidKernelParam;
8986 
8987   if (PT->isPointerType() || PT->isReferenceType()) {
8988     QualType PointeeType = PT->getPointeeType();
8989     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8990         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8991         PointeeType.getAddressSpace() == LangAS::Default)
8992       return InvalidAddrSpacePtrKernelParam;
8993 
8994     if (PointeeType->isPointerType()) {
8995       // This is a pointer to pointer parameter.
8996       // Recursively check inner type.
8997       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8998       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8999           ParamKind == InvalidKernelParam)
9000         return ParamKind;
9001 
9002       return PtrPtrKernelParam;
9003     }
9004 
9005     // C++ for OpenCL v1.0 s2.4:
9006     // Moreover the types used in parameters of the kernel functions must be:
9007     // Standard layout types for pointer parameters. The same applies to
9008     // reference if an implementation supports them in kernel parameters.
9009     if (S.getLangOpts().OpenCLCPlusPlus &&
9010         !S.getOpenCLOptions().isAvailableOption(
9011             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9012         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9013         !PointeeType->isStandardLayoutType())
9014       return InvalidKernelParam;
9015 
9016     return PtrKernelParam;
9017   }
9018 
9019   // OpenCL v1.2 s6.9.k:
9020   // Arguments to kernel functions in a program cannot be declared with the
9021   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9022   // uintptr_t or a struct and/or union that contain fields declared to be one
9023   // of these built-in scalar types.
9024   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9025     return InvalidKernelParam;
9026 
9027   if (PT->isImageType())
9028     return PtrKernelParam;
9029 
9030   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9031     return InvalidKernelParam;
9032 
9033   // OpenCL extension spec v1.2 s9.5:
9034   // This extension adds support for half scalar and vector types as built-in
9035   // types that can be used for arithmetic operations, conversions etc.
9036   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9037       PT->isHalfType())
9038     return InvalidKernelParam;
9039 
9040   // Look into an array argument to check if it has a forbidden type.
9041   if (PT->isArrayType()) {
9042     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9043     // Call ourself to check an underlying type of an array. Since the
9044     // getPointeeOrArrayElementType returns an innermost type which is not an
9045     // array, this recursive call only happens once.
9046     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9047   }
9048 
9049   // C++ for OpenCL v1.0 s2.4:
9050   // Moreover the types used in parameters of the kernel functions must be:
9051   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9052   // types) for parameters passed by value;
9053   if (S.getLangOpts().OpenCLCPlusPlus &&
9054       !S.getOpenCLOptions().isAvailableOption(
9055           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9056       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9057     return InvalidKernelParam;
9058 
9059   if (PT->isRecordType())
9060     return RecordKernelParam;
9061 
9062   return ValidKernelParam;
9063 }
9064 
9065 static void checkIsValidOpenCLKernelParameter(
9066   Sema &S,
9067   Declarator &D,
9068   ParmVarDecl *Param,
9069   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9070   QualType PT = Param->getType();
9071 
9072   // Cache the valid types we encounter to avoid rechecking structs that are
9073   // used again
9074   if (ValidTypes.count(PT.getTypePtr()))
9075     return;
9076 
9077   switch (getOpenCLKernelParameterType(S, PT)) {
9078   case PtrPtrKernelParam:
9079     // OpenCL v3.0 s6.11.a:
9080     // A kernel function argument cannot be declared as a pointer to a pointer
9081     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9082     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9083       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9084       D.setInvalidType();
9085       return;
9086     }
9087 
9088     ValidTypes.insert(PT.getTypePtr());
9089     return;
9090 
9091   case InvalidAddrSpacePtrKernelParam:
9092     // OpenCL v1.0 s6.5:
9093     // __kernel function arguments declared to be a pointer of a type can point
9094     // to one of the following address spaces only : __global, __local or
9095     // __constant.
9096     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9097     D.setInvalidType();
9098     return;
9099 
9100     // OpenCL v1.2 s6.9.k:
9101     // Arguments to kernel functions in a program cannot be declared with the
9102     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9103     // uintptr_t or a struct and/or union that contain fields declared to be
9104     // one of these built-in scalar types.
9105 
9106   case InvalidKernelParam:
9107     // OpenCL v1.2 s6.8 n:
9108     // A kernel function argument cannot be declared
9109     // of event_t type.
9110     // Do not diagnose half type since it is diagnosed as invalid argument
9111     // type for any function elsewhere.
9112     if (!PT->isHalfType()) {
9113       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9114 
9115       // Explain what typedefs are involved.
9116       const TypedefType *Typedef = nullptr;
9117       while ((Typedef = PT->getAs<TypedefType>())) {
9118         SourceLocation Loc = Typedef->getDecl()->getLocation();
9119         // SourceLocation may be invalid for a built-in type.
9120         if (Loc.isValid())
9121           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9122         PT = Typedef->desugar();
9123       }
9124     }
9125 
9126     D.setInvalidType();
9127     return;
9128 
9129   case PtrKernelParam:
9130   case ValidKernelParam:
9131     ValidTypes.insert(PT.getTypePtr());
9132     return;
9133 
9134   case RecordKernelParam:
9135     break;
9136   }
9137 
9138   // Track nested structs we will inspect
9139   SmallVector<const Decl *, 4> VisitStack;
9140 
9141   // Track where we are in the nested structs. Items will migrate from
9142   // VisitStack to HistoryStack as we do the DFS for bad field.
9143   SmallVector<const FieldDecl *, 4> HistoryStack;
9144   HistoryStack.push_back(nullptr);
9145 
9146   // At this point we already handled everything except of a RecordType or
9147   // an ArrayType of a RecordType.
9148   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9149   const RecordType *RecTy =
9150       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9151   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9152 
9153   VisitStack.push_back(RecTy->getDecl());
9154   assert(VisitStack.back() && "First decl null?");
9155 
9156   do {
9157     const Decl *Next = VisitStack.pop_back_val();
9158     if (!Next) {
9159       assert(!HistoryStack.empty());
9160       // Found a marker, we have gone up a level
9161       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9162         ValidTypes.insert(Hist->getType().getTypePtr());
9163 
9164       continue;
9165     }
9166 
9167     // Adds everything except the original parameter declaration (which is not a
9168     // field itself) to the history stack.
9169     const RecordDecl *RD;
9170     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9171       HistoryStack.push_back(Field);
9172 
9173       QualType FieldTy = Field->getType();
9174       // Other field types (known to be valid or invalid) are handled while we
9175       // walk around RecordDecl::fields().
9176       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9177              "Unexpected type.");
9178       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9179 
9180       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9181     } else {
9182       RD = cast<RecordDecl>(Next);
9183     }
9184 
9185     // Add a null marker so we know when we've gone back up a level
9186     VisitStack.push_back(nullptr);
9187 
9188     for (const auto *FD : RD->fields()) {
9189       QualType QT = FD->getType();
9190 
9191       if (ValidTypes.count(QT.getTypePtr()))
9192         continue;
9193 
9194       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9195       if (ParamType == ValidKernelParam)
9196         continue;
9197 
9198       if (ParamType == RecordKernelParam) {
9199         VisitStack.push_back(FD);
9200         continue;
9201       }
9202 
9203       // OpenCL v1.2 s6.9.p:
9204       // Arguments to kernel functions that are declared to be a struct or union
9205       // do not allow OpenCL objects to be passed as elements of the struct or
9206       // union.
9207       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9208           ParamType == InvalidAddrSpacePtrKernelParam) {
9209         S.Diag(Param->getLocation(),
9210                diag::err_record_with_pointers_kernel_param)
9211           << PT->isUnionType()
9212           << PT;
9213       } else {
9214         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9215       }
9216 
9217       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9218           << OrigRecDecl->getDeclName();
9219 
9220       // We have an error, now let's go back up through history and show where
9221       // the offending field came from
9222       for (ArrayRef<const FieldDecl *>::const_iterator
9223                I = HistoryStack.begin() + 1,
9224                E = HistoryStack.end();
9225            I != E; ++I) {
9226         const FieldDecl *OuterField = *I;
9227         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9228           << OuterField->getType();
9229       }
9230 
9231       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9232         << QT->isPointerType()
9233         << QT;
9234       D.setInvalidType();
9235       return;
9236     }
9237   } while (!VisitStack.empty());
9238 }
9239 
9240 /// Find the DeclContext in which a tag is implicitly declared if we see an
9241 /// elaborated type specifier in the specified context, and lookup finds
9242 /// nothing.
9243 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9244   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9245     DC = DC->getParent();
9246   return DC;
9247 }
9248 
9249 /// Find the Scope in which a tag is implicitly declared if we see an
9250 /// elaborated type specifier in the specified context, and lookup finds
9251 /// nothing.
9252 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9253   while (S->isClassScope() ||
9254          (LangOpts.CPlusPlus &&
9255           S->isFunctionPrototypeScope()) ||
9256          ((S->getFlags() & Scope::DeclScope) == 0) ||
9257          (S->getEntity() && S->getEntity()->isTransparentContext()))
9258     S = S->getParent();
9259   return S;
9260 }
9261 
9262 NamedDecl*
9263 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9264                               TypeSourceInfo *TInfo, LookupResult &Previous,
9265                               MultiTemplateParamsArg TemplateParamListsRef,
9266                               bool &AddToScope) {
9267   QualType R = TInfo->getType();
9268 
9269   assert(R->isFunctionType());
9270   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9271     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9272 
9273   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9274   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9275   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9276     if (!TemplateParamLists.empty() &&
9277         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9278       TemplateParamLists.back() = Invented;
9279     else
9280       TemplateParamLists.push_back(Invented);
9281   }
9282 
9283   // TODO: consider using NameInfo for diagnostic.
9284   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9285   DeclarationName Name = NameInfo.getName();
9286   StorageClass SC = getFunctionStorageClass(*this, D);
9287 
9288   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9289     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9290          diag::err_invalid_thread)
9291       << DeclSpec::getSpecifierName(TSCS);
9292 
9293   if (D.isFirstDeclarationOfMember())
9294     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9295                            D.getIdentifierLoc());
9296 
9297   bool isFriend = false;
9298   FunctionTemplateDecl *FunctionTemplate = nullptr;
9299   bool isMemberSpecialization = false;
9300   bool isFunctionTemplateSpecialization = false;
9301 
9302   bool isDependentClassScopeExplicitSpecialization = false;
9303   bool HasExplicitTemplateArgs = false;
9304   TemplateArgumentListInfo TemplateArgs;
9305 
9306   bool isVirtualOkay = false;
9307 
9308   DeclContext *OriginalDC = DC;
9309   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9310 
9311   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9312                                               isVirtualOkay);
9313   if (!NewFD) return nullptr;
9314 
9315   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9316     NewFD->setTopLevelDeclInObjCContainer();
9317 
9318   // Set the lexical context. If this is a function-scope declaration, or has a
9319   // C++ scope specifier, or is the object of a friend declaration, the lexical
9320   // context will be different from the semantic context.
9321   NewFD->setLexicalDeclContext(CurContext);
9322 
9323   if (IsLocalExternDecl)
9324     NewFD->setLocalExternDecl();
9325 
9326   if (getLangOpts().CPlusPlus) {
9327     bool isInline = D.getDeclSpec().isInlineSpecified();
9328     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9329     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9330     isFriend = D.getDeclSpec().isFriendSpecified();
9331     if (isFriend && !isInline && D.isFunctionDefinition()) {
9332       // C++ [class.friend]p5
9333       //   A function can be defined in a friend declaration of a
9334       //   class . . . . Such a function is implicitly inline.
9335       NewFD->setImplicitlyInline();
9336     }
9337 
9338     // If this is a method defined in an __interface, and is not a constructor
9339     // or an overloaded operator, then set the pure flag (isVirtual will already
9340     // return true).
9341     if (const CXXRecordDecl *Parent =
9342           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9343       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9344         NewFD->setPure(true);
9345 
9346       // C++ [class.union]p2
9347       //   A union can have member functions, but not virtual functions.
9348       if (isVirtual && Parent->isUnion()) {
9349         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9350         NewFD->setInvalidDecl();
9351       }
9352       if ((Parent->isClass() || Parent->isStruct()) &&
9353           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9354           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9355           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9356         if (auto *Def = Parent->getDefinition())
9357           Def->setInitMethod(true);
9358       }
9359     }
9360 
9361     SetNestedNameSpecifier(*this, NewFD, D);
9362     isMemberSpecialization = false;
9363     isFunctionTemplateSpecialization = false;
9364     if (D.isInvalidType())
9365       NewFD->setInvalidDecl();
9366 
9367     // Match up the template parameter lists with the scope specifier, then
9368     // determine whether we have a template or a template specialization.
9369     bool Invalid = false;
9370     TemplateParameterList *TemplateParams =
9371         MatchTemplateParametersToScopeSpecifier(
9372             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9373             D.getCXXScopeSpec(),
9374             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9375                 ? D.getName().TemplateId
9376                 : nullptr,
9377             TemplateParamLists, isFriend, isMemberSpecialization,
9378             Invalid);
9379     if (TemplateParams) {
9380       // Check that we can declare a template here.
9381       if (CheckTemplateDeclScope(S, TemplateParams))
9382         NewFD->setInvalidDecl();
9383 
9384       if (TemplateParams->size() > 0) {
9385         // This is a function template
9386 
9387         // A destructor cannot be a template.
9388         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9389           Diag(NewFD->getLocation(), diag::err_destructor_template);
9390           NewFD->setInvalidDecl();
9391         }
9392 
9393         // If we're adding a template to a dependent context, we may need to
9394         // rebuilding some of the types used within the template parameter list,
9395         // now that we know what the current instantiation is.
9396         if (DC->isDependentContext()) {
9397           ContextRAII SavedContext(*this, DC);
9398           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9399             Invalid = true;
9400         }
9401 
9402         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9403                                                         NewFD->getLocation(),
9404                                                         Name, TemplateParams,
9405                                                         NewFD);
9406         FunctionTemplate->setLexicalDeclContext(CurContext);
9407         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9408 
9409         // For source fidelity, store the other template param lists.
9410         if (TemplateParamLists.size() > 1) {
9411           NewFD->setTemplateParameterListsInfo(Context,
9412               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9413                   .drop_back(1));
9414         }
9415       } else {
9416         // This is a function template specialization.
9417         isFunctionTemplateSpecialization = true;
9418         // For source fidelity, store all the template param lists.
9419         if (TemplateParamLists.size() > 0)
9420           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9421 
9422         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9423         if (isFriend) {
9424           // We want to remove the "template<>", found here.
9425           SourceRange RemoveRange = TemplateParams->getSourceRange();
9426 
9427           // If we remove the template<> and the name is not a
9428           // template-id, we're actually silently creating a problem:
9429           // the friend declaration will refer to an untemplated decl,
9430           // and clearly the user wants a template specialization.  So
9431           // we need to insert '<>' after the name.
9432           SourceLocation InsertLoc;
9433           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9434             InsertLoc = D.getName().getSourceRange().getEnd();
9435             InsertLoc = getLocForEndOfToken(InsertLoc);
9436           }
9437 
9438           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9439             << Name << RemoveRange
9440             << FixItHint::CreateRemoval(RemoveRange)
9441             << FixItHint::CreateInsertion(InsertLoc, "<>");
9442           Invalid = true;
9443         }
9444       }
9445     } else {
9446       // Check that we can declare a template here.
9447       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9448           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9449         NewFD->setInvalidDecl();
9450 
9451       // All template param lists were matched against the scope specifier:
9452       // this is NOT (an explicit specialization of) a template.
9453       if (TemplateParamLists.size() > 0)
9454         // For source fidelity, store all the template param lists.
9455         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9456     }
9457 
9458     if (Invalid) {
9459       NewFD->setInvalidDecl();
9460       if (FunctionTemplate)
9461         FunctionTemplate->setInvalidDecl();
9462     }
9463 
9464     // C++ [dcl.fct.spec]p5:
9465     //   The virtual specifier shall only be used in declarations of
9466     //   nonstatic class member functions that appear within a
9467     //   member-specification of a class declaration; see 10.3.
9468     //
9469     if (isVirtual && !NewFD->isInvalidDecl()) {
9470       if (!isVirtualOkay) {
9471         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9472              diag::err_virtual_non_function);
9473       } else if (!CurContext->isRecord()) {
9474         // 'virtual' was specified outside of the class.
9475         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9476              diag::err_virtual_out_of_class)
9477           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9478       } else if (NewFD->getDescribedFunctionTemplate()) {
9479         // C++ [temp.mem]p3:
9480         //  A member function template shall not be virtual.
9481         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9482              diag::err_virtual_member_function_template)
9483           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9484       } else {
9485         // Okay: Add virtual to the method.
9486         NewFD->setVirtualAsWritten(true);
9487       }
9488 
9489       if (getLangOpts().CPlusPlus14 &&
9490           NewFD->getReturnType()->isUndeducedType())
9491         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9492     }
9493 
9494     if (getLangOpts().CPlusPlus14 &&
9495         (NewFD->isDependentContext() ||
9496          (isFriend && CurContext->isDependentContext())) &&
9497         NewFD->getReturnType()->isUndeducedType()) {
9498       // If the function template is referenced directly (for instance, as a
9499       // member of the current instantiation), pretend it has a dependent type.
9500       // This is not really justified by the standard, but is the only sane
9501       // thing to do.
9502       // FIXME: For a friend function, we have not marked the function as being
9503       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9504       const FunctionProtoType *FPT =
9505           NewFD->getType()->castAs<FunctionProtoType>();
9506       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9507       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9508                                              FPT->getExtProtoInfo()));
9509     }
9510 
9511     // C++ [dcl.fct.spec]p3:
9512     //  The inline specifier shall not appear on a block scope function
9513     //  declaration.
9514     if (isInline && !NewFD->isInvalidDecl()) {
9515       if (CurContext->isFunctionOrMethod()) {
9516         // 'inline' is not allowed on block scope function declaration.
9517         Diag(D.getDeclSpec().getInlineSpecLoc(),
9518              diag::err_inline_declaration_block_scope) << Name
9519           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9520       }
9521     }
9522 
9523     // C++ [dcl.fct.spec]p6:
9524     //  The explicit specifier shall be used only in the declaration of a
9525     //  constructor or conversion function within its class definition;
9526     //  see 12.3.1 and 12.3.2.
9527     if (hasExplicit && !NewFD->isInvalidDecl() &&
9528         !isa<CXXDeductionGuideDecl>(NewFD)) {
9529       if (!CurContext->isRecord()) {
9530         // 'explicit' was specified outside of the class.
9531         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9532              diag::err_explicit_out_of_class)
9533             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9534       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9535                  !isa<CXXConversionDecl>(NewFD)) {
9536         // 'explicit' was specified on a function that wasn't a constructor
9537         // or conversion function.
9538         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9539              diag::err_explicit_non_ctor_or_conv_function)
9540             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9541       }
9542     }
9543 
9544     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9545     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9546       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9547       // are implicitly inline.
9548       NewFD->setImplicitlyInline();
9549 
9550       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9551       // be either constructors or to return a literal type. Therefore,
9552       // destructors cannot be declared constexpr.
9553       if (isa<CXXDestructorDecl>(NewFD) &&
9554           (!getLangOpts().CPlusPlus20 ||
9555            ConstexprKind == ConstexprSpecKind::Consteval)) {
9556         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9557             << static_cast<int>(ConstexprKind);
9558         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9559                                     ? ConstexprSpecKind::Unspecified
9560                                     : ConstexprSpecKind::Constexpr);
9561       }
9562       // C++20 [dcl.constexpr]p2: An allocation function, or a
9563       // deallocation function shall not be declared with the consteval
9564       // specifier.
9565       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9566           (NewFD->getOverloadedOperator() == OO_New ||
9567            NewFD->getOverloadedOperator() == OO_Array_New ||
9568            NewFD->getOverloadedOperator() == OO_Delete ||
9569            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9570         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9571              diag::err_invalid_consteval_decl_kind)
9572             << NewFD;
9573         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9574       }
9575     }
9576 
9577     // If __module_private__ was specified, mark the function accordingly.
9578     if (D.getDeclSpec().isModulePrivateSpecified()) {
9579       if (isFunctionTemplateSpecialization) {
9580         SourceLocation ModulePrivateLoc
9581           = D.getDeclSpec().getModulePrivateSpecLoc();
9582         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9583           << 0
9584           << FixItHint::CreateRemoval(ModulePrivateLoc);
9585       } else {
9586         NewFD->setModulePrivate();
9587         if (FunctionTemplate)
9588           FunctionTemplate->setModulePrivate();
9589       }
9590     }
9591 
9592     if (isFriend) {
9593       if (FunctionTemplate) {
9594         FunctionTemplate->setObjectOfFriendDecl();
9595         FunctionTemplate->setAccess(AS_public);
9596       }
9597       NewFD->setObjectOfFriendDecl();
9598       NewFD->setAccess(AS_public);
9599     }
9600 
9601     // If a function is defined as defaulted or deleted, mark it as such now.
9602     // We'll do the relevant checks on defaulted / deleted functions later.
9603     switch (D.getFunctionDefinitionKind()) {
9604     case FunctionDefinitionKind::Declaration:
9605     case FunctionDefinitionKind::Definition:
9606       break;
9607 
9608     case FunctionDefinitionKind::Defaulted:
9609       NewFD->setDefaulted();
9610       break;
9611 
9612     case FunctionDefinitionKind::Deleted:
9613       NewFD->setDeletedAsWritten();
9614       break;
9615     }
9616 
9617     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9618         D.isFunctionDefinition()) {
9619       // C++ [class.mfct]p2:
9620       //   A member function may be defined (8.4) in its class definition, in
9621       //   which case it is an inline member function (7.1.2)
9622       NewFD->setImplicitlyInline();
9623     }
9624 
9625     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9626         !CurContext->isRecord()) {
9627       // C++ [class.static]p1:
9628       //   A data or function member of a class may be declared static
9629       //   in a class definition, in which case it is a static member of
9630       //   the class.
9631 
9632       // Complain about the 'static' specifier if it's on an out-of-line
9633       // member function definition.
9634 
9635       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9636       // member function template declaration and class member template
9637       // declaration (MSVC versions before 2015), warn about this.
9638       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9639            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9640              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9641            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9642            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9643         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9644     }
9645 
9646     // C++11 [except.spec]p15:
9647     //   A deallocation function with no exception-specification is treated
9648     //   as if it were specified with noexcept(true).
9649     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9650     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9651          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9652         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9653       NewFD->setType(Context.getFunctionType(
9654           FPT->getReturnType(), FPT->getParamTypes(),
9655           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9656   }
9657 
9658   // Filter out previous declarations that don't match the scope.
9659   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9660                        D.getCXXScopeSpec().isNotEmpty() ||
9661                        isMemberSpecialization ||
9662                        isFunctionTemplateSpecialization);
9663 
9664   // Handle GNU asm-label extension (encoded as an attribute).
9665   if (Expr *E = (Expr*) D.getAsmLabel()) {
9666     // The parser guarantees this is a string.
9667     StringLiteral *SE = cast<StringLiteral>(E);
9668     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9669                                         /*IsLiteralLabel=*/true,
9670                                         SE->getStrTokenLoc(0)));
9671   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9672     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9673       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9674     if (I != ExtnameUndeclaredIdentifiers.end()) {
9675       if (isDeclExternC(NewFD)) {
9676         NewFD->addAttr(I->second);
9677         ExtnameUndeclaredIdentifiers.erase(I);
9678       } else
9679         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9680             << /*Variable*/0 << NewFD;
9681     }
9682   }
9683 
9684   // Copy the parameter declarations from the declarator D to the function
9685   // declaration NewFD, if they are available.  First scavenge them into Params.
9686   SmallVector<ParmVarDecl*, 16> Params;
9687   unsigned FTIIdx;
9688   if (D.isFunctionDeclarator(FTIIdx)) {
9689     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9690 
9691     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9692     // function that takes no arguments, not a function that takes a
9693     // single void argument.
9694     // We let through "const void" here because Sema::GetTypeForDeclarator
9695     // already checks for that case.
9696     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9697       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9698         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9699         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9700         Param->setDeclContext(NewFD);
9701         Params.push_back(Param);
9702 
9703         if (Param->isInvalidDecl())
9704           NewFD->setInvalidDecl();
9705       }
9706     }
9707 
9708     if (!getLangOpts().CPlusPlus) {
9709       // In C, find all the tag declarations from the prototype and move them
9710       // into the function DeclContext. Remove them from the surrounding tag
9711       // injection context of the function, which is typically but not always
9712       // the TU.
9713       DeclContext *PrototypeTagContext =
9714           getTagInjectionContext(NewFD->getLexicalDeclContext());
9715       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9716         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9717 
9718         // We don't want to reparent enumerators. Look at their parent enum
9719         // instead.
9720         if (!TD) {
9721           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9722             TD = cast<EnumDecl>(ECD->getDeclContext());
9723         }
9724         if (!TD)
9725           continue;
9726         DeclContext *TagDC = TD->getLexicalDeclContext();
9727         if (!TagDC->containsDecl(TD))
9728           continue;
9729         TagDC->removeDecl(TD);
9730         TD->setDeclContext(NewFD);
9731         NewFD->addDecl(TD);
9732 
9733         // Preserve the lexical DeclContext if it is not the surrounding tag
9734         // injection context of the FD. In this example, the semantic context of
9735         // E will be f and the lexical context will be S, while both the
9736         // semantic and lexical contexts of S will be f:
9737         //   void f(struct S { enum E { a } f; } s);
9738         if (TagDC != PrototypeTagContext)
9739           TD->setLexicalDeclContext(TagDC);
9740       }
9741     }
9742   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9743     // When we're declaring a function with a typedef, typeof, etc as in the
9744     // following example, we'll need to synthesize (unnamed)
9745     // parameters for use in the declaration.
9746     //
9747     // @code
9748     // typedef void fn(int);
9749     // fn f;
9750     // @endcode
9751 
9752     // Synthesize a parameter for each argument type.
9753     for (const auto &AI : FT->param_types()) {
9754       ParmVarDecl *Param =
9755           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9756       Param->setScopeInfo(0, Params.size());
9757       Params.push_back(Param);
9758     }
9759   } else {
9760     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9761            "Should not need args for typedef of non-prototype fn");
9762   }
9763 
9764   // Finally, we know we have the right number of parameters, install them.
9765   NewFD->setParams(Params);
9766 
9767   if (D.getDeclSpec().isNoreturnSpecified())
9768     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9769                                            D.getDeclSpec().getNoreturnSpecLoc(),
9770                                            AttributeCommonInfo::AS_Keyword));
9771 
9772   // Functions returning a variably modified type violate C99 6.7.5.2p2
9773   // because all functions have linkage.
9774   if (!NewFD->isInvalidDecl() &&
9775       NewFD->getReturnType()->isVariablyModifiedType()) {
9776     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9777     NewFD->setInvalidDecl();
9778   }
9779 
9780   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9781   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9782       !NewFD->hasAttr<SectionAttr>())
9783     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9784         Context, PragmaClangTextSection.SectionName,
9785         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9786 
9787   // Apply an implicit SectionAttr if #pragma code_seg is active.
9788   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9789       !NewFD->hasAttr<SectionAttr>()) {
9790     NewFD->addAttr(SectionAttr::CreateImplicit(
9791         Context, CodeSegStack.CurrentValue->getString(),
9792         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9793         SectionAttr::Declspec_allocate));
9794     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9795                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9796                          ASTContext::PSF_Read,
9797                      NewFD))
9798       NewFD->dropAttr<SectionAttr>();
9799   }
9800 
9801   // Apply an implicit CodeSegAttr from class declspec or
9802   // apply an implicit SectionAttr from #pragma code_seg if active.
9803   if (!NewFD->hasAttr<CodeSegAttr>()) {
9804     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9805                                                                  D.isFunctionDefinition())) {
9806       NewFD->addAttr(SAttr);
9807     }
9808   }
9809 
9810   // Handle attributes.
9811   ProcessDeclAttributes(S, NewFD, D);
9812 
9813   if (getLangOpts().OpenCL) {
9814     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9815     // type declaration will generate a compilation error.
9816     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9817     if (AddressSpace != LangAS::Default) {
9818       Diag(NewFD->getLocation(),
9819            diag::err_opencl_return_value_with_address_space);
9820       NewFD->setInvalidDecl();
9821     }
9822   }
9823 
9824   if (!getLangOpts().CPlusPlus) {
9825     // Perform semantic checking on the function declaration.
9826     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9827       CheckMain(NewFD, D.getDeclSpec());
9828 
9829     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9830       CheckMSVCRTEntryPoint(NewFD);
9831 
9832     if (!NewFD->isInvalidDecl())
9833       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9834                                                   isMemberSpecialization,
9835                                                   D.isFunctionDefinition()));
9836     else if (!Previous.empty())
9837       // Recover gracefully from an invalid redeclaration.
9838       D.setRedeclaration(true);
9839     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9840             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9841            "previous declaration set still overloaded");
9842 
9843     // Diagnose no-prototype function declarations with calling conventions that
9844     // don't support variadic calls. Only do this in C and do it after merging
9845     // possibly prototyped redeclarations.
9846     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9847     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9848       CallingConv CC = FT->getExtInfo().getCC();
9849       if (!supportsVariadicCall(CC)) {
9850         // Windows system headers sometimes accidentally use stdcall without
9851         // (void) parameters, so we relax this to a warning.
9852         int DiagID =
9853             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9854         Diag(NewFD->getLocation(), DiagID)
9855             << FunctionType::getNameForCallConv(CC);
9856       }
9857     }
9858 
9859    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9860        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9861      checkNonTrivialCUnion(NewFD->getReturnType(),
9862                            NewFD->getReturnTypeSourceRange().getBegin(),
9863                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9864   } else {
9865     // C++11 [replacement.functions]p3:
9866     //  The program's definitions shall not be specified as inline.
9867     //
9868     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9869     //
9870     // Suppress the diagnostic if the function is __attribute__((used)), since
9871     // that forces an external definition to be emitted.
9872     if (D.getDeclSpec().isInlineSpecified() &&
9873         NewFD->isReplaceableGlobalAllocationFunction() &&
9874         !NewFD->hasAttr<UsedAttr>())
9875       Diag(D.getDeclSpec().getInlineSpecLoc(),
9876            diag::ext_operator_new_delete_declared_inline)
9877         << NewFD->getDeclName();
9878 
9879     // If the declarator is a template-id, translate the parser's template
9880     // argument list into our AST format.
9881     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9882       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9883       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9884       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9885       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9886                                          TemplateId->NumArgs);
9887       translateTemplateArguments(TemplateArgsPtr,
9888                                  TemplateArgs);
9889 
9890       HasExplicitTemplateArgs = true;
9891 
9892       if (NewFD->isInvalidDecl()) {
9893         HasExplicitTemplateArgs = false;
9894       } else if (FunctionTemplate) {
9895         // Function template with explicit template arguments.
9896         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9897           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9898 
9899         HasExplicitTemplateArgs = false;
9900       } else {
9901         assert((isFunctionTemplateSpecialization ||
9902                 D.getDeclSpec().isFriendSpecified()) &&
9903                "should have a 'template<>' for this decl");
9904         // "friend void foo<>(int);" is an implicit specialization decl.
9905         isFunctionTemplateSpecialization = true;
9906       }
9907     } else if (isFriend && isFunctionTemplateSpecialization) {
9908       // This combination is only possible in a recovery case;  the user
9909       // wrote something like:
9910       //   template <> friend void foo(int);
9911       // which we're recovering from as if the user had written:
9912       //   friend void foo<>(int);
9913       // Go ahead and fake up a template id.
9914       HasExplicitTemplateArgs = true;
9915       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9916       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9917     }
9918 
9919     // We do not add HD attributes to specializations here because
9920     // they may have different constexpr-ness compared to their
9921     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9922     // may end up with different effective targets. Instead, a
9923     // specialization inherits its target attributes from its template
9924     // in the CheckFunctionTemplateSpecialization() call below.
9925     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9926       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9927 
9928     // If it's a friend (and only if it's a friend), it's possible
9929     // that either the specialized function type or the specialized
9930     // template is dependent, and therefore matching will fail.  In
9931     // this case, don't check the specialization yet.
9932     if (isFunctionTemplateSpecialization && isFriend &&
9933         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9934          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9935              TemplateArgs.arguments()))) {
9936       assert(HasExplicitTemplateArgs &&
9937              "friend function specialization without template args");
9938       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9939                                                        Previous))
9940         NewFD->setInvalidDecl();
9941     } else if (isFunctionTemplateSpecialization) {
9942       if (CurContext->isDependentContext() && CurContext->isRecord()
9943           && !isFriend) {
9944         isDependentClassScopeExplicitSpecialization = true;
9945       } else if (!NewFD->isInvalidDecl() &&
9946                  CheckFunctionTemplateSpecialization(
9947                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9948                      Previous))
9949         NewFD->setInvalidDecl();
9950 
9951       // C++ [dcl.stc]p1:
9952       //   A storage-class-specifier shall not be specified in an explicit
9953       //   specialization (14.7.3)
9954       FunctionTemplateSpecializationInfo *Info =
9955           NewFD->getTemplateSpecializationInfo();
9956       if (Info && SC != SC_None) {
9957         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9958           Diag(NewFD->getLocation(),
9959                diag::err_explicit_specialization_inconsistent_storage_class)
9960             << SC
9961             << FixItHint::CreateRemoval(
9962                                       D.getDeclSpec().getStorageClassSpecLoc());
9963 
9964         else
9965           Diag(NewFD->getLocation(),
9966                diag::ext_explicit_specialization_storage_class)
9967             << FixItHint::CreateRemoval(
9968                                       D.getDeclSpec().getStorageClassSpecLoc());
9969       }
9970     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9971       if (CheckMemberSpecialization(NewFD, Previous))
9972           NewFD->setInvalidDecl();
9973     }
9974 
9975     // Perform semantic checking on the function declaration.
9976     if (!isDependentClassScopeExplicitSpecialization) {
9977       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9978         CheckMain(NewFD, D.getDeclSpec());
9979 
9980       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9981         CheckMSVCRTEntryPoint(NewFD);
9982 
9983       if (!NewFD->isInvalidDecl())
9984         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9985                                                     isMemberSpecialization,
9986                                                     D.isFunctionDefinition()));
9987       else if (!Previous.empty())
9988         // Recover gracefully from an invalid redeclaration.
9989         D.setRedeclaration(true);
9990     }
9991 
9992     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9993             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9994            "previous declaration set still overloaded");
9995 
9996     NamedDecl *PrincipalDecl = (FunctionTemplate
9997                                 ? cast<NamedDecl>(FunctionTemplate)
9998                                 : NewFD);
9999 
10000     if (isFriend && NewFD->getPreviousDecl()) {
10001       AccessSpecifier Access = AS_public;
10002       if (!NewFD->isInvalidDecl())
10003         Access = NewFD->getPreviousDecl()->getAccess();
10004 
10005       NewFD->setAccess(Access);
10006       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10007     }
10008 
10009     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10010         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10011       PrincipalDecl->setNonMemberOperator();
10012 
10013     // If we have a function template, check the template parameter
10014     // list. This will check and merge default template arguments.
10015     if (FunctionTemplate) {
10016       FunctionTemplateDecl *PrevTemplate =
10017                                      FunctionTemplate->getPreviousDecl();
10018       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10019                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10020                                     : nullptr,
10021                             D.getDeclSpec().isFriendSpecified()
10022                               ? (D.isFunctionDefinition()
10023                                    ? TPC_FriendFunctionTemplateDefinition
10024                                    : TPC_FriendFunctionTemplate)
10025                               : (D.getCXXScopeSpec().isSet() &&
10026                                  DC && DC->isRecord() &&
10027                                  DC->isDependentContext())
10028                                   ? TPC_ClassTemplateMember
10029                                   : TPC_FunctionTemplate);
10030     }
10031 
10032     if (NewFD->isInvalidDecl()) {
10033       // Ignore all the rest of this.
10034     } else if (!D.isRedeclaration()) {
10035       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10036                                        AddToScope };
10037       // Fake up an access specifier if it's supposed to be a class member.
10038       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10039         NewFD->setAccess(AS_public);
10040 
10041       // Qualified decls generally require a previous declaration.
10042       if (D.getCXXScopeSpec().isSet()) {
10043         // ...with the major exception of templated-scope or
10044         // dependent-scope friend declarations.
10045 
10046         // TODO: we currently also suppress this check in dependent
10047         // contexts because (1) the parameter depth will be off when
10048         // matching friend templates and (2) we might actually be
10049         // selecting a friend based on a dependent factor.  But there
10050         // are situations where these conditions don't apply and we
10051         // can actually do this check immediately.
10052         //
10053         // Unless the scope is dependent, it's always an error if qualified
10054         // redeclaration lookup found nothing at all. Diagnose that now;
10055         // nothing will diagnose that error later.
10056         if (isFriend &&
10057             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10058              (!Previous.empty() && CurContext->isDependentContext()))) {
10059           // ignore these
10060         } else if (NewFD->isCPUDispatchMultiVersion() ||
10061                    NewFD->isCPUSpecificMultiVersion()) {
10062           // ignore this, we allow the redeclaration behavior here to create new
10063           // versions of the function.
10064         } else {
10065           // The user tried to provide an out-of-line definition for a
10066           // function that is a member of a class or namespace, but there
10067           // was no such member function declared (C++ [class.mfct]p2,
10068           // C++ [namespace.memdef]p2). For example:
10069           //
10070           // class X {
10071           //   void f() const;
10072           // };
10073           //
10074           // void X::f() { } // ill-formed
10075           //
10076           // Complain about this problem, and attempt to suggest close
10077           // matches (e.g., those that differ only in cv-qualifiers and
10078           // whether the parameter types are references).
10079 
10080           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10081                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10082             AddToScope = ExtraArgs.AddToScope;
10083             return Result;
10084           }
10085         }
10086 
10087         // Unqualified local friend declarations are required to resolve
10088         // to something.
10089       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10090         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10091                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10092           AddToScope = ExtraArgs.AddToScope;
10093           return Result;
10094         }
10095       }
10096     } else if (!D.isFunctionDefinition() &&
10097                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10098                !isFriend && !isFunctionTemplateSpecialization &&
10099                !isMemberSpecialization) {
10100       // An out-of-line member function declaration must also be a
10101       // definition (C++ [class.mfct]p2).
10102       // Note that this is not the case for explicit specializations of
10103       // function templates or member functions of class templates, per
10104       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10105       // extension for compatibility with old SWIG code which likes to
10106       // generate them.
10107       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10108         << D.getCXXScopeSpec().getRange();
10109     }
10110   }
10111 
10112   // If this is the first declaration of a library builtin function, add
10113   // attributes as appropriate.
10114   if (!D.isRedeclaration() &&
10115       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10116     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10117       if (unsigned BuiltinID = II->getBuiltinID()) {
10118         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10119           // Validate the type matches unless this builtin is specified as
10120           // matching regardless of its declared type.
10121           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10122             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10123           } else {
10124             ASTContext::GetBuiltinTypeError Error;
10125             LookupNecessaryTypesForBuiltin(S, BuiltinID);
10126             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10127 
10128             if (!Error && !BuiltinType.isNull() &&
10129                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10130                     NewFD->getType(), BuiltinType))
10131               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10132           }
10133         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10134                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10135           // FIXME: We should consider this a builtin only in the std namespace.
10136           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10137         }
10138       }
10139     }
10140   }
10141 
10142   ProcessPragmaWeak(S, NewFD);
10143   checkAttributesAfterMerging(*this, *NewFD);
10144 
10145   AddKnownFunctionAttributes(NewFD);
10146 
10147   if (NewFD->hasAttr<OverloadableAttr>() &&
10148       !NewFD->getType()->getAs<FunctionProtoType>()) {
10149     Diag(NewFD->getLocation(),
10150          diag::err_attribute_overloadable_no_prototype)
10151       << NewFD;
10152 
10153     // Turn this into a variadic function with no parameters.
10154     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10155     FunctionProtoType::ExtProtoInfo EPI(
10156         Context.getDefaultCallingConvention(true, false));
10157     EPI.Variadic = true;
10158     EPI.ExtInfo = FT->getExtInfo();
10159 
10160     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10161     NewFD->setType(R);
10162   }
10163 
10164   // If there's a #pragma GCC visibility in scope, and this isn't a class
10165   // member, set the visibility of this function.
10166   if (!DC->isRecord() && NewFD->isExternallyVisible())
10167     AddPushedVisibilityAttribute(NewFD);
10168 
10169   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10170   // marking the function.
10171   AddCFAuditedAttribute(NewFD);
10172 
10173   // If this is a function definition, check if we have to apply optnone due to
10174   // a pragma.
10175   if(D.isFunctionDefinition())
10176     AddRangeBasedOptnone(NewFD);
10177 
10178   // If this is the first declaration of an extern C variable, update
10179   // the map of such variables.
10180   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10181       isIncompleteDeclExternC(*this, NewFD))
10182     RegisterLocallyScopedExternCDecl(NewFD, S);
10183 
10184   // Set this FunctionDecl's range up to the right paren.
10185   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10186 
10187   if (D.isRedeclaration() && !Previous.empty()) {
10188     NamedDecl *Prev = Previous.getRepresentativeDecl();
10189     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10190                                    isMemberSpecialization ||
10191                                        isFunctionTemplateSpecialization,
10192                                    D.isFunctionDefinition());
10193   }
10194 
10195   if (getLangOpts().CUDA) {
10196     IdentifierInfo *II = NewFD->getIdentifier();
10197     if (II && II->isStr(getCudaConfigureFuncName()) &&
10198         !NewFD->isInvalidDecl() &&
10199         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10200       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10201         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10202             << getCudaConfigureFuncName();
10203       Context.setcudaConfigureCallDecl(NewFD);
10204     }
10205 
10206     // Variadic functions, other than a *declaration* of printf, are not allowed
10207     // in device-side CUDA code, unless someone passed
10208     // -fcuda-allow-variadic-functions.
10209     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10210         (NewFD->hasAttr<CUDADeviceAttr>() ||
10211          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10212         !(II && II->isStr("printf") && NewFD->isExternC() &&
10213           !D.isFunctionDefinition())) {
10214       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10215     }
10216   }
10217 
10218   MarkUnusedFileScopedDecl(NewFD);
10219 
10220 
10221 
10222   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10223     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10224     if (SC == SC_Static) {
10225       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10226       D.setInvalidType();
10227     }
10228 
10229     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10230     if (!NewFD->getReturnType()->isVoidType()) {
10231       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10232       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10233           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10234                                 : FixItHint());
10235       D.setInvalidType();
10236     }
10237 
10238     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10239     for (auto Param : NewFD->parameters())
10240       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10241 
10242     if (getLangOpts().OpenCLCPlusPlus) {
10243       if (DC->isRecord()) {
10244         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10245         D.setInvalidType();
10246       }
10247       if (FunctionTemplate) {
10248         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10249         D.setInvalidType();
10250       }
10251     }
10252   }
10253 
10254   if (getLangOpts().CPlusPlus) {
10255     if (FunctionTemplate) {
10256       if (NewFD->isInvalidDecl())
10257         FunctionTemplate->setInvalidDecl();
10258       return FunctionTemplate;
10259     }
10260 
10261     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10262       CompleteMemberSpecialization(NewFD, Previous);
10263   }
10264 
10265   for (const ParmVarDecl *Param : NewFD->parameters()) {
10266     QualType PT = Param->getType();
10267 
10268     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10269     // types.
10270     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10271       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10272         QualType ElemTy = PipeTy->getElementType();
10273           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10274             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10275             D.setInvalidType();
10276           }
10277       }
10278     }
10279   }
10280 
10281   // Here we have an function template explicit specialization at class scope.
10282   // The actual specialization will be postponed to template instatiation
10283   // time via the ClassScopeFunctionSpecializationDecl node.
10284   if (isDependentClassScopeExplicitSpecialization) {
10285     ClassScopeFunctionSpecializationDecl *NewSpec =
10286                          ClassScopeFunctionSpecializationDecl::Create(
10287                                 Context, CurContext, NewFD->getLocation(),
10288                                 cast<CXXMethodDecl>(NewFD),
10289                                 HasExplicitTemplateArgs, TemplateArgs);
10290     CurContext->addDecl(NewSpec);
10291     AddToScope = false;
10292   }
10293 
10294   // Diagnose availability attributes. Availability cannot be used on functions
10295   // that are run during load/unload.
10296   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10297     if (NewFD->hasAttr<ConstructorAttr>()) {
10298       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10299           << 1;
10300       NewFD->dropAttr<AvailabilityAttr>();
10301     }
10302     if (NewFD->hasAttr<DestructorAttr>()) {
10303       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10304           << 2;
10305       NewFD->dropAttr<AvailabilityAttr>();
10306     }
10307   }
10308 
10309   // Diagnose no_builtin attribute on function declaration that are not a
10310   // definition.
10311   // FIXME: We should really be doing this in
10312   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10313   // the FunctionDecl and at this point of the code
10314   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10315   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10316   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10317     switch (D.getFunctionDefinitionKind()) {
10318     case FunctionDefinitionKind::Defaulted:
10319     case FunctionDefinitionKind::Deleted:
10320       Diag(NBA->getLocation(),
10321            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10322           << NBA->getSpelling();
10323       break;
10324     case FunctionDefinitionKind::Declaration:
10325       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10326           << NBA->getSpelling();
10327       break;
10328     case FunctionDefinitionKind::Definition:
10329       break;
10330     }
10331 
10332   return NewFD;
10333 }
10334 
10335 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10336 /// when __declspec(code_seg) "is applied to a class, all member functions of
10337 /// the class and nested classes -- this includes compiler-generated special
10338 /// member functions -- are put in the specified segment."
10339 /// The actual behavior is a little more complicated. The Microsoft compiler
10340 /// won't check outer classes if there is an active value from #pragma code_seg.
10341 /// The CodeSeg is always applied from the direct parent but only from outer
10342 /// classes when the #pragma code_seg stack is empty. See:
10343 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10344 /// available since MS has removed the page.
10345 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10346   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10347   if (!Method)
10348     return nullptr;
10349   const CXXRecordDecl *Parent = Method->getParent();
10350   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10351     Attr *NewAttr = SAttr->clone(S.getASTContext());
10352     NewAttr->setImplicit(true);
10353     return NewAttr;
10354   }
10355 
10356   // The Microsoft compiler won't check outer classes for the CodeSeg
10357   // when the #pragma code_seg stack is active.
10358   if (S.CodeSegStack.CurrentValue)
10359    return nullptr;
10360 
10361   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10362     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10363       Attr *NewAttr = SAttr->clone(S.getASTContext());
10364       NewAttr->setImplicit(true);
10365       return NewAttr;
10366     }
10367   }
10368   return nullptr;
10369 }
10370 
10371 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10372 /// containing class. Otherwise it will return implicit SectionAttr if the
10373 /// function is a definition and there is an active value on CodeSegStack
10374 /// (from the current #pragma code-seg value).
10375 ///
10376 /// \param FD Function being declared.
10377 /// \param IsDefinition Whether it is a definition or just a declarartion.
10378 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10379 ///          nullptr if no attribute should be added.
10380 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10381                                                        bool IsDefinition) {
10382   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10383     return A;
10384   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10385       CodeSegStack.CurrentValue)
10386     return SectionAttr::CreateImplicit(
10387         getASTContext(), CodeSegStack.CurrentValue->getString(),
10388         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10389         SectionAttr::Declspec_allocate);
10390   return nullptr;
10391 }
10392 
10393 /// Determines if we can perform a correct type check for \p D as a
10394 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10395 /// best-effort check.
10396 ///
10397 /// \param NewD The new declaration.
10398 /// \param OldD The old declaration.
10399 /// \param NewT The portion of the type of the new declaration to check.
10400 /// \param OldT The portion of the type of the old declaration to check.
10401 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10402                                           QualType NewT, QualType OldT) {
10403   if (!NewD->getLexicalDeclContext()->isDependentContext())
10404     return true;
10405 
10406   // For dependently-typed local extern declarations and friends, we can't
10407   // perform a correct type check in general until instantiation:
10408   //
10409   //   int f();
10410   //   template<typename T> void g() { T f(); }
10411   //
10412   // (valid if g() is only instantiated with T = int).
10413   if (NewT->isDependentType() &&
10414       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10415     return false;
10416 
10417   // Similarly, if the previous declaration was a dependent local extern
10418   // declaration, we don't really know its type yet.
10419   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10420     return false;
10421 
10422   return true;
10423 }
10424 
10425 /// Checks if the new declaration declared in dependent context must be
10426 /// put in the same redeclaration chain as the specified declaration.
10427 ///
10428 /// \param D Declaration that is checked.
10429 /// \param PrevDecl Previous declaration found with proper lookup method for the
10430 ///                 same declaration name.
10431 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10432 ///          belongs to.
10433 ///
10434 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10435   if (!D->getLexicalDeclContext()->isDependentContext())
10436     return true;
10437 
10438   // Don't chain dependent friend function definitions until instantiation, to
10439   // permit cases like
10440   //
10441   //   void func();
10442   //   template<typename T> class C1 { friend void func() {} };
10443   //   template<typename T> class C2 { friend void func() {} };
10444   //
10445   // ... which is valid if only one of C1 and C2 is ever instantiated.
10446   //
10447   // FIXME: This need only apply to function definitions. For now, we proxy
10448   // this by checking for a file-scope function. We do not want this to apply
10449   // to friend declarations nominating member functions, because that gets in
10450   // the way of access checks.
10451   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10452     return false;
10453 
10454   auto *VD = dyn_cast<ValueDecl>(D);
10455   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10456   return !VD || !PrevVD ||
10457          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10458                                         PrevVD->getType());
10459 }
10460 
10461 /// Check the target attribute of the function for MultiVersion
10462 /// validity.
10463 ///
10464 /// Returns true if there was an error, false otherwise.
10465 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10466   const auto *TA = FD->getAttr<TargetAttr>();
10467   assert(TA && "MultiVersion Candidate requires a target attribute");
10468   ParsedTargetAttr ParseInfo = TA->parse();
10469   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10470   enum ErrType { Feature = 0, Architecture = 1 };
10471 
10472   if (!ParseInfo.Architecture.empty() &&
10473       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10474     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10475         << Architecture << ParseInfo.Architecture;
10476     return true;
10477   }
10478 
10479   for (const auto &Feat : ParseInfo.Features) {
10480     auto BareFeat = StringRef{Feat}.substr(1);
10481     if (Feat[0] == '-') {
10482       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10483           << Feature << ("no-" + BareFeat).str();
10484       return true;
10485     }
10486 
10487     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10488         !TargetInfo.isValidFeatureName(BareFeat)) {
10489       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10490           << Feature << BareFeat;
10491       return true;
10492     }
10493   }
10494   return false;
10495 }
10496 
10497 // Provide a white-list of attributes that are allowed to be combined with
10498 // multiversion functions.
10499 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10500                                            MultiVersionKind MVKind) {
10501   // Note: this list/diagnosis must match the list in
10502   // checkMultiversionAttributesAllSame.
10503   switch (Kind) {
10504   default:
10505     return false;
10506   case attr::Used:
10507     return MVKind == MultiVersionKind::Target;
10508   case attr::NonNull:
10509   case attr::NoThrow:
10510     return true;
10511   }
10512 }
10513 
10514 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10515                                                  const FunctionDecl *FD,
10516                                                  const FunctionDecl *CausedFD,
10517                                                  MultiVersionKind MVKind) {
10518   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10519     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10520         << static_cast<unsigned>(MVKind) << A;
10521     if (CausedFD)
10522       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10523     return true;
10524   };
10525 
10526   for (const Attr *A : FD->attrs()) {
10527     switch (A->getKind()) {
10528     case attr::CPUDispatch:
10529     case attr::CPUSpecific:
10530       if (MVKind != MultiVersionKind::CPUDispatch &&
10531           MVKind != MultiVersionKind::CPUSpecific)
10532         return Diagnose(S, A);
10533       break;
10534     case attr::Target:
10535       if (MVKind != MultiVersionKind::Target)
10536         return Diagnose(S, A);
10537       break;
10538     case attr::TargetClones:
10539       if (MVKind != MultiVersionKind::TargetClones)
10540         return Diagnose(S, A);
10541       break;
10542     default:
10543       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10544         return Diagnose(S, A);
10545       break;
10546     }
10547   }
10548   return false;
10549 }
10550 
10551 bool Sema::areMultiversionVariantFunctionsCompatible(
10552     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10553     const PartialDiagnostic &NoProtoDiagID,
10554     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10555     const PartialDiagnosticAt &NoSupportDiagIDAt,
10556     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10557     bool ConstexprSupported, bool CLinkageMayDiffer) {
10558   enum DoesntSupport {
10559     FuncTemplates = 0,
10560     VirtFuncs = 1,
10561     DeducedReturn = 2,
10562     Constructors = 3,
10563     Destructors = 4,
10564     DeletedFuncs = 5,
10565     DefaultedFuncs = 6,
10566     ConstexprFuncs = 7,
10567     ConstevalFuncs = 8,
10568     Lambda = 9,
10569   };
10570   enum Different {
10571     CallingConv = 0,
10572     ReturnType = 1,
10573     ConstexprSpec = 2,
10574     InlineSpec = 3,
10575     Linkage = 4,
10576     LanguageLinkage = 5,
10577   };
10578 
10579   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10580       !OldFD->getType()->getAs<FunctionProtoType>()) {
10581     Diag(OldFD->getLocation(), NoProtoDiagID);
10582     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10583     return true;
10584   }
10585 
10586   if (NoProtoDiagID.getDiagID() != 0 &&
10587       !NewFD->getType()->getAs<FunctionProtoType>())
10588     return Diag(NewFD->getLocation(), NoProtoDiagID);
10589 
10590   if (!TemplatesSupported &&
10591       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10592     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10593            << FuncTemplates;
10594 
10595   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10596     if (NewCXXFD->isVirtual())
10597       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10598              << VirtFuncs;
10599 
10600     if (isa<CXXConstructorDecl>(NewCXXFD))
10601       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10602              << Constructors;
10603 
10604     if (isa<CXXDestructorDecl>(NewCXXFD))
10605       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10606              << Destructors;
10607   }
10608 
10609   if (NewFD->isDeleted())
10610     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10611            << DeletedFuncs;
10612 
10613   if (NewFD->isDefaulted())
10614     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10615            << DefaultedFuncs;
10616 
10617   if (!ConstexprSupported && NewFD->isConstexpr())
10618     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10619            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10620 
10621   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10622   const auto *NewType = cast<FunctionType>(NewQType);
10623   QualType NewReturnType = NewType->getReturnType();
10624 
10625   if (NewReturnType->isUndeducedType())
10626     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10627            << DeducedReturn;
10628 
10629   // Ensure the return type is identical.
10630   if (OldFD) {
10631     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10632     const auto *OldType = cast<FunctionType>(OldQType);
10633     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10634     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10635 
10636     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10637       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10638 
10639     QualType OldReturnType = OldType->getReturnType();
10640 
10641     if (OldReturnType != NewReturnType)
10642       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10643 
10644     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10645       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10646 
10647     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10648       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10649 
10650     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10651       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10652 
10653     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10654       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10655 
10656     if (CheckEquivalentExceptionSpec(
10657             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10658             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10659       return true;
10660   }
10661   return false;
10662 }
10663 
10664 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10665                                              const FunctionDecl *NewFD,
10666                                              bool CausesMV,
10667                                              MultiVersionKind MVKind) {
10668   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10669     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10670     if (OldFD)
10671       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10672     return true;
10673   }
10674 
10675   bool IsCPUSpecificCPUDispatchMVKind =
10676       MVKind == MultiVersionKind::CPUDispatch ||
10677       MVKind == MultiVersionKind::CPUSpecific;
10678 
10679   if (CausesMV && OldFD &&
10680       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10681     return true;
10682 
10683   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10684     return true;
10685 
10686   // Only allow transition to MultiVersion if it hasn't been used.
10687   if (OldFD && CausesMV && OldFD->isUsed(false))
10688     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10689 
10690   return S.areMultiversionVariantFunctionsCompatible(
10691       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10692       PartialDiagnosticAt(NewFD->getLocation(),
10693                           S.PDiag(diag::note_multiversioning_caused_here)),
10694       PartialDiagnosticAt(NewFD->getLocation(),
10695                           S.PDiag(diag::err_multiversion_doesnt_support)
10696                               << static_cast<unsigned>(MVKind)),
10697       PartialDiagnosticAt(NewFD->getLocation(),
10698                           S.PDiag(diag::err_multiversion_diff)),
10699       /*TemplatesSupported=*/false,
10700       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10701       /*CLinkageMayDiffer=*/false);
10702 }
10703 
10704 /// Check the validity of a multiversion function declaration that is the
10705 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10706 ///
10707 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10708 ///
10709 /// Returns true if there was an error, false otherwise.
10710 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10711                                            MultiVersionKind MVKind,
10712                                            const TargetAttr *TA) {
10713   assert(MVKind != MultiVersionKind::None &&
10714          "Function lacks multiversion attribute");
10715 
10716   // Target only causes MV if it is default, otherwise this is a normal
10717   // function.
10718   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10719     return false;
10720 
10721   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10722     FD->setInvalidDecl();
10723     return true;
10724   }
10725 
10726   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10727     FD->setInvalidDecl();
10728     return true;
10729   }
10730 
10731   FD->setIsMultiVersion();
10732   return false;
10733 }
10734 
10735 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10736   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10737     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10738       return true;
10739   }
10740 
10741   return false;
10742 }
10743 
10744 static bool CheckTargetCausesMultiVersioning(
10745     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10746     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10747   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10748   ParsedTargetAttr NewParsed = NewTA->parse();
10749   // Sort order doesn't matter, it just needs to be consistent.
10750   llvm::sort(NewParsed.Features);
10751 
10752   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10753   // to change, this is a simple redeclaration.
10754   if (!NewTA->isDefaultVersion() &&
10755       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10756     return false;
10757 
10758   // Otherwise, this decl causes MultiVersioning.
10759   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10760                                        MultiVersionKind::Target)) {
10761     NewFD->setInvalidDecl();
10762     return true;
10763   }
10764 
10765   if (CheckMultiVersionValue(S, NewFD)) {
10766     NewFD->setInvalidDecl();
10767     return true;
10768   }
10769 
10770   // If this is 'default', permit the forward declaration.
10771   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10772     Redeclaration = true;
10773     OldDecl = OldFD;
10774     OldFD->setIsMultiVersion();
10775     NewFD->setIsMultiVersion();
10776     return false;
10777   }
10778 
10779   if (CheckMultiVersionValue(S, OldFD)) {
10780     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10781     NewFD->setInvalidDecl();
10782     return true;
10783   }
10784 
10785   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10786 
10787   if (OldParsed == NewParsed) {
10788     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10789     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10790     NewFD->setInvalidDecl();
10791     return true;
10792   }
10793 
10794   for (const auto *FD : OldFD->redecls()) {
10795     const auto *CurTA = FD->getAttr<TargetAttr>();
10796     // We allow forward declarations before ANY multiversioning attributes, but
10797     // nothing after the fact.
10798     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10799         (!CurTA || CurTA->isInherited())) {
10800       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10801           << 0;
10802       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10803       NewFD->setInvalidDecl();
10804       return true;
10805     }
10806   }
10807 
10808   OldFD->setIsMultiVersion();
10809   NewFD->setIsMultiVersion();
10810   Redeclaration = false;
10811   OldDecl = nullptr;
10812   Previous.clear();
10813   return false;
10814 }
10815 
10816 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10817                                         MultiVersionKind New) {
10818   if (Old == New || Old == MultiVersionKind::None ||
10819       New == MultiVersionKind::None)
10820     return true;
10821 
10822   return (Old == MultiVersionKind::CPUDispatch &&
10823           New == MultiVersionKind::CPUSpecific) ||
10824          (Old == MultiVersionKind::CPUSpecific &&
10825           New == MultiVersionKind::CPUDispatch);
10826 }
10827 
10828 /// Check the validity of a new function declaration being added to an existing
10829 /// multiversioned declaration collection.
10830 static bool CheckMultiVersionAdditionalDecl(
10831     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10832     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10833     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10834     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10835     LookupResult &Previous) {
10836 
10837   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10838   // Disallow mixing of multiversioning types.
10839   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10840     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10841     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10842     NewFD->setInvalidDecl();
10843     return true;
10844   }
10845 
10846   ParsedTargetAttr NewParsed;
10847   if (NewTA) {
10848     NewParsed = NewTA->parse();
10849     llvm::sort(NewParsed.Features);
10850   }
10851 
10852   bool UseMemberUsingDeclRules =
10853       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10854 
10855   bool MayNeedOverloadableChecks =
10856       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10857 
10858   // Next, check ALL non-overloads to see if this is a redeclaration of a
10859   // previous member of the MultiVersion set.
10860   for (NamedDecl *ND : Previous) {
10861     FunctionDecl *CurFD = ND->getAsFunction();
10862     if (!CurFD)
10863       continue;
10864     if (MayNeedOverloadableChecks &&
10865         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10866       continue;
10867 
10868     switch (NewMVKind) {
10869     case MultiVersionKind::None:
10870       assert(OldMVKind == MultiVersionKind::TargetClones &&
10871              "Only target_clones can be omitted in subsequent declarations");
10872       break;
10873     case MultiVersionKind::Target: {
10874       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10875       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10876         NewFD->setIsMultiVersion();
10877         Redeclaration = true;
10878         OldDecl = ND;
10879         return false;
10880       }
10881 
10882       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10883       if (CurParsed == NewParsed) {
10884         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10885         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10886         NewFD->setInvalidDecl();
10887         return true;
10888       }
10889       break;
10890     }
10891     case MultiVersionKind::TargetClones: {
10892       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10893       Redeclaration = true;
10894       OldDecl = CurFD;
10895       NewFD->setIsMultiVersion();
10896 
10897       if (CurClones && NewClones &&
10898           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10899            !std::equal(CurClones->featuresStrs_begin(),
10900                        CurClones->featuresStrs_end(),
10901                        NewClones->featuresStrs_begin()))) {
10902         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10903         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10904         NewFD->setInvalidDecl();
10905         return true;
10906       }
10907 
10908       return false;
10909     }
10910     case MultiVersionKind::CPUSpecific:
10911     case MultiVersionKind::CPUDispatch: {
10912       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10913       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10914       // Handle CPUDispatch/CPUSpecific versions.
10915       // Only 1 CPUDispatch function is allowed, this will make it go through
10916       // the redeclaration errors.
10917       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10918           CurFD->hasAttr<CPUDispatchAttr>()) {
10919         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10920             std::equal(
10921                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10922                 NewCPUDisp->cpus_begin(),
10923                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10924                   return Cur->getName() == New->getName();
10925                 })) {
10926           NewFD->setIsMultiVersion();
10927           Redeclaration = true;
10928           OldDecl = ND;
10929           return false;
10930         }
10931 
10932         // If the declarations don't match, this is an error condition.
10933         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10934         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10935         NewFD->setInvalidDecl();
10936         return true;
10937       }
10938       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10939         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10940             std::equal(
10941                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10942                 NewCPUSpec->cpus_begin(),
10943                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10944                   return Cur->getName() == New->getName();
10945                 })) {
10946           NewFD->setIsMultiVersion();
10947           Redeclaration = true;
10948           OldDecl = ND;
10949           return false;
10950         }
10951 
10952         // Only 1 version of CPUSpecific is allowed for each CPU.
10953         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10954           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10955             if (CurII == NewII) {
10956               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10957                   << NewII;
10958               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10959               NewFD->setInvalidDecl();
10960               return true;
10961             }
10962           }
10963         }
10964       }
10965       break;
10966     }
10967     }
10968   }
10969 
10970   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10971   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10972   // handled in the attribute adding step.
10973   if (NewMVKind == MultiVersionKind::Target &&
10974       CheckMultiVersionValue(S, NewFD)) {
10975     NewFD->setInvalidDecl();
10976     return true;
10977   }
10978 
10979   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10980                                        !OldFD->isMultiVersion(), NewMVKind)) {
10981     NewFD->setInvalidDecl();
10982     return true;
10983   }
10984 
10985   // Permit forward declarations in the case where these two are compatible.
10986   if (!OldFD->isMultiVersion()) {
10987     OldFD->setIsMultiVersion();
10988     NewFD->setIsMultiVersion();
10989     Redeclaration = true;
10990     OldDecl = OldFD;
10991     return false;
10992   }
10993 
10994   NewFD->setIsMultiVersion();
10995   Redeclaration = false;
10996   OldDecl = nullptr;
10997   Previous.clear();
10998   return false;
10999 }
11000 
11001 /// Check the validity of a mulitversion function declaration.
11002 /// Also sets the multiversion'ness' of the function itself.
11003 ///
11004 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11005 ///
11006 /// Returns true if there was an error, false otherwise.
11007 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11008                                       bool &Redeclaration, NamedDecl *&OldDecl,
11009                                       LookupResult &Previous) {
11010   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11011   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11012   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11013   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11014   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11015 
11016   // Main isn't allowed to become a multiversion function, however it IS
11017   // permitted to have 'main' be marked with the 'target' optimization hint.
11018   if (NewFD->isMain()) {
11019     if (MVKind != MultiVersionKind::None &&
11020         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11021       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11022       NewFD->setInvalidDecl();
11023       return true;
11024     }
11025     return false;
11026   }
11027 
11028   if (!OldDecl || !OldDecl->getAsFunction() ||
11029       OldDecl->getDeclContext()->getRedeclContext() !=
11030           NewFD->getDeclContext()->getRedeclContext()) {
11031     // If there's no previous declaration, AND this isn't attempting to cause
11032     // multiversioning, this isn't an error condition.
11033     if (MVKind == MultiVersionKind::None)
11034       return false;
11035     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11036   }
11037 
11038   FunctionDecl *OldFD = OldDecl->getAsFunction();
11039 
11040   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11041     return false;
11042 
11043   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11044   // for target_clones.
11045   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11046       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11047     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11048         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11049     NewFD->setInvalidDecl();
11050     return true;
11051   }
11052 
11053   if (!OldFD->isMultiVersion()) {
11054     switch (MVKind) {
11055     case MultiVersionKind::Target:
11056       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11057                                               Redeclaration, OldDecl, Previous);
11058     case MultiVersionKind::TargetClones:
11059       if (OldFD->isUsed(false)) {
11060         NewFD->setInvalidDecl();
11061         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11062       }
11063       OldFD->setIsMultiVersion();
11064       break;
11065     case MultiVersionKind::CPUDispatch:
11066     case MultiVersionKind::CPUSpecific:
11067     case MultiVersionKind::None:
11068       break;
11069     }
11070   }
11071 
11072   // At this point, we have a multiversion function decl (in OldFD) AND an
11073   // appropriate attribute in the current function decl.  Resolve that these are
11074   // still compatible with previous declarations.
11075   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11076                                          NewCPUDisp, NewCPUSpec, NewClones,
11077                                          Redeclaration, OldDecl, Previous);
11078 }
11079 
11080 /// Perform semantic checking of a new function declaration.
11081 ///
11082 /// Performs semantic analysis of the new function declaration
11083 /// NewFD. This routine performs all semantic checking that does not
11084 /// require the actual declarator involved in the declaration, and is
11085 /// used both for the declaration of functions as they are parsed
11086 /// (called via ActOnDeclarator) and for the declaration of functions
11087 /// that have been instantiated via C++ template instantiation (called
11088 /// via InstantiateDecl).
11089 ///
11090 /// \param IsMemberSpecialization whether this new function declaration is
11091 /// a member specialization (that replaces any definition provided by the
11092 /// previous declaration).
11093 ///
11094 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11095 ///
11096 /// \returns true if the function declaration is a redeclaration.
11097 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11098                                     LookupResult &Previous,
11099                                     bool IsMemberSpecialization,
11100                                     bool DeclIsDefn) {
11101   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11102          "Variably modified return types are not handled here");
11103 
11104   // Determine whether the type of this function should be merged with
11105   // a previous visible declaration. This never happens for functions in C++,
11106   // and always happens in C if the previous declaration was visible.
11107   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11108                                !Previous.isShadowed();
11109 
11110   bool Redeclaration = false;
11111   NamedDecl *OldDecl = nullptr;
11112   bool MayNeedOverloadableChecks = false;
11113 
11114   // Merge or overload the declaration with an existing declaration of
11115   // the same name, if appropriate.
11116   if (!Previous.empty()) {
11117     // Determine whether NewFD is an overload of PrevDecl or
11118     // a declaration that requires merging. If it's an overload,
11119     // there's no more work to do here; we'll just add the new
11120     // function to the scope.
11121     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11122       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11123       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11124         Redeclaration = true;
11125         OldDecl = Candidate;
11126       }
11127     } else {
11128       MayNeedOverloadableChecks = true;
11129       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11130                             /*NewIsUsingDecl*/ false)) {
11131       case Ovl_Match:
11132         Redeclaration = true;
11133         break;
11134 
11135       case Ovl_NonFunction:
11136         Redeclaration = true;
11137         break;
11138 
11139       case Ovl_Overload:
11140         Redeclaration = false;
11141         break;
11142       }
11143     }
11144   }
11145 
11146   // Check for a previous extern "C" declaration with this name.
11147   if (!Redeclaration &&
11148       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11149     if (!Previous.empty()) {
11150       // This is an extern "C" declaration with the same name as a previous
11151       // declaration, and thus redeclares that entity...
11152       Redeclaration = true;
11153       OldDecl = Previous.getFoundDecl();
11154       MergeTypeWithPrevious = false;
11155 
11156       // ... except in the presence of __attribute__((overloadable)).
11157       if (OldDecl->hasAttr<OverloadableAttr>() ||
11158           NewFD->hasAttr<OverloadableAttr>()) {
11159         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11160           MayNeedOverloadableChecks = true;
11161           Redeclaration = false;
11162           OldDecl = nullptr;
11163         }
11164       }
11165     }
11166   }
11167 
11168   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11169     return Redeclaration;
11170 
11171   // PPC MMA non-pointer types are not allowed as function return types.
11172   if (Context.getTargetInfo().getTriple().isPPC64() &&
11173       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11174     NewFD->setInvalidDecl();
11175   }
11176 
11177   // C++11 [dcl.constexpr]p8:
11178   //   A constexpr specifier for a non-static member function that is not
11179   //   a constructor declares that member function to be const.
11180   //
11181   // This needs to be delayed until we know whether this is an out-of-line
11182   // definition of a static member function.
11183   //
11184   // This rule is not present in C++1y, so we produce a backwards
11185   // compatibility warning whenever it happens in C++11.
11186   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11187   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11188       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11189       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11190     CXXMethodDecl *OldMD = nullptr;
11191     if (OldDecl)
11192       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11193     if (!OldMD || !OldMD->isStatic()) {
11194       const FunctionProtoType *FPT =
11195         MD->getType()->castAs<FunctionProtoType>();
11196       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11197       EPI.TypeQuals.addConst();
11198       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11199                                           FPT->getParamTypes(), EPI));
11200 
11201       // Warn that we did this, if we're not performing template instantiation.
11202       // In that case, we'll have warned already when the template was defined.
11203       if (!inTemplateInstantiation()) {
11204         SourceLocation AddConstLoc;
11205         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11206                 .IgnoreParens().getAs<FunctionTypeLoc>())
11207           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11208 
11209         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11210           << FixItHint::CreateInsertion(AddConstLoc, " const");
11211       }
11212     }
11213   }
11214 
11215   if (Redeclaration) {
11216     // NewFD and OldDecl represent declarations that need to be
11217     // merged.
11218     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11219                           DeclIsDefn)) {
11220       NewFD->setInvalidDecl();
11221       return Redeclaration;
11222     }
11223 
11224     Previous.clear();
11225     Previous.addDecl(OldDecl);
11226 
11227     if (FunctionTemplateDecl *OldTemplateDecl =
11228             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11229       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11230       FunctionTemplateDecl *NewTemplateDecl
11231         = NewFD->getDescribedFunctionTemplate();
11232       assert(NewTemplateDecl && "Template/non-template mismatch");
11233 
11234       // The call to MergeFunctionDecl above may have created some state in
11235       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11236       // can add it as a redeclaration.
11237       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11238 
11239       NewFD->setPreviousDeclaration(OldFD);
11240       if (NewFD->isCXXClassMember()) {
11241         NewFD->setAccess(OldTemplateDecl->getAccess());
11242         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11243       }
11244 
11245       // If this is an explicit specialization of a member that is a function
11246       // template, mark it as a member specialization.
11247       if (IsMemberSpecialization &&
11248           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11249         NewTemplateDecl->setMemberSpecialization();
11250         assert(OldTemplateDecl->isMemberSpecialization());
11251         // Explicit specializations of a member template do not inherit deleted
11252         // status from the parent member template that they are specializing.
11253         if (OldFD->isDeleted()) {
11254           // FIXME: This assert will not hold in the presence of modules.
11255           assert(OldFD->getCanonicalDecl() == OldFD);
11256           // FIXME: We need an update record for this AST mutation.
11257           OldFD->setDeletedAsWritten(false);
11258         }
11259       }
11260 
11261     } else {
11262       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11263         auto *OldFD = cast<FunctionDecl>(OldDecl);
11264         // This needs to happen first so that 'inline' propagates.
11265         NewFD->setPreviousDeclaration(OldFD);
11266         if (NewFD->isCXXClassMember())
11267           NewFD->setAccess(OldFD->getAccess());
11268       }
11269     }
11270   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11271              !NewFD->getAttr<OverloadableAttr>()) {
11272     assert((Previous.empty() ||
11273             llvm::any_of(Previous,
11274                          [](const NamedDecl *ND) {
11275                            return ND->hasAttr<OverloadableAttr>();
11276                          })) &&
11277            "Non-redecls shouldn't happen without overloadable present");
11278 
11279     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11280       const auto *FD = dyn_cast<FunctionDecl>(ND);
11281       return FD && !FD->hasAttr<OverloadableAttr>();
11282     });
11283 
11284     if (OtherUnmarkedIter != Previous.end()) {
11285       Diag(NewFD->getLocation(),
11286            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11287       Diag((*OtherUnmarkedIter)->getLocation(),
11288            diag::note_attribute_overloadable_prev_overload)
11289           << false;
11290 
11291       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11292     }
11293   }
11294 
11295   if (LangOpts.OpenMP)
11296     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11297 
11298   // Semantic checking for this function declaration (in isolation).
11299 
11300   if (getLangOpts().CPlusPlus) {
11301     // C++-specific checks.
11302     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11303       CheckConstructor(Constructor);
11304     } else if (CXXDestructorDecl *Destructor =
11305                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11306       CXXRecordDecl *Record = Destructor->getParent();
11307       QualType ClassType = Context.getTypeDeclType(Record);
11308 
11309       // FIXME: Shouldn't we be able to perform this check even when the class
11310       // type is dependent? Both gcc and edg can handle that.
11311       if (!ClassType->isDependentType()) {
11312         DeclarationName Name
11313           = Context.DeclarationNames.getCXXDestructorName(
11314                                         Context.getCanonicalType(ClassType));
11315         if (NewFD->getDeclName() != Name) {
11316           Diag(NewFD->getLocation(), diag::err_destructor_name);
11317           NewFD->setInvalidDecl();
11318           return Redeclaration;
11319         }
11320       }
11321     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11322       if (auto *TD = Guide->getDescribedFunctionTemplate())
11323         CheckDeductionGuideTemplate(TD);
11324 
11325       // A deduction guide is not on the list of entities that can be
11326       // explicitly specialized.
11327       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11328         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11329             << /*explicit specialization*/ 1;
11330     }
11331 
11332     // Find any virtual functions that this function overrides.
11333     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11334       if (!Method->isFunctionTemplateSpecialization() &&
11335           !Method->getDescribedFunctionTemplate() &&
11336           Method->isCanonicalDecl()) {
11337         AddOverriddenMethods(Method->getParent(), Method);
11338       }
11339       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11340         // C++2a [class.virtual]p6
11341         // A virtual method shall not have a requires-clause.
11342         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11343              diag::err_constrained_virtual_method);
11344 
11345       if (Method->isStatic())
11346         checkThisInStaticMemberFunctionType(Method);
11347     }
11348 
11349     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11350       ActOnConversionDeclarator(Conversion);
11351 
11352     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11353     if (NewFD->isOverloadedOperator() &&
11354         CheckOverloadedOperatorDeclaration(NewFD)) {
11355       NewFD->setInvalidDecl();
11356       return Redeclaration;
11357     }
11358 
11359     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11360     if (NewFD->getLiteralIdentifier() &&
11361         CheckLiteralOperatorDeclaration(NewFD)) {
11362       NewFD->setInvalidDecl();
11363       return Redeclaration;
11364     }
11365 
11366     // In C++, check default arguments now that we have merged decls. Unless
11367     // the lexical context is the class, because in this case this is done
11368     // during delayed parsing anyway.
11369     if (!CurContext->isRecord())
11370       CheckCXXDefaultArguments(NewFD);
11371 
11372     // If this function is declared as being extern "C", then check to see if
11373     // the function returns a UDT (class, struct, or union type) that is not C
11374     // compatible, and if it does, warn the user.
11375     // But, issue any diagnostic on the first declaration only.
11376     if (Previous.empty() && NewFD->isExternC()) {
11377       QualType R = NewFD->getReturnType();
11378       if (R->isIncompleteType() && !R->isVoidType())
11379         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11380             << NewFD << R;
11381       else if (!R.isPODType(Context) && !R->isVoidType() &&
11382                !R->isObjCObjectPointerType())
11383         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11384     }
11385 
11386     // C++1z [dcl.fct]p6:
11387     //   [...] whether the function has a non-throwing exception-specification
11388     //   [is] part of the function type
11389     //
11390     // This results in an ABI break between C++14 and C++17 for functions whose
11391     // declared type includes an exception-specification in a parameter or
11392     // return type. (Exception specifications on the function itself are OK in
11393     // most cases, and exception specifications are not permitted in most other
11394     // contexts where they could make it into a mangling.)
11395     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11396       auto HasNoexcept = [&](QualType T) -> bool {
11397         // Strip off declarator chunks that could be between us and a function
11398         // type. We don't need to look far, exception specifications are very
11399         // restricted prior to C++17.
11400         if (auto *RT = T->getAs<ReferenceType>())
11401           T = RT->getPointeeType();
11402         else if (T->isAnyPointerType())
11403           T = T->getPointeeType();
11404         else if (auto *MPT = T->getAs<MemberPointerType>())
11405           T = MPT->getPointeeType();
11406         if (auto *FPT = T->getAs<FunctionProtoType>())
11407           if (FPT->isNothrow())
11408             return true;
11409         return false;
11410       };
11411 
11412       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11413       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11414       for (QualType T : FPT->param_types())
11415         AnyNoexcept |= HasNoexcept(T);
11416       if (AnyNoexcept)
11417         Diag(NewFD->getLocation(),
11418              diag::warn_cxx17_compat_exception_spec_in_signature)
11419             << NewFD;
11420     }
11421 
11422     if (!Redeclaration && LangOpts.CUDA)
11423       checkCUDATargetOverload(NewFD, Previous);
11424   }
11425   return Redeclaration;
11426 }
11427 
11428 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11429   // C++11 [basic.start.main]p3:
11430   //   A program that [...] declares main to be inline, static or
11431   //   constexpr is ill-formed.
11432   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11433   //   appear in a declaration of main.
11434   // static main is not an error under C99, but we should warn about it.
11435   // We accept _Noreturn main as an extension.
11436   if (FD->getStorageClass() == SC_Static)
11437     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11438          ? diag::err_static_main : diag::warn_static_main)
11439       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11440   if (FD->isInlineSpecified())
11441     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11442       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11443   if (DS.isNoreturnSpecified()) {
11444     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11445     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11446     Diag(NoreturnLoc, diag::ext_noreturn_main);
11447     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11448       << FixItHint::CreateRemoval(NoreturnRange);
11449   }
11450   if (FD->isConstexpr()) {
11451     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11452         << FD->isConsteval()
11453         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11454     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11455   }
11456 
11457   if (getLangOpts().OpenCL) {
11458     Diag(FD->getLocation(), diag::err_opencl_no_main)
11459         << FD->hasAttr<OpenCLKernelAttr>();
11460     FD->setInvalidDecl();
11461     return;
11462   }
11463 
11464   // Functions named main in hlsl are default entries, but don't have specific
11465   // signatures they are required to conform to.
11466   if (getLangOpts().HLSL)
11467     return;
11468 
11469   QualType T = FD->getType();
11470   assert(T->isFunctionType() && "function decl is not of function type");
11471   const FunctionType* FT = T->castAs<FunctionType>();
11472 
11473   // Set default calling convention for main()
11474   if (FT->getCallConv() != CC_C) {
11475     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11476     FD->setType(QualType(FT, 0));
11477     T = Context.getCanonicalType(FD->getType());
11478   }
11479 
11480   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11481     // In C with GNU extensions we allow main() to have non-integer return
11482     // type, but we should warn about the extension, and we disable the
11483     // implicit-return-zero rule.
11484 
11485     // GCC in C mode accepts qualified 'int'.
11486     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11487       FD->setHasImplicitReturnZero(true);
11488     else {
11489       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11490       SourceRange RTRange = FD->getReturnTypeSourceRange();
11491       if (RTRange.isValid())
11492         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11493             << FixItHint::CreateReplacement(RTRange, "int");
11494     }
11495   } else {
11496     // In C and C++, main magically returns 0 if you fall off the end;
11497     // set the flag which tells us that.
11498     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11499 
11500     // All the standards say that main() should return 'int'.
11501     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11502       FD->setHasImplicitReturnZero(true);
11503     else {
11504       // Otherwise, this is just a flat-out error.
11505       SourceRange RTRange = FD->getReturnTypeSourceRange();
11506       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11507           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11508                                 : FixItHint());
11509       FD->setInvalidDecl(true);
11510     }
11511   }
11512 
11513   // Treat protoless main() as nullary.
11514   if (isa<FunctionNoProtoType>(FT)) return;
11515 
11516   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11517   unsigned nparams = FTP->getNumParams();
11518   assert(FD->getNumParams() == nparams);
11519 
11520   bool HasExtraParameters = (nparams > 3);
11521 
11522   if (FTP->isVariadic()) {
11523     Diag(FD->getLocation(), diag::ext_variadic_main);
11524     // FIXME: if we had information about the location of the ellipsis, we
11525     // could add a FixIt hint to remove it as a parameter.
11526   }
11527 
11528   // Darwin passes an undocumented fourth argument of type char**.  If
11529   // other platforms start sprouting these, the logic below will start
11530   // getting shifty.
11531   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11532     HasExtraParameters = false;
11533 
11534   if (HasExtraParameters) {
11535     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11536     FD->setInvalidDecl(true);
11537     nparams = 3;
11538   }
11539 
11540   // FIXME: a lot of the following diagnostics would be improved
11541   // if we had some location information about types.
11542 
11543   QualType CharPP =
11544     Context.getPointerType(Context.getPointerType(Context.CharTy));
11545   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11546 
11547   for (unsigned i = 0; i < nparams; ++i) {
11548     QualType AT = FTP->getParamType(i);
11549 
11550     bool mismatch = true;
11551 
11552     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11553       mismatch = false;
11554     else if (Expected[i] == CharPP) {
11555       // As an extension, the following forms are okay:
11556       //   char const **
11557       //   char const * const *
11558       //   char * const *
11559 
11560       QualifierCollector qs;
11561       const PointerType* PT;
11562       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11563           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11564           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11565                               Context.CharTy)) {
11566         qs.removeConst();
11567         mismatch = !qs.empty();
11568       }
11569     }
11570 
11571     if (mismatch) {
11572       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11573       // TODO: suggest replacing given type with expected type
11574       FD->setInvalidDecl(true);
11575     }
11576   }
11577 
11578   if (nparams == 1 && !FD->isInvalidDecl()) {
11579     Diag(FD->getLocation(), diag::warn_main_one_arg);
11580   }
11581 
11582   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11583     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11584     FD->setInvalidDecl();
11585   }
11586 }
11587 
11588 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11589 
11590   // Default calling convention for main and wmain is __cdecl
11591   if (FD->getName() == "main" || FD->getName() == "wmain")
11592     return false;
11593 
11594   // Default calling convention for MinGW is __cdecl
11595   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11596   if (T.isWindowsGNUEnvironment())
11597     return false;
11598 
11599   // Default calling convention for WinMain, wWinMain and DllMain
11600   // is __stdcall on 32 bit Windows
11601   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11602     return true;
11603 
11604   return false;
11605 }
11606 
11607 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11608   QualType T = FD->getType();
11609   assert(T->isFunctionType() && "function decl is not of function type");
11610   const FunctionType *FT = T->castAs<FunctionType>();
11611 
11612   // Set an implicit return of 'zero' if the function can return some integral,
11613   // enumeration, pointer or nullptr type.
11614   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11615       FT->getReturnType()->isAnyPointerType() ||
11616       FT->getReturnType()->isNullPtrType())
11617     // DllMain is exempt because a return value of zero means it failed.
11618     if (FD->getName() != "DllMain")
11619       FD->setHasImplicitReturnZero(true);
11620 
11621   // Explicity specified calling conventions are applied to MSVC entry points
11622   if (!hasExplicitCallingConv(T)) {
11623     if (isDefaultStdCall(FD, *this)) {
11624       if (FT->getCallConv() != CC_X86StdCall) {
11625         FT = Context.adjustFunctionType(
11626             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11627         FD->setType(QualType(FT, 0));
11628       }
11629     } else if (FT->getCallConv() != CC_C) {
11630       FT = Context.adjustFunctionType(FT,
11631                                       FT->getExtInfo().withCallingConv(CC_C));
11632       FD->setType(QualType(FT, 0));
11633     }
11634   }
11635 
11636   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11637     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11638     FD->setInvalidDecl();
11639   }
11640 }
11641 
11642 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11643   // FIXME: Need strict checking.  In C89, we need to check for
11644   // any assignment, increment, decrement, function-calls, or
11645   // commas outside of a sizeof.  In C99, it's the same list,
11646   // except that the aforementioned are allowed in unevaluated
11647   // expressions.  Everything else falls under the
11648   // "may accept other forms of constant expressions" exception.
11649   //
11650   // Regular C++ code will not end up here (exceptions: language extensions,
11651   // OpenCL C++ etc), so the constant expression rules there don't matter.
11652   if (Init->isValueDependent()) {
11653     assert(Init->containsErrors() &&
11654            "Dependent code should only occur in error-recovery path.");
11655     return true;
11656   }
11657   const Expr *Culprit;
11658   if (Init->isConstantInitializer(Context, false, &Culprit))
11659     return false;
11660   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11661     << Culprit->getSourceRange();
11662   return true;
11663 }
11664 
11665 namespace {
11666   // Visits an initialization expression to see if OrigDecl is evaluated in
11667   // its own initialization and throws a warning if it does.
11668   class SelfReferenceChecker
11669       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11670     Sema &S;
11671     Decl *OrigDecl;
11672     bool isRecordType;
11673     bool isPODType;
11674     bool isReferenceType;
11675 
11676     bool isInitList;
11677     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11678 
11679   public:
11680     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11681 
11682     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11683                                                     S(S), OrigDecl(OrigDecl) {
11684       isPODType = false;
11685       isRecordType = false;
11686       isReferenceType = false;
11687       isInitList = false;
11688       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11689         isPODType = VD->getType().isPODType(S.Context);
11690         isRecordType = VD->getType()->isRecordType();
11691         isReferenceType = VD->getType()->isReferenceType();
11692       }
11693     }
11694 
11695     // For most expressions, just call the visitor.  For initializer lists,
11696     // track the index of the field being initialized since fields are
11697     // initialized in order allowing use of previously initialized fields.
11698     void CheckExpr(Expr *E) {
11699       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11700       if (!InitList) {
11701         Visit(E);
11702         return;
11703       }
11704 
11705       // Track and increment the index here.
11706       isInitList = true;
11707       InitFieldIndex.push_back(0);
11708       for (auto Child : InitList->children()) {
11709         CheckExpr(cast<Expr>(Child));
11710         ++InitFieldIndex.back();
11711       }
11712       InitFieldIndex.pop_back();
11713     }
11714 
11715     // Returns true if MemberExpr is checked and no further checking is needed.
11716     // Returns false if additional checking is required.
11717     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11718       llvm::SmallVector<FieldDecl*, 4> Fields;
11719       Expr *Base = E;
11720       bool ReferenceField = false;
11721 
11722       // Get the field members used.
11723       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11724         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11725         if (!FD)
11726           return false;
11727         Fields.push_back(FD);
11728         if (FD->getType()->isReferenceType())
11729           ReferenceField = true;
11730         Base = ME->getBase()->IgnoreParenImpCasts();
11731       }
11732 
11733       // Keep checking only if the base Decl is the same.
11734       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11735       if (!DRE || DRE->getDecl() != OrigDecl)
11736         return false;
11737 
11738       // A reference field can be bound to an unininitialized field.
11739       if (CheckReference && !ReferenceField)
11740         return true;
11741 
11742       // Convert FieldDecls to their index number.
11743       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11744       for (const FieldDecl *I : llvm::reverse(Fields))
11745         UsedFieldIndex.push_back(I->getFieldIndex());
11746 
11747       // See if a warning is needed by checking the first difference in index
11748       // numbers.  If field being used has index less than the field being
11749       // initialized, then the use is safe.
11750       for (auto UsedIter = UsedFieldIndex.begin(),
11751                 UsedEnd = UsedFieldIndex.end(),
11752                 OrigIter = InitFieldIndex.begin(),
11753                 OrigEnd = InitFieldIndex.end();
11754            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11755         if (*UsedIter < *OrigIter)
11756           return true;
11757         if (*UsedIter > *OrigIter)
11758           break;
11759       }
11760 
11761       // TODO: Add a different warning which will print the field names.
11762       HandleDeclRefExpr(DRE);
11763       return true;
11764     }
11765 
11766     // For most expressions, the cast is directly above the DeclRefExpr.
11767     // For conditional operators, the cast can be outside the conditional
11768     // operator if both expressions are DeclRefExpr's.
11769     void HandleValue(Expr *E) {
11770       E = E->IgnoreParens();
11771       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11772         HandleDeclRefExpr(DRE);
11773         return;
11774       }
11775 
11776       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11777         Visit(CO->getCond());
11778         HandleValue(CO->getTrueExpr());
11779         HandleValue(CO->getFalseExpr());
11780         return;
11781       }
11782 
11783       if (BinaryConditionalOperator *BCO =
11784               dyn_cast<BinaryConditionalOperator>(E)) {
11785         Visit(BCO->getCond());
11786         HandleValue(BCO->getFalseExpr());
11787         return;
11788       }
11789 
11790       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11791         HandleValue(OVE->getSourceExpr());
11792         return;
11793       }
11794 
11795       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11796         if (BO->getOpcode() == BO_Comma) {
11797           Visit(BO->getLHS());
11798           HandleValue(BO->getRHS());
11799           return;
11800         }
11801       }
11802 
11803       if (isa<MemberExpr>(E)) {
11804         if (isInitList) {
11805           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11806                                       false /*CheckReference*/))
11807             return;
11808         }
11809 
11810         Expr *Base = E->IgnoreParenImpCasts();
11811         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11812           // Check for static member variables and don't warn on them.
11813           if (!isa<FieldDecl>(ME->getMemberDecl()))
11814             return;
11815           Base = ME->getBase()->IgnoreParenImpCasts();
11816         }
11817         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11818           HandleDeclRefExpr(DRE);
11819         return;
11820       }
11821 
11822       Visit(E);
11823     }
11824 
11825     // Reference types not handled in HandleValue are handled here since all
11826     // uses of references are bad, not just r-value uses.
11827     void VisitDeclRefExpr(DeclRefExpr *E) {
11828       if (isReferenceType)
11829         HandleDeclRefExpr(E);
11830     }
11831 
11832     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11833       if (E->getCastKind() == CK_LValueToRValue) {
11834         HandleValue(E->getSubExpr());
11835         return;
11836       }
11837 
11838       Inherited::VisitImplicitCastExpr(E);
11839     }
11840 
11841     void VisitMemberExpr(MemberExpr *E) {
11842       if (isInitList) {
11843         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11844           return;
11845       }
11846 
11847       // Don't warn on arrays since they can be treated as pointers.
11848       if (E->getType()->canDecayToPointerType()) return;
11849 
11850       // Warn when a non-static method call is followed by non-static member
11851       // field accesses, which is followed by a DeclRefExpr.
11852       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11853       bool Warn = (MD && !MD->isStatic());
11854       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11855       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11856         if (!isa<FieldDecl>(ME->getMemberDecl()))
11857           Warn = false;
11858         Base = ME->getBase()->IgnoreParenImpCasts();
11859       }
11860 
11861       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11862         if (Warn)
11863           HandleDeclRefExpr(DRE);
11864         return;
11865       }
11866 
11867       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11868       // Visit that expression.
11869       Visit(Base);
11870     }
11871 
11872     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11873       Expr *Callee = E->getCallee();
11874 
11875       if (isa<UnresolvedLookupExpr>(Callee))
11876         return Inherited::VisitCXXOperatorCallExpr(E);
11877 
11878       Visit(Callee);
11879       for (auto Arg: E->arguments())
11880         HandleValue(Arg->IgnoreParenImpCasts());
11881     }
11882 
11883     void VisitUnaryOperator(UnaryOperator *E) {
11884       // For POD record types, addresses of its own members are well-defined.
11885       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11886           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11887         if (!isPODType)
11888           HandleValue(E->getSubExpr());
11889         return;
11890       }
11891 
11892       if (E->isIncrementDecrementOp()) {
11893         HandleValue(E->getSubExpr());
11894         return;
11895       }
11896 
11897       Inherited::VisitUnaryOperator(E);
11898     }
11899 
11900     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11901 
11902     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11903       if (E->getConstructor()->isCopyConstructor()) {
11904         Expr *ArgExpr = E->getArg(0);
11905         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11906           if (ILE->getNumInits() == 1)
11907             ArgExpr = ILE->getInit(0);
11908         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11909           if (ICE->getCastKind() == CK_NoOp)
11910             ArgExpr = ICE->getSubExpr();
11911         HandleValue(ArgExpr);
11912         return;
11913       }
11914       Inherited::VisitCXXConstructExpr(E);
11915     }
11916 
11917     void VisitCallExpr(CallExpr *E) {
11918       // Treat std::move as a use.
11919       if (E->isCallToStdMove()) {
11920         HandleValue(E->getArg(0));
11921         return;
11922       }
11923 
11924       Inherited::VisitCallExpr(E);
11925     }
11926 
11927     void VisitBinaryOperator(BinaryOperator *E) {
11928       if (E->isCompoundAssignmentOp()) {
11929         HandleValue(E->getLHS());
11930         Visit(E->getRHS());
11931         return;
11932       }
11933 
11934       Inherited::VisitBinaryOperator(E);
11935     }
11936 
11937     // A custom visitor for BinaryConditionalOperator is needed because the
11938     // regular visitor would check the condition and true expression separately
11939     // but both point to the same place giving duplicate diagnostics.
11940     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11941       Visit(E->getCond());
11942       Visit(E->getFalseExpr());
11943     }
11944 
11945     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11946       Decl* ReferenceDecl = DRE->getDecl();
11947       if (OrigDecl != ReferenceDecl) return;
11948       unsigned diag;
11949       if (isReferenceType) {
11950         diag = diag::warn_uninit_self_reference_in_reference_init;
11951       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11952         diag = diag::warn_static_self_reference_in_init;
11953       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11954                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11955                  DRE->getDecl()->getType()->isRecordType()) {
11956         diag = diag::warn_uninit_self_reference_in_init;
11957       } else {
11958         // Local variables will be handled by the CFG analysis.
11959         return;
11960       }
11961 
11962       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11963                             S.PDiag(diag)
11964                                 << DRE->getDecl() << OrigDecl->getLocation()
11965                                 << DRE->getSourceRange());
11966     }
11967   };
11968 
11969   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11970   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11971                                  bool DirectInit) {
11972     // Parameters arguments are occassionially constructed with itself,
11973     // for instance, in recursive functions.  Skip them.
11974     if (isa<ParmVarDecl>(OrigDecl))
11975       return;
11976 
11977     E = E->IgnoreParens();
11978 
11979     // Skip checking T a = a where T is not a record or reference type.
11980     // Doing so is a way to silence uninitialized warnings.
11981     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11982       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11983         if (ICE->getCastKind() == CK_LValueToRValue)
11984           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11985             if (DRE->getDecl() == OrigDecl)
11986               return;
11987 
11988     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11989   }
11990 } // end anonymous namespace
11991 
11992 namespace {
11993   // Simple wrapper to add the name of a variable or (if no variable is
11994   // available) a DeclarationName into a diagnostic.
11995   struct VarDeclOrName {
11996     VarDecl *VDecl;
11997     DeclarationName Name;
11998 
11999     friend const Sema::SemaDiagnosticBuilder &
12000     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12001       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12002     }
12003   };
12004 } // end anonymous namespace
12005 
12006 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12007                                             DeclarationName Name, QualType Type,
12008                                             TypeSourceInfo *TSI,
12009                                             SourceRange Range, bool DirectInit,
12010                                             Expr *Init) {
12011   bool IsInitCapture = !VDecl;
12012   assert((!VDecl || !VDecl->isInitCapture()) &&
12013          "init captures are expected to be deduced prior to initialization");
12014 
12015   VarDeclOrName VN{VDecl, Name};
12016 
12017   DeducedType *Deduced = Type->getContainedDeducedType();
12018   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12019 
12020   // C++11 [dcl.spec.auto]p3
12021   if (!Init) {
12022     assert(VDecl && "no init for init capture deduction?");
12023 
12024     // Except for class argument deduction, and then for an initializing
12025     // declaration only, i.e. no static at class scope or extern.
12026     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12027         VDecl->hasExternalStorage() ||
12028         VDecl->isStaticDataMember()) {
12029       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12030         << VDecl->getDeclName() << Type;
12031       return QualType();
12032     }
12033   }
12034 
12035   ArrayRef<Expr*> DeduceInits;
12036   if (Init)
12037     DeduceInits = Init;
12038 
12039   if (DirectInit) {
12040     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12041       DeduceInits = PL->exprs();
12042   }
12043 
12044   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12045     assert(VDecl && "non-auto type for init capture deduction?");
12046     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12047     InitializationKind Kind = InitializationKind::CreateForInit(
12048         VDecl->getLocation(), DirectInit, Init);
12049     // FIXME: Initialization should not be taking a mutable list of inits.
12050     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12051     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12052                                                        InitsCopy);
12053   }
12054 
12055   if (DirectInit) {
12056     if (auto *IL = dyn_cast<InitListExpr>(Init))
12057       DeduceInits = IL->inits();
12058   }
12059 
12060   // Deduction only works if we have exactly one source expression.
12061   if (DeduceInits.empty()) {
12062     // It isn't possible to write this directly, but it is possible to
12063     // end up in this situation with "auto x(some_pack...);"
12064     Diag(Init->getBeginLoc(), IsInitCapture
12065                                   ? diag::err_init_capture_no_expression
12066                                   : diag::err_auto_var_init_no_expression)
12067         << VN << Type << Range;
12068     return QualType();
12069   }
12070 
12071   if (DeduceInits.size() > 1) {
12072     Diag(DeduceInits[1]->getBeginLoc(),
12073          IsInitCapture ? diag::err_init_capture_multiple_expressions
12074                        : diag::err_auto_var_init_multiple_expressions)
12075         << VN << Type << Range;
12076     return QualType();
12077   }
12078 
12079   Expr *DeduceInit = DeduceInits[0];
12080   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12081     Diag(Init->getBeginLoc(), IsInitCapture
12082                                   ? diag::err_init_capture_paren_braces
12083                                   : diag::err_auto_var_init_paren_braces)
12084         << isa<InitListExpr>(Init) << VN << Type << Range;
12085     return QualType();
12086   }
12087 
12088   // Expressions default to 'id' when we're in a debugger.
12089   bool DefaultedAnyToId = false;
12090   if (getLangOpts().DebuggerCastResultToId &&
12091       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12092     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12093     if (Result.isInvalid()) {
12094       return QualType();
12095     }
12096     Init = Result.get();
12097     DefaultedAnyToId = true;
12098   }
12099 
12100   // C++ [dcl.decomp]p1:
12101   //   If the assignment-expression [...] has array type A and no ref-qualifier
12102   //   is present, e has type cv A
12103   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12104       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12105       DeduceInit->getType()->isConstantArrayType())
12106     return Context.getQualifiedType(DeduceInit->getType(),
12107                                     Type.getQualifiers());
12108 
12109   QualType DeducedType;
12110   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12111     if (!IsInitCapture)
12112       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12113     else if (isa<InitListExpr>(Init))
12114       Diag(Range.getBegin(),
12115            diag::err_init_capture_deduction_failure_from_init_list)
12116           << VN
12117           << (DeduceInit->getType().isNull() ? TSI->getType()
12118                                              : DeduceInit->getType())
12119           << DeduceInit->getSourceRange();
12120     else
12121       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12122           << VN << TSI->getType()
12123           << (DeduceInit->getType().isNull() ? TSI->getType()
12124                                              : DeduceInit->getType())
12125           << DeduceInit->getSourceRange();
12126   }
12127 
12128   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12129   // 'id' instead of a specific object type prevents most of our usual
12130   // checks.
12131   // We only want to warn outside of template instantiations, though:
12132   // inside a template, the 'id' could have come from a parameter.
12133   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12134       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12135     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12136     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12137   }
12138 
12139   return DeducedType;
12140 }
12141 
12142 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12143                                          Expr *Init) {
12144   assert(!Init || !Init->containsErrors());
12145   QualType DeducedType = deduceVarTypeFromInitializer(
12146       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12147       VDecl->getSourceRange(), DirectInit, Init);
12148   if (DeducedType.isNull()) {
12149     VDecl->setInvalidDecl();
12150     return true;
12151   }
12152 
12153   VDecl->setType(DeducedType);
12154   assert(VDecl->isLinkageValid());
12155 
12156   // In ARC, infer lifetime.
12157   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12158     VDecl->setInvalidDecl();
12159 
12160   if (getLangOpts().OpenCL)
12161     deduceOpenCLAddressSpace(VDecl);
12162 
12163   // If this is a redeclaration, check that the type we just deduced matches
12164   // the previously declared type.
12165   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12166     // We never need to merge the type, because we cannot form an incomplete
12167     // array of auto, nor deduce such a type.
12168     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12169   }
12170 
12171   // Check the deduced type is valid for a variable declaration.
12172   CheckVariableDeclarationType(VDecl);
12173   return VDecl->isInvalidDecl();
12174 }
12175 
12176 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12177                                               SourceLocation Loc) {
12178   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12179     Init = EWC->getSubExpr();
12180 
12181   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12182     Init = CE->getSubExpr();
12183 
12184   QualType InitType = Init->getType();
12185   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12186           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12187          "shouldn't be called if type doesn't have a non-trivial C struct");
12188   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12189     for (auto I : ILE->inits()) {
12190       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12191           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12192         continue;
12193       SourceLocation SL = I->getExprLoc();
12194       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12195     }
12196     return;
12197   }
12198 
12199   if (isa<ImplicitValueInitExpr>(Init)) {
12200     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12201       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12202                             NTCUK_Init);
12203   } else {
12204     // Assume all other explicit initializers involving copying some existing
12205     // object.
12206     // TODO: ignore any explicit initializers where we can guarantee
12207     // copy-elision.
12208     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12209       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12210   }
12211 }
12212 
12213 namespace {
12214 
12215 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12216   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12217   // in the source code or implicitly by the compiler if it is in a union
12218   // defined in a system header and has non-trivial ObjC ownership
12219   // qualifications. We don't want those fields to participate in determining
12220   // whether the containing union is non-trivial.
12221   return FD->hasAttr<UnavailableAttr>();
12222 }
12223 
12224 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12225     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12226                                     void> {
12227   using Super =
12228       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12229                                     void>;
12230 
12231   DiagNonTrivalCUnionDefaultInitializeVisitor(
12232       QualType OrigTy, SourceLocation OrigLoc,
12233       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12234       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12235 
12236   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12237                      const FieldDecl *FD, bool InNonTrivialUnion) {
12238     if (const auto *AT = S.Context.getAsArrayType(QT))
12239       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12240                                      InNonTrivialUnion);
12241     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12242   }
12243 
12244   void visitARCStrong(QualType QT, const FieldDecl *FD,
12245                       bool InNonTrivialUnion) {
12246     if (InNonTrivialUnion)
12247       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12248           << 1 << 0 << QT << FD->getName();
12249   }
12250 
12251   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12252     if (InNonTrivialUnion)
12253       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12254           << 1 << 0 << QT << FD->getName();
12255   }
12256 
12257   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12258     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12259     if (RD->isUnion()) {
12260       if (OrigLoc.isValid()) {
12261         bool IsUnion = false;
12262         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12263           IsUnion = OrigRD->isUnion();
12264         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12265             << 0 << OrigTy << IsUnion << UseContext;
12266         // Reset OrigLoc so that this diagnostic is emitted only once.
12267         OrigLoc = SourceLocation();
12268       }
12269       InNonTrivialUnion = true;
12270     }
12271 
12272     if (InNonTrivialUnion)
12273       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12274           << 0 << 0 << QT.getUnqualifiedType() << "";
12275 
12276     for (const FieldDecl *FD : RD->fields())
12277       if (!shouldIgnoreForRecordTriviality(FD))
12278         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12279   }
12280 
12281   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12282 
12283   // The non-trivial C union type or the struct/union type that contains a
12284   // non-trivial C union.
12285   QualType OrigTy;
12286   SourceLocation OrigLoc;
12287   Sema::NonTrivialCUnionContext UseContext;
12288   Sema &S;
12289 };
12290 
12291 struct DiagNonTrivalCUnionDestructedTypeVisitor
12292     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12293   using Super =
12294       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12295 
12296   DiagNonTrivalCUnionDestructedTypeVisitor(
12297       QualType OrigTy, SourceLocation OrigLoc,
12298       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12299       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12300 
12301   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12302                      const FieldDecl *FD, bool InNonTrivialUnion) {
12303     if (const auto *AT = S.Context.getAsArrayType(QT))
12304       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12305                                      InNonTrivialUnion);
12306     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12307   }
12308 
12309   void visitARCStrong(QualType QT, const FieldDecl *FD,
12310                       bool InNonTrivialUnion) {
12311     if (InNonTrivialUnion)
12312       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12313           << 1 << 1 << QT << FD->getName();
12314   }
12315 
12316   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12317     if (InNonTrivialUnion)
12318       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12319           << 1 << 1 << QT << FD->getName();
12320   }
12321 
12322   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12323     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12324     if (RD->isUnion()) {
12325       if (OrigLoc.isValid()) {
12326         bool IsUnion = false;
12327         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12328           IsUnion = OrigRD->isUnion();
12329         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12330             << 1 << OrigTy << IsUnion << UseContext;
12331         // Reset OrigLoc so that this diagnostic is emitted only once.
12332         OrigLoc = SourceLocation();
12333       }
12334       InNonTrivialUnion = true;
12335     }
12336 
12337     if (InNonTrivialUnion)
12338       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12339           << 0 << 1 << QT.getUnqualifiedType() << "";
12340 
12341     for (const FieldDecl *FD : RD->fields())
12342       if (!shouldIgnoreForRecordTriviality(FD))
12343         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12344   }
12345 
12346   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12347   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12348                           bool InNonTrivialUnion) {}
12349 
12350   // The non-trivial C union type or the struct/union type that contains a
12351   // non-trivial C union.
12352   QualType OrigTy;
12353   SourceLocation OrigLoc;
12354   Sema::NonTrivialCUnionContext UseContext;
12355   Sema &S;
12356 };
12357 
12358 struct DiagNonTrivalCUnionCopyVisitor
12359     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12360   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12361 
12362   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12363                                  Sema::NonTrivialCUnionContext UseContext,
12364                                  Sema &S)
12365       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12366 
12367   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12368                      const FieldDecl *FD, bool InNonTrivialUnion) {
12369     if (const auto *AT = S.Context.getAsArrayType(QT))
12370       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12371                                      InNonTrivialUnion);
12372     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12373   }
12374 
12375   void visitARCStrong(QualType QT, const FieldDecl *FD,
12376                       bool InNonTrivialUnion) {
12377     if (InNonTrivialUnion)
12378       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12379           << 1 << 2 << QT << FD->getName();
12380   }
12381 
12382   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12383     if (InNonTrivialUnion)
12384       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12385           << 1 << 2 << QT << FD->getName();
12386   }
12387 
12388   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12389     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12390     if (RD->isUnion()) {
12391       if (OrigLoc.isValid()) {
12392         bool IsUnion = false;
12393         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12394           IsUnion = OrigRD->isUnion();
12395         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12396             << 2 << OrigTy << IsUnion << UseContext;
12397         // Reset OrigLoc so that this diagnostic is emitted only once.
12398         OrigLoc = SourceLocation();
12399       }
12400       InNonTrivialUnion = true;
12401     }
12402 
12403     if (InNonTrivialUnion)
12404       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12405           << 0 << 2 << QT.getUnqualifiedType() << "";
12406 
12407     for (const FieldDecl *FD : RD->fields())
12408       if (!shouldIgnoreForRecordTriviality(FD))
12409         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12410   }
12411 
12412   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12413                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12414   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12415   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12416                             bool InNonTrivialUnion) {}
12417 
12418   // The non-trivial C union type or the struct/union type that contains a
12419   // non-trivial C union.
12420   QualType OrigTy;
12421   SourceLocation OrigLoc;
12422   Sema::NonTrivialCUnionContext UseContext;
12423   Sema &S;
12424 };
12425 
12426 } // namespace
12427 
12428 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12429                                  NonTrivialCUnionContext UseContext,
12430                                  unsigned NonTrivialKind) {
12431   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12432           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12433           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12434          "shouldn't be called if type doesn't have a non-trivial C union");
12435 
12436   if ((NonTrivialKind & NTCUK_Init) &&
12437       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12438     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12439         .visit(QT, nullptr, false);
12440   if ((NonTrivialKind & NTCUK_Destruct) &&
12441       QT.hasNonTrivialToPrimitiveDestructCUnion())
12442     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12443         .visit(QT, nullptr, false);
12444   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12445     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12446         .visit(QT, nullptr, false);
12447 }
12448 
12449 /// AddInitializerToDecl - Adds the initializer Init to the
12450 /// declaration dcl. If DirectInit is true, this is C++ direct
12451 /// initialization rather than copy initialization.
12452 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12453   // If there is no declaration, there was an error parsing it.  Just ignore
12454   // the initializer.
12455   if (!RealDecl || RealDecl->isInvalidDecl()) {
12456     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12457     return;
12458   }
12459 
12460   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12461     // Pure-specifiers are handled in ActOnPureSpecifier.
12462     Diag(Method->getLocation(), diag::err_member_function_initialization)
12463       << Method->getDeclName() << Init->getSourceRange();
12464     Method->setInvalidDecl();
12465     return;
12466   }
12467 
12468   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12469   if (!VDecl) {
12470     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12471     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12472     RealDecl->setInvalidDecl();
12473     return;
12474   }
12475 
12476   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12477   if (VDecl->getType()->isUndeducedType()) {
12478     // Attempt typo correction early so that the type of the init expression can
12479     // be deduced based on the chosen correction if the original init contains a
12480     // TypoExpr.
12481     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12482     if (!Res.isUsable()) {
12483       // There are unresolved typos in Init, just drop them.
12484       // FIXME: improve the recovery strategy to preserve the Init.
12485       RealDecl->setInvalidDecl();
12486       return;
12487     }
12488     if (Res.get()->containsErrors()) {
12489       // Invalidate the decl as we don't know the type for recovery-expr yet.
12490       RealDecl->setInvalidDecl();
12491       VDecl->setInit(Res.get());
12492       return;
12493     }
12494     Init = Res.get();
12495 
12496     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12497       return;
12498   }
12499 
12500   // dllimport cannot be used on variable definitions.
12501   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12502     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12503     VDecl->setInvalidDecl();
12504     return;
12505   }
12506 
12507   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12508     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12509     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12510     VDecl->setInvalidDecl();
12511     return;
12512   }
12513 
12514   if (!VDecl->getType()->isDependentType()) {
12515     // A definition must end up with a complete type, which means it must be
12516     // complete with the restriction that an array type might be completed by
12517     // the initializer; note that later code assumes this restriction.
12518     QualType BaseDeclType = VDecl->getType();
12519     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12520       BaseDeclType = Array->getElementType();
12521     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12522                             diag::err_typecheck_decl_incomplete_type)) {
12523       RealDecl->setInvalidDecl();
12524       return;
12525     }
12526 
12527     // The variable can not have an abstract class type.
12528     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12529                                diag::err_abstract_type_in_decl,
12530                                AbstractVariableType))
12531       VDecl->setInvalidDecl();
12532   }
12533 
12534   // If adding the initializer will turn this declaration into a definition,
12535   // and we already have a definition for this variable, diagnose or otherwise
12536   // handle the situation.
12537   if (VarDecl *Def = VDecl->getDefinition())
12538     if (Def != VDecl &&
12539         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12540         !VDecl->isThisDeclarationADemotedDefinition() &&
12541         checkVarDeclRedefinition(Def, VDecl))
12542       return;
12543 
12544   if (getLangOpts().CPlusPlus) {
12545     // C++ [class.static.data]p4
12546     //   If a static data member is of const integral or const
12547     //   enumeration type, its declaration in the class definition can
12548     //   specify a constant-initializer which shall be an integral
12549     //   constant expression (5.19). In that case, the member can appear
12550     //   in integral constant expressions. The member shall still be
12551     //   defined in a namespace scope if it is used in the program and the
12552     //   namespace scope definition shall not contain an initializer.
12553     //
12554     // We already performed a redefinition check above, but for static
12555     // data members we also need to check whether there was an in-class
12556     // declaration with an initializer.
12557     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12558       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12559           << VDecl->getDeclName();
12560       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12561            diag::note_previous_initializer)
12562           << 0;
12563       return;
12564     }
12565 
12566     if (VDecl->hasLocalStorage())
12567       setFunctionHasBranchProtectedScope();
12568 
12569     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12570       VDecl->setInvalidDecl();
12571       return;
12572     }
12573   }
12574 
12575   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12576   // a kernel function cannot be initialized."
12577   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12578     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12579     VDecl->setInvalidDecl();
12580     return;
12581   }
12582 
12583   // The LoaderUninitialized attribute acts as a definition (of undef).
12584   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12585     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12586     VDecl->setInvalidDecl();
12587     return;
12588   }
12589 
12590   // Get the decls type and save a reference for later, since
12591   // CheckInitializerTypes may change it.
12592   QualType DclT = VDecl->getType(), SavT = DclT;
12593 
12594   // Expressions default to 'id' when we're in a debugger
12595   // and we are assigning it to a variable of Objective-C pointer type.
12596   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12597       Init->getType() == Context.UnknownAnyTy) {
12598     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12599     if (Result.isInvalid()) {
12600       VDecl->setInvalidDecl();
12601       return;
12602     }
12603     Init = Result.get();
12604   }
12605 
12606   // Perform the initialization.
12607   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12608   if (!VDecl->isInvalidDecl()) {
12609     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12610     InitializationKind Kind = InitializationKind::CreateForInit(
12611         VDecl->getLocation(), DirectInit, Init);
12612 
12613     MultiExprArg Args = Init;
12614     if (CXXDirectInit)
12615       Args = MultiExprArg(CXXDirectInit->getExprs(),
12616                           CXXDirectInit->getNumExprs());
12617 
12618     // Try to correct any TypoExprs in the initialization arguments.
12619     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12620       ExprResult Res = CorrectDelayedTyposInExpr(
12621           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12622           [this, Entity, Kind](Expr *E) {
12623             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12624             return Init.Failed() ? ExprError() : E;
12625           });
12626       if (Res.isInvalid()) {
12627         VDecl->setInvalidDecl();
12628       } else if (Res.get() != Args[Idx]) {
12629         Args[Idx] = Res.get();
12630       }
12631     }
12632     if (VDecl->isInvalidDecl())
12633       return;
12634 
12635     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12636                                    /*TopLevelOfInitList=*/false,
12637                                    /*TreatUnavailableAsInvalid=*/false);
12638     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12639     if (Result.isInvalid()) {
12640       // If the provided initializer fails to initialize the var decl,
12641       // we attach a recovery expr for better recovery.
12642       auto RecoveryExpr =
12643           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12644       if (RecoveryExpr.get())
12645         VDecl->setInit(RecoveryExpr.get());
12646       return;
12647     }
12648 
12649     Init = Result.getAs<Expr>();
12650   }
12651 
12652   // Check for self-references within variable initializers.
12653   // Variables declared within a function/method body (except for references)
12654   // are handled by a dataflow analysis.
12655   // This is undefined behavior in C++, but valid in C.
12656   if (getLangOpts().CPlusPlus)
12657     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12658         VDecl->getType()->isReferenceType())
12659       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12660 
12661   // If the type changed, it means we had an incomplete type that was
12662   // completed by the initializer. For example:
12663   //   int ary[] = { 1, 3, 5 };
12664   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12665   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12666     VDecl->setType(DclT);
12667 
12668   if (!VDecl->isInvalidDecl()) {
12669     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12670 
12671     if (VDecl->hasAttr<BlocksAttr>())
12672       checkRetainCycles(VDecl, Init);
12673 
12674     // It is safe to assign a weak reference into a strong variable.
12675     // Although this code can still have problems:
12676     //   id x = self.weakProp;
12677     //   id y = self.weakProp;
12678     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12679     // paths through the function. This should be revisited if
12680     // -Wrepeated-use-of-weak is made flow-sensitive.
12681     if (FunctionScopeInfo *FSI = getCurFunction())
12682       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12683            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12684           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12685                            Init->getBeginLoc()))
12686         FSI->markSafeWeakUse(Init);
12687   }
12688 
12689   // The initialization is usually a full-expression.
12690   //
12691   // FIXME: If this is a braced initialization of an aggregate, it is not
12692   // an expression, and each individual field initializer is a separate
12693   // full-expression. For instance, in:
12694   //
12695   //   struct Temp { ~Temp(); };
12696   //   struct S { S(Temp); };
12697   //   struct T { S a, b; } t = { Temp(), Temp() }
12698   //
12699   // we should destroy the first Temp before constructing the second.
12700   ExprResult Result =
12701       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12702                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12703   if (Result.isInvalid()) {
12704     VDecl->setInvalidDecl();
12705     return;
12706   }
12707   Init = Result.get();
12708 
12709   // Attach the initializer to the decl.
12710   VDecl->setInit(Init);
12711 
12712   if (VDecl->isLocalVarDecl()) {
12713     // Don't check the initializer if the declaration is malformed.
12714     if (VDecl->isInvalidDecl()) {
12715       // do nothing
12716 
12717     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12718     // This is true even in C++ for OpenCL.
12719     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12720       CheckForConstantInitializer(Init, DclT);
12721 
12722     // Otherwise, C++ does not restrict the initializer.
12723     } else if (getLangOpts().CPlusPlus) {
12724       // do nothing
12725 
12726     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12727     // static storage duration shall be constant expressions or string literals.
12728     } else if (VDecl->getStorageClass() == SC_Static) {
12729       CheckForConstantInitializer(Init, DclT);
12730 
12731     // C89 is stricter than C99 for aggregate initializers.
12732     // C89 6.5.7p3: All the expressions [...] in an initializer list
12733     // for an object that has aggregate or union type shall be
12734     // constant expressions.
12735     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12736                isa<InitListExpr>(Init)) {
12737       const Expr *Culprit;
12738       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12739         Diag(Culprit->getExprLoc(),
12740              diag::ext_aggregate_init_not_constant)
12741           << Culprit->getSourceRange();
12742       }
12743     }
12744 
12745     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12746       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12747         if (VDecl->hasLocalStorage())
12748           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12749   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12750              VDecl->getLexicalDeclContext()->isRecord()) {
12751     // This is an in-class initialization for a static data member, e.g.,
12752     //
12753     // struct S {
12754     //   static const int value = 17;
12755     // };
12756 
12757     // C++ [class.mem]p4:
12758     //   A member-declarator can contain a constant-initializer only
12759     //   if it declares a static member (9.4) of const integral or
12760     //   const enumeration type, see 9.4.2.
12761     //
12762     // C++11 [class.static.data]p3:
12763     //   If a non-volatile non-inline const static data member is of integral
12764     //   or enumeration type, its declaration in the class definition can
12765     //   specify a brace-or-equal-initializer in which every initializer-clause
12766     //   that is an assignment-expression is a constant expression. A static
12767     //   data member of literal type can be declared in the class definition
12768     //   with the constexpr specifier; if so, its declaration shall specify a
12769     //   brace-or-equal-initializer in which every initializer-clause that is
12770     //   an assignment-expression is a constant expression.
12771 
12772     // Do nothing on dependent types.
12773     if (DclT->isDependentType()) {
12774 
12775     // Allow any 'static constexpr' members, whether or not they are of literal
12776     // type. We separately check that every constexpr variable is of literal
12777     // type.
12778     } else if (VDecl->isConstexpr()) {
12779 
12780     // Require constness.
12781     } else if (!DclT.isConstQualified()) {
12782       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12783         << Init->getSourceRange();
12784       VDecl->setInvalidDecl();
12785 
12786     // We allow integer constant expressions in all cases.
12787     } else if (DclT->isIntegralOrEnumerationType()) {
12788       // Check whether the expression is a constant expression.
12789       SourceLocation Loc;
12790       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12791         // In C++11, a non-constexpr const static data member with an
12792         // in-class initializer cannot be volatile.
12793         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12794       else if (Init->isValueDependent())
12795         ; // Nothing to check.
12796       else if (Init->isIntegerConstantExpr(Context, &Loc))
12797         ; // Ok, it's an ICE!
12798       else if (Init->getType()->isScopedEnumeralType() &&
12799                Init->isCXX11ConstantExpr(Context))
12800         ; // Ok, it is a scoped-enum constant expression.
12801       else if (Init->isEvaluatable(Context)) {
12802         // If we can constant fold the initializer through heroics, accept it,
12803         // but report this as a use of an extension for -pedantic.
12804         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12805           << Init->getSourceRange();
12806       } else {
12807         // Otherwise, this is some crazy unknown case.  Report the issue at the
12808         // location provided by the isIntegerConstantExpr failed check.
12809         Diag(Loc, diag::err_in_class_initializer_non_constant)
12810           << Init->getSourceRange();
12811         VDecl->setInvalidDecl();
12812       }
12813 
12814     // We allow foldable floating-point constants as an extension.
12815     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12816       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12817       // it anyway and provide a fixit to add the 'constexpr'.
12818       if (getLangOpts().CPlusPlus11) {
12819         Diag(VDecl->getLocation(),
12820              diag::ext_in_class_initializer_float_type_cxx11)
12821             << DclT << Init->getSourceRange();
12822         Diag(VDecl->getBeginLoc(),
12823              diag::note_in_class_initializer_float_type_cxx11)
12824             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12825       } else {
12826         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12827           << DclT << Init->getSourceRange();
12828 
12829         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12830           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12831             << Init->getSourceRange();
12832           VDecl->setInvalidDecl();
12833         }
12834       }
12835 
12836     // Suggest adding 'constexpr' in C++11 for literal types.
12837     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12838       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12839           << DclT << Init->getSourceRange()
12840           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12841       VDecl->setConstexpr(true);
12842 
12843     } else {
12844       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12845         << DclT << Init->getSourceRange();
12846       VDecl->setInvalidDecl();
12847     }
12848   } else if (VDecl->isFileVarDecl()) {
12849     // In C, extern is typically used to avoid tentative definitions when
12850     // declaring variables in headers, but adding an intializer makes it a
12851     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12852     // In C++, extern is often used to give implictly static const variables
12853     // external linkage, so don't warn in that case. If selectany is present,
12854     // this might be header code intended for C and C++ inclusion, so apply the
12855     // C++ rules.
12856     if (VDecl->getStorageClass() == SC_Extern &&
12857         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12858          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12859         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12860         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12861       Diag(VDecl->getLocation(), diag::warn_extern_init);
12862 
12863     // In Microsoft C++ mode, a const variable defined in namespace scope has
12864     // external linkage by default if the variable is declared with
12865     // __declspec(dllexport).
12866     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12867         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12868         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12869       VDecl->setStorageClass(SC_Extern);
12870 
12871     // C99 6.7.8p4. All file scoped initializers need to be constant.
12872     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12873       CheckForConstantInitializer(Init, DclT);
12874   }
12875 
12876   QualType InitType = Init->getType();
12877   if (!InitType.isNull() &&
12878       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12879        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12880     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12881 
12882   // We will represent direct-initialization similarly to copy-initialization:
12883   //    int x(1);  -as-> int x = 1;
12884   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12885   //
12886   // Clients that want to distinguish between the two forms, can check for
12887   // direct initializer using VarDecl::getInitStyle().
12888   // A major benefit is that clients that don't particularly care about which
12889   // exactly form was it (like the CodeGen) can handle both cases without
12890   // special case code.
12891 
12892   // C++ 8.5p11:
12893   // The form of initialization (using parentheses or '=') is generally
12894   // insignificant, but does matter when the entity being initialized has a
12895   // class type.
12896   if (CXXDirectInit) {
12897     assert(DirectInit && "Call-style initializer must be direct init.");
12898     VDecl->setInitStyle(VarDecl::CallInit);
12899   } else if (DirectInit) {
12900     // This must be list-initialization. No other way is direct-initialization.
12901     VDecl->setInitStyle(VarDecl::ListInit);
12902   }
12903 
12904   if (LangOpts.OpenMP &&
12905       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12906       VDecl->isFileVarDecl())
12907     DeclsToCheckForDeferredDiags.insert(VDecl);
12908   CheckCompleteVariableDeclaration(VDecl);
12909 }
12910 
12911 /// ActOnInitializerError - Given that there was an error parsing an
12912 /// initializer for the given declaration, try to at least re-establish
12913 /// invariants such as whether a variable's type is either dependent or
12914 /// complete.
12915 void Sema::ActOnInitializerError(Decl *D) {
12916   // Our main concern here is re-establishing invariants like "a
12917   // variable's type is either dependent or complete".
12918   if (!D || D->isInvalidDecl()) return;
12919 
12920   VarDecl *VD = dyn_cast<VarDecl>(D);
12921   if (!VD) return;
12922 
12923   // Bindings are not usable if we can't make sense of the initializer.
12924   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12925     for (auto *BD : DD->bindings())
12926       BD->setInvalidDecl();
12927 
12928   // Auto types are meaningless if we can't make sense of the initializer.
12929   if (VD->getType()->isUndeducedType()) {
12930     D->setInvalidDecl();
12931     return;
12932   }
12933 
12934   QualType Ty = VD->getType();
12935   if (Ty->isDependentType()) return;
12936 
12937   // Require a complete type.
12938   if (RequireCompleteType(VD->getLocation(),
12939                           Context.getBaseElementType(Ty),
12940                           diag::err_typecheck_decl_incomplete_type)) {
12941     VD->setInvalidDecl();
12942     return;
12943   }
12944 
12945   // Require a non-abstract type.
12946   if (RequireNonAbstractType(VD->getLocation(), Ty,
12947                              diag::err_abstract_type_in_decl,
12948                              AbstractVariableType)) {
12949     VD->setInvalidDecl();
12950     return;
12951   }
12952 
12953   // Don't bother complaining about constructors or destructors,
12954   // though.
12955 }
12956 
12957 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12958   // If there is no declaration, there was an error parsing it. Just ignore it.
12959   if (!RealDecl)
12960     return;
12961 
12962   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12963     QualType Type = Var->getType();
12964 
12965     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12966     if (isa<DecompositionDecl>(RealDecl)) {
12967       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12968       Var->setInvalidDecl();
12969       return;
12970     }
12971 
12972     if (Type->isUndeducedType() &&
12973         DeduceVariableDeclarationType(Var, false, nullptr))
12974       return;
12975 
12976     // C++11 [class.static.data]p3: A static data member can be declared with
12977     // the constexpr specifier; if so, its declaration shall specify
12978     // a brace-or-equal-initializer.
12979     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12980     // the definition of a variable [...] or the declaration of a static data
12981     // member.
12982     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12983         !Var->isThisDeclarationADemotedDefinition()) {
12984       if (Var->isStaticDataMember()) {
12985         // C++1z removes the relevant rule; the in-class declaration is always
12986         // a definition there.
12987         if (!getLangOpts().CPlusPlus17 &&
12988             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12989           Diag(Var->getLocation(),
12990                diag::err_constexpr_static_mem_var_requires_init)
12991               << Var;
12992           Var->setInvalidDecl();
12993           return;
12994         }
12995       } else {
12996         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12997         Var->setInvalidDecl();
12998         return;
12999       }
13000     }
13001 
13002     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13003     // be initialized.
13004     if (!Var->isInvalidDecl() &&
13005         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13006         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13007       bool HasConstExprDefaultConstructor = false;
13008       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13009         for (auto *Ctor : RD->ctors()) {
13010           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13011               Ctor->getMethodQualifiers().getAddressSpace() ==
13012                   LangAS::opencl_constant) {
13013             HasConstExprDefaultConstructor = true;
13014           }
13015         }
13016       }
13017       if (!HasConstExprDefaultConstructor) {
13018         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13019         Var->setInvalidDecl();
13020         return;
13021       }
13022     }
13023 
13024     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13025       if (Var->getStorageClass() == SC_Extern) {
13026         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13027             << Var;
13028         Var->setInvalidDecl();
13029         return;
13030       }
13031       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13032                               diag::err_typecheck_decl_incomplete_type)) {
13033         Var->setInvalidDecl();
13034         return;
13035       }
13036       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13037         if (!RD->hasTrivialDefaultConstructor()) {
13038           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13039           Var->setInvalidDecl();
13040           return;
13041         }
13042       }
13043       // The declaration is unitialized, no need for further checks.
13044       return;
13045     }
13046 
13047     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13048     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13049         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13050       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13051                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13052 
13053 
13054     switch (DefKind) {
13055     case VarDecl::Definition:
13056       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13057         break;
13058 
13059       // We have an out-of-line definition of a static data member
13060       // that has an in-class initializer, so we type-check this like
13061       // a declaration.
13062       //
13063       LLVM_FALLTHROUGH;
13064 
13065     case VarDecl::DeclarationOnly:
13066       // It's only a declaration.
13067 
13068       // Block scope. C99 6.7p7: If an identifier for an object is
13069       // declared with no linkage (C99 6.2.2p6), the type for the
13070       // object shall be complete.
13071       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13072           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13073           RequireCompleteType(Var->getLocation(), Type,
13074                               diag::err_typecheck_decl_incomplete_type))
13075         Var->setInvalidDecl();
13076 
13077       // Make sure that the type is not abstract.
13078       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13079           RequireNonAbstractType(Var->getLocation(), Type,
13080                                  diag::err_abstract_type_in_decl,
13081                                  AbstractVariableType))
13082         Var->setInvalidDecl();
13083       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13084           Var->getStorageClass() == SC_PrivateExtern) {
13085         Diag(Var->getLocation(), diag::warn_private_extern);
13086         Diag(Var->getLocation(), diag::note_private_extern);
13087       }
13088 
13089       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13090           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13091         ExternalDeclarations.push_back(Var);
13092 
13093       return;
13094 
13095     case VarDecl::TentativeDefinition:
13096       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13097       // object that has file scope without an initializer, and without a
13098       // storage-class specifier or with the storage-class specifier "static",
13099       // constitutes a tentative definition. Note: A tentative definition with
13100       // external linkage is valid (C99 6.2.2p5).
13101       if (!Var->isInvalidDecl()) {
13102         if (const IncompleteArrayType *ArrayT
13103                                     = Context.getAsIncompleteArrayType(Type)) {
13104           if (RequireCompleteSizedType(
13105                   Var->getLocation(), ArrayT->getElementType(),
13106                   diag::err_array_incomplete_or_sizeless_type))
13107             Var->setInvalidDecl();
13108         } else if (Var->getStorageClass() == SC_Static) {
13109           // C99 6.9.2p3: If the declaration of an identifier for an object is
13110           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13111           // declared type shall not be an incomplete type.
13112           // NOTE: code such as the following
13113           //     static struct s;
13114           //     struct s { int a; };
13115           // is accepted by gcc. Hence here we issue a warning instead of
13116           // an error and we do not invalidate the static declaration.
13117           // NOTE: to avoid multiple warnings, only check the first declaration.
13118           if (Var->isFirstDecl())
13119             RequireCompleteType(Var->getLocation(), Type,
13120                                 diag::ext_typecheck_decl_incomplete_type);
13121         }
13122       }
13123 
13124       // Record the tentative definition; we're done.
13125       if (!Var->isInvalidDecl())
13126         TentativeDefinitions.push_back(Var);
13127       return;
13128     }
13129 
13130     // Provide a specific diagnostic for uninitialized variable
13131     // definitions with incomplete array type.
13132     if (Type->isIncompleteArrayType()) {
13133       Diag(Var->getLocation(),
13134            diag::err_typecheck_incomplete_array_needs_initializer);
13135       Var->setInvalidDecl();
13136       return;
13137     }
13138 
13139     // Provide a specific diagnostic for uninitialized variable
13140     // definitions with reference type.
13141     if (Type->isReferenceType()) {
13142       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13143           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13144       Var->setInvalidDecl();
13145       return;
13146     }
13147 
13148     // Do not attempt to type-check the default initializer for a
13149     // variable with dependent type.
13150     if (Type->isDependentType())
13151       return;
13152 
13153     if (Var->isInvalidDecl())
13154       return;
13155 
13156     if (!Var->hasAttr<AliasAttr>()) {
13157       if (RequireCompleteType(Var->getLocation(),
13158                               Context.getBaseElementType(Type),
13159                               diag::err_typecheck_decl_incomplete_type)) {
13160         Var->setInvalidDecl();
13161         return;
13162       }
13163     } else {
13164       return;
13165     }
13166 
13167     // The variable can not have an abstract class type.
13168     if (RequireNonAbstractType(Var->getLocation(), Type,
13169                                diag::err_abstract_type_in_decl,
13170                                AbstractVariableType)) {
13171       Var->setInvalidDecl();
13172       return;
13173     }
13174 
13175     // Check for jumps past the implicit initializer.  C++0x
13176     // clarifies that this applies to a "variable with automatic
13177     // storage duration", not a "local variable".
13178     // C++11 [stmt.dcl]p3
13179     //   A program that jumps from a point where a variable with automatic
13180     //   storage duration is not in scope to a point where it is in scope is
13181     //   ill-formed unless the variable has scalar type, class type with a
13182     //   trivial default constructor and a trivial destructor, a cv-qualified
13183     //   version of one of these types, or an array of one of the preceding
13184     //   types and is declared without an initializer.
13185     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13186       if (const RecordType *Record
13187             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13188         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13189         // Mark the function (if we're in one) for further checking even if the
13190         // looser rules of C++11 do not require such checks, so that we can
13191         // diagnose incompatibilities with C++98.
13192         if (!CXXRecord->isPOD())
13193           setFunctionHasBranchProtectedScope();
13194       }
13195     }
13196     // In OpenCL, we can't initialize objects in the __local address space,
13197     // even implicitly, so don't synthesize an implicit initializer.
13198     if (getLangOpts().OpenCL &&
13199         Var->getType().getAddressSpace() == LangAS::opencl_local)
13200       return;
13201     // C++03 [dcl.init]p9:
13202     //   If no initializer is specified for an object, and the
13203     //   object is of (possibly cv-qualified) non-POD class type (or
13204     //   array thereof), the object shall be default-initialized; if
13205     //   the object is of const-qualified type, the underlying class
13206     //   type shall have a user-declared default
13207     //   constructor. Otherwise, if no initializer is specified for
13208     //   a non- static object, the object and its subobjects, if
13209     //   any, have an indeterminate initial value); if the object
13210     //   or any of its subobjects are of const-qualified type, the
13211     //   program is ill-formed.
13212     // C++0x [dcl.init]p11:
13213     //   If no initializer is specified for an object, the object is
13214     //   default-initialized; [...].
13215     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13216     InitializationKind Kind
13217       = InitializationKind::CreateDefault(Var->getLocation());
13218 
13219     InitializationSequence InitSeq(*this, Entity, Kind, None);
13220     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13221 
13222     if (Init.get()) {
13223       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13224       // This is important for template substitution.
13225       Var->setInitStyle(VarDecl::CallInit);
13226     } else if (Init.isInvalid()) {
13227       // If default-init fails, attach a recovery-expr initializer to track
13228       // that initialization was attempted and failed.
13229       auto RecoveryExpr =
13230           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13231       if (RecoveryExpr.get())
13232         Var->setInit(RecoveryExpr.get());
13233     }
13234 
13235     CheckCompleteVariableDeclaration(Var);
13236   }
13237 }
13238 
13239 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13240   // If there is no declaration, there was an error parsing it. Ignore it.
13241   if (!D)
13242     return;
13243 
13244   VarDecl *VD = dyn_cast<VarDecl>(D);
13245   if (!VD) {
13246     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13247     D->setInvalidDecl();
13248     return;
13249   }
13250 
13251   VD->setCXXForRangeDecl(true);
13252 
13253   // for-range-declaration cannot be given a storage class specifier.
13254   int Error = -1;
13255   switch (VD->getStorageClass()) {
13256   case SC_None:
13257     break;
13258   case SC_Extern:
13259     Error = 0;
13260     break;
13261   case SC_Static:
13262     Error = 1;
13263     break;
13264   case SC_PrivateExtern:
13265     Error = 2;
13266     break;
13267   case SC_Auto:
13268     Error = 3;
13269     break;
13270   case SC_Register:
13271     Error = 4;
13272     break;
13273   }
13274 
13275   // for-range-declaration cannot be given a storage class specifier con't.
13276   switch (VD->getTSCSpec()) {
13277   case TSCS_thread_local:
13278     Error = 6;
13279     break;
13280   case TSCS___thread:
13281   case TSCS__Thread_local:
13282   case TSCS_unspecified:
13283     break;
13284   }
13285 
13286   if (Error != -1) {
13287     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13288         << VD << Error;
13289     D->setInvalidDecl();
13290   }
13291 }
13292 
13293 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13294                                             IdentifierInfo *Ident,
13295                                             ParsedAttributes &Attrs) {
13296   // C++1y [stmt.iter]p1:
13297   //   A range-based for statement of the form
13298   //      for ( for-range-identifier : for-range-initializer ) statement
13299   //   is equivalent to
13300   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13301   DeclSpec DS(Attrs.getPool().getFactory());
13302 
13303   const char *PrevSpec;
13304   unsigned DiagID;
13305   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13306                      getPrintingPolicy());
13307 
13308   Declarator D(DS, DeclaratorContext::ForInit);
13309   D.SetIdentifier(Ident, IdentLoc);
13310   D.takeAttributes(Attrs);
13311 
13312   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13313                 IdentLoc);
13314   Decl *Var = ActOnDeclarator(S, D);
13315   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13316   FinalizeDeclaration(Var);
13317   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13318                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13319                                                       : IdentLoc);
13320 }
13321 
13322 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13323   if (var->isInvalidDecl()) return;
13324 
13325   MaybeAddCUDAConstantAttr(var);
13326 
13327   if (getLangOpts().OpenCL) {
13328     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13329     // initialiser
13330     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13331         !var->hasInit()) {
13332       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13333           << 1 /*Init*/;
13334       var->setInvalidDecl();
13335       return;
13336     }
13337   }
13338 
13339   // In Objective-C, don't allow jumps past the implicit initialization of a
13340   // local retaining variable.
13341   if (getLangOpts().ObjC &&
13342       var->hasLocalStorage()) {
13343     switch (var->getType().getObjCLifetime()) {
13344     case Qualifiers::OCL_None:
13345     case Qualifiers::OCL_ExplicitNone:
13346     case Qualifiers::OCL_Autoreleasing:
13347       break;
13348 
13349     case Qualifiers::OCL_Weak:
13350     case Qualifiers::OCL_Strong:
13351       setFunctionHasBranchProtectedScope();
13352       break;
13353     }
13354   }
13355 
13356   if (var->hasLocalStorage() &&
13357       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13358     setFunctionHasBranchProtectedScope();
13359 
13360   // Warn about externally-visible variables being defined without a
13361   // prior declaration.  We only want to do this for global
13362   // declarations, but we also specifically need to avoid doing it for
13363   // class members because the linkage of an anonymous class can
13364   // change if it's later given a typedef name.
13365   if (var->isThisDeclarationADefinition() &&
13366       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13367       var->isExternallyVisible() && var->hasLinkage() &&
13368       !var->isInline() && !var->getDescribedVarTemplate() &&
13369       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13370       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13371       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13372                                   var->getLocation())) {
13373     // Find a previous declaration that's not a definition.
13374     VarDecl *prev = var->getPreviousDecl();
13375     while (prev && prev->isThisDeclarationADefinition())
13376       prev = prev->getPreviousDecl();
13377 
13378     if (!prev) {
13379       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13380       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13381           << /* variable */ 0;
13382     }
13383   }
13384 
13385   // Cache the result of checking for constant initialization.
13386   Optional<bool> CacheHasConstInit;
13387   const Expr *CacheCulprit = nullptr;
13388   auto checkConstInit = [&]() mutable {
13389     if (!CacheHasConstInit)
13390       CacheHasConstInit = var->getInit()->isConstantInitializer(
13391             Context, var->getType()->isReferenceType(), &CacheCulprit);
13392     return *CacheHasConstInit;
13393   };
13394 
13395   if (var->getTLSKind() == VarDecl::TLS_Static) {
13396     if (var->getType().isDestructedType()) {
13397       // GNU C++98 edits for __thread, [basic.start.term]p3:
13398       //   The type of an object with thread storage duration shall not
13399       //   have a non-trivial destructor.
13400       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13401       if (getLangOpts().CPlusPlus11)
13402         Diag(var->getLocation(), diag::note_use_thread_local);
13403     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13404       if (!checkConstInit()) {
13405         // GNU C++98 edits for __thread, [basic.start.init]p4:
13406         //   An object of thread storage duration shall not require dynamic
13407         //   initialization.
13408         // FIXME: Need strict checking here.
13409         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13410           << CacheCulprit->getSourceRange();
13411         if (getLangOpts().CPlusPlus11)
13412           Diag(var->getLocation(), diag::note_use_thread_local);
13413       }
13414     }
13415   }
13416 
13417 
13418   if (!var->getType()->isStructureType() && var->hasInit() &&
13419       isa<InitListExpr>(var->getInit())) {
13420     const auto *ILE = cast<InitListExpr>(var->getInit());
13421     unsigned NumInits = ILE->getNumInits();
13422     if (NumInits > 2)
13423       for (unsigned I = 0; I < NumInits; ++I) {
13424         const auto *Init = ILE->getInit(I);
13425         if (!Init)
13426           break;
13427         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13428         if (!SL)
13429           break;
13430 
13431         unsigned NumConcat = SL->getNumConcatenated();
13432         // Diagnose missing comma in string array initialization.
13433         // Do not warn when all the elements in the initializer are concatenated
13434         // together. Do not warn for macros too.
13435         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13436           bool OnlyOneMissingComma = true;
13437           for (unsigned J = I + 1; J < NumInits; ++J) {
13438             const auto *Init = ILE->getInit(J);
13439             if (!Init)
13440               break;
13441             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13442             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13443               OnlyOneMissingComma = false;
13444               break;
13445             }
13446           }
13447 
13448           if (OnlyOneMissingComma) {
13449             SmallVector<FixItHint, 1> Hints;
13450             for (unsigned i = 0; i < NumConcat - 1; ++i)
13451               Hints.push_back(FixItHint::CreateInsertion(
13452                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13453 
13454             Diag(SL->getStrTokenLoc(1),
13455                  diag::warn_concatenated_literal_array_init)
13456                 << Hints;
13457             Diag(SL->getBeginLoc(),
13458                  diag::note_concatenated_string_literal_silence);
13459           }
13460           // In any case, stop now.
13461           break;
13462         }
13463       }
13464   }
13465 
13466 
13467   QualType type = var->getType();
13468 
13469   if (var->hasAttr<BlocksAttr>())
13470     getCurFunction()->addByrefBlockVar(var);
13471 
13472   Expr *Init = var->getInit();
13473   bool GlobalStorage = var->hasGlobalStorage();
13474   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13475   QualType baseType = Context.getBaseElementType(type);
13476   bool HasConstInit = true;
13477 
13478   // Check whether the initializer is sufficiently constant.
13479   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13480       !Init->isValueDependent() &&
13481       (GlobalStorage || var->isConstexpr() ||
13482        var->mightBeUsableInConstantExpressions(Context))) {
13483     // If this variable might have a constant initializer or might be usable in
13484     // constant expressions, check whether or not it actually is now.  We can't
13485     // do this lazily, because the result might depend on things that change
13486     // later, such as which constexpr functions happen to be defined.
13487     SmallVector<PartialDiagnosticAt, 8> Notes;
13488     if (!getLangOpts().CPlusPlus11) {
13489       // Prior to C++11, in contexts where a constant initializer is required,
13490       // the set of valid constant initializers is described by syntactic rules
13491       // in [expr.const]p2-6.
13492       // FIXME: Stricter checking for these rules would be useful for constinit /
13493       // -Wglobal-constructors.
13494       HasConstInit = checkConstInit();
13495 
13496       // Compute and cache the constant value, and remember that we have a
13497       // constant initializer.
13498       if (HasConstInit) {
13499         (void)var->checkForConstantInitialization(Notes);
13500         Notes.clear();
13501       } else if (CacheCulprit) {
13502         Notes.emplace_back(CacheCulprit->getExprLoc(),
13503                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13504         Notes.back().second << CacheCulprit->getSourceRange();
13505       }
13506     } else {
13507       // Evaluate the initializer to see if it's a constant initializer.
13508       HasConstInit = var->checkForConstantInitialization(Notes);
13509     }
13510 
13511     if (HasConstInit) {
13512       // FIXME: Consider replacing the initializer with a ConstantExpr.
13513     } else if (var->isConstexpr()) {
13514       SourceLocation DiagLoc = var->getLocation();
13515       // If the note doesn't add any useful information other than a source
13516       // location, fold it into the primary diagnostic.
13517       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13518                                    diag::note_invalid_subexpr_in_const_expr) {
13519         DiagLoc = Notes[0].first;
13520         Notes.clear();
13521       }
13522       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13523           << var << Init->getSourceRange();
13524       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13525         Diag(Notes[I].first, Notes[I].second);
13526     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13527       auto *Attr = var->getAttr<ConstInitAttr>();
13528       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13529           << Init->getSourceRange();
13530       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13531           << Attr->getRange() << Attr->isConstinit();
13532       for (auto &it : Notes)
13533         Diag(it.first, it.second);
13534     } else if (IsGlobal &&
13535                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13536                                            var->getLocation())) {
13537       // Warn about globals which don't have a constant initializer.  Don't
13538       // warn about globals with a non-trivial destructor because we already
13539       // warned about them.
13540       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13541       if (!(RD && !RD->hasTrivialDestructor())) {
13542         // checkConstInit() here permits trivial default initialization even in
13543         // C++11 onwards, where such an initializer is not a constant initializer
13544         // but nonetheless doesn't require a global constructor.
13545         if (!checkConstInit())
13546           Diag(var->getLocation(), diag::warn_global_constructor)
13547               << Init->getSourceRange();
13548       }
13549     }
13550   }
13551 
13552   // Apply section attributes and pragmas to global variables.
13553   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13554       !inTemplateInstantiation()) {
13555     PragmaStack<StringLiteral *> *Stack = nullptr;
13556     int SectionFlags = ASTContext::PSF_Read;
13557     if (var->getType().isConstQualified()) {
13558       if (HasConstInit)
13559         Stack = &ConstSegStack;
13560       else {
13561         Stack = &BSSSegStack;
13562         SectionFlags |= ASTContext::PSF_Write;
13563       }
13564     } else if (var->hasInit() && HasConstInit) {
13565       Stack = &DataSegStack;
13566       SectionFlags |= ASTContext::PSF_Write;
13567     } else {
13568       Stack = &BSSSegStack;
13569       SectionFlags |= ASTContext::PSF_Write;
13570     }
13571     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13572       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13573         SectionFlags |= ASTContext::PSF_Implicit;
13574       UnifySection(SA->getName(), SectionFlags, var);
13575     } else if (Stack->CurrentValue) {
13576       SectionFlags |= ASTContext::PSF_Implicit;
13577       auto SectionName = Stack->CurrentValue->getString();
13578       var->addAttr(SectionAttr::CreateImplicit(
13579           Context, SectionName, Stack->CurrentPragmaLocation,
13580           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13581       if (UnifySection(SectionName, SectionFlags, var))
13582         var->dropAttr<SectionAttr>();
13583     }
13584 
13585     // Apply the init_seg attribute if this has an initializer.  If the
13586     // initializer turns out to not be dynamic, we'll end up ignoring this
13587     // attribute.
13588     if (CurInitSeg && var->getInit())
13589       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13590                                                CurInitSegLoc,
13591                                                AttributeCommonInfo::AS_Pragma));
13592   }
13593 
13594   // All the following checks are C++ only.
13595   if (!getLangOpts().CPlusPlus) {
13596     // If this variable must be emitted, add it as an initializer for the
13597     // current module.
13598     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13599       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13600     return;
13601   }
13602 
13603   // Require the destructor.
13604   if (!type->isDependentType())
13605     if (const RecordType *recordType = baseType->getAs<RecordType>())
13606       FinalizeVarWithDestructor(var, recordType);
13607 
13608   // If this variable must be emitted, add it as an initializer for the current
13609   // module.
13610   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13611     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13612 
13613   // Build the bindings if this is a structured binding declaration.
13614   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13615     CheckCompleteDecompositionDeclaration(DD);
13616 }
13617 
13618 /// Check if VD needs to be dllexport/dllimport due to being in a
13619 /// dllexport/import function.
13620 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13621   assert(VD->isStaticLocal());
13622 
13623   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13624 
13625   // Find outermost function when VD is in lambda function.
13626   while (FD && !getDLLAttr(FD) &&
13627          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13628          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13629     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13630   }
13631 
13632   if (!FD)
13633     return;
13634 
13635   // Static locals inherit dll attributes from their function.
13636   if (Attr *A = getDLLAttr(FD)) {
13637     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13638     NewAttr->setInherited(true);
13639     VD->addAttr(NewAttr);
13640   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13641     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13642     NewAttr->setInherited(true);
13643     VD->addAttr(NewAttr);
13644 
13645     // Export this function to enforce exporting this static variable even
13646     // if it is not used in this compilation unit.
13647     if (!FD->hasAttr<DLLExportAttr>())
13648       FD->addAttr(NewAttr);
13649 
13650   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13651     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13652     NewAttr->setInherited(true);
13653     VD->addAttr(NewAttr);
13654   }
13655 }
13656 
13657 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13658 /// any semantic actions necessary after any initializer has been attached.
13659 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13660   // Note that we are no longer parsing the initializer for this declaration.
13661   ParsingInitForAutoVars.erase(ThisDecl);
13662 
13663   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13664   if (!VD)
13665     return;
13666 
13667   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13668   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13669       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13670     if (PragmaClangBSSSection.Valid)
13671       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13672           Context, PragmaClangBSSSection.SectionName,
13673           PragmaClangBSSSection.PragmaLocation,
13674           AttributeCommonInfo::AS_Pragma));
13675     if (PragmaClangDataSection.Valid)
13676       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13677           Context, PragmaClangDataSection.SectionName,
13678           PragmaClangDataSection.PragmaLocation,
13679           AttributeCommonInfo::AS_Pragma));
13680     if (PragmaClangRodataSection.Valid)
13681       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13682           Context, PragmaClangRodataSection.SectionName,
13683           PragmaClangRodataSection.PragmaLocation,
13684           AttributeCommonInfo::AS_Pragma));
13685     if (PragmaClangRelroSection.Valid)
13686       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13687           Context, PragmaClangRelroSection.SectionName,
13688           PragmaClangRelroSection.PragmaLocation,
13689           AttributeCommonInfo::AS_Pragma));
13690   }
13691 
13692   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13693     for (auto *BD : DD->bindings()) {
13694       FinalizeDeclaration(BD);
13695     }
13696   }
13697 
13698   checkAttributesAfterMerging(*this, *VD);
13699 
13700   // Perform TLS alignment check here after attributes attached to the variable
13701   // which may affect the alignment have been processed. Only perform the check
13702   // if the target has a maximum TLS alignment (zero means no constraints).
13703   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13704     // Protect the check so that it's not performed on dependent types and
13705     // dependent alignments (we can't determine the alignment in that case).
13706     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13707       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13708       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13709         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13710           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13711           << (unsigned)MaxAlignChars.getQuantity();
13712       }
13713     }
13714   }
13715 
13716   if (VD->isStaticLocal())
13717     CheckStaticLocalForDllExport(VD);
13718 
13719   // Perform check for initializers of device-side global variables.
13720   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13721   // 7.5). We must also apply the same checks to all __shared__
13722   // variables whether they are local or not. CUDA also allows
13723   // constant initializers for __constant__ and __device__ variables.
13724   if (getLangOpts().CUDA)
13725     checkAllowedCUDAInitializer(VD);
13726 
13727   // Grab the dllimport or dllexport attribute off of the VarDecl.
13728   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13729 
13730   // Imported static data members cannot be defined out-of-line.
13731   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13732     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13733         VD->isThisDeclarationADefinition()) {
13734       // We allow definitions of dllimport class template static data members
13735       // with a warning.
13736       CXXRecordDecl *Context =
13737         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13738       bool IsClassTemplateMember =
13739           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13740           Context->getDescribedClassTemplate();
13741 
13742       Diag(VD->getLocation(),
13743            IsClassTemplateMember
13744                ? diag::warn_attribute_dllimport_static_field_definition
13745                : diag::err_attribute_dllimport_static_field_definition);
13746       Diag(IA->getLocation(), diag::note_attribute);
13747       if (!IsClassTemplateMember)
13748         VD->setInvalidDecl();
13749     }
13750   }
13751 
13752   // dllimport/dllexport variables cannot be thread local, their TLS index
13753   // isn't exported with the variable.
13754   if (DLLAttr && VD->getTLSKind()) {
13755     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13756     if (F && getDLLAttr(F)) {
13757       assert(VD->isStaticLocal());
13758       // But if this is a static local in a dlimport/dllexport function, the
13759       // function will never be inlined, which means the var would never be
13760       // imported, so having it marked import/export is safe.
13761     } else {
13762       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13763                                                                     << DLLAttr;
13764       VD->setInvalidDecl();
13765     }
13766   }
13767 
13768   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13769     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13770       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13771           << Attr;
13772       VD->dropAttr<UsedAttr>();
13773     }
13774   }
13775   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13776     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13777       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13778           << Attr;
13779       VD->dropAttr<RetainAttr>();
13780     }
13781   }
13782 
13783   const DeclContext *DC = VD->getDeclContext();
13784   // If there's a #pragma GCC visibility in scope, and this isn't a class
13785   // member, set the visibility of this variable.
13786   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13787     AddPushedVisibilityAttribute(VD);
13788 
13789   // FIXME: Warn on unused var template partial specializations.
13790   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13791     MarkUnusedFileScopedDecl(VD);
13792 
13793   // Now we have parsed the initializer and can update the table of magic
13794   // tag values.
13795   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13796       !VD->getType()->isIntegralOrEnumerationType())
13797     return;
13798 
13799   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13800     const Expr *MagicValueExpr = VD->getInit();
13801     if (!MagicValueExpr) {
13802       continue;
13803     }
13804     Optional<llvm::APSInt> MagicValueInt;
13805     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13806       Diag(I->getRange().getBegin(),
13807            diag::err_type_tag_for_datatype_not_ice)
13808         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13809       continue;
13810     }
13811     if (MagicValueInt->getActiveBits() > 64) {
13812       Diag(I->getRange().getBegin(),
13813            diag::err_type_tag_for_datatype_too_large)
13814         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13815       continue;
13816     }
13817     uint64_t MagicValue = MagicValueInt->getZExtValue();
13818     RegisterTypeTagForDatatype(I->getArgumentKind(),
13819                                MagicValue,
13820                                I->getMatchingCType(),
13821                                I->getLayoutCompatible(),
13822                                I->getMustBeNull());
13823   }
13824 }
13825 
13826 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13827   auto *VD = dyn_cast<VarDecl>(DD);
13828   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13829 }
13830 
13831 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13832                                                    ArrayRef<Decl *> Group) {
13833   SmallVector<Decl*, 8> Decls;
13834 
13835   if (DS.isTypeSpecOwned())
13836     Decls.push_back(DS.getRepAsDecl());
13837 
13838   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13839   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13840   bool DiagnosedMultipleDecomps = false;
13841   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13842   bool DiagnosedNonDeducedAuto = false;
13843 
13844   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13845     if (Decl *D = Group[i]) {
13846       // For declarators, there are some additional syntactic-ish checks we need
13847       // to perform.
13848       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13849         if (!FirstDeclaratorInGroup)
13850           FirstDeclaratorInGroup = DD;
13851         if (!FirstDecompDeclaratorInGroup)
13852           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13853         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13854             !hasDeducedAuto(DD))
13855           FirstNonDeducedAutoInGroup = DD;
13856 
13857         if (FirstDeclaratorInGroup != DD) {
13858           // A decomposition declaration cannot be combined with any other
13859           // declaration in the same group.
13860           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13861             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13862                  diag::err_decomp_decl_not_alone)
13863                 << FirstDeclaratorInGroup->getSourceRange()
13864                 << DD->getSourceRange();
13865             DiagnosedMultipleDecomps = true;
13866           }
13867 
13868           // A declarator that uses 'auto' in any way other than to declare a
13869           // variable with a deduced type cannot be combined with any other
13870           // declarator in the same group.
13871           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13872             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13873                  diag::err_auto_non_deduced_not_alone)
13874                 << FirstNonDeducedAutoInGroup->getType()
13875                        ->hasAutoForTrailingReturnType()
13876                 << FirstDeclaratorInGroup->getSourceRange()
13877                 << DD->getSourceRange();
13878             DiagnosedNonDeducedAuto = true;
13879           }
13880         }
13881       }
13882 
13883       Decls.push_back(D);
13884     }
13885   }
13886 
13887   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13888     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13889       handleTagNumbering(Tag, S);
13890       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13891           getLangOpts().CPlusPlus)
13892         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13893     }
13894   }
13895 
13896   return BuildDeclaratorGroup(Decls);
13897 }
13898 
13899 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13900 /// group, performing any necessary semantic checking.
13901 Sema::DeclGroupPtrTy
13902 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13903   // C++14 [dcl.spec.auto]p7: (DR1347)
13904   //   If the type that replaces the placeholder type is not the same in each
13905   //   deduction, the program is ill-formed.
13906   if (Group.size() > 1) {
13907     QualType Deduced;
13908     VarDecl *DeducedDecl = nullptr;
13909     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13910       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13911       if (!D || D->isInvalidDecl())
13912         break;
13913       DeducedType *DT = D->getType()->getContainedDeducedType();
13914       if (!DT || DT->getDeducedType().isNull())
13915         continue;
13916       if (Deduced.isNull()) {
13917         Deduced = DT->getDeducedType();
13918         DeducedDecl = D;
13919       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13920         auto *AT = dyn_cast<AutoType>(DT);
13921         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13922                         diag::err_auto_different_deductions)
13923                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13924                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13925                    << D->getDeclName();
13926         if (DeducedDecl->hasInit())
13927           Dia << DeducedDecl->getInit()->getSourceRange();
13928         if (D->getInit())
13929           Dia << D->getInit()->getSourceRange();
13930         D->setInvalidDecl();
13931         break;
13932       }
13933     }
13934   }
13935 
13936   ActOnDocumentableDecls(Group);
13937 
13938   return DeclGroupPtrTy::make(
13939       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13940 }
13941 
13942 void Sema::ActOnDocumentableDecl(Decl *D) {
13943   ActOnDocumentableDecls(D);
13944 }
13945 
13946 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13947   // Don't parse the comment if Doxygen diagnostics are ignored.
13948   if (Group.empty() || !Group[0])
13949     return;
13950 
13951   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13952                       Group[0]->getLocation()) &&
13953       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13954                       Group[0]->getLocation()))
13955     return;
13956 
13957   if (Group.size() >= 2) {
13958     // This is a decl group.  Normally it will contain only declarations
13959     // produced from declarator list.  But in case we have any definitions or
13960     // additional declaration references:
13961     //   'typedef struct S {} S;'
13962     //   'typedef struct S *S;'
13963     //   'struct S *pS;'
13964     // FinalizeDeclaratorGroup adds these as separate declarations.
13965     Decl *MaybeTagDecl = Group[0];
13966     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13967       Group = Group.slice(1);
13968     }
13969   }
13970 
13971   // FIMXE: We assume every Decl in the group is in the same file.
13972   // This is false when preprocessor constructs the group from decls in
13973   // different files (e. g. macros or #include).
13974   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13975 }
13976 
13977 /// Common checks for a parameter-declaration that should apply to both function
13978 /// parameters and non-type template parameters.
13979 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13980   // Check that there are no default arguments inside the type of this
13981   // parameter.
13982   if (getLangOpts().CPlusPlus)
13983     CheckExtraCXXDefaultArguments(D);
13984 
13985   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13986   if (D.getCXXScopeSpec().isSet()) {
13987     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13988       << D.getCXXScopeSpec().getRange();
13989   }
13990 
13991   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13992   // simple identifier except [...irrelevant cases...].
13993   switch (D.getName().getKind()) {
13994   case UnqualifiedIdKind::IK_Identifier:
13995     break;
13996 
13997   case UnqualifiedIdKind::IK_OperatorFunctionId:
13998   case UnqualifiedIdKind::IK_ConversionFunctionId:
13999   case UnqualifiedIdKind::IK_LiteralOperatorId:
14000   case UnqualifiedIdKind::IK_ConstructorName:
14001   case UnqualifiedIdKind::IK_DestructorName:
14002   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14003   case UnqualifiedIdKind::IK_DeductionGuideName:
14004     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14005       << GetNameForDeclarator(D).getName();
14006     break;
14007 
14008   case UnqualifiedIdKind::IK_TemplateId:
14009   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14010     // GetNameForDeclarator would not produce a useful name in this case.
14011     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14012     break;
14013   }
14014 }
14015 
14016 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14017 /// to introduce parameters into function prototype scope.
14018 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14019   const DeclSpec &DS = D.getDeclSpec();
14020 
14021   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14022 
14023   // C++03 [dcl.stc]p2 also permits 'auto'.
14024   StorageClass SC = SC_None;
14025   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14026     SC = SC_Register;
14027     // In C++11, the 'register' storage class specifier is deprecated.
14028     // In C++17, it is not allowed, but we tolerate it as an extension.
14029     if (getLangOpts().CPlusPlus11) {
14030       Diag(DS.getStorageClassSpecLoc(),
14031            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14032                                      : diag::warn_deprecated_register)
14033         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14034     }
14035   } else if (getLangOpts().CPlusPlus &&
14036              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14037     SC = SC_Auto;
14038   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14039     Diag(DS.getStorageClassSpecLoc(),
14040          diag::err_invalid_storage_class_in_func_decl);
14041     D.getMutableDeclSpec().ClearStorageClassSpecs();
14042   }
14043 
14044   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14045     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14046       << DeclSpec::getSpecifierName(TSCS);
14047   if (DS.isInlineSpecified())
14048     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14049         << getLangOpts().CPlusPlus17;
14050   if (DS.hasConstexprSpecifier())
14051     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14052         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14053 
14054   DiagnoseFunctionSpecifiers(DS);
14055 
14056   CheckFunctionOrTemplateParamDeclarator(S, D);
14057 
14058   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14059   QualType parmDeclType = TInfo->getType();
14060 
14061   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14062   IdentifierInfo *II = D.getIdentifier();
14063   if (II) {
14064     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14065                    ForVisibleRedeclaration);
14066     LookupName(R, S);
14067     if (R.isSingleResult()) {
14068       NamedDecl *PrevDecl = R.getFoundDecl();
14069       if (PrevDecl->isTemplateParameter()) {
14070         // Maybe we will complain about the shadowed template parameter.
14071         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14072         // Just pretend that we didn't see the previous declaration.
14073         PrevDecl = nullptr;
14074       } else if (S->isDeclScope(PrevDecl)) {
14075         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14076         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14077 
14078         // Recover by removing the name
14079         II = nullptr;
14080         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14081         D.setInvalidType(true);
14082       }
14083     }
14084   }
14085 
14086   // Temporarily put parameter variables in the translation unit, not
14087   // the enclosing context.  This prevents them from accidentally
14088   // looking like class members in C++.
14089   ParmVarDecl *New =
14090       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14091                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14092 
14093   if (D.isInvalidType())
14094     New->setInvalidDecl();
14095 
14096   assert(S->isFunctionPrototypeScope());
14097   assert(S->getFunctionPrototypeDepth() >= 1);
14098   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14099                     S->getNextFunctionPrototypeIndex());
14100 
14101   // Add the parameter declaration into this scope.
14102   S->AddDecl(New);
14103   if (II)
14104     IdResolver.AddDecl(New);
14105 
14106   ProcessDeclAttributes(S, New, D);
14107 
14108   if (D.getDeclSpec().isModulePrivateSpecified())
14109     Diag(New->getLocation(), diag::err_module_private_local)
14110         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14111         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14112 
14113   if (New->hasAttr<BlocksAttr>()) {
14114     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14115   }
14116 
14117   if (getLangOpts().OpenCL)
14118     deduceOpenCLAddressSpace(New);
14119 
14120   return New;
14121 }
14122 
14123 /// Synthesizes a variable for a parameter arising from a
14124 /// typedef.
14125 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14126                                               SourceLocation Loc,
14127                                               QualType T) {
14128   /* FIXME: setting StartLoc == Loc.
14129      Would it be worth to modify callers so as to provide proper source
14130      location for the unnamed parameters, embedding the parameter's type? */
14131   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14132                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14133                                            SC_None, nullptr);
14134   Param->setImplicit();
14135   return Param;
14136 }
14137 
14138 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14139   // Don't diagnose unused-parameter errors in template instantiations; we
14140   // will already have done so in the template itself.
14141   if (inTemplateInstantiation())
14142     return;
14143 
14144   for (const ParmVarDecl *Parameter : Parameters) {
14145     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14146         !Parameter->hasAttr<UnusedAttr>()) {
14147       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14148         << Parameter->getDeclName();
14149     }
14150   }
14151 }
14152 
14153 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14154     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14155   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14156     return;
14157 
14158   // Warn if the return value is pass-by-value and larger than the specified
14159   // threshold.
14160   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14161     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14162     if (Size > LangOpts.NumLargeByValueCopy)
14163       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14164   }
14165 
14166   // Warn if any parameter is pass-by-value and larger than the specified
14167   // threshold.
14168   for (const ParmVarDecl *Parameter : Parameters) {
14169     QualType T = Parameter->getType();
14170     if (T->isDependentType() || !T.isPODType(Context))
14171       continue;
14172     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14173     if (Size > LangOpts.NumLargeByValueCopy)
14174       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14175           << Parameter << Size;
14176   }
14177 }
14178 
14179 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14180                                   SourceLocation NameLoc, IdentifierInfo *Name,
14181                                   QualType T, TypeSourceInfo *TSInfo,
14182                                   StorageClass SC) {
14183   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14184   if (getLangOpts().ObjCAutoRefCount &&
14185       T.getObjCLifetime() == Qualifiers::OCL_None &&
14186       T->isObjCLifetimeType()) {
14187 
14188     Qualifiers::ObjCLifetime lifetime;
14189 
14190     // Special cases for arrays:
14191     //   - if it's const, use __unsafe_unretained
14192     //   - otherwise, it's an error
14193     if (T->isArrayType()) {
14194       if (!T.isConstQualified()) {
14195         if (DelayedDiagnostics.shouldDelayDiagnostics())
14196           DelayedDiagnostics.add(
14197               sema::DelayedDiagnostic::makeForbiddenType(
14198               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14199         else
14200           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14201               << TSInfo->getTypeLoc().getSourceRange();
14202       }
14203       lifetime = Qualifiers::OCL_ExplicitNone;
14204     } else {
14205       lifetime = T->getObjCARCImplicitLifetime();
14206     }
14207     T = Context.getLifetimeQualifiedType(T, lifetime);
14208   }
14209 
14210   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14211                                          Context.getAdjustedParameterType(T),
14212                                          TSInfo, SC, nullptr);
14213 
14214   // Make a note if we created a new pack in the scope of a lambda, so that
14215   // we know that references to that pack must also be expanded within the
14216   // lambda scope.
14217   if (New->isParameterPack())
14218     if (auto *LSI = getEnclosingLambda())
14219       LSI->LocalPacks.push_back(New);
14220 
14221   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14222       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14223     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14224                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14225 
14226   // Parameters can not be abstract class types.
14227   // For record types, this is done by the AbstractClassUsageDiagnoser once
14228   // the class has been completely parsed.
14229   if (!CurContext->isRecord() &&
14230       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14231                              AbstractParamType))
14232     New->setInvalidDecl();
14233 
14234   // Parameter declarators cannot be interface types. All ObjC objects are
14235   // passed by reference.
14236   if (T->isObjCObjectType()) {
14237     SourceLocation TypeEndLoc =
14238         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14239     Diag(NameLoc,
14240          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14241       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14242     T = Context.getObjCObjectPointerType(T);
14243     New->setType(T);
14244   }
14245 
14246   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14247   // duration shall not be qualified by an address-space qualifier."
14248   // Since all parameters have automatic store duration, they can not have
14249   // an address space.
14250   if (T.getAddressSpace() != LangAS::Default &&
14251       // OpenCL allows function arguments declared to be an array of a type
14252       // to be qualified with an address space.
14253       !(getLangOpts().OpenCL &&
14254         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14255     Diag(NameLoc, diag::err_arg_with_address_space);
14256     New->setInvalidDecl();
14257   }
14258 
14259   // PPC MMA non-pointer types are not allowed as function argument types.
14260   if (Context.getTargetInfo().getTriple().isPPC64() &&
14261       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14262     New->setInvalidDecl();
14263   }
14264 
14265   return New;
14266 }
14267 
14268 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14269                                            SourceLocation LocAfterDecls) {
14270   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14271 
14272   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14273   // for a K&R function.
14274   if (!FTI.hasPrototype) {
14275     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14276       --i;
14277       if (FTI.Params[i].Param == nullptr) {
14278         SmallString<256> Code;
14279         llvm::raw_svector_ostream(Code)
14280             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14281         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14282             << FTI.Params[i].Ident
14283             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14284 
14285         // Implicitly declare the argument as type 'int' for lack of a better
14286         // type.
14287         AttributeFactory attrs;
14288         DeclSpec DS(attrs);
14289         const char* PrevSpec; // unused
14290         unsigned DiagID; // unused
14291         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14292                            DiagID, Context.getPrintingPolicy());
14293         // Use the identifier location for the type source range.
14294         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14295         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14296         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14297         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14298         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14299       }
14300     }
14301   }
14302 }
14303 
14304 Decl *
14305 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14306                               MultiTemplateParamsArg TemplateParameterLists,
14307                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14308   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14309   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14310   Scope *ParentScope = FnBodyScope->getParent();
14311 
14312   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14313   // we define a non-templated function definition, we will create a declaration
14314   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14315   // The base function declaration will have the equivalent of an `omp declare
14316   // variant` annotation which specifies the mangled definition as a
14317   // specialization function under the OpenMP context defined as part of the
14318   // `omp begin declare variant`.
14319   SmallVector<FunctionDecl *, 4> Bases;
14320   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14321     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14322         ParentScope, D, TemplateParameterLists, Bases);
14323 
14324   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14325   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14326   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14327 
14328   if (!Bases.empty())
14329     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14330 
14331   return Dcl;
14332 }
14333 
14334 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14335   Consumer.HandleInlineFunctionDefinition(D);
14336 }
14337 
14338 static bool
14339 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14340                                 const FunctionDecl *&PossiblePrototype) {
14341   // Don't warn about invalid declarations.
14342   if (FD->isInvalidDecl())
14343     return false;
14344 
14345   // Or declarations that aren't global.
14346   if (!FD->isGlobal())
14347     return false;
14348 
14349   // Don't warn about C++ member functions.
14350   if (isa<CXXMethodDecl>(FD))
14351     return false;
14352 
14353   // Don't warn about 'main'.
14354   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14355     if (IdentifierInfo *II = FD->getIdentifier())
14356       if (II->isStr("main") || II->isStr("efi_main"))
14357         return false;
14358 
14359   // Don't warn about inline functions.
14360   if (FD->isInlined())
14361     return false;
14362 
14363   // Don't warn about function templates.
14364   if (FD->getDescribedFunctionTemplate())
14365     return false;
14366 
14367   // Don't warn about function template specializations.
14368   if (FD->isFunctionTemplateSpecialization())
14369     return false;
14370 
14371   // Don't warn for OpenCL kernels.
14372   if (FD->hasAttr<OpenCLKernelAttr>())
14373     return false;
14374 
14375   // Don't warn on explicitly deleted functions.
14376   if (FD->isDeleted())
14377     return false;
14378 
14379   // Don't warn on implicitly local functions (such as having local-typed
14380   // parameters).
14381   if (!FD->isExternallyVisible())
14382     return false;
14383 
14384   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14385        Prev; Prev = Prev->getPreviousDecl()) {
14386     // Ignore any declarations that occur in function or method
14387     // scope, because they aren't visible from the header.
14388     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14389       continue;
14390 
14391     PossiblePrototype = Prev;
14392     return Prev->getType()->isFunctionNoProtoType();
14393   }
14394 
14395   return true;
14396 }
14397 
14398 void
14399 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14400                                    const FunctionDecl *EffectiveDefinition,
14401                                    SkipBodyInfo *SkipBody) {
14402   const FunctionDecl *Definition = EffectiveDefinition;
14403   if (!Definition &&
14404       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14405     return;
14406 
14407   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14408     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14409       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14410         // A merged copy of the same function, instantiated as a member of
14411         // the same class, is OK.
14412         if (declaresSameEntity(OrigFD, OrigDef) &&
14413             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14414                                cast<Decl>(FD->getLexicalDeclContext())))
14415           return;
14416       }
14417     }
14418   }
14419 
14420   if (canRedefineFunction(Definition, getLangOpts()))
14421     return;
14422 
14423   // Don't emit an error when this is redefinition of a typo-corrected
14424   // definition.
14425   if (TypoCorrectedFunctionDefinitions.count(Definition))
14426     return;
14427 
14428   // If we don't have a visible definition of the function, and it's inline or
14429   // a template, skip the new definition.
14430   if (SkipBody && !hasVisibleDefinition(Definition) &&
14431       (Definition->getFormalLinkage() == InternalLinkage ||
14432        Definition->isInlined() ||
14433        Definition->getDescribedFunctionTemplate() ||
14434        Definition->getNumTemplateParameterLists())) {
14435     SkipBody->ShouldSkip = true;
14436     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14437     if (auto *TD = Definition->getDescribedFunctionTemplate())
14438       makeMergedDefinitionVisible(TD);
14439     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14440     return;
14441   }
14442 
14443   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14444       Definition->getStorageClass() == SC_Extern)
14445     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14446         << FD << getLangOpts().CPlusPlus;
14447   else
14448     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14449 
14450   Diag(Definition->getLocation(), diag::note_previous_definition);
14451   FD->setInvalidDecl();
14452 }
14453 
14454 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14455                                    Sema &S) {
14456   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14457 
14458   LambdaScopeInfo *LSI = S.PushLambdaScope();
14459   LSI->CallOperator = CallOperator;
14460   LSI->Lambda = LambdaClass;
14461   LSI->ReturnType = CallOperator->getReturnType();
14462   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14463 
14464   if (LCD == LCD_None)
14465     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14466   else if (LCD == LCD_ByCopy)
14467     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14468   else if (LCD == LCD_ByRef)
14469     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14470   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14471 
14472   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14473   LSI->Mutable = !CallOperator->isConst();
14474 
14475   // Add the captures to the LSI so they can be noted as already
14476   // captured within tryCaptureVar.
14477   auto I = LambdaClass->field_begin();
14478   for (const auto &C : LambdaClass->captures()) {
14479     if (C.capturesVariable()) {
14480       VarDecl *VD = C.getCapturedVar();
14481       if (VD->isInitCapture())
14482         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14483       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14484       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14485           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14486           /*EllipsisLoc*/C.isPackExpansion()
14487                          ? C.getEllipsisLoc() : SourceLocation(),
14488           I->getType(), /*Invalid*/false);
14489 
14490     } else if (C.capturesThis()) {
14491       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14492                           C.getCaptureKind() == LCK_StarThis);
14493     } else {
14494       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14495                              I->getType());
14496     }
14497     ++I;
14498   }
14499 }
14500 
14501 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14502                                     SkipBodyInfo *SkipBody,
14503                                     FnBodyKind BodyKind) {
14504   if (!D) {
14505     // Parsing the function declaration failed in some way. Push on a fake scope
14506     // anyway so we can try to parse the function body.
14507     PushFunctionScope();
14508     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14509     return D;
14510   }
14511 
14512   FunctionDecl *FD = nullptr;
14513 
14514   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14515     FD = FunTmpl->getTemplatedDecl();
14516   else
14517     FD = cast<FunctionDecl>(D);
14518 
14519   // Do not push if it is a lambda because one is already pushed when building
14520   // the lambda in ActOnStartOfLambdaDefinition().
14521   if (!isLambdaCallOperator(FD))
14522     PushExpressionEvaluationContext(
14523         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14524                           : ExprEvalContexts.back().Context);
14525 
14526   // Check for defining attributes before the check for redefinition.
14527   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14528     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14529     FD->dropAttr<AliasAttr>();
14530     FD->setInvalidDecl();
14531   }
14532   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14533     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14534     FD->dropAttr<IFuncAttr>();
14535     FD->setInvalidDecl();
14536   }
14537 
14538   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14539     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14540         Ctor->isDefaultConstructor() &&
14541         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14542       // If this is an MS ABI dllexport default constructor, instantiate any
14543       // default arguments.
14544       InstantiateDefaultCtorDefaultArgs(Ctor);
14545     }
14546   }
14547 
14548   // See if this is a redefinition. If 'will have body' (or similar) is already
14549   // set, then these checks were already performed when it was set.
14550   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14551       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14552     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14553 
14554     // If we're skipping the body, we're done. Don't enter the scope.
14555     if (SkipBody && SkipBody->ShouldSkip)
14556       return D;
14557   }
14558 
14559   // Mark this function as "will have a body eventually".  This lets users to
14560   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14561   // this function.
14562   FD->setWillHaveBody();
14563 
14564   // If we are instantiating a generic lambda call operator, push
14565   // a LambdaScopeInfo onto the function stack.  But use the information
14566   // that's already been calculated (ActOnLambdaExpr) to prime the current
14567   // LambdaScopeInfo.
14568   // When the template operator is being specialized, the LambdaScopeInfo,
14569   // has to be properly restored so that tryCaptureVariable doesn't try
14570   // and capture any new variables. In addition when calculating potential
14571   // captures during transformation of nested lambdas, it is necessary to
14572   // have the LSI properly restored.
14573   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14574     assert(inTemplateInstantiation() &&
14575            "There should be an active template instantiation on the stack "
14576            "when instantiating a generic lambda!");
14577     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14578   } else {
14579     // Enter a new function scope
14580     PushFunctionScope();
14581   }
14582 
14583   // Builtin functions cannot be defined.
14584   if (unsigned BuiltinID = FD->getBuiltinID()) {
14585     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14586         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14587       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14588       FD->setInvalidDecl();
14589     }
14590   }
14591 
14592   // The return type of a function definition must be complete (C99 6.9.1p3),
14593   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14594   QualType ResultType = FD->getReturnType();
14595   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14596       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14597       RequireCompleteType(FD->getLocation(), ResultType,
14598                           diag::err_func_def_incomplete_result))
14599     FD->setInvalidDecl();
14600 
14601   if (FnBodyScope)
14602     PushDeclContext(FnBodyScope, FD);
14603 
14604   // Check the validity of our function parameters
14605   if (BodyKind != FnBodyKind::Delete)
14606     CheckParmsForFunctionDef(FD->parameters(),
14607                              /*CheckParameterNames=*/true);
14608 
14609   // Add non-parameter declarations already in the function to the current
14610   // scope.
14611   if (FnBodyScope) {
14612     for (Decl *NPD : FD->decls()) {
14613       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14614       if (!NonParmDecl)
14615         continue;
14616       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14617              "parameters should not be in newly created FD yet");
14618 
14619       // If the decl has a name, make it accessible in the current scope.
14620       if (NonParmDecl->getDeclName())
14621         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14622 
14623       // Similarly, dive into enums and fish their constants out, making them
14624       // accessible in this scope.
14625       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14626         for (auto *EI : ED->enumerators())
14627           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14628       }
14629     }
14630   }
14631 
14632   // Introduce our parameters into the function scope
14633   for (auto Param : FD->parameters()) {
14634     Param->setOwningFunction(FD);
14635 
14636     // If this has an identifier, add it to the scope stack.
14637     if (Param->getIdentifier() && FnBodyScope) {
14638       CheckShadow(FnBodyScope, Param);
14639 
14640       PushOnScopeChains(Param, FnBodyScope);
14641     }
14642   }
14643 
14644   // Ensure that the function's exception specification is instantiated.
14645   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14646     ResolveExceptionSpec(D->getLocation(), FPT);
14647 
14648   // dllimport cannot be applied to non-inline function definitions.
14649   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14650       !FD->isTemplateInstantiation()) {
14651     assert(!FD->hasAttr<DLLExportAttr>());
14652     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14653     FD->setInvalidDecl();
14654     return D;
14655   }
14656   // We want to attach documentation to original Decl (which might be
14657   // a function template).
14658   ActOnDocumentableDecl(D);
14659   if (getCurLexicalContext()->isObjCContainer() &&
14660       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14661       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14662     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14663 
14664   return D;
14665 }
14666 
14667 /// Given the set of return statements within a function body,
14668 /// compute the variables that are subject to the named return value
14669 /// optimization.
14670 ///
14671 /// Each of the variables that is subject to the named return value
14672 /// optimization will be marked as NRVO variables in the AST, and any
14673 /// return statement that has a marked NRVO variable as its NRVO candidate can
14674 /// use the named return value optimization.
14675 ///
14676 /// This function applies a very simplistic algorithm for NRVO: if every return
14677 /// statement in the scope of a variable has the same NRVO candidate, that
14678 /// candidate is an NRVO variable.
14679 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14680   ReturnStmt **Returns = Scope->Returns.data();
14681 
14682   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14683     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14684       if (!NRVOCandidate->isNRVOVariable())
14685         Returns[I]->setNRVOCandidate(nullptr);
14686     }
14687   }
14688 }
14689 
14690 bool Sema::canDelayFunctionBody(const Declarator &D) {
14691   // We can't delay parsing the body of a constexpr function template (yet).
14692   if (D.getDeclSpec().hasConstexprSpecifier())
14693     return false;
14694 
14695   // We can't delay parsing the body of a function template with a deduced
14696   // return type (yet).
14697   if (D.getDeclSpec().hasAutoTypeSpec()) {
14698     // If the placeholder introduces a non-deduced trailing return type,
14699     // we can still delay parsing it.
14700     if (D.getNumTypeObjects()) {
14701       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14702       if (Outer.Kind == DeclaratorChunk::Function &&
14703           Outer.Fun.hasTrailingReturnType()) {
14704         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14705         return Ty.isNull() || !Ty->isUndeducedType();
14706       }
14707     }
14708     return false;
14709   }
14710 
14711   return true;
14712 }
14713 
14714 bool Sema::canSkipFunctionBody(Decl *D) {
14715   // We cannot skip the body of a function (or function template) which is
14716   // constexpr, since we may need to evaluate its body in order to parse the
14717   // rest of the file.
14718   // We cannot skip the body of a function with an undeduced return type,
14719   // because any callers of that function need to know the type.
14720   if (const FunctionDecl *FD = D->getAsFunction()) {
14721     if (FD->isConstexpr())
14722       return false;
14723     // We can't simply call Type::isUndeducedType here, because inside template
14724     // auto can be deduced to a dependent type, which is not considered
14725     // "undeduced".
14726     if (FD->getReturnType()->getContainedDeducedType())
14727       return false;
14728   }
14729   return Consumer.shouldSkipFunctionBody(D);
14730 }
14731 
14732 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14733   if (!Decl)
14734     return nullptr;
14735   if (FunctionDecl *FD = Decl->getAsFunction())
14736     FD->setHasSkippedBody();
14737   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14738     MD->setHasSkippedBody();
14739   return Decl;
14740 }
14741 
14742 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14743   return ActOnFinishFunctionBody(D, BodyArg, false);
14744 }
14745 
14746 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14747 /// body.
14748 class ExitFunctionBodyRAII {
14749 public:
14750   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14751   ~ExitFunctionBodyRAII() {
14752     if (!IsLambda)
14753       S.PopExpressionEvaluationContext();
14754   }
14755 
14756 private:
14757   Sema &S;
14758   bool IsLambda = false;
14759 };
14760 
14761 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14762   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14763 
14764   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14765     if (EscapeInfo.count(BD))
14766       return EscapeInfo[BD];
14767 
14768     bool R = false;
14769     const BlockDecl *CurBD = BD;
14770 
14771     do {
14772       R = !CurBD->doesNotEscape();
14773       if (R)
14774         break;
14775       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14776     } while (CurBD);
14777 
14778     return EscapeInfo[BD] = R;
14779   };
14780 
14781   // If the location where 'self' is implicitly retained is inside a escaping
14782   // block, emit a diagnostic.
14783   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14784        S.ImplicitlyRetainedSelfLocs)
14785     if (IsOrNestedInEscapingBlock(P.second))
14786       S.Diag(P.first, diag::warn_implicitly_retains_self)
14787           << FixItHint::CreateInsertion(P.first, "self->");
14788 }
14789 
14790 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14791                                     bool IsInstantiation) {
14792   FunctionScopeInfo *FSI = getCurFunction();
14793   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14794 
14795   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14796     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14797 
14798   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14799   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14800 
14801   if (getLangOpts().Coroutines && FSI->isCoroutine())
14802     CheckCompletedCoroutineBody(FD, Body);
14803 
14804   {
14805     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14806     // one is already popped when finishing the lambda in BuildLambdaExpr().
14807     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14808     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14809 
14810     if (FD) {
14811       FD->setBody(Body);
14812       FD->setWillHaveBody(false);
14813 
14814       if (getLangOpts().CPlusPlus14) {
14815         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14816             FD->getReturnType()->isUndeducedType()) {
14817           // For a function with a deduced result type to return void,
14818           // the result type as written must be 'auto' or 'decltype(auto)',
14819           // possibly cv-qualified or constrained, but not ref-qualified.
14820           if (!FD->getReturnType()->getAs<AutoType>()) {
14821             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14822                 << FD->getReturnType();
14823             FD->setInvalidDecl();
14824           } else {
14825             // Falling off the end of the function is the same as 'return;'.
14826             Expr *Dummy = nullptr;
14827             if (DeduceFunctionTypeFromReturnExpr(
14828                     FD, dcl->getLocation(), Dummy,
14829                     FD->getReturnType()->getAs<AutoType>()))
14830               FD->setInvalidDecl();
14831           }
14832         }
14833       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14834         // In C++11, we don't use 'auto' deduction rules for lambda call
14835         // operators because we don't support return type deduction.
14836         auto *LSI = getCurLambda();
14837         if (LSI->HasImplicitReturnType) {
14838           deduceClosureReturnType(*LSI);
14839 
14840           // C++11 [expr.prim.lambda]p4:
14841           //   [...] if there are no return statements in the compound-statement
14842           //   [the deduced type is] the type void
14843           QualType RetType =
14844               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14845 
14846           // Update the return type to the deduced type.
14847           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14848           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14849                                               Proto->getExtProtoInfo()));
14850         }
14851       }
14852 
14853       // If the function implicitly returns zero (like 'main') or is naked,
14854       // don't complain about missing return statements.
14855       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14856         WP.disableCheckFallThrough();
14857 
14858       // MSVC permits the use of pure specifier (=0) on function definition,
14859       // defined at class scope, warn about this non-standard construct.
14860       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14861         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14862 
14863       if (!FD->isInvalidDecl()) {
14864         // Don't diagnose unused parameters of defaulted, deleted or naked
14865         // functions.
14866         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14867             !FD->hasAttr<NakedAttr>())
14868           DiagnoseUnusedParameters(FD->parameters());
14869         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14870                                                FD->getReturnType(), FD);
14871 
14872         // If this is a structor, we need a vtable.
14873         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14874           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14875         else if (CXXDestructorDecl *Destructor =
14876                      dyn_cast<CXXDestructorDecl>(FD))
14877           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14878 
14879         // Try to apply the named return value optimization. We have to check
14880         // if we can do this here because lambdas keep return statements around
14881         // to deduce an implicit return type.
14882         if (FD->getReturnType()->isRecordType() &&
14883             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14884           computeNRVO(Body, FSI);
14885       }
14886 
14887       // GNU warning -Wmissing-prototypes:
14888       //   Warn if a global function is defined without a previous
14889       //   prototype declaration. This warning is issued even if the
14890       //   definition itself provides a prototype. The aim is to detect
14891       //   global functions that fail to be declared in header files.
14892       const FunctionDecl *PossiblePrototype = nullptr;
14893       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14894         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14895 
14896         if (PossiblePrototype) {
14897           // We found a declaration that is not a prototype,
14898           // but that could be a zero-parameter prototype
14899           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14900             TypeLoc TL = TI->getTypeLoc();
14901             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14902               Diag(PossiblePrototype->getLocation(),
14903                    diag::note_declaration_not_a_prototype)
14904                   << (FD->getNumParams() != 0)
14905                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14906                                                     FTL.getRParenLoc(), "void")
14907                                               : FixItHint{});
14908           }
14909         } else {
14910           // Returns true if the token beginning at this Loc is `const`.
14911           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14912                                   const LangOptions &LangOpts) {
14913             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14914             if (LocInfo.first.isInvalid())
14915               return false;
14916 
14917             bool Invalid = false;
14918             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14919             if (Invalid)
14920               return false;
14921 
14922             if (LocInfo.second > Buffer.size())
14923               return false;
14924 
14925             const char *LexStart = Buffer.data() + LocInfo.second;
14926             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14927 
14928             return StartTok.consume_front("const") &&
14929                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14930                     StartTok.startswith("/*") || StartTok.startswith("//"));
14931           };
14932 
14933           auto findBeginLoc = [&]() {
14934             // If the return type has `const` qualifier, we want to insert
14935             // `static` before `const` (and not before the typename).
14936             if ((FD->getReturnType()->isAnyPointerType() &&
14937                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14938                 FD->getReturnType().isConstQualified()) {
14939               // But only do this if we can determine where the `const` is.
14940 
14941               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14942                                getLangOpts()))
14943 
14944                 return FD->getBeginLoc();
14945             }
14946             return FD->getTypeSpecStartLoc();
14947           };
14948           Diag(FD->getTypeSpecStartLoc(),
14949                diag::note_static_for_internal_linkage)
14950               << /* function */ 1
14951               << (FD->getStorageClass() == SC_None
14952                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14953                       : FixItHint{});
14954         }
14955       }
14956 
14957       // If the function being defined does not have a prototype, then we may
14958       // need to diagnose it as changing behavior in C2x because we now know
14959       // whether the function accepts arguments or not. This only handles the
14960       // case where the definition has no prototype but does have parameters
14961       // and either there is no previous potential prototype, or the previous
14962       // potential prototype also has no actual prototype. This handles cases
14963       // like:
14964       //   void f(); void f(a) int a; {}
14965       //   void g(a) int a; {}
14966       // See MergeFunctionDecl() for other cases of the behavior change
14967       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
14968       // type without a prototype.
14969       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
14970           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
14971                                   !PossiblePrototype->isImplicit()))) {
14972         // The function definition has parameters, so this will change behavior
14973         // in C2x. If there is a possible prototype, it comes before the
14974         // function definition.
14975         // FIXME: The declaration may have already been diagnosed as being
14976         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
14977         // there's no way to test for the "changes behavior" condition in
14978         // SemaType.cpp when forming the declaration's function type. So, we do
14979         // this awkward dance instead.
14980         //
14981         // If we have a possible prototype and it declares a function with a
14982         // prototype, we don't want to diagnose it; if we have a possible
14983         // prototype and it has no prototype, it may have already been
14984         // diagnosed in SemaType.cpp as deprecated depending on whether
14985         // -Wstrict-prototypes is enabled. If we already warned about it being
14986         // deprecated, add a note that it also changes behavior. If we didn't
14987         // warn about it being deprecated (because the diagnostic is not
14988         // enabled), warn now that it is deprecated and changes behavior.
14989         bool AddNote = false;
14990         if (PossiblePrototype) {
14991           if (Diags.isIgnored(diag::warn_strict_prototypes,
14992                               PossiblePrototype->getLocation())) {
14993 
14994             PartialDiagnostic PD =
14995                 PDiag(diag::warn_non_prototype_changes_behavior);
14996             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
14997               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
14998                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
14999             }
15000             Diag(PossiblePrototype->getLocation(), PD);
15001           } else {
15002             AddNote = true;
15003           }
15004         }
15005 
15006         // Because this function definition has no prototype and it has
15007         // parameters, it will definitely change behavior in C2x.
15008         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
15009         if (AddNote)
15010           Diag(PossiblePrototype->getLocation(),
15011                diag::note_func_decl_changes_behavior);
15012       }
15013 
15014       // Warn on CPUDispatch with an actual body.
15015       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15016         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15017           if (!CmpndBody->body_empty())
15018             Diag(CmpndBody->body_front()->getBeginLoc(),
15019                  diag::warn_dispatch_body_ignored);
15020 
15021       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15022         const CXXMethodDecl *KeyFunction;
15023         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15024             MD->isVirtual() &&
15025             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15026             MD == KeyFunction->getCanonicalDecl()) {
15027           // Update the key-function state if necessary for this ABI.
15028           if (FD->isInlined() &&
15029               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15030             Context.setNonKeyFunction(MD);
15031 
15032             // If the newly-chosen key function is already defined, then we
15033             // need to mark the vtable as used retroactively.
15034             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15035             const FunctionDecl *Definition;
15036             if (KeyFunction && KeyFunction->isDefined(Definition))
15037               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15038           } else {
15039             // We just defined they key function; mark the vtable as used.
15040             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15041           }
15042         }
15043       }
15044 
15045       assert(
15046           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15047           "Function parsing confused");
15048     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15049       assert(MD == getCurMethodDecl() && "Method parsing confused");
15050       MD->setBody(Body);
15051       if (!MD->isInvalidDecl()) {
15052         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15053                                                MD->getReturnType(), MD);
15054 
15055         if (Body)
15056           computeNRVO(Body, FSI);
15057       }
15058       if (FSI->ObjCShouldCallSuper) {
15059         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15060             << MD->getSelector().getAsString();
15061         FSI->ObjCShouldCallSuper = false;
15062       }
15063       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15064         const ObjCMethodDecl *InitMethod = nullptr;
15065         bool isDesignated =
15066             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15067         assert(isDesignated && InitMethod);
15068         (void)isDesignated;
15069 
15070         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15071           auto IFace = MD->getClassInterface();
15072           if (!IFace)
15073             return false;
15074           auto SuperD = IFace->getSuperClass();
15075           if (!SuperD)
15076             return false;
15077           return SuperD->getIdentifier() ==
15078                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15079         };
15080         // Don't issue this warning for unavailable inits or direct subclasses
15081         // of NSObject.
15082         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15083           Diag(MD->getLocation(),
15084                diag::warn_objc_designated_init_missing_super_call);
15085           Diag(InitMethod->getLocation(),
15086                diag::note_objc_designated_init_marked_here);
15087         }
15088         FSI->ObjCWarnForNoDesignatedInitChain = false;
15089       }
15090       if (FSI->ObjCWarnForNoInitDelegation) {
15091         // Don't issue this warning for unavaialable inits.
15092         if (!MD->isUnavailable())
15093           Diag(MD->getLocation(),
15094                diag::warn_objc_secondary_init_missing_init_call);
15095         FSI->ObjCWarnForNoInitDelegation = false;
15096       }
15097 
15098       diagnoseImplicitlyRetainedSelf(*this);
15099     } else {
15100       // Parsing the function declaration failed in some way. Pop the fake scope
15101       // we pushed on.
15102       PopFunctionScopeInfo(ActivePolicy, dcl);
15103       return nullptr;
15104     }
15105 
15106     if (Body && FSI->HasPotentialAvailabilityViolations)
15107       DiagnoseUnguardedAvailabilityViolations(dcl);
15108 
15109     assert(!FSI->ObjCShouldCallSuper &&
15110            "This should only be set for ObjC methods, which should have been "
15111            "handled in the block above.");
15112 
15113     // Verify and clean out per-function state.
15114     if (Body && (!FD || !FD->isDefaulted())) {
15115       // C++ constructors that have function-try-blocks can't have return
15116       // statements in the handlers of that block. (C++ [except.handle]p14)
15117       // Verify this.
15118       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15119         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15120 
15121       // Verify that gotos and switch cases don't jump into scopes illegally.
15122       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15123         DiagnoseInvalidJumps(Body);
15124 
15125       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15126         if (!Destructor->getParent()->isDependentType())
15127           CheckDestructor(Destructor);
15128 
15129         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15130                                                Destructor->getParent());
15131       }
15132 
15133       // If any errors have occurred, clear out any temporaries that may have
15134       // been leftover. This ensures that these temporaries won't be picked up
15135       // for deletion in some later function.
15136       if (hasUncompilableErrorOccurred() ||
15137           getDiagnostics().getSuppressAllDiagnostics()) {
15138         DiscardCleanupsInEvaluationContext();
15139       }
15140       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15141         // Since the body is valid, issue any analysis-based warnings that are
15142         // enabled.
15143         ActivePolicy = &WP;
15144       }
15145 
15146       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15147           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15148         FD->setInvalidDecl();
15149 
15150       if (FD && FD->hasAttr<NakedAttr>()) {
15151         for (const Stmt *S : Body->children()) {
15152           // Allow local register variables without initializer as they don't
15153           // require prologue.
15154           bool RegisterVariables = false;
15155           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15156             for (const auto *Decl : DS->decls()) {
15157               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15158                 RegisterVariables =
15159                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15160                 if (!RegisterVariables)
15161                   break;
15162               }
15163             }
15164           }
15165           if (RegisterVariables)
15166             continue;
15167           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15168             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15169             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15170             FD->setInvalidDecl();
15171             break;
15172           }
15173         }
15174       }
15175 
15176       assert(ExprCleanupObjects.size() ==
15177                  ExprEvalContexts.back().NumCleanupObjects &&
15178              "Leftover temporaries in function");
15179       assert(!Cleanup.exprNeedsCleanups() &&
15180              "Unaccounted cleanups in function");
15181       assert(MaybeODRUseExprs.empty() &&
15182              "Leftover expressions for odr-use checking");
15183     }
15184   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15185     // the declaration context below. Otherwise, we're unable to transform
15186     // 'this' expressions when transforming immediate context functions.
15187 
15188   if (!IsInstantiation)
15189     PopDeclContext();
15190 
15191   PopFunctionScopeInfo(ActivePolicy, dcl);
15192   // If any errors have occurred, clear out any temporaries that may have
15193   // been leftover. This ensures that these temporaries won't be picked up for
15194   // deletion in some later function.
15195   if (hasUncompilableErrorOccurred()) {
15196     DiscardCleanupsInEvaluationContext();
15197   }
15198 
15199   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15200                                   !LangOpts.OMPTargetTriples.empty())) ||
15201              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15202     auto ES = getEmissionStatus(FD);
15203     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15204         ES == Sema::FunctionEmissionStatus::Unknown)
15205       DeclsToCheckForDeferredDiags.insert(FD);
15206   }
15207 
15208   if (FD && !FD->isDeleted())
15209     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15210 
15211   return dcl;
15212 }
15213 
15214 /// When we finish delayed parsing of an attribute, we must attach it to the
15215 /// relevant Decl.
15216 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15217                                        ParsedAttributes &Attrs) {
15218   // Always attach attributes to the underlying decl.
15219   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15220     D = TD->getTemplatedDecl();
15221   ProcessDeclAttributeList(S, D, Attrs);
15222 
15223   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15224     if (Method->isStatic())
15225       checkThisInStaticMemberFunctionAttributes(Method);
15226 }
15227 
15228 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15229 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15230 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15231                                           IdentifierInfo &II, Scope *S) {
15232   // Find the scope in which the identifier is injected and the corresponding
15233   // DeclContext.
15234   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15235   // In that case, we inject the declaration into the translation unit scope
15236   // instead.
15237   Scope *BlockScope = S;
15238   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15239     BlockScope = BlockScope->getParent();
15240 
15241   Scope *ContextScope = BlockScope;
15242   while (!ContextScope->getEntity())
15243     ContextScope = ContextScope->getParent();
15244   ContextRAII SavedContext(*this, ContextScope->getEntity());
15245 
15246   // Before we produce a declaration for an implicitly defined
15247   // function, see whether there was a locally-scoped declaration of
15248   // this name as a function or variable. If so, use that
15249   // (non-visible) declaration, and complain about it.
15250   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15251   if (ExternCPrev) {
15252     // We still need to inject the function into the enclosing block scope so
15253     // that later (non-call) uses can see it.
15254     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15255 
15256     // C89 footnote 38:
15257     //   If in fact it is not defined as having type "function returning int",
15258     //   the behavior is undefined.
15259     if (!isa<FunctionDecl>(ExternCPrev) ||
15260         !Context.typesAreCompatible(
15261             cast<FunctionDecl>(ExternCPrev)->getType(),
15262             Context.getFunctionNoProtoType(Context.IntTy))) {
15263       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15264           << ExternCPrev << !getLangOpts().C99;
15265       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15266       return ExternCPrev;
15267     }
15268   }
15269 
15270   // Extension in C99.  Legal in C90, but warn about it.
15271   unsigned diag_id;
15272   if (II.getName().startswith("__builtin_"))
15273     diag_id = diag::warn_builtin_unknown;
15274   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15275   else if (getLangOpts().OpenCL)
15276     diag_id = diag::err_opencl_implicit_function_decl;
15277   else if (getLangOpts().C99)
15278     diag_id = diag::ext_implicit_function_decl;
15279   else
15280     diag_id = diag::warn_implicit_function_decl;
15281 
15282   TypoCorrection Corrected;
15283   // Because typo correction is expensive, only do it if the implicit
15284   // function declaration is going to be treated as an error.
15285   //
15286   // Perform the corection before issuing the main diagnostic, as some consumers
15287   // use typo-correction callbacks to enhance the main diagnostic.
15288   if (S && !ExternCPrev &&
15289       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15290     DeclFilterCCC<FunctionDecl> CCC{};
15291     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15292                             S, nullptr, CCC, CTK_NonError);
15293   }
15294 
15295   Diag(Loc, diag_id) << &II;
15296   if (Corrected)
15297     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15298                  /*ErrorRecovery*/ false);
15299 
15300   // If we found a prior declaration of this function, don't bother building
15301   // another one. We've already pushed that one into scope, so there's nothing
15302   // more to do.
15303   if (ExternCPrev)
15304     return ExternCPrev;
15305 
15306   // Set a Declarator for the implicit definition: int foo();
15307   const char *Dummy;
15308   AttributeFactory attrFactory;
15309   DeclSpec DS(attrFactory);
15310   unsigned DiagID;
15311   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15312                                   Context.getPrintingPolicy());
15313   (void)Error; // Silence warning.
15314   assert(!Error && "Error setting up implicit decl!");
15315   SourceLocation NoLoc;
15316   Declarator D(DS, DeclaratorContext::Block);
15317   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15318                                              /*IsAmbiguous=*/false,
15319                                              /*LParenLoc=*/NoLoc,
15320                                              /*Params=*/nullptr,
15321                                              /*NumParams=*/0,
15322                                              /*EllipsisLoc=*/NoLoc,
15323                                              /*RParenLoc=*/NoLoc,
15324                                              /*RefQualifierIsLvalueRef=*/true,
15325                                              /*RefQualifierLoc=*/NoLoc,
15326                                              /*MutableLoc=*/NoLoc, EST_None,
15327                                              /*ESpecRange=*/SourceRange(),
15328                                              /*Exceptions=*/nullptr,
15329                                              /*ExceptionRanges=*/nullptr,
15330                                              /*NumExceptions=*/0,
15331                                              /*NoexceptExpr=*/nullptr,
15332                                              /*ExceptionSpecTokens=*/nullptr,
15333                                              /*DeclsInPrototype=*/None, Loc,
15334                                              Loc, D),
15335                 std::move(DS.getAttributes()), SourceLocation());
15336   D.SetIdentifier(&II, Loc);
15337 
15338   // Insert this function into the enclosing block scope.
15339   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15340   FD->setImplicit();
15341 
15342   AddKnownFunctionAttributes(FD);
15343 
15344   return FD;
15345 }
15346 
15347 /// If this function is a C++ replaceable global allocation function
15348 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15349 /// adds any function attributes that we know a priori based on the standard.
15350 ///
15351 /// We need to check for duplicate attributes both here and where user-written
15352 /// attributes are applied to declarations.
15353 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15354     FunctionDecl *FD) {
15355   if (FD->isInvalidDecl())
15356     return;
15357 
15358   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15359       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15360     return;
15361 
15362   Optional<unsigned> AlignmentParam;
15363   bool IsNothrow = false;
15364   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15365     return;
15366 
15367   // C++2a [basic.stc.dynamic.allocation]p4:
15368   //   An allocation function that has a non-throwing exception specification
15369   //   indicates failure by returning a null pointer value. Any other allocation
15370   //   function never returns a null pointer value and indicates failure only by
15371   //   throwing an exception [...]
15372   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15373     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15374 
15375   // C++2a [basic.stc.dynamic.allocation]p2:
15376   //   An allocation function attempts to allocate the requested amount of
15377   //   storage. [...] If the request succeeds, the value returned by a
15378   //   replaceable allocation function is a [...] pointer value p0 different
15379   //   from any previously returned value p1 [...]
15380   //
15381   // However, this particular information is being added in codegen,
15382   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15383 
15384   // C++2a [basic.stc.dynamic.allocation]p2:
15385   //   An allocation function attempts to allocate the requested amount of
15386   //   storage. If it is successful, it returns the address of the start of a
15387   //   block of storage whose length in bytes is at least as large as the
15388   //   requested size.
15389   if (!FD->hasAttr<AllocSizeAttr>()) {
15390     FD->addAttr(AllocSizeAttr::CreateImplicit(
15391         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15392         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15393   }
15394 
15395   // C++2a [basic.stc.dynamic.allocation]p3:
15396   //   For an allocation function [...], the pointer returned on a successful
15397   //   call shall represent the address of storage that is aligned as follows:
15398   //   (3.1) If the allocation function takes an argument of type
15399   //         std​::​align_­val_­t, the storage will have the alignment
15400   //         specified by the value of this argument.
15401   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15402     FD->addAttr(AllocAlignAttr::CreateImplicit(
15403         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15404   }
15405 
15406   // FIXME:
15407   // C++2a [basic.stc.dynamic.allocation]p3:
15408   //   For an allocation function [...], the pointer returned on a successful
15409   //   call shall represent the address of storage that is aligned as follows:
15410   //   (3.2) Otherwise, if the allocation function is named operator new[],
15411   //         the storage is aligned for any object that does not have
15412   //         new-extended alignment ([basic.align]) and is no larger than the
15413   //         requested size.
15414   //   (3.3) Otherwise, the storage is aligned for any object that does not
15415   //         have new-extended alignment and is of the requested size.
15416 }
15417 
15418 /// Adds any function attributes that we know a priori based on
15419 /// the declaration of this function.
15420 ///
15421 /// These attributes can apply both to implicitly-declared builtins
15422 /// (like __builtin___printf_chk) or to library-declared functions
15423 /// like NSLog or printf.
15424 ///
15425 /// We need to check for duplicate attributes both here and where user-written
15426 /// attributes are applied to declarations.
15427 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15428   if (FD->isInvalidDecl())
15429     return;
15430 
15431   // If this is a built-in function, map its builtin attributes to
15432   // actual attributes.
15433   if (unsigned BuiltinID = FD->getBuiltinID()) {
15434     // Handle printf-formatting attributes.
15435     unsigned FormatIdx;
15436     bool HasVAListArg;
15437     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15438       if (!FD->hasAttr<FormatAttr>()) {
15439         const char *fmt = "printf";
15440         unsigned int NumParams = FD->getNumParams();
15441         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15442             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15443           fmt = "NSString";
15444         FD->addAttr(FormatAttr::CreateImplicit(Context,
15445                                                &Context.Idents.get(fmt),
15446                                                FormatIdx+1,
15447                                                HasVAListArg ? 0 : FormatIdx+2,
15448                                                FD->getLocation()));
15449       }
15450     }
15451     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15452                                              HasVAListArg)) {
15453      if (!FD->hasAttr<FormatAttr>())
15454        FD->addAttr(FormatAttr::CreateImplicit(Context,
15455                                               &Context.Idents.get("scanf"),
15456                                               FormatIdx+1,
15457                                               HasVAListArg ? 0 : FormatIdx+2,
15458                                               FD->getLocation()));
15459     }
15460 
15461     // Handle automatically recognized callbacks.
15462     SmallVector<int, 4> Encoding;
15463     if (!FD->hasAttr<CallbackAttr>() &&
15464         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15465       FD->addAttr(CallbackAttr::CreateImplicit(
15466           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15467 
15468     // Mark const if we don't care about errno and that is the only thing
15469     // preventing the function from being const. This allows IRgen to use LLVM
15470     // intrinsics for such functions.
15471     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15472         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15473       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15474 
15475     // We make "fma" on GNU or Windows const because we know it does not set
15476     // errno in those environments even though it could set errno based on the
15477     // C standard.
15478     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15479     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15480         !FD->hasAttr<ConstAttr>()) {
15481       switch (BuiltinID) {
15482       case Builtin::BI__builtin_fma:
15483       case Builtin::BI__builtin_fmaf:
15484       case Builtin::BI__builtin_fmal:
15485       case Builtin::BIfma:
15486       case Builtin::BIfmaf:
15487       case Builtin::BIfmal:
15488         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15489         break;
15490       default:
15491         break;
15492       }
15493     }
15494 
15495     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15496         !FD->hasAttr<ReturnsTwiceAttr>())
15497       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15498                                          FD->getLocation()));
15499     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15500       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15501     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15502       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15503     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15504       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15505     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15506         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15507       // Add the appropriate attribute, depending on the CUDA compilation mode
15508       // and which target the builtin belongs to. For example, during host
15509       // compilation, aux builtins are __device__, while the rest are __host__.
15510       if (getLangOpts().CUDAIsDevice !=
15511           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15512         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15513       else
15514         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15515     }
15516 
15517     // Add known guaranteed alignment for allocation functions.
15518     switch (BuiltinID) {
15519     case Builtin::BImemalign:
15520     case Builtin::BIaligned_alloc:
15521       if (!FD->hasAttr<AllocAlignAttr>())
15522         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15523                                                    FD->getLocation()));
15524       break;
15525     default:
15526       break;
15527     }
15528 
15529     // Add allocsize attribute for allocation functions.
15530     switch (BuiltinID) {
15531     case Builtin::BIcalloc:
15532       FD->addAttr(AllocSizeAttr::CreateImplicit(
15533           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15534       break;
15535     case Builtin::BImemalign:
15536     case Builtin::BIaligned_alloc:
15537     case Builtin::BIrealloc:
15538       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15539                                                 ParamIdx(), FD->getLocation()));
15540       break;
15541     case Builtin::BImalloc:
15542       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15543                                                 ParamIdx(), FD->getLocation()));
15544       break;
15545     default:
15546       break;
15547     }
15548   }
15549 
15550   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15551 
15552   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15553   // throw, add an implicit nothrow attribute to any extern "C" function we come
15554   // across.
15555   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15556       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15557     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15558     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15559       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15560   }
15561 
15562   IdentifierInfo *Name = FD->getIdentifier();
15563   if (!Name)
15564     return;
15565   if ((!getLangOpts().CPlusPlus &&
15566        FD->getDeclContext()->isTranslationUnit()) ||
15567       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15568        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15569        LinkageSpecDecl::lang_c)) {
15570     // Okay: this could be a libc/libm/Objective-C function we know
15571     // about.
15572   } else
15573     return;
15574 
15575   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15576     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15577     // target-specific builtins, perhaps?
15578     if (!FD->hasAttr<FormatAttr>())
15579       FD->addAttr(FormatAttr::CreateImplicit(Context,
15580                                              &Context.Idents.get("printf"), 2,
15581                                              Name->isStr("vasprintf") ? 0 : 3,
15582                                              FD->getLocation()));
15583   }
15584 
15585   if (Name->isStr("__CFStringMakeConstantString")) {
15586     // We already have a __builtin___CFStringMakeConstantString,
15587     // but builds that use -fno-constant-cfstrings don't go through that.
15588     if (!FD->hasAttr<FormatArgAttr>())
15589       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15590                                                 FD->getLocation()));
15591   }
15592 }
15593 
15594 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15595                                     TypeSourceInfo *TInfo) {
15596   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15597   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15598 
15599   if (!TInfo) {
15600     assert(D.isInvalidType() && "no declarator info for valid type");
15601     TInfo = Context.getTrivialTypeSourceInfo(T);
15602   }
15603 
15604   // Scope manipulation handled by caller.
15605   TypedefDecl *NewTD =
15606       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15607                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15608 
15609   // Bail out immediately if we have an invalid declaration.
15610   if (D.isInvalidType()) {
15611     NewTD->setInvalidDecl();
15612     return NewTD;
15613   }
15614 
15615   if (D.getDeclSpec().isModulePrivateSpecified()) {
15616     if (CurContext->isFunctionOrMethod())
15617       Diag(NewTD->getLocation(), diag::err_module_private_local)
15618           << 2 << NewTD
15619           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15620           << FixItHint::CreateRemoval(
15621                  D.getDeclSpec().getModulePrivateSpecLoc());
15622     else
15623       NewTD->setModulePrivate();
15624   }
15625 
15626   // C++ [dcl.typedef]p8:
15627   //   If the typedef declaration defines an unnamed class (or
15628   //   enum), the first typedef-name declared by the declaration
15629   //   to be that class type (or enum type) is used to denote the
15630   //   class type (or enum type) for linkage purposes only.
15631   // We need to check whether the type was declared in the declaration.
15632   switch (D.getDeclSpec().getTypeSpecType()) {
15633   case TST_enum:
15634   case TST_struct:
15635   case TST_interface:
15636   case TST_union:
15637   case TST_class: {
15638     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15639     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15640     break;
15641   }
15642 
15643   default:
15644     break;
15645   }
15646 
15647   return NewTD;
15648 }
15649 
15650 /// Check that this is a valid underlying type for an enum declaration.
15651 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15652   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15653   QualType T = TI->getType();
15654 
15655   if (T->isDependentType())
15656     return false;
15657 
15658   // This doesn't use 'isIntegralType' despite the error message mentioning
15659   // integral type because isIntegralType would also allow enum types in C.
15660   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15661     if (BT->isInteger())
15662       return false;
15663 
15664   if (T->isBitIntType())
15665     return false;
15666 
15667   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15668 }
15669 
15670 /// Check whether this is a valid redeclaration of a previous enumeration.
15671 /// \return true if the redeclaration was invalid.
15672 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15673                                   QualType EnumUnderlyingTy, bool IsFixed,
15674                                   const EnumDecl *Prev) {
15675   if (IsScoped != Prev->isScoped()) {
15676     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15677       << Prev->isScoped();
15678     Diag(Prev->getLocation(), diag::note_previous_declaration);
15679     return true;
15680   }
15681 
15682   if (IsFixed && Prev->isFixed()) {
15683     if (!EnumUnderlyingTy->isDependentType() &&
15684         !Prev->getIntegerType()->isDependentType() &&
15685         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15686                                         Prev->getIntegerType())) {
15687       // TODO: Highlight the underlying type of the redeclaration.
15688       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15689         << EnumUnderlyingTy << Prev->getIntegerType();
15690       Diag(Prev->getLocation(), diag::note_previous_declaration)
15691           << Prev->getIntegerTypeRange();
15692       return true;
15693     }
15694   } else if (IsFixed != Prev->isFixed()) {
15695     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15696       << Prev->isFixed();
15697     Diag(Prev->getLocation(), diag::note_previous_declaration);
15698     return true;
15699   }
15700 
15701   return false;
15702 }
15703 
15704 /// Get diagnostic %select index for tag kind for
15705 /// redeclaration diagnostic message.
15706 /// WARNING: Indexes apply to particular diagnostics only!
15707 ///
15708 /// \returns diagnostic %select index.
15709 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15710   switch (Tag) {
15711   case TTK_Struct: return 0;
15712   case TTK_Interface: return 1;
15713   case TTK_Class:  return 2;
15714   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15715   }
15716 }
15717 
15718 /// Determine if tag kind is a class-key compatible with
15719 /// class for redeclaration (class, struct, or __interface).
15720 ///
15721 /// \returns true iff the tag kind is compatible.
15722 static bool isClassCompatTagKind(TagTypeKind Tag)
15723 {
15724   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15725 }
15726 
15727 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15728                                              TagTypeKind TTK) {
15729   if (isa<TypedefDecl>(PrevDecl))
15730     return NTK_Typedef;
15731   else if (isa<TypeAliasDecl>(PrevDecl))
15732     return NTK_TypeAlias;
15733   else if (isa<ClassTemplateDecl>(PrevDecl))
15734     return NTK_Template;
15735   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15736     return NTK_TypeAliasTemplate;
15737   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15738     return NTK_TemplateTemplateArgument;
15739   switch (TTK) {
15740   case TTK_Struct:
15741   case TTK_Interface:
15742   case TTK_Class:
15743     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15744   case TTK_Union:
15745     return NTK_NonUnion;
15746   case TTK_Enum:
15747     return NTK_NonEnum;
15748   }
15749   llvm_unreachable("invalid TTK");
15750 }
15751 
15752 /// Determine whether a tag with a given kind is acceptable
15753 /// as a redeclaration of the given tag declaration.
15754 ///
15755 /// \returns true if the new tag kind is acceptable, false otherwise.
15756 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15757                                         TagTypeKind NewTag, bool isDefinition,
15758                                         SourceLocation NewTagLoc,
15759                                         const IdentifierInfo *Name) {
15760   // C++ [dcl.type.elab]p3:
15761   //   The class-key or enum keyword present in the
15762   //   elaborated-type-specifier shall agree in kind with the
15763   //   declaration to which the name in the elaborated-type-specifier
15764   //   refers. This rule also applies to the form of
15765   //   elaborated-type-specifier that declares a class-name or
15766   //   friend class since it can be construed as referring to the
15767   //   definition of the class. Thus, in any
15768   //   elaborated-type-specifier, the enum keyword shall be used to
15769   //   refer to an enumeration (7.2), the union class-key shall be
15770   //   used to refer to a union (clause 9), and either the class or
15771   //   struct class-key shall be used to refer to a class (clause 9)
15772   //   declared using the class or struct class-key.
15773   TagTypeKind OldTag = Previous->getTagKind();
15774   if (OldTag != NewTag &&
15775       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15776     return false;
15777 
15778   // Tags are compatible, but we might still want to warn on mismatched tags.
15779   // Non-class tags can't be mismatched at this point.
15780   if (!isClassCompatTagKind(NewTag))
15781     return true;
15782 
15783   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15784   // by our warning analysis. We don't want to warn about mismatches with (eg)
15785   // declarations in system headers that are designed to be specialized, but if
15786   // a user asks us to warn, we should warn if their code contains mismatched
15787   // declarations.
15788   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15789     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15790                                       Loc);
15791   };
15792   if (IsIgnoredLoc(NewTagLoc))
15793     return true;
15794 
15795   auto IsIgnored = [&](const TagDecl *Tag) {
15796     return IsIgnoredLoc(Tag->getLocation());
15797   };
15798   while (IsIgnored(Previous)) {
15799     Previous = Previous->getPreviousDecl();
15800     if (!Previous)
15801       return true;
15802     OldTag = Previous->getTagKind();
15803   }
15804 
15805   bool isTemplate = false;
15806   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15807     isTemplate = Record->getDescribedClassTemplate();
15808 
15809   if (inTemplateInstantiation()) {
15810     if (OldTag != NewTag) {
15811       // In a template instantiation, do not offer fix-its for tag mismatches
15812       // since they usually mess up the template instead of fixing the problem.
15813       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15814         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15815         << getRedeclDiagFromTagKind(OldTag);
15816       // FIXME: Note previous location?
15817     }
15818     return true;
15819   }
15820 
15821   if (isDefinition) {
15822     // On definitions, check all previous tags and issue a fix-it for each
15823     // one that doesn't match the current tag.
15824     if (Previous->getDefinition()) {
15825       // Don't suggest fix-its for redefinitions.
15826       return true;
15827     }
15828 
15829     bool previousMismatch = false;
15830     for (const TagDecl *I : Previous->redecls()) {
15831       if (I->getTagKind() != NewTag) {
15832         // Ignore previous declarations for which the warning was disabled.
15833         if (IsIgnored(I))
15834           continue;
15835 
15836         if (!previousMismatch) {
15837           previousMismatch = true;
15838           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15839             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15840             << getRedeclDiagFromTagKind(I->getTagKind());
15841         }
15842         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15843           << getRedeclDiagFromTagKind(NewTag)
15844           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15845                TypeWithKeyword::getTagTypeKindName(NewTag));
15846       }
15847     }
15848     return true;
15849   }
15850 
15851   // Identify the prevailing tag kind: this is the kind of the definition (if
15852   // there is a non-ignored definition), or otherwise the kind of the prior
15853   // (non-ignored) declaration.
15854   const TagDecl *PrevDef = Previous->getDefinition();
15855   if (PrevDef && IsIgnored(PrevDef))
15856     PrevDef = nullptr;
15857   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15858   if (Redecl->getTagKind() != NewTag) {
15859     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15860       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15861       << getRedeclDiagFromTagKind(OldTag);
15862     Diag(Redecl->getLocation(), diag::note_previous_use);
15863 
15864     // If there is a previous definition, suggest a fix-it.
15865     if (PrevDef) {
15866       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15867         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15868         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15869              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15870     }
15871   }
15872 
15873   return true;
15874 }
15875 
15876 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15877 /// from an outer enclosing namespace or file scope inside a friend declaration.
15878 /// This should provide the commented out code in the following snippet:
15879 ///   namespace N {
15880 ///     struct X;
15881 ///     namespace M {
15882 ///       struct Y { friend struct /*N::*/ X; };
15883 ///     }
15884 ///   }
15885 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15886                                          SourceLocation NameLoc) {
15887   // While the decl is in a namespace, do repeated lookup of that name and see
15888   // if we get the same namespace back.  If we do not, continue until
15889   // translation unit scope, at which point we have a fully qualified NNS.
15890   SmallVector<IdentifierInfo *, 4> Namespaces;
15891   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15892   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15893     // This tag should be declared in a namespace, which can only be enclosed by
15894     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15895     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15896     if (!Namespace || Namespace->isAnonymousNamespace())
15897       return FixItHint();
15898     IdentifierInfo *II = Namespace->getIdentifier();
15899     Namespaces.push_back(II);
15900     NamedDecl *Lookup = SemaRef.LookupSingleName(
15901         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15902     if (Lookup == Namespace)
15903       break;
15904   }
15905 
15906   // Once we have all the namespaces, reverse them to go outermost first, and
15907   // build an NNS.
15908   SmallString<64> Insertion;
15909   llvm::raw_svector_ostream OS(Insertion);
15910   if (DC->isTranslationUnit())
15911     OS << "::";
15912   std::reverse(Namespaces.begin(), Namespaces.end());
15913   for (auto *II : Namespaces)
15914     OS << II->getName() << "::";
15915   return FixItHint::CreateInsertion(NameLoc, Insertion);
15916 }
15917 
15918 /// Determine whether a tag originally declared in context \p OldDC can
15919 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15920 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15921 /// using-declaration).
15922 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15923                                          DeclContext *NewDC) {
15924   OldDC = OldDC->getRedeclContext();
15925   NewDC = NewDC->getRedeclContext();
15926 
15927   if (OldDC->Equals(NewDC))
15928     return true;
15929 
15930   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15931   // encloses the other).
15932   if (S.getLangOpts().MSVCCompat &&
15933       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15934     return true;
15935 
15936   return false;
15937 }
15938 
15939 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15940 /// former case, Name will be non-null.  In the later case, Name will be null.
15941 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15942 /// reference/declaration/definition of a tag.
15943 ///
15944 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15945 /// trailing-type-specifier) other than one in an alias-declaration.
15946 ///
15947 /// \param SkipBody If non-null, will be set to indicate if the caller should
15948 /// skip the definition of this tag and treat it as if it were a declaration.
15949 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15950                      SourceLocation KWLoc, CXXScopeSpec &SS,
15951                      IdentifierInfo *Name, SourceLocation NameLoc,
15952                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15953                      SourceLocation ModulePrivateLoc,
15954                      MultiTemplateParamsArg TemplateParameterLists,
15955                      bool &OwnedDecl, bool &IsDependent,
15956                      SourceLocation ScopedEnumKWLoc,
15957                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15958                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15959                      SkipBodyInfo *SkipBody) {
15960   // If this is not a definition, it must have a name.
15961   IdentifierInfo *OrigName = Name;
15962   assert((Name != nullptr || TUK == TUK_Definition) &&
15963          "Nameless record must be a definition!");
15964   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15965 
15966   OwnedDecl = false;
15967   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15968   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15969 
15970   // FIXME: Check member specializations more carefully.
15971   bool isMemberSpecialization = false;
15972   bool Invalid = false;
15973 
15974   // We only need to do this matching if we have template parameters
15975   // or a scope specifier, which also conveniently avoids this work
15976   // for non-C++ cases.
15977   if (TemplateParameterLists.size() > 0 ||
15978       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15979     if (TemplateParameterList *TemplateParams =
15980             MatchTemplateParametersToScopeSpecifier(
15981                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15982                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15983       if (Kind == TTK_Enum) {
15984         Diag(KWLoc, diag::err_enum_template);
15985         return nullptr;
15986       }
15987 
15988       if (TemplateParams->size() > 0) {
15989         // This is a declaration or definition of a class template (which may
15990         // be a member of another template).
15991 
15992         if (Invalid)
15993           return nullptr;
15994 
15995         OwnedDecl = false;
15996         DeclResult Result = CheckClassTemplate(
15997             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15998             AS, ModulePrivateLoc,
15999             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16000             TemplateParameterLists.data(), SkipBody);
16001         return Result.get();
16002       } else {
16003         // The "template<>" header is extraneous.
16004         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16005           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16006         isMemberSpecialization = true;
16007       }
16008     }
16009 
16010     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16011         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16012       return nullptr;
16013   }
16014 
16015   // Figure out the underlying type if this a enum declaration. We need to do
16016   // this early, because it's needed to detect if this is an incompatible
16017   // redeclaration.
16018   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16019   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16020 
16021   if (Kind == TTK_Enum) {
16022     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16023       // No underlying type explicitly specified, or we failed to parse the
16024       // type, default to int.
16025       EnumUnderlying = Context.IntTy.getTypePtr();
16026     } else if (UnderlyingType.get()) {
16027       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16028       // integral type; any cv-qualification is ignored.
16029       TypeSourceInfo *TI = nullptr;
16030       GetTypeFromParser(UnderlyingType.get(), &TI);
16031       EnumUnderlying = TI;
16032 
16033       if (CheckEnumUnderlyingType(TI))
16034         // Recover by falling back to int.
16035         EnumUnderlying = Context.IntTy.getTypePtr();
16036 
16037       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16038                                           UPPC_FixedUnderlyingType))
16039         EnumUnderlying = Context.IntTy.getTypePtr();
16040 
16041     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16042       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16043       // of 'int'. However, if this is an unfixed forward declaration, don't set
16044       // the underlying type unless the user enables -fms-compatibility. This
16045       // makes unfixed forward declared enums incomplete and is more conforming.
16046       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16047         EnumUnderlying = Context.IntTy.getTypePtr();
16048     }
16049   }
16050 
16051   DeclContext *SearchDC = CurContext;
16052   DeclContext *DC = CurContext;
16053   bool isStdBadAlloc = false;
16054   bool isStdAlignValT = false;
16055 
16056   RedeclarationKind Redecl = forRedeclarationInCurContext();
16057   if (TUK == TUK_Friend || TUK == TUK_Reference)
16058     Redecl = NotForRedeclaration;
16059 
16060   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16061   /// implemented asks for structural equivalence checking, the returned decl
16062   /// here is passed back to the parser, allowing the tag body to be parsed.
16063   auto createTagFromNewDecl = [&]() -> TagDecl * {
16064     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16065     // If there is an identifier, use the location of the identifier as the
16066     // location of the decl, otherwise use the location of the struct/union
16067     // keyword.
16068     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16069     TagDecl *New = nullptr;
16070 
16071     if (Kind == TTK_Enum) {
16072       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16073                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16074       // If this is an undefined enum, bail.
16075       if (TUK != TUK_Definition && !Invalid)
16076         return nullptr;
16077       if (EnumUnderlying) {
16078         EnumDecl *ED = cast<EnumDecl>(New);
16079         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16080           ED->setIntegerTypeSourceInfo(TI);
16081         else
16082           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16083         ED->setPromotionType(ED->getIntegerType());
16084       }
16085     } else { // struct/union
16086       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16087                                nullptr);
16088     }
16089 
16090     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16091       // Add alignment attributes if necessary; these attributes are checked
16092       // when the ASTContext lays out the structure.
16093       //
16094       // It is important for implementing the correct semantics that this
16095       // happen here (in ActOnTag). The #pragma pack stack is
16096       // maintained as a result of parser callbacks which can occur at
16097       // many points during the parsing of a struct declaration (because
16098       // the #pragma tokens are effectively skipped over during the
16099       // parsing of the struct).
16100       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16101         AddAlignmentAttributesForRecord(RD);
16102         AddMsStructLayoutForRecord(RD);
16103       }
16104     }
16105     New->setLexicalDeclContext(CurContext);
16106     return New;
16107   };
16108 
16109   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16110   if (Name && SS.isNotEmpty()) {
16111     // We have a nested-name tag ('struct foo::bar').
16112 
16113     // Check for invalid 'foo::'.
16114     if (SS.isInvalid()) {
16115       Name = nullptr;
16116       goto CreateNewDecl;
16117     }
16118 
16119     // If this is a friend or a reference to a class in a dependent
16120     // context, don't try to make a decl for it.
16121     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16122       DC = computeDeclContext(SS, false);
16123       if (!DC) {
16124         IsDependent = true;
16125         return nullptr;
16126       }
16127     } else {
16128       DC = computeDeclContext(SS, true);
16129       if (!DC) {
16130         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16131           << SS.getRange();
16132         return nullptr;
16133       }
16134     }
16135 
16136     if (RequireCompleteDeclContext(SS, DC))
16137       return nullptr;
16138 
16139     SearchDC = DC;
16140     // Look-up name inside 'foo::'.
16141     LookupQualifiedName(Previous, DC);
16142 
16143     if (Previous.isAmbiguous())
16144       return nullptr;
16145 
16146     if (Previous.empty()) {
16147       // Name lookup did not find anything. However, if the
16148       // nested-name-specifier refers to the current instantiation,
16149       // and that current instantiation has any dependent base
16150       // classes, we might find something at instantiation time: treat
16151       // this as a dependent elaborated-type-specifier.
16152       // But this only makes any sense for reference-like lookups.
16153       if (Previous.wasNotFoundInCurrentInstantiation() &&
16154           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16155         IsDependent = true;
16156         return nullptr;
16157       }
16158 
16159       // A tag 'foo::bar' must already exist.
16160       Diag(NameLoc, diag::err_not_tag_in_scope)
16161         << Kind << Name << DC << SS.getRange();
16162       Name = nullptr;
16163       Invalid = true;
16164       goto CreateNewDecl;
16165     }
16166   } else if (Name) {
16167     // C++14 [class.mem]p14:
16168     //   If T is the name of a class, then each of the following shall have a
16169     //   name different from T:
16170     //    -- every member of class T that is itself a type
16171     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16172         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16173       return nullptr;
16174 
16175     // If this is a named struct, check to see if there was a previous forward
16176     // declaration or definition.
16177     // FIXME: We're looking into outer scopes here, even when we
16178     // shouldn't be. Doing so can result in ambiguities that we
16179     // shouldn't be diagnosing.
16180     LookupName(Previous, S);
16181 
16182     // When declaring or defining a tag, ignore ambiguities introduced
16183     // by types using'ed into this scope.
16184     if (Previous.isAmbiguous() &&
16185         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16186       LookupResult::Filter F = Previous.makeFilter();
16187       while (F.hasNext()) {
16188         NamedDecl *ND = F.next();
16189         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16190                 SearchDC->getRedeclContext()))
16191           F.erase();
16192       }
16193       F.done();
16194     }
16195 
16196     // C++11 [namespace.memdef]p3:
16197     //   If the name in a friend declaration is neither qualified nor
16198     //   a template-id and the declaration is a function or an
16199     //   elaborated-type-specifier, the lookup to determine whether
16200     //   the entity has been previously declared shall not consider
16201     //   any scopes outside the innermost enclosing namespace.
16202     //
16203     // MSVC doesn't implement the above rule for types, so a friend tag
16204     // declaration may be a redeclaration of a type declared in an enclosing
16205     // scope.  They do implement this rule for friend functions.
16206     //
16207     // Does it matter that this should be by scope instead of by
16208     // semantic context?
16209     if (!Previous.empty() && TUK == TUK_Friend) {
16210       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16211       LookupResult::Filter F = Previous.makeFilter();
16212       bool FriendSawTagOutsideEnclosingNamespace = false;
16213       while (F.hasNext()) {
16214         NamedDecl *ND = F.next();
16215         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16216         if (DC->isFileContext() &&
16217             !EnclosingNS->Encloses(ND->getDeclContext())) {
16218           if (getLangOpts().MSVCCompat)
16219             FriendSawTagOutsideEnclosingNamespace = true;
16220           else
16221             F.erase();
16222         }
16223       }
16224       F.done();
16225 
16226       // Diagnose this MSVC extension in the easy case where lookup would have
16227       // unambiguously found something outside the enclosing namespace.
16228       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16229         NamedDecl *ND = Previous.getFoundDecl();
16230         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16231             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16232       }
16233     }
16234 
16235     // Note:  there used to be some attempt at recovery here.
16236     if (Previous.isAmbiguous())
16237       return nullptr;
16238 
16239     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16240       // FIXME: This makes sure that we ignore the contexts associated
16241       // with C structs, unions, and enums when looking for a matching
16242       // tag declaration or definition. See the similar lookup tweak
16243       // in Sema::LookupName; is there a better way to deal with this?
16244       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16245         SearchDC = SearchDC->getParent();
16246     } else if (getLangOpts().CPlusPlus) {
16247       // Inside ObjCContainer want to keep it as a lexical decl context but go
16248       // past it (most often to TranslationUnit) to find the semantic decl
16249       // context.
16250       while (isa<ObjCContainerDecl>(SearchDC))
16251         SearchDC = SearchDC->getParent();
16252     }
16253   } else if (getLangOpts().CPlusPlus) {
16254     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16255     // TagDecl the same way as we skip it for named TagDecl.
16256     while (isa<ObjCContainerDecl>(SearchDC))
16257       SearchDC = SearchDC->getParent();
16258   }
16259 
16260   if (Previous.isSingleResult() &&
16261       Previous.getFoundDecl()->isTemplateParameter()) {
16262     // Maybe we will complain about the shadowed template parameter.
16263     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16264     // Just pretend that we didn't see the previous declaration.
16265     Previous.clear();
16266   }
16267 
16268   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16269       DC->Equals(getStdNamespace())) {
16270     if (Name->isStr("bad_alloc")) {
16271       // This is a declaration of or a reference to "std::bad_alloc".
16272       isStdBadAlloc = true;
16273 
16274       // If std::bad_alloc has been implicitly declared (but made invisible to
16275       // name lookup), fill in this implicit declaration as the previous
16276       // declaration, so that the declarations get chained appropriately.
16277       if (Previous.empty() && StdBadAlloc)
16278         Previous.addDecl(getStdBadAlloc());
16279     } else if (Name->isStr("align_val_t")) {
16280       isStdAlignValT = true;
16281       if (Previous.empty() && StdAlignValT)
16282         Previous.addDecl(getStdAlignValT());
16283     }
16284   }
16285 
16286   // If we didn't find a previous declaration, and this is a reference
16287   // (or friend reference), move to the correct scope.  In C++, we
16288   // also need to do a redeclaration lookup there, just in case
16289   // there's a shadow friend decl.
16290   if (Name && Previous.empty() &&
16291       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16292     if (Invalid) goto CreateNewDecl;
16293     assert(SS.isEmpty());
16294 
16295     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16296       // C++ [basic.scope.pdecl]p5:
16297       //   -- for an elaborated-type-specifier of the form
16298       //
16299       //          class-key identifier
16300       //
16301       //      if the elaborated-type-specifier is used in the
16302       //      decl-specifier-seq or parameter-declaration-clause of a
16303       //      function defined in namespace scope, the identifier is
16304       //      declared as a class-name in the namespace that contains
16305       //      the declaration; otherwise, except as a friend
16306       //      declaration, the identifier is declared in the smallest
16307       //      non-class, non-function-prototype scope that contains the
16308       //      declaration.
16309       //
16310       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16311       // C structs and unions.
16312       //
16313       // It is an error in C++ to declare (rather than define) an enum
16314       // type, including via an elaborated type specifier.  We'll
16315       // diagnose that later; for now, declare the enum in the same
16316       // scope as we would have picked for any other tag type.
16317       //
16318       // GNU C also supports this behavior as part of its incomplete
16319       // enum types extension, while GNU C++ does not.
16320       //
16321       // Find the context where we'll be declaring the tag.
16322       // FIXME: We would like to maintain the current DeclContext as the
16323       // lexical context,
16324       SearchDC = getTagInjectionContext(SearchDC);
16325 
16326       // Find the scope where we'll be declaring the tag.
16327       S = getTagInjectionScope(S, getLangOpts());
16328     } else {
16329       assert(TUK == TUK_Friend);
16330       // C++ [namespace.memdef]p3:
16331       //   If a friend declaration in a non-local class first declares a
16332       //   class or function, the friend class or function is a member of
16333       //   the innermost enclosing namespace.
16334       SearchDC = SearchDC->getEnclosingNamespaceContext();
16335     }
16336 
16337     // In C++, we need to do a redeclaration lookup to properly
16338     // diagnose some problems.
16339     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16340     // hidden declaration so that we don't get ambiguity errors when using a
16341     // type declared by an elaborated-type-specifier.  In C that is not correct
16342     // and we should instead merge compatible types found by lookup.
16343     if (getLangOpts().CPlusPlus) {
16344       // FIXME: This can perform qualified lookups into function contexts,
16345       // which are meaningless.
16346       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16347       LookupQualifiedName(Previous, SearchDC);
16348     } else {
16349       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16350       LookupName(Previous, S);
16351     }
16352   }
16353 
16354   // If we have a known previous declaration to use, then use it.
16355   if (Previous.empty() && SkipBody && SkipBody->Previous)
16356     Previous.addDecl(SkipBody->Previous);
16357 
16358   if (!Previous.empty()) {
16359     NamedDecl *PrevDecl = Previous.getFoundDecl();
16360     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16361 
16362     // It's okay to have a tag decl in the same scope as a typedef
16363     // which hides a tag decl in the same scope.  Finding this
16364     // with a redeclaration lookup can only actually happen in C++.
16365     //
16366     // This is also okay for elaborated-type-specifiers, which is
16367     // technically forbidden by the current standard but which is
16368     // okay according to the likely resolution of an open issue;
16369     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16370     if (getLangOpts().CPlusPlus) {
16371       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16372         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16373           TagDecl *Tag = TT->getDecl();
16374           if (Tag->getDeclName() == Name &&
16375               Tag->getDeclContext()->getRedeclContext()
16376                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16377             PrevDecl = Tag;
16378             Previous.clear();
16379             Previous.addDecl(Tag);
16380             Previous.resolveKind();
16381           }
16382         }
16383       }
16384     }
16385 
16386     // If this is a redeclaration of a using shadow declaration, it must
16387     // declare a tag in the same context. In MSVC mode, we allow a
16388     // redefinition if either context is within the other.
16389     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16390       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16391       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16392           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16393           !(OldTag && isAcceptableTagRedeclContext(
16394                           *this, OldTag->getDeclContext(), SearchDC))) {
16395         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16396         Diag(Shadow->getTargetDecl()->getLocation(),
16397              diag::note_using_decl_target);
16398         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16399             << 0;
16400         // Recover by ignoring the old declaration.
16401         Previous.clear();
16402         goto CreateNewDecl;
16403       }
16404     }
16405 
16406     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16407       // If this is a use of a previous tag, or if the tag is already declared
16408       // in the same scope (so that the definition/declaration completes or
16409       // rementions the tag), reuse the decl.
16410       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16411           isDeclInScope(DirectPrevDecl, SearchDC, S,
16412                         SS.isNotEmpty() || isMemberSpecialization)) {
16413         // Make sure that this wasn't declared as an enum and now used as a
16414         // struct or something similar.
16415         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16416                                           TUK == TUK_Definition, KWLoc,
16417                                           Name)) {
16418           bool SafeToContinue
16419             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16420                Kind != TTK_Enum);
16421           if (SafeToContinue)
16422             Diag(KWLoc, diag::err_use_with_wrong_tag)
16423               << Name
16424               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16425                                               PrevTagDecl->getKindName());
16426           else
16427             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16428           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16429 
16430           if (SafeToContinue)
16431             Kind = PrevTagDecl->getTagKind();
16432           else {
16433             // Recover by making this an anonymous redefinition.
16434             Name = nullptr;
16435             Previous.clear();
16436             Invalid = true;
16437           }
16438         }
16439 
16440         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16441           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16442           if (TUK == TUK_Reference || TUK == TUK_Friend)
16443             return PrevTagDecl;
16444 
16445           QualType EnumUnderlyingTy;
16446           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16447             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16448           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16449             EnumUnderlyingTy = QualType(T, 0);
16450 
16451           // All conflicts with previous declarations are recovered by
16452           // returning the previous declaration, unless this is a definition,
16453           // in which case we want the caller to bail out.
16454           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16455                                      ScopedEnum, EnumUnderlyingTy,
16456                                      IsFixed, PrevEnum))
16457             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16458         }
16459 
16460         // C++11 [class.mem]p1:
16461         //   A member shall not be declared twice in the member-specification,
16462         //   except that a nested class or member class template can be declared
16463         //   and then later defined.
16464         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16465             S->isDeclScope(PrevDecl)) {
16466           Diag(NameLoc, diag::ext_member_redeclared);
16467           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16468         }
16469 
16470         if (!Invalid) {
16471           // If this is a use, just return the declaration we found, unless
16472           // we have attributes.
16473           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16474             if (!Attrs.empty()) {
16475               // FIXME: Diagnose these attributes. For now, we create a new
16476               // declaration to hold them.
16477             } else if (TUK == TUK_Reference &&
16478                        (PrevTagDecl->getFriendObjectKind() ==
16479                             Decl::FOK_Undeclared ||
16480                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16481                        SS.isEmpty()) {
16482               // This declaration is a reference to an existing entity, but
16483               // has different visibility from that entity: it either makes
16484               // a friend visible or it makes a type visible in a new module.
16485               // In either case, create a new declaration. We only do this if
16486               // the declaration would have meant the same thing if no prior
16487               // declaration were found, that is, if it was found in the same
16488               // scope where we would have injected a declaration.
16489               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16490                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16491                 return PrevTagDecl;
16492               // This is in the injected scope, create a new declaration in
16493               // that scope.
16494               S = getTagInjectionScope(S, getLangOpts());
16495             } else {
16496               return PrevTagDecl;
16497             }
16498           }
16499 
16500           // Diagnose attempts to redefine a tag.
16501           if (TUK == TUK_Definition) {
16502             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16503               // If we're defining a specialization and the previous definition
16504               // is from an implicit instantiation, don't emit an error
16505               // here; we'll catch this in the general case below.
16506               bool IsExplicitSpecializationAfterInstantiation = false;
16507               if (isMemberSpecialization) {
16508                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16509                   IsExplicitSpecializationAfterInstantiation =
16510                     RD->getTemplateSpecializationKind() !=
16511                     TSK_ExplicitSpecialization;
16512                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16513                   IsExplicitSpecializationAfterInstantiation =
16514                     ED->getTemplateSpecializationKind() !=
16515                     TSK_ExplicitSpecialization;
16516               }
16517 
16518               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16519               // not keep more that one definition around (merge them). However,
16520               // ensure the decl passes the structural compatibility check in
16521               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16522               NamedDecl *Hidden = nullptr;
16523               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16524                 // There is a definition of this tag, but it is not visible. We
16525                 // explicitly make use of C++'s one definition rule here, and
16526                 // assume that this definition is identical to the hidden one
16527                 // we already have. Make the existing definition visible and
16528                 // use it in place of this one.
16529                 if (!getLangOpts().CPlusPlus) {
16530                   // Postpone making the old definition visible until after we
16531                   // complete parsing the new one and do the structural
16532                   // comparison.
16533                   SkipBody->CheckSameAsPrevious = true;
16534                   SkipBody->New = createTagFromNewDecl();
16535                   SkipBody->Previous = Def;
16536                   return Def;
16537                 } else {
16538                   SkipBody->ShouldSkip = true;
16539                   SkipBody->Previous = Def;
16540                   makeMergedDefinitionVisible(Hidden);
16541                   // Carry on and handle it like a normal definition. We'll
16542                   // skip starting the definitiion later.
16543                 }
16544               } else if (!IsExplicitSpecializationAfterInstantiation) {
16545                 // A redeclaration in function prototype scope in C isn't
16546                 // visible elsewhere, so merely issue a warning.
16547                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16548                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16549                 else
16550                   Diag(NameLoc, diag::err_redefinition) << Name;
16551                 notePreviousDefinition(Def,
16552                                        NameLoc.isValid() ? NameLoc : KWLoc);
16553                 // If this is a redefinition, recover by making this
16554                 // struct be anonymous, which will make any later
16555                 // references get the previous definition.
16556                 Name = nullptr;
16557                 Previous.clear();
16558                 Invalid = true;
16559               }
16560             } else {
16561               // If the type is currently being defined, complain
16562               // about a nested redefinition.
16563               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16564               if (TD->isBeingDefined()) {
16565                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16566                 Diag(PrevTagDecl->getLocation(),
16567                      diag::note_previous_definition);
16568                 Name = nullptr;
16569                 Previous.clear();
16570                 Invalid = true;
16571               }
16572             }
16573 
16574             // Okay, this is definition of a previously declared or referenced
16575             // tag. We're going to create a new Decl for it.
16576           }
16577 
16578           // Okay, we're going to make a redeclaration.  If this is some kind
16579           // of reference, make sure we build the redeclaration in the same DC
16580           // as the original, and ignore the current access specifier.
16581           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16582             SearchDC = PrevTagDecl->getDeclContext();
16583             AS = AS_none;
16584           }
16585         }
16586         // If we get here we have (another) forward declaration or we
16587         // have a definition.  Just create a new decl.
16588 
16589       } else {
16590         // If we get here, this is a definition of a new tag type in a nested
16591         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16592         // new decl/type.  We set PrevDecl to NULL so that the entities
16593         // have distinct types.
16594         Previous.clear();
16595       }
16596       // If we get here, we're going to create a new Decl. If PrevDecl
16597       // is non-NULL, it's a definition of the tag declared by
16598       // PrevDecl. If it's NULL, we have a new definition.
16599 
16600     // Otherwise, PrevDecl is not a tag, but was found with tag
16601     // lookup.  This is only actually possible in C++, where a few
16602     // things like templates still live in the tag namespace.
16603     } else {
16604       // Use a better diagnostic if an elaborated-type-specifier
16605       // found the wrong kind of type on the first
16606       // (non-redeclaration) lookup.
16607       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16608           !Previous.isForRedeclaration()) {
16609         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16610         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16611                                                        << Kind;
16612         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16613         Invalid = true;
16614 
16615       // Otherwise, only diagnose if the declaration is in scope.
16616       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16617                                 SS.isNotEmpty() || isMemberSpecialization)) {
16618         // do nothing
16619 
16620       // Diagnose implicit declarations introduced by elaborated types.
16621       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16622         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16623         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16624         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16625         Invalid = true;
16626 
16627       // Otherwise it's a declaration.  Call out a particularly common
16628       // case here.
16629       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16630         unsigned Kind = 0;
16631         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16632         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16633           << Name << Kind << TND->getUnderlyingType();
16634         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16635         Invalid = true;
16636 
16637       // Otherwise, diagnose.
16638       } else {
16639         // The tag name clashes with something else in the target scope,
16640         // issue an error and recover by making this tag be anonymous.
16641         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16642         notePreviousDefinition(PrevDecl, NameLoc);
16643         Name = nullptr;
16644         Invalid = true;
16645       }
16646 
16647       // The existing declaration isn't relevant to us; we're in a
16648       // new scope, so clear out the previous declaration.
16649       Previous.clear();
16650     }
16651   }
16652 
16653 CreateNewDecl:
16654 
16655   TagDecl *PrevDecl = nullptr;
16656   if (Previous.isSingleResult())
16657     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16658 
16659   // If there is an identifier, use the location of the identifier as the
16660   // location of the decl, otherwise use the location of the struct/union
16661   // keyword.
16662   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16663 
16664   // Otherwise, create a new declaration. If there is a previous
16665   // declaration of the same entity, the two will be linked via
16666   // PrevDecl.
16667   TagDecl *New;
16668 
16669   if (Kind == TTK_Enum) {
16670     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16671     // enum X { A, B, C } D;    D should chain to X.
16672     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16673                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16674                            ScopedEnumUsesClassTag, IsFixed);
16675 
16676     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16677       StdAlignValT = cast<EnumDecl>(New);
16678 
16679     // If this is an undefined enum, warn.
16680     if (TUK != TUK_Definition && !Invalid) {
16681       TagDecl *Def;
16682       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16683         // C++0x: 7.2p2: opaque-enum-declaration.
16684         // Conflicts are diagnosed above. Do nothing.
16685       }
16686       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16687         Diag(Loc, diag::ext_forward_ref_enum_def)
16688           << New;
16689         Diag(Def->getLocation(), diag::note_previous_definition);
16690       } else {
16691         unsigned DiagID = diag::ext_forward_ref_enum;
16692         if (getLangOpts().MSVCCompat)
16693           DiagID = diag::ext_ms_forward_ref_enum;
16694         else if (getLangOpts().CPlusPlus)
16695           DiagID = diag::err_forward_ref_enum;
16696         Diag(Loc, DiagID);
16697       }
16698     }
16699 
16700     if (EnumUnderlying) {
16701       EnumDecl *ED = cast<EnumDecl>(New);
16702       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16703         ED->setIntegerTypeSourceInfo(TI);
16704       else
16705         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16706       ED->setPromotionType(ED->getIntegerType());
16707       assert(ED->isComplete() && "enum with type should be complete");
16708     }
16709   } else {
16710     // struct/union/class
16711 
16712     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16713     // struct X { int A; } D;    D should chain to X.
16714     if (getLangOpts().CPlusPlus) {
16715       // FIXME: Look for a way to use RecordDecl for simple structs.
16716       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16717                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16718 
16719       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16720         StdBadAlloc = cast<CXXRecordDecl>(New);
16721     } else
16722       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16723                                cast_or_null<RecordDecl>(PrevDecl));
16724   }
16725 
16726   // C++11 [dcl.type]p3:
16727   //   A type-specifier-seq shall not define a class or enumeration [...].
16728   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16729       TUK == TUK_Definition) {
16730     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16731       << Context.getTagDeclType(New);
16732     Invalid = true;
16733   }
16734 
16735   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16736       DC->getDeclKind() == Decl::Enum) {
16737     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16738       << Context.getTagDeclType(New);
16739     Invalid = true;
16740   }
16741 
16742   // Maybe add qualifier info.
16743   if (SS.isNotEmpty()) {
16744     if (SS.isSet()) {
16745       // If this is either a declaration or a definition, check the
16746       // nested-name-specifier against the current context.
16747       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16748           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16749                                        isMemberSpecialization))
16750         Invalid = true;
16751 
16752       New->setQualifierInfo(SS.getWithLocInContext(Context));
16753       if (TemplateParameterLists.size() > 0) {
16754         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16755       }
16756     }
16757     else
16758       Invalid = true;
16759   }
16760 
16761   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16762     // Add alignment attributes if necessary; these attributes are checked when
16763     // the ASTContext lays out the structure.
16764     //
16765     // It is important for implementing the correct semantics that this
16766     // happen here (in ActOnTag). The #pragma pack stack is
16767     // maintained as a result of parser callbacks which can occur at
16768     // many points during the parsing of a struct declaration (because
16769     // the #pragma tokens are effectively skipped over during the
16770     // parsing of the struct).
16771     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16772       AddAlignmentAttributesForRecord(RD);
16773       AddMsStructLayoutForRecord(RD);
16774     }
16775   }
16776 
16777   if (ModulePrivateLoc.isValid()) {
16778     if (isMemberSpecialization)
16779       Diag(New->getLocation(), diag::err_module_private_specialization)
16780         << 2
16781         << FixItHint::CreateRemoval(ModulePrivateLoc);
16782     // __module_private__ does not apply to local classes. However, we only
16783     // diagnose this as an error when the declaration specifiers are
16784     // freestanding. Here, we just ignore the __module_private__.
16785     else if (!SearchDC->isFunctionOrMethod())
16786       New->setModulePrivate();
16787   }
16788 
16789   // If this is a specialization of a member class (of a class template),
16790   // check the specialization.
16791   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16792     Invalid = true;
16793 
16794   // If we're declaring or defining a tag in function prototype scope in C,
16795   // note that this type can only be used within the function and add it to
16796   // the list of decls to inject into the function definition scope.
16797   if ((Name || Kind == TTK_Enum) &&
16798       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16799     if (getLangOpts().CPlusPlus) {
16800       // C++ [dcl.fct]p6:
16801       //   Types shall not be defined in return or parameter types.
16802       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16803         Diag(Loc, diag::err_type_defined_in_param_type)
16804             << Name;
16805         Invalid = true;
16806       }
16807     } else if (!PrevDecl) {
16808       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16809     }
16810   }
16811 
16812   if (Invalid)
16813     New->setInvalidDecl();
16814 
16815   // Set the lexical context. If the tag has a C++ scope specifier, the
16816   // lexical context will be different from the semantic context.
16817   New->setLexicalDeclContext(CurContext);
16818 
16819   // Mark this as a friend decl if applicable.
16820   // In Microsoft mode, a friend declaration also acts as a forward
16821   // declaration so we always pass true to setObjectOfFriendDecl to make
16822   // the tag name visible.
16823   if (TUK == TUK_Friend)
16824     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16825 
16826   // Set the access specifier.
16827   if (!Invalid && SearchDC->isRecord())
16828     SetMemberAccessSpecifier(New, PrevDecl, AS);
16829 
16830   if (PrevDecl)
16831     CheckRedeclarationInModule(New, PrevDecl);
16832 
16833   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16834     New->startDefinition();
16835 
16836   ProcessDeclAttributeList(S, New, Attrs);
16837   AddPragmaAttributes(S, New);
16838 
16839   // If this has an identifier, add it to the scope stack.
16840   if (TUK == TUK_Friend) {
16841     // We might be replacing an existing declaration in the lookup tables;
16842     // if so, borrow its access specifier.
16843     if (PrevDecl)
16844       New->setAccess(PrevDecl->getAccess());
16845 
16846     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16847     DC->makeDeclVisibleInContext(New);
16848     if (Name) // can be null along some error paths
16849       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16850         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16851   } else if (Name) {
16852     S = getNonFieldDeclScope(S);
16853     PushOnScopeChains(New, S, true);
16854   } else {
16855     CurContext->addDecl(New);
16856   }
16857 
16858   // If this is the C FILE type, notify the AST context.
16859   if (IdentifierInfo *II = New->getIdentifier())
16860     if (!New->isInvalidDecl() &&
16861         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16862         II->isStr("FILE"))
16863       Context.setFILEDecl(New);
16864 
16865   if (PrevDecl)
16866     mergeDeclAttributes(New, PrevDecl);
16867 
16868   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16869     inferGslOwnerPointerAttribute(CXXRD);
16870 
16871   // If there's a #pragma GCC visibility in scope, set the visibility of this
16872   // record.
16873   AddPushedVisibilityAttribute(New);
16874 
16875   if (isMemberSpecialization && !New->isInvalidDecl())
16876     CompleteMemberSpecialization(New, Previous);
16877 
16878   OwnedDecl = true;
16879   // In C++, don't return an invalid declaration. We can't recover well from
16880   // the cases where we make the type anonymous.
16881   if (Invalid && getLangOpts().CPlusPlus) {
16882     if (New->isBeingDefined())
16883       if (auto RD = dyn_cast<RecordDecl>(New))
16884         RD->completeDefinition();
16885     return nullptr;
16886   } else if (SkipBody && SkipBody->ShouldSkip) {
16887     return SkipBody->Previous;
16888   } else {
16889     return New;
16890   }
16891 }
16892 
16893 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16894   AdjustDeclIfTemplate(TagD);
16895   TagDecl *Tag = cast<TagDecl>(TagD);
16896 
16897   // Enter the tag context.
16898   PushDeclContext(S, Tag);
16899 
16900   ActOnDocumentableDecl(TagD);
16901 
16902   // If there's a #pragma GCC visibility in scope, set the visibility of this
16903   // record.
16904   AddPushedVisibilityAttribute(Tag);
16905 }
16906 
16907 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16908   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16909     return false;
16910 
16911   // Make the previous decl visible.
16912   makeMergedDefinitionVisible(SkipBody.Previous);
16913   return true;
16914 }
16915 
16916 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16917   assert(isa<ObjCContainerDecl>(IDecl) &&
16918          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16919   DeclContext *OCD = cast<DeclContext>(IDecl);
16920   assert(OCD->getLexicalParent() == CurContext &&
16921       "The next DeclContext should be lexically contained in the current one.");
16922   CurContext = OCD;
16923   return IDecl;
16924 }
16925 
16926 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16927                                            SourceLocation FinalLoc,
16928                                            bool IsFinalSpelledSealed,
16929                                            bool IsAbstract,
16930                                            SourceLocation LBraceLoc) {
16931   AdjustDeclIfTemplate(TagD);
16932   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16933 
16934   FieldCollector->StartClass();
16935 
16936   if (!Record->getIdentifier())
16937     return;
16938 
16939   if (IsAbstract)
16940     Record->markAbstract();
16941 
16942   if (FinalLoc.isValid()) {
16943     Record->addAttr(FinalAttr::Create(
16944         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16945         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16946   }
16947   // C++ [class]p2:
16948   //   [...] The class-name is also inserted into the scope of the
16949   //   class itself; this is known as the injected-class-name. For
16950   //   purposes of access checking, the injected-class-name is treated
16951   //   as if it were a public member name.
16952   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16953       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16954       Record->getLocation(), Record->getIdentifier(),
16955       /*PrevDecl=*/nullptr,
16956       /*DelayTypeCreation=*/true);
16957   Context.getTypeDeclType(InjectedClassName, Record);
16958   InjectedClassName->setImplicit();
16959   InjectedClassName->setAccess(AS_public);
16960   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16961       InjectedClassName->setDescribedClassTemplate(Template);
16962   PushOnScopeChains(InjectedClassName, S);
16963   assert(InjectedClassName->isInjectedClassName() &&
16964          "Broken injected-class-name");
16965 }
16966 
16967 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16968                                     SourceRange BraceRange) {
16969   AdjustDeclIfTemplate(TagD);
16970   TagDecl *Tag = cast<TagDecl>(TagD);
16971   Tag->setBraceRange(BraceRange);
16972 
16973   // Make sure we "complete" the definition even it is invalid.
16974   if (Tag->isBeingDefined()) {
16975     assert(Tag->isInvalidDecl() && "We should already have completed it");
16976     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16977       RD->completeDefinition();
16978   }
16979 
16980   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16981     FieldCollector->FinishClass();
16982     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16983       auto *Def = RD->getDefinition();
16984       assert(Def && "The record is expected to have a completed definition");
16985       unsigned NumInitMethods = 0;
16986       for (auto *Method : Def->methods()) {
16987         if (!Method->getIdentifier())
16988             continue;
16989         if (Method->getName() == "__init")
16990           NumInitMethods++;
16991       }
16992       if (NumInitMethods > 1 || !Def->hasInitMethod())
16993         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16994     }
16995   }
16996 
16997   // Exit this scope of this tag's definition.
16998   PopDeclContext();
16999 
17000   if (getCurLexicalContext()->isObjCContainer() &&
17001       Tag->getDeclContext()->isFileContext())
17002     Tag->setTopLevelDeclInObjCContainer();
17003 
17004   // Notify the consumer that we've defined a tag.
17005   if (!Tag->isInvalidDecl())
17006     Consumer.HandleTagDeclDefinition(Tag);
17007 
17008   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17009   // from XLs and instead matches the XL #pragma pack(1) behavior.
17010   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17011       AlignPackStack.hasValue()) {
17012     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17013     // Only diagnose #pragma align(packed).
17014     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17015       return;
17016     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17017     if (!RD)
17018       return;
17019     // Only warn if there is at least 1 bitfield member.
17020     if (llvm::any_of(RD->fields(),
17021                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17022       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17023   }
17024 }
17025 
17026 void Sema::ActOnObjCContainerFinishDefinition() {
17027   // Exit this scope of this interface definition.
17028   PopDeclContext();
17029 }
17030 
17031 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
17032   assert(DC == CurContext && "Mismatch of container contexts");
17033   OriginalLexicalContext = DC;
17034   ActOnObjCContainerFinishDefinition();
17035 }
17036 
17037 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
17038   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
17039   OriginalLexicalContext = nullptr;
17040 }
17041 
17042 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17043   AdjustDeclIfTemplate(TagD);
17044   TagDecl *Tag = cast<TagDecl>(TagD);
17045   Tag->setInvalidDecl();
17046 
17047   // Make sure we "complete" the definition even it is invalid.
17048   if (Tag->isBeingDefined()) {
17049     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17050       RD->completeDefinition();
17051   }
17052 
17053   // We're undoing ActOnTagStartDefinition here, not
17054   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17055   // the FieldCollector.
17056 
17057   PopDeclContext();
17058 }
17059 
17060 // Note that FieldName may be null for anonymous bitfields.
17061 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17062                                 IdentifierInfo *FieldName,
17063                                 QualType FieldTy, bool IsMsStruct,
17064                                 Expr *BitWidth, bool *ZeroWidth) {
17065   assert(BitWidth);
17066   if (BitWidth->containsErrors())
17067     return ExprError();
17068 
17069   // Default to true; that shouldn't confuse checks for emptiness
17070   if (ZeroWidth)
17071     *ZeroWidth = true;
17072 
17073   // C99 6.7.2.1p4 - verify the field type.
17074   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17075   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17076     // Handle incomplete and sizeless types with a specific error.
17077     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17078                                  diag::err_field_incomplete_or_sizeless))
17079       return ExprError();
17080     if (FieldName)
17081       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17082         << FieldName << FieldTy << BitWidth->getSourceRange();
17083     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17084       << FieldTy << BitWidth->getSourceRange();
17085   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17086                                              UPPC_BitFieldWidth))
17087     return ExprError();
17088 
17089   // If the bit-width is type- or value-dependent, don't try to check
17090   // it now.
17091   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17092     return BitWidth;
17093 
17094   llvm::APSInt Value;
17095   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17096   if (ICE.isInvalid())
17097     return ICE;
17098   BitWidth = ICE.get();
17099 
17100   if (Value != 0 && ZeroWidth)
17101     *ZeroWidth = false;
17102 
17103   // Zero-width bitfield is ok for anonymous field.
17104   if (Value == 0 && FieldName)
17105     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17106 
17107   if (Value.isSigned() && Value.isNegative()) {
17108     if (FieldName)
17109       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17110                << FieldName << toString(Value, 10);
17111     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17112       << toString(Value, 10);
17113   }
17114 
17115   // The size of the bit-field must not exceed our maximum permitted object
17116   // size.
17117   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17118     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17119            << !FieldName << FieldName << toString(Value, 10);
17120   }
17121 
17122   if (!FieldTy->isDependentType()) {
17123     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17124     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17125     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17126 
17127     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17128     // ABI.
17129     bool CStdConstraintViolation =
17130         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17131     bool MSBitfieldViolation =
17132         Value.ugt(TypeStorageSize) &&
17133         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17134     if (CStdConstraintViolation || MSBitfieldViolation) {
17135       unsigned DiagWidth =
17136           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17137       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17138              << (bool)FieldName << FieldName << toString(Value, 10)
17139              << !CStdConstraintViolation << DiagWidth;
17140     }
17141 
17142     // Warn on types where the user might conceivably expect to get all
17143     // specified bits as value bits: that's all integral types other than
17144     // 'bool'.
17145     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17146       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17147           << FieldName << toString(Value, 10)
17148           << (unsigned)TypeWidth;
17149     }
17150   }
17151 
17152   return BitWidth;
17153 }
17154 
17155 /// ActOnField - Each field of a C struct/union is passed into this in order
17156 /// to create a FieldDecl object for it.
17157 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17158                        Declarator &D, Expr *BitfieldWidth) {
17159   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17160                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17161                                /*InitStyle=*/ICIS_NoInit, AS_public);
17162   return Res;
17163 }
17164 
17165 /// HandleField - Analyze a field of a C struct or a C++ data member.
17166 ///
17167 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17168                              SourceLocation DeclStart,
17169                              Declarator &D, Expr *BitWidth,
17170                              InClassInitStyle InitStyle,
17171                              AccessSpecifier AS) {
17172   if (D.isDecompositionDeclarator()) {
17173     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17174     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17175       << Decomp.getSourceRange();
17176     return nullptr;
17177   }
17178 
17179   IdentifierInfo *II = D.getIdentifier();
17180   SourceLocation Loc = DeclStart;
17181   if (II) Loc = D.getIdentifierLoc();
17182 
17183   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17184   QualType T = TInfo->getType();
17185   if (getLangOpts().CPlusPlus) {
17186     CheckExtraCXXDefaultArguments(D);
17187 
17188     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17189                                         UPPC_DataMemberType)) {
17190       D.setInvalidType();
17191       T = Context.IntTy;
17192       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17193     }
17194   }
17195 
17196   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17197 
17198   if (D.getDeclSpec().isInlineSpecified())
17199     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17200         << getLangOpts().CPlusPlus17;
17201   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17202     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17203          diag::err_invalid_thread)
17204       << DeclSpec::getSpecifierName(TSCS);
17205 
17206   // Check to see if this name was declared as a member previously
17207   NamedDecl *PrevDecl = nullptr;
17208   LookupResult Previous(*this, II, Loc, LookupMemberName,
17209                         ForVisibleRedeclaration);
17210   LookupName(Previous, S);
17211   switch (Previous.getResultKind()) {
17212     case LookupResult::Found:
17213     case LookupResult::FoundUnresolvedValue:
17214       PrevDecl = Previous.getAsSingle<NamedDecl>();
17215       break;
17216 
17217     case LookupResult::FoundOverloaded:
17218       PrevDecl = Previous.getRepresentativeDecl();
17219       break;
17220 
17221     case LookupResult::NotFound:
17222     case LookupResult::NotFoundInCurrentInstantiation:
17223     case LookupResult::Ambiguous:
17224       break;
17225   }
17226   Previous.suppressDiagnostics();
17227 
17228   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17229     // Maybe we will complain about the shadowed template parameter.
17230     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17231     // Just pretend that we didn't see the previous declaration.
17232     PrevDecl = nullptr;
17233   }
17234 
17235   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17236     PrevDecl = nullptr;
17237 
17238   bool Mutable
17239     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17240   SourceLocation TSSL = D.getBeginLoc();
17241   FieldDecl *NewFD
17242     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17243                      TSSL, AS, PrevDecl, &D);
17244 
17245   if (NewFD->isInvalidDecl())
17246     Record->setInvalidDecl();
17247 
17248   if (D.getDeclSpec().isModulePrivateSpecified())
17249     NewFD->setModulePrivate();
17250 
17251   if (NewFD->isInvalidDecl() && PrevDecl) {
17252     // Don't introduce NewFD into scope; there's already something
17253     // with the same name in the same scope.
17254   } else if (II) {
17255     PushOnScopeChains(NewFD, S);
17256   } else
17257     Record->addDecl(NewFD);
17258 
17259   return NewFD;
17260 }
17261 
17262 /// Build a new FieldDecl and check its well-formedness.
17263 ///
17264 /// This routine builds a new FieldDecl given the fields name, type,
17265 /// record, etc. \p PrevDecl should refer to any previous declaration
17266 /// with the same name and in the same scope as the field to be
17267 /// created.
17268 ///
17269 /// \returns a new FieldDecl.
17270 ///
17271 /// \todo The Declarator argument is a hack. It will be removed once
17272 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17273                                 TypeSourceInfo *TInfo,
17274                                 RecordDecl *Record, SourceLocation Loc,
17275                                 bool Mutable, Expr *BitWidth,
17276                                 InClassInitStyle InitStyle,
17277                                 SourceLocation TSSL,
17278                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17279                                 Declarator *D) {
17280   IdentifierInfo *II = Name.getAsIdentifierInfo();
17281   bool InvalidDecl = false;
17282   if (D) InvalidDecl = D->isInvalidType();
17283 
17284   // If we receive a broken type, recover by assuming 'int' and
17285   // marking this declaration as invalid.
17286   if (T.isNull() || T->containsErrors()) {
17287     InvalidDecl = true;
17288     T = Context.IntTy;
17289   }
17290 
17291   QualType EltTy = Context.getBaseElementType(T);
17292   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17293     if (RequireCompleteSizedType(Loc, EltTy,
17294                                  diag::err_field_incomplete_or_sizeless)) {
17295       // Fields of incomplete type force their record to be invalid.
17296       Record->setInvalidDecl();
17297       InvalidDecl = true;
17298     } else {
17299       NamedDecl *Def;
17300       EltTy->isIncompleteType(&Def);
17301       if (Def && Def->isInvalidDecl()) {
17302         Record->setInvalidDecl();
17303         InvalidDecl = true;
17304       }
17305     }
17306   }
17307 
17308   // TR 18037 does not allow fields to be declared with address space
17309   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17310       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17311     Diag(Loc, diag::err_field_with_address_space);
17312     Record->setInvalidDecl();
17313     InvalidDecl = true;
17314   }
17315 
17316   if (LangOpts.OpenCL) {
17317     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17318     // used as structure or union field: image, sampler, event or block types.
17319     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17320         T->isBlockPointerType()) {
17321       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17322       Record->setInvalidDecl();
17323       InvalidDecl = true;
17324     }
17325     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17326     // is enabled.
17327     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17328                         "__cl_clang_bitfields", LangOpts)) {
17329       Diag(Loc, diag::err_opencl_bitfields);
17330       InvalidDecl = true;
17331     }
17332   }
17333 
17334   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17335   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17336       T.hasQualifiers()) {
17337     InvalidDecl = true;
17338     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17339   }
17340 
17341   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17342   // than a variably modified type.
17343   if (!InvalidDecl && T->isVariablyModifiedType()) {
17344     if (!tryToFixVariablyModifiedVarType(
17345             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17346       InvalidDecl = true;
17347   }
17348 
17349   // Fields can not have abstract class types
17350   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17351                                              diag::err_abstract_type_in_decl,
17352                                              AbstractFieldType))
17353     InvalidDecl = true;
17354 
17355   bool ZeroWidth = false;
17356   if (InvalidDecl)
17357     BitWidth = nullptr;
17358   // If this is declared as a bit-field, check the bit-field.
17359   if (BitWidth) {
17360     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17361                               &ZeroWidth).get();
17362     if (!BitWidth) {
17363       InvalidDecl = true;
17364       BitWidth = nullptr;
17365       ZeroWidth = false;
17366     }
17367   }
17368 
17369   // Check that 'mutable' is consistent with the type of the declaration.
17370   if (!InvalidDecl && Mutable) {
17371     unsigned DiagID = 0;
17372     if (T->isReferenceType())
17373       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17374                                         : diag::err_mutable_reference;
17375     else if (T.isConstQualified())
17376       DiagID = diag::err_mutable_const;
17377 
17378     if (DiagID) {
17379       SourceLocation ErrLoc = Loc;
17380       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17381         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17382       Diag(ErrLoc, DiagID);
17383       if (DiagID != diag::ext_mutable_reference) {
17384         Mutable = false;
17385         InvalidDecl = true;
17386       }
17387     }
17388   }
17389 
17390   // C++11 [class.union]p8 (DR1460):
17391   //   At most one variant member of a union may have a
17392   //   brace-or-equal-initializer.
17393   if (InitStyle != ICIS_NoInit)
17394     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17395 
17396   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17397                                        BitWidth, Mutable, InitStyle);
17398   if (InvalidDecl)
17399     NewFD->setInvalidDecl();
17400 
17401   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17402     Diag(Loc, diag::err_duplicate_member) << II;
17403     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17404     NewFD->setInvalidDecl();
17405   }
17406 
17407   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17408     if (Record->isUnion()) {
17409       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17410         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17411         if (RDecl->getDefinition()) {
17412           // C++ [class.union]p1: An object of a class with a non-trivial
17413           // constructor, a non-trivial copy constructor, a non-trivial
17414           // destructor, or a non-trivial copy assignment operator
17415           // cannot be a member of a union, nor can an array of such
17416           // objects.
17417           if (CheckNontrivialField(NewFD))
17418             NewFD->setInvalidDecl();
17419         }
17420       }
17421 
17422       // C++ [class.union]p1: If a union contains a member of reference type,
17423       // the program is ill-formed, except when compiling with MSVC extensions
17424       // enabled.
17425       if (EltTy->isReferenceType()) {
17426         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17427                                     diag::ext_union_member_of_reference_type :
17428                                     diag::err_union_member_of_reference_type)
17429           << NewFD->getDeclName() << EltTy;
17430         if (!getLangOpts().MicrosoftExt)
17431           NewFD->setInvalidDecl();
17432       }
17433     }
17434   }
17435 
17436   // FIXME: We need to pass in the attributes given an AST
17437   // representation, not a parser representation.
17438   if (D) {
17439     // FIXME: The current scope is almost... but not entirely... correct here.
17440     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17441 
17442     if (NewFD->hasAttrs())
17443       CheckAlignasUnderalignment(NewFD);
17444   }
17445 
17446   // In auto-retain/release, infer strong retension for fields of
17447   // retainable type.
17448   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17449     NewFD->setInvalidDecl();
17450 
17451   if (T.isObjCGCWeak())
17452     Diag(Loc, diag::warn_attribute_weak_on_field);
17453 
17454   // PPC MMA non-pointer types are not allowed as field types.
17455   if (Context.getTargetInfo().getTriple().isPPC64() &&
17456       CheckPPCMMAType(T, NewFD->getLocation()))
17457     NewFD->setInvalidDecl();
17458 
17459   NewFD->setAccess(AS);
17460   return NewFD;
17461 }
17462 
17463 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17464   assert(FD);
17465   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17466 
17467   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17468     return false;
17469 
17470   QualType EltTy = Context.getBaseElementType(FD->getType());
17471   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17472     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17473     if (RDecl->getDefinition()) {
17474       // We check for copy constructors before constructors
17475       // because otherwise we'll never get complaints about
17476       // copy constructors.
17477 
17478       CXXSpecialMember member = CXXInvalid;
17479       // We're required to check for any non-trivial constructors. Since the
17480       // implicit default constructor is suppressed if there are any
17481       // user-declared constructors, we just need to check that there is a
17482       // trivial default constructor and a trivial copy constructor. (We don't
17483       // worry about move constructors here, since this is a C++98 check.)
17484       if (RDecl->hasNonTrivialCopyConstructor())
17485         member = CXXCopyConstructor;
17486       else if (!RDecl->hasTrivialDefaultConstructor())
17487         member = CXXDefaultConstructor;
17488       else if (RDecl->hasNonTrivialCopyAssignment())
17489         member = CXXCopyAssignment;
17490       else if (RDecl->hasNonTrivialDestructor())
17491         member = CXXDestructor;
17492 
17493       if (member != CXXInvalid) {
17494         if (!getLangOpts().CPlusPlus11 &&
17495             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17496           // Objective-C++ ARC: it is an error to have a non-trivial field of
17497           // a union. However, system headers in Objective-C programs
17498           // occasionally have Objective-C lifetime objects within unions,
17499           // and rather than cause the program to fail, we make those
17500           // members unavailable.
17501           SourceLocation Loc = FD->getLocation();
17502           if (getSourceManager().isInSystemHeader(Loc)) {
17503             if (!FD->hasAttr<UnavailableAttr>())
17504               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17505                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17506             return false;
17507           }
17508         }
17509 
17510         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17511                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17512                diag::err_illegal_union_or_anon_struct_member)
17513           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17514         DiagnoseNontrivial(RDecl, member);
17515         return !getLangOpts().CPlusPlus11;
17516       }
17517     }
17518   }
17519 
17520   return false;
17521 }
17522 
17523 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17524 ///  AST enum value.
17525 static ObjCIvarDecl::AccessControl
17526 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17527   switch (ivarVisibility) {
17528   default: llvm_unreachable("Unknown visitibility kind");
17529   case tok::objc_private: return ObjCIvarDecl::Private;
17530   case tok::objc_public: return ObjCIvarDecl::Public;
17531   case tok::objc_protected: return ObjCIvarDecl::Protected;
17532   case tok::objc_package: return ObjCIvarDecl::Package;
17533   }
17534 }
17535 
17536 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17537 /// in order to create an IvarDecl object for it.
17538 Decl *Sema::ActOnIvar(Scope *S,
17539                                 SourceLocation DeclStart,
17540                                 Declarator &D, Expr *BitfieldWidth,
17541                                 tok::ObjCKeywordKind Visibility) {
17542 
17543   IdentifierInfo *II = D.getIdentifier();
17544   Expr *BitWidth = (Expr*)BitfieldWidth;
17545   SourceLocation Loc = DeclStart;
17546   if (II) Loc = D.getIdentifierLoc();
17547 
17548   // FIXME: Unnamed fields can be handled in various different ways, for
17549   // example, unnamed unions inject all members into the struct namespace!
17550 
17551   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17552   QualType T = TInfo->getType();
17553 
17554   if (BitWidth) {
17555     // 6.7.2.1p3, 6.7.2.1p4
17556     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17557     if (!BitWidth)
17558       D.setInvalidType();
17559   } else {
17560     // Not a bitfield.
17561 
17562     // validate II.
17563 
17564   }
17565   if (T->isReferenceType()) {
17566     Diag(Loc, diag::err_ivar_reference_type);
17567     D.setInvalidType();
17568   }
17569   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17570   // than a variably modified type.
17571   else if (T->isVariablyModifiedType()) {
17572     if (!tryToFixVariablyModifiedVarType(
17573             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17574       D.setInvalidType();
17575   }
17576 
17577   // Get the visibility (access control) for this ivar.
17578   ObjCIvarDecl::AccessControl ac =
17579     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17580                                         : ObjCIvarDecl::None;
17581   // Must set ivar's DeclContext to its enclosing interface.
17582   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17583   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17584     return nullptr;
17585   ObjCContainerDecl *EnclosingContext;
17586   if (ObjCImplementationDecl *IMPDecl =
17587       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17588     if (LangOpts.ObjCRuntime.isFragile()) {
17589     // Case of ivar declared in an implementation. Context is that of its class.
17590       EnclosingContext = IMPDecl->getClassInterface();
17591       assert(EnclosingContext && "Implementation has no class interface!");
17592     }
17593     else
17594       EnclosingContext = EnclosingDecl;
17595   } else {
17596     if (ObjCCategoryDecl *CDecl =
17597         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17598       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17599         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17600         return nullptr;
17601       }
17602     }
17603     EnclosingContext = EnclosingDecl;
17604   }
17605 
17606   // Construct the decl.
17607   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17608                                              DeclStart, Loc, II, T,
17609                                              TInfo, ac, (Expr *)BitfieldWidth);
17610 
17611   if (II) {
17612     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17613                                            ForVisibleRedeclaration);
17614     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17615         && !isa<TagDecl>(PrevDecl)) {
17616       Diag(Loc, diag::err_duplicate_member) << II;
17617       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17618       NewID->setInvalidDecl();
17619     }
17620   }
17621 
17622   // Process attributes attached to the ivar.
17623   ProcessDeclAttributes(S, NewID, D);
17624 
17625   if (D.isInvalidType())
17626     NewID->setInvalidDecl();
17627 
17628   // In ARC, infer 'retaining' for ivars of retainable type.
17629   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17630     NewID->setInvalidDecl();
17631 
17632   if (D.getDeclSpec().isModulePrivateSpecified())
17633     NewID->setModulePrivate();
17634 
17635   if (II) {
17636     // FIXME: When interfaces are DeclContexts, we'll need to add
17637     // these to the interface.
17638     S->AddDecl(NewID);
17639     IdResolver.AddDecl(NewID);
17640   }
17641 
17642   if (LangOpts.ObjCRuntime.isNonFragile() &&
17643       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17644     Diag(Loc, diag::warn_ivars_in_interface);
17645 
17646   return NewID;
17647 }
17648 
17649 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17650 /// class and class extensions. For every class \@interface and class
17651 /// extension \@interface, if the last ivar is a bitfield of any type,
17652 /// then add an implicit `char :0` ivar to the end of that interface.
17653 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17654                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17655   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17656     return;
17657 
17658   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17659   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17660 
17661   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17662     return;
17663   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17664   if (!ID) {
17665     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17666       if (!CD->IsClassExtension())
17667         return;
17668     }
17669     // No need to add this to end of @implementation.
17670     else
17671       return;
17672   }
17673   // All conditions are met. Add a new bitfield to the tail end of ivars.
17674   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17675   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17676 
17677   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17678                               DeclLoc, DeclLoc, nullptr,
17679                               Context.CharTy,
17680                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17681                                                                DeclLoc),
17682                               ObjCIvarDecl::Private, BW,
17683                               true);
17684   AllIvarDecls.push_back(Ivar);
17685 }
17686 
17687 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17688                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17689                        SourceLocation RBrac,
17690                        const ParsedAttributesView &Attrs) {
17691   assert(EnclosingDecl && "missing record or interface decl");
17692 
17693   // If this is an Objective-C @implementation or category and we have
17694   // new fields here we should reset the layout of the interface since
17695   // it will now change.
17696   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17697     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17698     switch (DC->getKind()) {
17699     default: break;
17700     case Decl::ObjCCategory:
17701       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17702       break;
17703     case Decl::ObjCImplementation:
17704       Context.
17705         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17706       break;
17707     }
17708   }
17709 
17710   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17711   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17712 
17713   // Start counting up the number of named members; make sure to include
17714   // members of anonymous structs and unions in the total.
17715   unsigned NumNamedMembers = 0;
17716   if (Record) {
17717     for (const auto *I : Record->decls()) {
17718       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17719         if (IFD->getDeclName())
17720           ++NumNamedMembers;
17721     }
17722   }
17723 
17724   // Verify that all the fields are okay.
17725   SmallVector<FieldDecl*, 32> RecFields;
17726 
17727   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17728        i != end; ++i) {
17729     FieldDecl *FD = cast<FieldDecl>(*i);
17730 
17731     // Get the type for the field.
17732     const Type *FDTy = FD->getType().getTypePtr();
17733 
17734     if (!FD->isAnonymousStructOrUnion()) {
17735       // Remember all fields written by the user.
17736       RecFields.push_back(FD);
17737     }
17738 
17739     // If the field is already invalid for some reason, don't emit more
17740     // diagnostics about it.
17741     if (FD->isInvalidDecl()) {
17742       EnclosingDecl->setInvalidDecl();
17743       continue;
17744     }
17745 
17746     // C99 6.7.2.1p2:
17747     //   A structure or union shall not contain a member with
17748     //   incomplete or function type (hence, a structure shall not
17749     //   contain an instance of itself, but may contain a pointer to
17750     //   an instance of itself), except that the last member of a
17751     //   structure with more than one named member may have incomplete
17752     //   array type; such a structure (and any union containing,
17753     //   possibly recursively, a member that is such a structure)
17754     //   shall not be a member of a structure or an element of an
17755     //   array.
17756     bool IsLastField = (i + 1 == Fields.end());
17757     if (FDTy->isFunctionType()) {
17758       // Field declared as a function.
17759       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17760         << FD->getDeclName();
17761       FD->setInvalidDecl();
17762       EnclosingDecl->setInvalidDecl();
17763       continue;
17764     } else if (FDTy->isIncompleteArrayType() &&
17765                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17766       if (Record) {
17767         // Flexible array member.
17768         // Microsoft and g++ is more permissive regarding flexible array.
17769         // It will accept flexible array in union and also
17770         // as the sole element of a struct/class.
17771         unsigned DiagID = 0;
17772         if (!Record->isUnion() && !IsLastField) {
17773           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17774             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17775           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17776           FD->setInvalidDecl();
17777           EnclosingDecl->setInvalidDecl();
17778           continue;
17779         } else if (Record->isUnion())
17780           DiagID = getLangOpts().MicrosoftExt
17781                        ? diag::ext_flexible_array_union_ms
17782                        : getLangOpts().CPlusPlus
17783                              ? diag::ext_flexible_array_union_gnu
17784                              : diag::err_flexible_array_union;
17785         else if (NumNamedMembers < 1)
17786           DiagID = getLangOpts().MicrosoftExt
17787                        ? diag::ext_flexible_array_empty_aggregate_ms
17788                        : getLangOpts().CPlusPlus
17789                              ? diag::ext_flexible_array_empty_aggregate_gnu
17790                              : diag::err_flexible_array_empty_aggregate;
17791 
17792         if (DiagID)
17793           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17794                                           << Record->getTagKind();
17795         // While the layout of types that contain virtual bases is not specified
17796         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17797         // virtual bases after the derived members.  This would make a flexible
17798         // array member declared at the end of an object not adjacent to the end
17799         // of the type.
17800         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17801           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17802               << FD->getDeclName() << Record->getTagKind();
17803         if (!getLangOpts().C99)
17804           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17805             << FD->getDeclName() << Record->getTagKind();
17806 
17807         // If the element type has a non-trivial destructor, we would not
17808         // implicitly destroy the elements, so disallow it for now.
17809         //
17810         // FIXME: GCC allows this. We should probably either implicitly delete
17811         // the destructor of the containing class, or just allow this.
17812         QualType BaseElem = Context.getBaseElementType(FD->getType());
17813         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17814           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17815             << FD->getDeclName() << FD->getType();
17816           FD->setInvalidDecl();
17817           EnclosingDecl->setInvalidDecl();
17818           continue;
17819         }
17820         // Okay, we have a legal flexible array member at the end of the struct.
17821         Record->setHasFlexibleArrayMember(true);
17822       } else {
17823         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17824         // unless they are followed by another ivar. That check is done
17825         // elsewhere, after synthesized ivars are known.
17826       }
17827     } else if (!FDTy->isDependentType() &&
17828                RequireCompleteSizedType(
17829                    FD->getLocation(), FD->getType(),
17830                    diag::err_field_incomplete_or_sizeless)) {
17831       // Incomplete type
17832       FD->setInvalidDecl();
17833       EnclosingDecl->setInvalidDecl();
17834       continue;
17835     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17836       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17837         // A type which contains a flexible array member is considered to be a
17838         // flexible array member.
17839         Record->setHasFlexibleArrayMember(true);
17840         if (!Record->isUnion()) {
17841           // If this is a struct/class and this is not the last element, reject
17842           // it.  Note that GCC supports variable sized arrays in the middle of
17843           // structures.
17844           if (!IsLastField)
17845             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17846               << FD->getDeclName() << FD->getType();
17847           else {
17848             // We support flexible arrays at the end of structs in
17849             // other structs as an extension.
17850             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17851               << FD->getDeclName();
17852           }
17853         }
17854       }
17855       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17856           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17857                                  diag::err_abstract_type_in_decl,
17858                                  AbstractIvarType)) {
17859         // Ivars can not have abstract class types
17860         FD->setInvalidDecl();
17861       }
17862       if (Record && FDTTy->getDecl()->hasObjectMember())
17863         Record->setHasObjectMember(true);
17864       if (Record && FDTTy->getDecl()->hasVolatileMember())
17865         Record->setHasVolatileMember(true);
17866     } else if (FDTy->isObjCObjectType()) {
17867       /// A field cannot be an Objective-c object
17868       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17869         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17870       QualType T = Context.getObjCObjectPointerType(FD->getType());
17871       FD->setType(T);
17872     } else if (Record && Record->isUnion() &&
17873                FD->getType().hasNonTrivialObjCLifetime() &&
17874                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17875                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17876                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17877                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17878       // For backward compatibility, fields of C unions declared in system
17879       // headers that have non-trivial ObjC ownership qualifications are marked
17880       // as unavailable unless the qualifier is explicit and __strong. This can
17881       // break ABI compatibility between programs compiled with ARC and MRR, but
17882       // is a better option than rejecting programs using those unions under
17883       // ARC.
17884       FD->addAttr(UnavailableAttr::CreateImplicit(
17885           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17886           FD->getLocation()));
17887     } else if (getLangOpts().ObjC &&
17888                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17889                !Record->hasObjectMember()) {
17890       if (FD->getType()->isObjCObjectPointerType() ||
17891           FD->getType().isObjCGCStrong())
17892         Record->setHasObjectMember(true);
17893       else if (Context.getAsArrayType(FD->getType())) {
17894         QualType BaseType = Context.getBaseElementType(FD->getType());
17895         if (BaseType->isRecordType() &&
17896             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17897           Record->setHasObjectMember(true);
17898         else if (BaseType->isObjCObjectPointerType() ||
17899                  BaseType.isObjCGCStrong())
17900                Record->setHasObjectMember(true);
17901       }
17902     }
17903 
17904     if (Record && !getLangOpts().CPlusPlus &&
17905         !shouldIgnoreForRecordTriviality(FD)) {
17906       QualType FT = FD->getType();
17907       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17908         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17909         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17910             Record->isUnion())
17911           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17912       }
17913       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17914       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17915         Record->setNonTrivialToPrimitiveCopy(true);
17916         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17917           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17918       }
17919       if (FT.isDestructedType()) {
17920         Record->setNonTrivialToPrimitiveDestroy(true);
17921         Record->setParamDestroyedInCallee(true);
17922         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17923           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17924       }
17925 
17926       if (const auto *RT = FT->getAs<RecordType>()) {
17927         if (RT->getDecl()->getArgPassingRestrictions() ==
17928             RecordDecl::APK_CanNeverPassInRegs)
17929           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17930       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17931         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17932     }
17933 
17934     if (Record && FD->getType().isVolatileQualified())
17935       Record->setHasVolatileMember(true);
17936     // Keep track of the number of named members.
17937     if (FD->getIdentifier())
17938       ++NumNamedMembers;
17939   }
17940 
17941   // Okay, we successfully defined 'Record'.
17942   if (Record) {
17943     bool Completed = false;
17944     if (CXXRecord) {
17945       if (!CXXRecord->isInvalidDecl()) {
17946         // Set access bits correctly on the directly-declared conversions.
17947         for (CXXRecordDecl::conversion_iterator
17948                I = CXXRecord->conversion_begin(),
17949                E = CXXRecord->conversion_end(); I != E; ++I)
17950           I.setAccess((*I)->getAccess());
17951       }
17952 
17953       // Add any implicitly-declared members to this class.
17954       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17955 
17956       if (!CXXRecord->isDependentType()) {
17957         if (!CXXRecord->isInvalidDecl()) {
17958           // If we have virtual base classes, we may end up finding multiple
17959           // final overriders for a given virtual function. Check for this
17960           // problem now.
17961           if (CXXRecord->getNumVBases()) {
17962             CXXFinalOverriderMap FinalOverriders;
17963             CXXRecord->getFinalOverriders(FinalOverriders);
17964 
17965             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17966                                              MEnd = FinalOverriders.end();
17967                  M != MEnd; ++M) {
17968               for (OverridingMethods::iterator SO = M->second.begin(),
17969                                             SOEnd = M->second.end();
17970                    SO != SOEnd; ++SO) {
17971                 assert(SO->second.size() > 0 &&
17972                        "Virtual function without overriding functions?");
17973                 if (SO->second.size() == 1)
17974                   continue;
17975 
17976                 // C++ [class.virtual]p2:
17977                 //   In a derived class, if a virtual member function of a base
17978                 //   class subobject has more than one final overrider the
17979                 //   program is ill-formed.
17980                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17981                   << (const NamedDecl *)M->first << Record;
17982                 Diag(M->first->getLocation(),
17983                      diag::note_overridden_virtual_function);
17984                 for (OverridingMethods::overriding_iterator
17985                           OM = SO->second.begin(),
17986                        OMEnd = SO->second.end();
17987                      OM != OMEnd; ++OM)
17988                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17989                     << (const NamedDecl *)M->first << OM->Method->getParent();
17990 
17991                 Record->setInvalidDecl();
17992               }
17993             }
17994             CXXRecord->completeDefinition(&FinalOverriders);
17995             Completed = true;
17996           }
17997         }
17998       }
17999     }
18000 
18001     if (!Completed)
18002       Record->completeDefinition();
18003 
18004     // Handle attributes before checking the layout.
18005     ProcessDeclAttributeList(S, Record, Attrs);
18006 
18007     // Maybe randomize the field order.
18008     if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() &&
18009         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18010         !Record->isRandomized()) {
18011       SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields());
18012       SmallVector<Decl *, 32> NewFieldOrdering;
18013       if (randstruct::randomizeStructureLayout(
18014               Context, Record->getNameAsString(), OrigFieldOrdering,
18015               NewFieldOrdering))
18016         Record->reorderFields(NewFieldOrdering);
18017     }
18018 
18019     // We may have deferred checking for a deleted destructor. Check now.
18020     if (CXXRecord) {
18021       auto *Dtor = CXXRecord->getDestructor();
18022       if (Dtor && Dtor->isImplicit() &&
18023           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18024         CXXRecord->setImplicitDestructorIsDeleted();
18025         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18026       }
18027     }
18028 
18029     if (Record->hasAttrs()) {
18030       CheckAlignasUnderalignment(Record);
18031 
18032       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18033         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18034                                            IA->getRange(), IA->getBestCase(),
18035                                            IA->getInheritanceModel());
18036     }
18037 
18038     // Check if the structure/union declaration is a type that can have zero
18039     // size in C. For C this is a language extension, for C++ it may cause
18040     // compatibility problems.
18041     bool CheckForZeroSize;
18042     if (!getLangOpts().CPlusPlus) {
18043       CheckForZeroSize = true;
18044     } else {
18045       // For C++ filter out types that cannot be referenced in C code.
18046       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18047       CheckForZeroSize =
18048           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18049           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18050           CXXRecord->isCLike();
18051     }
18052     if (CheckForZeroSize) {
18053       bool ZeroSize = true;
18054       bool IsEmpty = true;
18055       unsigned NonBitFields = 0;
18056       for (RecordDecl::field_iterator I = Record->field_begin(),
18057                                       E = Record->field_end();
18058            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18059         IsEmpty = false;
18060         if (I->isUnnamedBitfield()) {
18061           if (!I->isZeroLengthBitField(Context))
18062             ZeroSize = false;
18063         } else {
18064           ++NonBitFields;
18065           QualType FieldType = I->getType();
18066           if (FieldType->isIncompleteType() ||
18067               !Context.getTypeSizeInChars(FieldType).isZero())
18068             ZeroSize = false;
18069         }
18070       }
18071 
18072       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18073       // allowed in C++, but warn if its declaration is inside
18074       // extern "C" block.
18075       if (ZeroSize) {
18076         Diag(RecLoc, getLangOpts().CPlusPlus ?
18077                          diag::warn_zero_size_struct_union_in_extern_c :
18078                          diag::warn_zero_size_struct_union_compat)
18079           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18080       }
18081 
18082       // Structs without named members are extension in C (C99 6.7.2.1p7),
18083       // but are accepted by GCC.
18084       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18085         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18086                                diag::ext_no_named_members_in_struct_union)
18087           << Record->isUnion();
18088       }
18089     }
18090   } else {
18091     ObjCIvarDecl **ClsFields =
18092       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18093     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18094       ID->setEndOfDefinitionLoc(RBrac);
18095       // Add ivar's to class's DeclContext.
18096       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18097         ClsFields[i]->setLexicalDeclContext(ID);
18098         ID->addDecl(ClsFields[i]);
18099       }
18100       // Must enforce the rule that ivars in the base classes may not be
18101       // duplicates.
18102       if (ID->getSuperClass())
18103         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18104     } else if (ObjCImplementationDecl *IMPDecl =
18105                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18106       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18107       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18108         // Ivar declared in @implementation never belongs to the implementation.
18109         // Only it is in implementation's lexical context.
18110         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18111       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18112       IMPDecl->setIvarLBraceLoc(LBrac);
18113       IMPDecl->setIvarRBraceLoc(RBrac);
18114     } else if (ObjCCategoryDecl *CDecl =
18115                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18116       // case of ivars in class extension; all other cases have been
18117       // reported as errors elsewhere.
18118       // FIXME. Class extension does not have a LocEnd field.
18119       // CDecl->setLocEnd(RBrac);
18120       // Add ivar's to class extension's DeclContext.
18121       // Diagnose redeclaration of private ivars.
18122       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18123       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18124         if (IDecl) {
18125           if (const ObjCIvarDecl *ClsIvar =
18126               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18127             Diag(ClsFields[i]->getLocation(),
18128                  diag::err_duplicate_ivar_declaration);
18129             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18130             continue;
18131           }
18132           for (const auto *Ext : IDecl->known_extensions()) {
18133             if (const ObjCIvarDecl *ClsExtIvar
18134                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18135               Diag(ClsFields[i]->getLocation(),
18136                    diag::err_duplicate_ivar_declaration);
18137               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18138               continue;
18139             }
18140           }
18141         }
18142         ClsFields[i]->setLexicalDeclContext(CDecl);
18143         CDecl->addDecl(ClsFields[i]);
18144       }
18145       CDecl->setIvarLBraceLoc(LBrac);
18146       CDecl->setIvarRBraceLoc(RBrac);
18147     }
18148   }
18149 }
18150 
18151 /// Determine whether the given integral value is representable within
18152 /// the given type T.
18153 static bool isRepresentableIntegerValue(ASTContext &Context,
18154                                         llvm::APSInt &Value,
18155                                         QualType T) {
18156   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18157          "Integral type required!");
18158   unsigned BitWidth = Context.getIntWidth(T);
18159 
18160   if (Value.isUnsigned() || Value.isNonNegative()) {
18161     if (T->isSignedIntegerOrEnumerationType())
18162       --BitWidth;
18163     return Value.getActiveBits() <= BitWidth;
18164   }
18165   return Value.getMinSignedBits() <= BitWidth;
18166 }
18167 
18168 // Given an integral type, return the next larger integral type
18169 // (or a NULL type of no such type exists).
18170 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18171   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18172   // enum checking below.
18173   assert((T->isIntegralType(Context) ||
18174          T->isEnumeralType()) && "Integral type required!");
18175   const unsigned NumTypes = 4;
18176   QualType SignedIntegralTypes[NumTypes] = {
18177     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18178   };
18179   QualType UnsignedIntegralTypes[NumTypes] = {
18180     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18181     Context.UnsignedLongLongTy
18182   };
18183 
18184   unsigned BitWidth = Context.getTypeSize(T);
18185   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18186                                                         : UnsignedIntegralTypes;
18187   for (unsigned I = 0; I != NumTypes; ++I)
18188     if (Context.getTypeSize(Types[I]) > BitWidth)
18189       return Types[I];
18190 
18191   return QualType();
18192 }
18193 
18194 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18195                                           EnumConstantDecl *LastEnumConst,
18196                                           SourceLocation IdLoc,
18197                                           IdentifierInfo *Id,
18198                                           Expr *Val) {
18199   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18200   llvm::APSInt EnumVal(IntWidth);
18201   QualType EltTy;
18202 
18203   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18204     Val = nullptr;
18205 
18206   if (Val)
18207     Val = DefaultLvalueConversion(Val).get();
18208 
18209   if (Val) {
18210     if (Enum->isDependentType() || Val->isTypeDependent() ||
18211         Val->containsErrors())
18212       EltTy = Context.DependentTy;
18213     else {
18214       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18215       // underlying type, but do allow it in all other contexts.
18216       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18217         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18218         // constant-expression in the enumerator-definition shall be a converted
18219         // constant expression of the underlying type.
18220         EltTy = Enum->getIntegerType();
18221         ExprResult Converted =
18222           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18223                                            CCEK_Enumerator);
18224         if (Converted.isInvalid())
18225           Val = nullptr;
18226         else
18227           Val = Converted.get();
18228       } else if (!Val->isValueDependent() &&
18229                  !(Val =
18230                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18231                            .get())) {
18232         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18233       } else {
18234         if (Enum->isComplete()) {
18235           EltTy = Enum->getIntegerType();
18236 
18237           // In Obj-C and Microsoft mode, require the enumeration value to be
18238           // representable in the underlying type of the enumeration. In C++11,
18239           // we perform a non-narrowing conversion as part of converted constant
18240           // expression checking.
18241           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18242             if (Context.getTargetInfo()
18243                     .getTriple()
18244                     .isWindowsMSVCEnvironment()) {
18245               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18246             } else {
18247               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18248             }
18249           }
18250 
18251           // Cast to the underlying type.
18252           Val = ImpCastExprToType(Val, EltTy,
18253                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18254                                                          : CK_IntegralCast)
18255                     .get();
18256         } else if (getLangOpts().CPlusPlus) {
18257           // C++11 [dcl.enum]p5:
18258           //   If the underlying type is not fixed, the type of each enumerator
18259           //   is the type of its initializing value:
18260           //     - If an initializer is specified for an enumerator, the
18261           //       initializing value has the same type as the expression.
18262           EltTy = Val->getType();
18263         } else {
18264           // C99 6.7.2.2p2:
18265           //   The expression that defines the value of an enumeration constant
18266           //   shall be an integer constant expression that has a value
18267           //   representable as an int.
18268 
18269           // Complain if the value is not representable in an int.
18270           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18271             Diag(IdLoc, diag::ext_enum_value_not_int)
18272               << toString(EnumVal, 10) << Val->getSourceRange()
18273               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18274           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18275             // Force the type of the expression to 'int'.
18276             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18277           }
18278           EltTy = Val->getType();
18279         }
18280       }
18281     }
18282   }
18283 
18284   if (!Val) {
18285     if (Enum->isDependentType())
18286       EltTy = Context.DependentTy;
18287     else if (!LastEnumConst) {
18288       // C++0x [dcl.enum]p5:
18289       //   If the underlying type is not fixed, the type of each enumerator
18290       //   is the type of its initializing value:
18291       //     - If no initializer is specified for the first enumerator, the
18292       //       initializing value has an unspecified integral type.
18293       //
18294       // GCC uses 'int' for its unspecified integral type, as does
18295       // C99 6.7.2.2p3.
18296       if (Enum->isFixed()) {
18297         EltTy = Enum->getIntegerType();
18298       }
18299       else {
18300         EltTy = Context.IntTy;
18301       }
18302     } else {
18303       // Assign the last value + 1.
18304       EnumVal = LastEnumConst->getInitVal();
18305       ++EnumVal;
18306       EltTy = LastEnumConst->getType();
18307 
18308       // Check for overflow on increment.
18309       if (EnumVal < LastEnumConst->getInitVal()) {
18310         // C++0x [dcl.enum]p5:
18311         //   If the underlying type is not fixed, the type of each enumerator
18312         //   is the type of its initializing value:
18313         //
18314         //     - Otherwise the type of the initializing value is the same as
18315         //       the type of the initializing value of the preceding enumerator
18316         //       unless the incremented value is not representable in that type,
18317         //       in which case the type is an unspecified integral type
18318         //       sufficient to contain the incremented value. If no such type
18319         //       exists, the program is ill-formed.
18320         QualType T = getNextLargerIntegralType(Context, EltTy);
18321         if (T.isNull() || Enum->isFixed()) {
18322           // There is no integral type larger enough to represent this
18323           // value. Complain, then allow the value to wrap around.
18324           EnumVal = LastEnumConst->getInitVal();
18325           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18326           ++EnumVal;
18327           if (Enum->isFixed())
18328             // When the underlying type is fixed, this is ill-formed.
18329             Diag(IdLoc, diag::err_enumerator_wrapped)
18330               << toString(EnumVal, 10)
18331               << EltTy;
18332           else
18333             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18334               << toString(EnumVal, 10);
18335         } else {
18336           EltTy = T;
18337         }
18338 
18339         // Retrieve the last enumerator's value, extent that type to the
18340         // type that is supposed to be large enough to represent the incremented
18341         // value, then increment.
18342         EnumVal = LastEnumConst->getInitVal();
18343         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18344         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18345         ++EnumVal;
18346 
18347         // If we're not in C++, diagnose the overflow of enumerator values,
18348         // which in C99 means that the enumerator value is not representable in
18349         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18350         // permits enumerator values that are representable in some larger
18351         // integral type.
18352         if (!getLangOpts().CPlusPlus && !T.isNull())
18353           Diag(IdLoc, diag::warn_enum_value_overflow);
18354       } else if (!getLangOpts().CPlusPlus &&
18355                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18356         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18357         Diag(IdLoc, diag::ext_enum_value_not_int)
18358           << toString(EnumVal, 10) << 1;
18359       }
18360     }
18361   }
18362 
18363   if (!EltTy->isDependentType()) {
18364     // Make the enumerator value match the signedness and size of the
18365     // enumerator's type.
18366     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18367     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18368   }
18369 
18370   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18371                                   Val, EnumVal);
18372 }
18373 
18374 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18375                                                 SourceLocation IILoc) {
18376   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18377       !getLangOpts().CPlusPlus)
18378     return SkipBodyInfo();
18379 
18380   // We have an anonymous enum definition. Look up the first enumerator to
18381   // determine if we should merge the definition with an existing one and
18382   // skip the body.
18383   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18384                                          forRedeclarationInCurContext());
18385   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18386   if (!PrevECD)
18387     return SkipBodyInfo();
18388 
18389   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18390   NamedDecl *Hidden;
18391   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18392     SkipBodyInfo Skip;
18393     Skip.Previous = Hidden;
18394     return Skip;
18395   }
18396 
18397   return SkipBodyInfo();
18398 }
18399 
18400 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18401                               SourceLocation IdLoc, IdentifierInfo *Id,
18402                               const ParsedAttributesView &Attrs,
18403                               SourceLocation EqualLoc, Expr *Val) {
18404   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18405   EnumConstantDecl *LastEnumConst =
18406     cast_or_null<EnumConstantDecl>(lastEnumConst);
18407 
18408   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18409   // we find one that is.
18410   S = getNonFieldDeclScope(S);
18411 
18412   // Verify that there isn't already something declared with this name in this
18413   // scope.
18414   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18415   LookupName(R, S);
18416   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18417 
18418   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18419     // Maybe we will complain about the shadowed template parameter.
18420     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18421     // Just pretend that we didn't see the previous declaration.
18422     PrevDecl = nullptr;
18423   }
18424 
18425   // C++ [class.mem]p15:
18426   // If T is the name of a class, then each of the following shall have a name
18427   // different from T:
18428   // - every enumerator of every member of class T that is an unscoped
18429   // enumerated type
18430   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18431     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18432                             DeclarationNameInfo(Id, IdLoc));
18433 
18434   EnumConstantDecl *New =
18435     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18436   if (!New)
18437     return nullptr;
18438 
18439   if (PrevDecl) {
18440     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18441       // Check for other kinds of shadowing not already handled.
18442       CheckShadow(New, PrevDecl, R);
18443     }
18444 
18445     // When in C++, we may get a TagDecl with the same name; in this case the
18446     // enum constant will 'hide' the tag.
18447     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18448            "Received TagDecl when not in C++!");
18449     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18450       if (isa<EnumConstantDecl>(PrevDecl))
18451         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18452       else
18453         Diag(IdLoc, diag::err_redefinition) << Id;
18454       notePreviousDefinition(PrevDecl, IdLoc);
18455       return nullptr;
18456     }
18457   }
18458 
18459   // Process attributes.
18460   ProcessDeclAttributeList(S, New, Attrs);
18461   AddPragmaAttributes(S, New);
18462 
18463   // Register this decl in the current scope stack.
18464   New->setAccess(TheEnumDecl->getAccess());
18465   PushOnScopeChains(New, S);
18466 
18467   ActOnDocumentableDecl(New);
18468 
18469   return New;
18470 }
18471 
18472 // Returns true when the enum initial expression does not trigger the
18473 // duplicate enum warning.  A few common cases are exempted as follows:
18474 // Element2 = Element1
18475 // Element2 = Element1 + 1
18476 // Element2 = Element1 - 1
18477 // Where Element2 and Element1 are from the same enum.
18478 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18479   Expr *InitExpr = ECD->getInitExpr();
18480   if (!InitExpr)
18481     return true;
18482   InitExpr = InitExpr->IgnoreImpCasts();
18483 
18484   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18485     if (!BO->isAdditiveOp())
18486       return true;
18487     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18488     if (!IL)
18489       return true;
18490     if (IL->getValue() != 1)
18491       return true;
18492 
18493     InitExpr = BO->getLHS();
18494   }
18495 
18496   // This checks if the elements are from the same enum.
18497   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18498   if (!DRE)
18499     return true;
18500 
18501   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18502   if (!EnumConstant)
18503     return true;
18504 
18505   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18506       Enum)
18507     return true;
18508 
18509   return false;
18510 }
18511 
18512 // Emits a warning when an element is implicitly set a value that
18513 // a previous element has already been set to.
18514 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18515                                         EnumDecl *Enum, QualType EnumType) {
18516   // Avoid anonymous enums
18517   if (!Enum->getIdentifier())
18518     return;
18519 
18520   // Only check for small enums.
18521   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18522     return;
18523 
18524   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18525     return;
18526 
18527   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18528   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18529 
18530   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18531 
18532   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18533   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18534 
18535   // Use int64_t as a key to avoid needing special handling for map keys.
18536   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18537     llvm::APSInt Val = D->getInitVal();
18538     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18539   };
18540 
18541   DuplicatesVector DupVector;
18542   ValueToVectorMap EnumMap;
18543 
18544   // Populate the EnumMap with all values represented by enum constants without
18545   // an initializer.
18546   for (auto *Element : Elements) {
18547     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18548 
18549     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18550     // this constant.  Skip this enum since it may be ill-formed.
18551     if (!ECD) {
18552       return;
18553     }
18554 
18555     // Constants with initalizers are handled in the next loop.
18556     if (ECD->getInitExpr())
18557       continue;
18558 
18559     // Duplicate values are handled in the next loop.
18560     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18561   }
18562 
18563   if (EnumMap.size() == 0)
18564     return;
18565 
18566   // Create vectors for any values that has duplicates.
18567   for (auto *Element : Elements) {
18568     // The last loop returned if any constant was null.
18569     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18570     if (!ValidDuplicateEnum(ECD, Enum))
18571       continue;
18572 
18573     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18574     if (Iter == EnumMap.end())
18575       continue;
18576 
18577     DeclOrVector& Entry = Iter->second;
18578     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18579       // Ensure constants are different.
18580       if (D == ECD)
18581         continue;
18582 
18583       // Create new vector and push values onto it.
18584       auto Vec = std::make_unique<ECDVector>();
18585       Vec->push_back(D);
18586       Vec->push_back(ECD);
18587 
18588       // Update entry to point to the duplicates vector.
18589       Entry = Vec.get();
18590 
18591       // Store the vector somewhere we can consult later for quick emission of
18592       // diagnostics.
18593       DupVector.emplace_back(std::move(Vec));
18594       continue;
18595     }
18596 
18597     ECDVector *Vec = Entry.get<ECDVector*>();
18598     // Make sure constants are not added more than once.
18599     if (*Vec->begin() == ECD)
18600       continue;
18601 
18602     Vec->push_back(ECD);
18603   }
18604 
18605   // Emit diagnostics.
18606   for (const auto &Vec : DupVector) {
18607     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18608 
18609     // Emit warning for one enum constant.
18610     auto *FirstECD = Vec->front();
18611     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18612       << FirstECD << toString(FirstECD->getInitVal(), 10)
18613       << FirstECD->getSourceRange();
18614 
18615     // Emit one note for each of the remaining enum constants with
18616     // the same value.
18617     for (auto *ECD : llvm::drop_begin(*Vec))
18618       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18619         << ECD << toString(ECD->getInitVal(), 10)
18620         << ECD->getSourceRange();
18621   }
18622 }
18623 
18624 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18625                              bool AllowMask) const {
18626   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18627   assert(ED->isCompleteDefinition() && "expected enum definition");
18628 
18629   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18630   llvm::APInt &FlagBits = R.first->second;
18631 
18632   if (R.second) {
18633     for (auto *E : ED->enumerators()) {
18634       const auto &EVal = E->getInitVal();
18635       // Only single-bit enumerators introduce new flag values.
18636       if (EVal.isPowerOf2())
18637         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18638     }
18639   }
18640 
18641   // A value is in a flag enum if either its bits are a subset of the enum's
18642   // flag bits (the first condition) or we are allowing masks and the same is
18643   // true of its complement (the second condition). When masks are allowed, we
18644   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18645   //
18646   // While it's true that any value could be used as a mask, the assumption is
18647   // that a mask will have all of the insignificant bits set. Anything else is
18648   // likely a logic error.
18649   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18650   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18651 }
18652 
18653 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18654                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18655                          const ParsedAttributesView &Attrs) {
18656   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18657   QualType EnumType = Context.getTypeDeclType(Enum);
18658 
18659   ProcessDeclAttributeList(S, Enum, Attrs);
18660 
18661   if (Enum->isDependentType()) {
18662     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18663       EnumConstantDecl *ECD =
18664         cast_or_null<EnumConstantDecl>(Elements[i]);
18665       if (!ECD) continue;
18666 
18667       ECD->setType(EnumType);
18668     }
18669 
18670     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18671     return;
18672   }
18673 
18674   // TODO: If the result value doesn't fit in an int, it must be a long or long
18675   // long value.  ISO C does not support this, but GCC does as an extension,
18676   // emit a warning.
18677   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18678   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18679   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18680 
18681   // Verify that all the values are okay, compute the size of the values, and
18682   // reverse the list.
18683   unsigned NumNegativeBits = 0;
18684   unsigned NumPositiveBits = 0;
18685 
18686   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18687     EnumConstantDecl *ECD =
18688       cast_or_null<EnumConstantDecl>(Elements[i]);
18689     if (!ECD) continue;  // Already issued a diagnostic.
18690 
18691     const llvm::APSInt &InitVal = ECD->getInitVal();
18692 
18693     // Keep track of the size of positive and negative values.
18694     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18695       NumPositiveBits = std::max(NumPositiveBits,
18696                                  (unsigned)InitVal.getActiveBits());
18697     else
18698       NumNegativeBits = std::max(NumNegativeBits,
18699                                  (unsigned)InitVal.getMinSignedBits());
18700   }
18701 
18702   // Figure out the type that should be used for this enum.
18703   QualType BestType;
18704   unsigned BestWidth;
18705 
18706   // C++0x N3000 [conv.prom]p3:
18707   //   An rvalue of an unscoped enumeration type whose underlying
18708   //   type is not fixed can be converted to an rvalue of the first
18709   //   of the following types that can represent all the values of
18710   //   the enumeration: int, unsigned int, long int, unsigned long
18711   //   int, long long int, or unsigned long long int.
18712   // C99 6.4.4.3p2:
18713   //   An identifier declared as an enumeration constant has type int.
18714   // The C99 rule is modified by a gcc extension
18715   QualType BestPromotionType;
18716 
18717   bool Packed = Enum->hasAttr<PackedAttr>();
18718   // -fshort-enums is the equivalent to specifying the packed attribute on all
18719   // enum definitions.
18720   if (LangOpts.ShortEnums)
18721     Packed = true;
18722 
18723   // If the enum already has a type because it is fixed or dictated by the
18724   // target, promote that type instead of analyzing the enumerators.
18725   if (Enum->isComplete()) {
18726     BestType = Enum->getIntegerType();
18727     if (BestType->isPromotableIntegerType())
18728       BestPromotionType = Context.getPromotedIntegerType(BestType);
18729     else
18730       BestPromotionType = BestType;
18731 
18732     BestWidth = Context.getIntWidth(BestType);
18733   }
18734   else if (NumNegativeBits) {
18735     // If there is a negative value, figure out the smallest integer type (of
18736     // int/long/longlong) that fits.
18737     // If it's packed, check also if it fits a char or a short.
18738     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18739       BestType = Context.SignedCharTy;
18740       BestWidth = CharWidth;
18741     } else if (Packed && NumNegativeBits <= ShortWidth &&
18742                NumPositiveBits < ShortWidth) {
18743       BestType = Context.ShortTy;
18744       BestWidth = ShortWidth;
18745     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18746       BestType = Context.IntTy;
18747       BestWidth = IntWidth;
18748     } else {
18749       BestWidth = Context.getTargetInfo().getLongWidth();
18750 
18751       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18752         BestType = Context.LongTy;
18753       } else {
18754         BestWidth = Context.getTargetInfo().getLongLongWidth();
18755 
18756         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18757           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18758         BestType = Context.LongLongTy;
18759       }
18760     }
18761     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18762   } else {
18763     // If there is no negative value, figure out the smallest type that fits
18764     // all of the enumerator values.
18765     // If it's packed, check also if it fits a char or a short.
18766     if (Packed && NumPositiveBits <= CharWidth) {
18767       BestType = Context.UnsignedCharTy;
18768       BestPromotionType = Context.IntTy;
18769       BestWidth = CharWidth;
18770     } else if (Packed && NumPositiveBits <= ShortWidth) {
18771       BestType = Context.UnsignedShortTy;
18772       BestPromotionType = Context.IntTy;
18773       BestWidth = ShortWidth;
18774     } else if (NumPositiveBits <= IntWidth) {
18775       BestType = Context.UnsignedIntTy;
18776       BestWidth = IntWidth;
18777       BestPromotionType
18778         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18779                            ? Context.UnsignedIntTy : Context.IntTy;
18780     } else if (NumPositiveBits <=
18781                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18782       BestType = Context.UnsignedLongTy;
18783       BestPromotionType
18784         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18785                            ? Context.UnsignedLongTy : Context.LongTy;
18786     } else {
18787       BestWidth = Context.getTargetInfo().getLongLongWidth();
18788       assert(NumPositiveBits <= BestWidth &&
18789              "How could an initializer get larger than ULL?");
18790       BestType = Context.UnsignedLongLongTy;
18791       BestPromotionType
18792         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18793                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18794     }
18795   }
18796 
18797   // Loop over all of the enumerator constants, changing their types to match
18798   // the type of the enum if needed.
18799   for (auto *D : Elements) {
18800     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18801     if (!ECD) continue;  // Already issued a diagnostic.
18802 
18803     // Standard C says the enumerators have int type, but we allow, as an
18804     // extension, the enumerators to be larger than int size.  If each
18805     // enumerator value fits in an int, type it as an int, otherwise type it the
18806     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18807     // that X has type 'int', not 'unsigned'.
18808 
18809     // Determine whether the value fits into an int.
18810     llvm::APSInt InitVal = ECD->getInitVal();
18811 
18812     // If it fits into an integer type, force it.  Otherwise force it to match
18813     // the enum decl type.
18814     QualType NewTy;
18815     unsigned NewWidth;
18816     bool NewSign;
18817     if (!getLangOpts().CPlusPlus &&
18818         !Enum->isFixed() &&
18819         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18820       NewTy = Context.IntTy;
18821       NewWidth = IntWidth;
18822       NewSign = true;
18823     } else if (ECD->getType() == BestType) {
18824       // Already the right type!
18825       if (getLangOpts().CPlusPlus)
18826         // C++ [dcl.enum]p4: Following the closing brace of an
18827         // enum-specifier, each enumerator has the type of its
18828         // enumeration.
18829         ECD->setType(EnumType);
18830       continue;
18831     } else {
18832       NewTy = BestType;
18833       NewWidth = BestWidth;
18834       NewSign = BestType->isSignedIntegerOrEnumerationType();
18835     }
18836 
18837     // Adjust the APSInt value.
18838     InitVal = InitVal.extOrTrunc(NewWidth);
18839     InitVal.setIsSigned(NewSign);
18840     ECD->setInitVal(InitVal);
18841 
18842     // Adjust the Expr initializer and type.
18843     if (ECD->getInitExpr() &&
18844         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18845       ECD->setInitExpr(ImplicitCastExpr::Create(
18846           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18847           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18848     if (getLangOpts().CPlusPlus)
18849       // C++ [dcl.enum]p4: Following the closing brace of an
18850       // enum-specifier, each enumerator has the type of its
18851       // enumeration.
18852       ECD->setType(EnumType);
18853     else
18854       ECD->setType(NewTy);
18855   }
18856 
18857   Enum->completeDefinition(BestType, BestPromotionType,
18858                            NumPositiveBits, NumNegativeBits);
18859 
18860   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18861 
18862   if (Enum->isClosedFlag()) {
18863     for (Decl *D : Elements) {
18864       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18865       if (!ECD) continue;  // Already issued a diagnostic.
18866 
18867       llvm::APSInt InitVal = ECD->getInitVal();
18868       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18869           !IsValueInFlagEnum(Enum, InitVal, true))
18870         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18871           << ECD << Enum;
18872     }
18873   }
18874 
18875   // Now that the enum type is defined, ensure it's not been underaligned.
18876   if (Enum->hasAttrs())
18877     CheckAlignasUnderalignment(Enum);
18878 }
18879 
18880 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18881                                   SourceLocation StartLoc,
18882                                   SourceLocation EndLoc) {
18883   StringLiteral *AsmString = cast<StringLiteral>(expr);
18884 
18885   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18886                                                    AsmString, StartLoc,
18887                                                    EndLoc);
18888   CurContext->addDecl(New);
18889   return New;
18890 }
18891 
18892 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18893                                       IdentifierInfo* AliasName,
18894                                       SourceLocation PragmaLoc,
18895                                       SourceLocation NameLoc,
18896                                       SourceLocation AliasNameLoc) {
18897   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18898                                          LookupOrdinaryName);
18899   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18900                            AttributeCommonInfo::AS_Pragma);
18901   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18902       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18903 
18904   // If a declaration that:
18905   // 1) declares a function or a variable
18906   // 2) has external linkage
18907   // already exists, add a label attribute to it.
18908   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18909     if (isDeclExternC(PrevDecl))
18910       PrevDecl->addAttr(Attr);
18911     else
18912       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18913           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18914   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18915   } else
18916     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18917 }
18918 
18919 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18920                              SourceLocation PragmaLoc,
18921                              SourceLocation NameLoc) {
18922   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18923 
18924   if (PrevDecl) {
18925     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18926   } else {
18927     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18928   }
18929 }
18930 
18931 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18932                                 IdentifierInfo* AliasName,
18933                                 SourceLocation PragmaLoc,
18934                                 SourceLocation NameLoc,
18935                                 SourceLocation AliasNameLoc) {
18936   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18937                                     LookupOrdinaryName);
18938   WeakInfo W = WeakInfo(Name, NameLoc);
18939 
18940   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18941     if (!PrevDecl->hasAttr<AliasAttr>())
18942       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18943         DeclApplyPragmaWeak(TUScope, ND, W);
18944   } else {
18945     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18946   }
18947 }
18948 
18949 Decl *Sema::getObjCDeclContext() const {
18950   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18951 }
18952 
18953 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18954                                                      bool Final) {
18955   assert(FD && "Expected non-null FunctionDecl");
18956 
18957   // SYCL functions can be template, so we check if they have appropriate
18958   // attribute prior to checking if it is a template.
18959   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18960     return FunctionEmissionStatus::Emitted;
18961 
18962   // Templates are emitted when they're instantiated.
18963   if (FD->isDependentContext())
18964     return FunctionEmissionStatus::TemplateDiscarded;
18965 
18966   // Check whether this function is an externally visible definition.
18967   auto IsEmittedForExternalSymbol = [this, FD]() {
18968     // We have to check the GVA linkage of the function's *definition* -- if we
18969     // only have a declaration, we don't know whether or not the function will
18970     // be emitted, because (say) the definition could include "inline".
18971     FunctionDecl *Def = FD->getDefinition();
18972 
18973     return Def && !isDiscardableGVALinkage(
18974                       getASTContext().GetGVALinkageForFunction(Def));
18975   };
18976 
18977   if (LangOpts.OpenMPIsDevice) {
18978     // In OpenMP device mode we will not emit host only functions, or functions
18979     // we don't need due to their linkage.
18980     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18981         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18982     // DevTy may be changed later by
18983     //  #pragma omp declare target to(*) device_type(*).
18984     // Therefore DevTy having no value does not imply host. The emission status
18985     // will be checked again at the end of compilation unit with Final = true.
18986     if (DevTy.hasValue())
18987       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18988         return FunctionEmissionStatus::OMPDiscarded;
18989     // If we have an explicit value for the device type, or we are in a target
18990     // declare context, we need to emit all extern and used symbols.
18991     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18992       if (IsEmittedForExternalSymbol())
18993         return FunctionEmissionStatus::Emitted;
18994     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18995     // we'll omit it.
18996     if (Final)
18997       return FunctionEmissionStatus::OMPDiscarded;
18998   } else if (LangOpts.OpenMP > 45) {
18999     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19000     // function. In 5.0, no_host was introduced which might cause a function to
19001     // be ommitted.
19002     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19003         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19004     if (DevTy.hasValue())
19005       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19006         return FunctionEmissionStatus::OMPDiscarded;
19007   }
19008 
19009   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19010     return FunctionEmissionStatus::Emitted;
19011 
19012   if (LangOpts.CUDA) {
19013     // When compiling for device, host functions are never emitted.  Similarly,
19014     // when compiling for host, device and global functions are never emitted.
19015     // (Technically, we do emit a host-side stub for global functions, but this
19016     // doesn't count for our purposes here.)
19017     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19018     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19019       return FunctionEmissionStatus::CUDADiscarded;
19020     if (!LangOpts.CUDAIsDevice &&
19021         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19022       return FunctionEmissionStatus::CUDADiscarded;
19023 
19024     if (IsEmittedForExternalSymbol())
19025       return FunctionEmissionStatus::Emitted;
19026   }
19027 
19028   // Otherwise, the function is known-emitted if it's in our set of
19029   // known-emitted functions.
19030   return FunctionEmissionStatus::Unknown;
19031 }
19032 
19033 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19034   // Host-side references to a __global__ function refer to the stub, so the
19035   // function itself is never emitted and therefore should not be marked.
19036   // If we have host fn calls kernel fn calls host+device, the HD function
19037   // does not get instantiated on the host. We model this by omitting at the
19038   // call to the kernel from the callgraph. This ensures that, when compiling
19039   // for host, only HD functions actually called from the host get marked as
19040   // known-emitted.
19041   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19042          IdentifyCUDATarget(Callee) == CFT_Global;
19043 }
19044