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       // FIXME: TemplateName should include FoundUsingShadow sugar.
508       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
509                                                        QualType(), false);
510       // Don't wrap in a further UsingType.
511       FoundUsingShadow = nullptr;
512     }
513   }
514 
515   if (T.isNull()) {
516     // If it's not plausibly a type, suppress diagnostics.
517     Result.suppressDiagnostics();
518     return nullptr;
519   }
520 
521   if (FoundUsingShadow)
522     T = Context.getUsingType(FoundUsingShadow, T);
523 
524   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
525   // constructor or destructor name (in such a case, the scope specifier
526   // will be attached to the enclosing Expr or Decl node).
527   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
528       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
529     if (WantNontrivialTypeSourceInfo) {
530       // Construct a type with type-source information.
531       TypeLocBuilder Builder;
532       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
533 
534       T = getElaboratedType(ETK_None, *SS, T);
535       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
536       ElabTL.setElaboratedKeywordLoc(SourceLocation());
537       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
538       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
539     } else {
540       T = getElaboratedType(ETK_None, *SS, T);
541     }
542   }
543 
544   return ParsedType::make(T);
545 }
546 
547 // Builds a fake NNS for the given decl context.
548 static NestedNameSpecifier *
549 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
550   for (;; DC = DC->getLookupParent()) {
551     DC = DC->getPrimaryContext();
552     auto *ND = dyn_cast<NamespaceDecl>(DC);
553     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
554       return NestedNameSpecifier::Create(Context, nullptr, ND);
555     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
556       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
557                                          RD->getTypeForDecl());
558     else if (isa<TranslationUnitDecl>(DC))
559       return NestedNameSpecifier::GlobalSpecifier(Context);
560   }
561   llvm_unreachable("something isn't in TU scope?");
562 }
563 
564 /// Find the parent class with dependent bases of the innermost enclosing method
565 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
566 /// up allowing unqualified dependent type names at class-level, which MSVC
567 /// correctly rejects.
568 static const CXXRecordDecl *
569 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
570   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
571     DC = DC->getPrimaryContext();
572     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
573       if (MD->getParent()->hasAnyDependentBases())
574         return MD->getParent();
575   }
576   return nullptr;
577 }
578 
579 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
580                                           SourceLocation NameLoc,
581                                           bool IsTemplateTypeArg) {
582   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
583 
584   NestedNameSpecifier *NNS = nullptr;
585   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
586     // If we weren't able to parse a default template argument, delay lookup
587     // until instantiation time by making a non-dependent DependentTypeName. We
588     // pretend we saw a NestedNameSpecifier referring to the current scope, and
589     // lookup is retried.
590     // FIXME: This hurts our diagnostic quality, since we get errors like "no
591     // type named 'Foo' in 'current_namespace'" when the user didn't write any
592     // name specifiers.
593     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
594     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
595   } else if (const CXXRecordDecl *RD =
596                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
597     // Build a DependentNameType that will perform lookup into RD at
598     // instantiation time.
599     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
600                                       RD->getTypeForDecl());
601 
602     // Diagnose that this identifier was undeclared, and retry the lookup during
603     // template instantiation.
604     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
605                                                                       << RD;
606   } else {
607     // This is not a situation that we should recover from.
608     return ParsedType();
609   }
610 
611   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
612 
613   // Build type location information.  We synthesized the qualifier, so we have
614   // to build a fake NestedNameSpecifierLoc.
615   NestedNameSpecifierLocBuilder NNSLocBuilder;
616   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
617   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
618 
619   TypeLocBuilder Builder;
620   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
621   DepTL.setNameLoc(NameLoc);
622   DepTL.setElaboratedKeywordLoc(SourceLocation());
623   DepTL.setQualifierLoc(QualifierLoc);
624   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
625 }
626 
627 /// isTagName() - This method is called *for error recovery purposes only*
628 /// to determine if the specified name is a valid tag name ("struct foo").  If
629 /// so, this returns the TST for the tag corresponding to it (TST_enum,
630 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
631 /// cases in C where the user forgot to specify the tag.
632 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
633   // Do a tag name lookup in this scope.
634   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
635   LookupName(R, S, false);
636   R.suppressDiagnostics();
637   if (R.getResultKind() == LookupResult::Found)
638     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
639       switch (TD->getTagKind()) {
640       case TTK_Struct: return DeclSpec::TST_struct;
641       case TTK_Interface: return DeclSpec::TST_interface;
642       case TTK_Union:  return DeclSpec::TST_union;
643       case TTK_Class:  return DeclSpec::TST_class;
644       case TTK_Enum:   return DeclSpec::TST_enum;
645       }
646     }
647 
648   return DeclSpec::TST_unspecified;
649 }
650 
651 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
652 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
653 /// then downgrade the missing typename error to a warning.
654 /// This is needed for MSVC compatibility; Example:
655 /// @code
656 /// template<class T> class A {
657 /// public:
658 ///   typedef int TYPE;
659 /// };
660 /// template<class T> class B : public A<T> {
661 /// public:
662 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
663 /// };
664 /// @endcode
665 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
666   if (CurContext->isRecord()) {
667     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
668       return true;
669 
670     const Type *Ty = SS->getScopeRep()->getAsType();
671 
672     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
673     for (const auto &Base : RD->bases())
674       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
675         return true;
676     return S->isFunctionPrototypeScope();
677   }
678   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
679 }
680 
681 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
682                                    SourceLocation IILoc,
683                                    Scope *S,
684                                    CXXScopeSpec *SS,
685                                    ParsedType &SuggestedType,
686                                    bool IsTemplateName) {
687   // Don't report typename errors for editor placeholders.
688   if (II->isEditorPlaceholder())
689     return;
690   // We don't have anything to suggest (yet).
691   SuggestedType = nullptr;
692 
693   // There may have been a typo in the name of the type. Look up typo
694   // results, in case we have something that we can suggest.
695   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
696                            /*AllowTemplates=*/IsTemplateName,
697                            /*AllowNonTemplates=*/!IsTemplateName);
698   if (TypoCorrection Corrected =
699           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
700                       CCC, CTK_ErrorRecovery)) {
701     // FIXME: Support error recovery for the template-name case.
702     bool CanRecover = !IsTemplateName;
703     if (Corrected.isKeyword()) {
704       // We corrected to a keyword.
705       diagnoseTypo(Corrected,
706                    PDiag(IsTemplateName ? diag::err_no_template_suggest
707                                         : diag::err_unknown_typename_suggest)
708                        << II);
709       II = Corrected.getCorrectionAsIdentifierInfo();
710     } else {
711       // We found a similarly-named type or interface; suggest that.
712       if (!SS || !SS->isSet()) {
713         diagnoseTypo(Corrected,
714                      PDiag(IsTemplateName ? diag::err_no_template_suggest
715                                           : diag::err_unknown_typename_suggest)
716                          << II, CanRecover);
717       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
718         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
719         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
720                                 II->getName().equals(CorrectedStr);
721         diagnoseTypo(Corrected,
722                      PDiag(IsTemplateName
723                                ? diag::err_no_member_template_suggest
724                                : diag::err_unknown_nested_typename_suggest)
725                          << II << DC << DroppedSpecifier << SS->getRange(),
726                      CanRecover);
727       } else {
728         llvm_unreachable("could not have corrected a typo here");
729       }
730 
731       if (!CanRecover)
732         return;
733 
734       CXXScopeSpec tmpSS;
735       if (Corrected.getCorrectionSpecifier())
736         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
737                           SourceRange(IILoc));
738       // FIXME: Support class template argument deduction here.
739       SuggestedType =
740           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
741                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
742                       /*IsCtorOrDtorName=*/false,
743                       /*WantNontrivialTypeSourceInfo=*/true);
744     }
745     return;
746   }
747 
748   if (getLangOpts().CPlusPlus && !IsTemplateName) {
749     // See if II is a class template that the user forgot to pass arguments to.
750     UnqualifiedId Name;
751     Name.setIdentifier(II, IILoc);
752     CXXScopeSpec EmptySS;
753     TemplateTy TemplateResult;
754     bool MemberOfUnknownSpecialization;
755     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
756                        Name, nullptr, true, TemplateResult,
757                        MemberOfUnknownSpecialization) == TNK_Type_template) {
758       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
759       return;
760     }
761   }
762 
763   // FIXME: Should we move the logic that tries to recover from a missing tag
764   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
765 
766   if (!SS || (!SS->isSet() && !SS->isInvalid()))
767     Diag(IILoc, IsTemplateName ? diag::err_no_template
768                                : diag::err_unknown_typename)
769         << II;
770   else if (DeclContext *DC = computeDeclContext(*SS, false))
771     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
772                                : diag::err_typename_nested_not_found)
773         << II << DC << SS->getRange();
774   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
775     SuggestedType =
776         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
777   } else if (isDependentScopeSpecifier(*SS)) {
778     unsigned DiagID = diag::err_typename_missing;
779     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
780       DiagID = diag::ext_typename_missing;
781 
782     Diag(SS->getRange().getBegin(), DiagID)
783       << SS->getScopeRep() << II->getName()
784       << SourceRange(SS->getRange().getBegin(), IILoc)
785       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
786     SuggestedType = ActOnTypenameType(S, SourceLocation(),
787                                       *SS, *II, IILoc).get();
788   } else {
789     assert(SS && SS->isInvalid() &&
790            "Invalid scope specifier has already been diagnosed");
791   }
792 }
793 
794 /// Determine whether the given result set contains either a type name
795 /// or
796 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
797   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
798                        NextToken.is(tok::less);
799 
800   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
801     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
802       return true;
803 
804     if (CheckTemplate && isa<TemplateDecl>(*I))
805       return true;
806   }
807 
808   return false;
809 }
810 
811 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
812                                     Scope *S, CXXScopeSpec &SS,
813                                     IdentifierInfo *&Name,
814                                     SourceLocation NameLoc) {
815   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
816   SemaRef.LookupParsedName(R, S, &SS);
817   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
818     StringRef FixItTagName;
819     switch (Tag->getTagKind()) {
820       case TTK_Class:
821         FixItTagName = "class ";
822         break;
823 
824       case TTK_Enum:
825         FixItTagName = "enum ";
826         break;
827 
828       case TTK_Struct:
829         FixItTagName = "struct ";
830         break;
831 
832       case TTK_Interface:
833         FixItTagName = "__interface ";
834         break;
835 
836       case TTK_Union:
837         FixItTagName = "union ";
838         break;
839     }
840 
841     StringRef TagName = FixItTagName.drop_back();
842     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
843       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
844       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
845 
846     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
847          I != IEnd; ++I)
848       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
849         << Name << TagName;
850 
851     // Replace lookup results with just the tag decl.
852     Result.clear(Sema::LookupTagName);
853     SemaRef.LookupParsedName(Result, S, &SS);
854     return true;
855   }
856 
857   return false;
858 }
859 
860 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861                                             IdentifierInfo *&Name,
862                                             SourceLocation NameLoc,
863                                             const Token &NextToken,
864                                             CorrectionCandidateCallback *CCC) {
865   DeclarationNameInfo NameInfo(Name, NameLoc);
866   ObjCMethodDecl *CurMethod = getCurMethodDecl();
867 
868   assert(NextToken.isNot(tok::coloncolon) &&
869          "parse nested name specifiers before calling ClassifyName");
870   if (getLangOpts().CPlusPlus && SS.isSet() &&
871       isCurrentClassName(*Name, S, &SS)) {
872     // Per [class.qual]p2, this names the constructors of SS, not the
873     // injected-class-name. We don't have a classification for that.
874     // There's not much point caching this result, since the parser
875     // will reject it later.
876     return NameClassification::Unknown();
877   }
878 
879   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880   LookupParsedName(Result, S, &SS, !CurMethod);
881 
882   if (SS.isInvalid())
883     return NameClassification::Error();
884 
885   // For unqualified lookup in a class template in MSVC mode, look into
886   // dependent base classes where the primary class template is known.
887   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888     if (ParsedType TypeInBase =
889             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890       return TypeInBase;
891   }
892 
893   // Perform lookup for Objective-C instance variables (including automatically
894   // synthesized instance variables), if we're in an Objective-C method.
895   // FIXME: This lookup really, really needs to be folded in to the normal
896   // unqualified lookup mechanism.
897   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899     if (Ivar.isInvalid())
900       return NameClassification::Error();
901     if (Ivar.isUsable())
902       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903 
904     // We defer builtin creation until after ivar lookup inside ObjC methods.
905     if (Result.empty())
906       LookupBuiltin(Result);
907   }
908 
909   bool SecondTry = false;
910   bool IsFilteredTemplateName = false;
911 
912 Corrected:
913   switch (Result.getResultKind()) {
914   case LookupResult::NotFound:
915     // If an unqualified-id is followed by a '(', then we have a function
916     // call.
917     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918       // In C++, this is an ADL-only call.
919       // FIXME: Reference?
920       if (getLangOpts().CPlusPlus)
921         return NameClassification::UndeclaredNonType();
922 
923       // C90 6.3.2.2:
924       //   If the expression that precedes the parenthesized argument list in a
925       //   function call consists solely of an identifier, and if no
926       //   declaration is visible for this identifier, the identifier is
927       //   implicitly declared exactly as if, in the innermost block containing
928       //   the function call, the declaration
929       //
930       //     extern int identifier ();
931       //
932       //   appeared.
933       //
934       // We also allow this in C99 as an extension.
935       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936         return NameClassification::NonType(D);
937     }
938 
939     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940       // In C++20 onwards, this could be an ADL-only call to a function
941       // template, and we're required to assume that this is a template name.
942       //
943       // FIXME: Find a way to still do typo correction in this case.
944       TemplateName Template =
945           Context.getAssumedTemplateName(NameInfo.getName());
946       return NameClassification::UndeclaredTemplate(Template);
947     }
948 
949     // In C, we first see whether there is a tag type by the same name, in
950     // which case it's likely that the user just forgot to write "enum",
951     // "struct", or "union".
952     if (!getLangOpts().CPlusPlus && !SecondTry &&
953         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954       break;
955     }
956 
957     // Perform typo correction to determine if there is another name that is
958     // close to this name.
959     if (!SecondTry && CCC) {
960       SecondTry = true;
961       if (TypoCorrection Corrected =
962               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963                           &SS, *CCC, CTK_ErrorRecovery)) {
964         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965         unsigned QualifiedDiag = diag::err_no_member_suggest;
966 
967         NamedDecl *FirstDecl = Corrected.getFoundDecl();
968         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971           UnqualifiedDiag = diag::err_no_template_suggest;
972           QualifiedDiag = diag::err_no_member_template_suggest;
973         } else if (UnderlyingFirstDecl &&
974                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977           UnqualifiedDiag = diag::err_unknown_typename_suggest;
978           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979         }
980 
981         if (SS.isEmpty()) {
982           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983         } else {// FIXME: is this even reachable? Test it.
984           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986                                   Name->getName().equals(CorrectedStr);
987           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988                                     << Name << computeDeclContext(SS, false)
989                                     << DroppedSpecifier << SS.getRange());
990         }
991 
992         // Update the name, so that the caller has the new name.
993         Name = Corrected.getCorrectionAsIdentifierInfo();
994 
995         // Typo correction corrected to a keyword.
996         if (Corrected.isKeyword())
997           return Name;
998 
999         // Also update the LookupResult...
1000         // FIXME: This should probably go away at some point
1001         Result.clear();
1002         Result.setLookupName(Corrected.getCorrection());
1003         if (FirstDecl)
1004           Result.addDecl(FirstDecl);
1005 
1006         // If we found an Objective-C instance variable, let
1007         // LookupInObjCMethod build the appropriate expression to
1008         // reference the ivar.
1009         // FIXME: This is a gross hack.
1010         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011           DeclResult R =
1012               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013           if (R.isInvalid())
1014             return NameClassification::Error();
1015           if (R.isUsable())
1016             return NameClassification::NonType(Ivar);
1017         }
1018 
1019         goto Corrected;
1020       }
1021     }
1022 
1023     // We failed to correct; just fall through and let the parser deal with it.
1024     Result.suppressDiagnostics();
1025     return NameClassification::Unknown();
1026 
1027   case LookupResult::NotFoundInCurrentInstantiation: {
1028     // We performed name lookup into the current instantiation, and there were
1029     // dependent bases, so we treat this result the same way as any other
1030     // dependent nested-name-specifier.
1031 
1032     // C++ [temp.res]p2:
1033     //   A name used in a template declaration or definition and that is
1034     //   dependent on a template-parameter is assumed not to name a type
1035     //   unless the applicable name lookup finds a type name or the name is
1036     //   qualified by the keyword typename.
1037     //
1038     // FIXME: If the next token is '<', we might want to ask the parser to
1039     // perform some heroics to see if we actually have a
1040     // template-argument-list, which would indicate a missing 'template'
1041     // keyword here.
1042     return NameClassification::DependentNonType();
1043   }
1044 
1045   case LookupResult::Found:
1046   case LookupResult::FoundOverloaded:
1047   case LookupResult::FoundUnresolvedValue:
1048     break;
1049 
1050   case LookupResult::Ambiguous:
1051     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053                                       /*AllowDependent=*/false)) {
1054       // C++ [temp.local]p3:
1055       //   A lookup that finds an injected-class-name (10.2) can result in an
1056       //   ambiguity in certain cases (for example, if it is found in more than
1057       //   one base class). If all of the injected-class-names that are found
1058       //   refer to specializations of the same class template, and if the name
1059       //   is followed by a template-argument-list, the reference refers to the
1060       //   class template itself and not a specialization thereof, and is not
1061       //   ambiguous.
1062       //
1063       // This filtering can make an ambiguous result into an unambiguous one,
1064       // so try again after filtering out template names.
1065       FilterAcceptableTemplateNames(Result);
1066       if (!Result.isAmbiguous()) {
1067         IsFilteredTemplateName = true;
1068         break;
1069       }
1070     }
1071 
1072     // Diagnose the ambiguity and return an error.
1073     return NameClassification::Error();
1074   }
1075 
1076   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077       (IsFilteredTemplateName ||
1078        hasAnyAcceptableTemplateNames(
1079            Result, /*AllowFunctionTemplates=*/true,
1080            /*AllowDependent=*/false,
1081            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082                getLangOpts().CPlusPlus20))) {
1083     // C++ [temp.names]p3:
1084     //   After name lookup (3.4) finds that a name is a template-name or that
1085     //   an operator-function-id or a literal- operator-id refers to a set of
1086     //   overloaded functions any member of which is a function template if
1087     //   this is followed by a <, the < is always taken as the delimiter of a
1088     //   template-argument-list and never as the less-than operator.
1089     // C++2a [temp.names]p2:
1090     //   A name is also considered to refer to a template if it is an
1091     //   unqualified-id followed by a < and name lookup finds either one
1092     //   or more functions or finds nothing.
1093     if (!IsFilteredTemplateName)
1094       FilterAcceptableTemplateNames(Result);
1095 
1096     bool IsFunctionTemplate;
1097     bool IsVarTemplate;
1098     TemplateName Template;
1099     if (Result.end() - Result.begin() > 1) {
1100       IsFunctionTemplate = true;
1101       Template = Context.getOverloadedTemplateName(Result.begin(),
1102                                                    Result.end());
1103     } else if (!Result.empty()) {
1104       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105           *Result.begin(), /*AllowFunctionTemplates=*/true,
1106           /*AllowDependent=*/false));
1107       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108       IsVarTemplate = isa<VarTemplateDecl>(TD);
1109 
1110       if (SS.isNotEmpty())
1111         Template =
1112             Context.getQualifiedTemplateName(SS.getScopeRep(),
1113                                              /*TemplateKeyword=*/false, TD);
1114       else
1115         Template = TemplateName(TD);
1116     } else {
1117       // All results were non-template functions. This is a function template
1118       // name.
1119       IsFunctionTemplate = true;
1120       Template = Context.getAssumedTemplateName(NameInfo.getName());
1121     }
1122 
1123     if (IsFunctionTemplate) {
1124       // Function templates always go through overload resolution, at which
1125       // point we'll perform the various checks (e.g., accessibility) we need
1126       // to based on which function we selected.
1127       Result.suppressDiagnostics();
1128 
1129       return NameClassification::FunctionTemplate(Template);
1130     }
1131 
1132     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133                          : NameClassification::TypeTemplate(Template);
1134   }
1135 
1136   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1137     QualType T = Context.getTypeDeclType(Type);
1138     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1139       T = Context.getUsingType(USD, T);
1140 
1141     if (SS.isEmpty()) // No elaborated type, trivial location info
1142       return ParsedType::make(T);
1143 
1144     TypeLocBuilder Builder;
1145     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1146     T = getElaboratedType(ETK_None, SS, T);
1147     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1148     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1149     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1150     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1151   };
1152 
1153   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1154   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1155     DiagnoseUseOfDecl(Type, NameLoc);
1156     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1157     return BuildTypeFor(Type, *Result.begin());
1158   }
1159 
1160   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1161   if (!Class) {
1162     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1163     if (ObjCCompatibleAliasDecl *Alias =
1164             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1165       Class = Alias->getClassInterface();
1166   }
1167 
1168   if (Class) {
1169     DiagnoseUseOfDecl(Class, NameLoc);
1170 
1171     if (NextToken.is(tok::period)) {
1172       // Interface. <something> is parsed as a property reference expression.
1173       // Just return "unknown" as a fall-through for now.
1174       Result.suppressDiagnostics();
1175       return NameClassification::Unknown();
1176     }
1177 
1178     QualType T = Context.getObjCInterfaceType(Class);
1179     return ParsedType::make(T);
1180   }
1181 
1182   if (isa<ConceptDecl>(FirstDecl))
1183     return NameClassification::Concept(
1184         TemplateName(cast<TemplateDecl>(FirstDecl)));
1185 
1186   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1187     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1188     return NameClassification::Error();
1189   }
1190 
1191   // We can have a type template here if we're classifying a template argument.
1192   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1193       !isa<VarTemplateDecl>(FirstDecl))
1194     return NameClassification::TypeTemplate(
1195         TemplateName(cast<TemplateDecl>(FirstDecl)));
1196 
1197   // Check for a tag type hidden by a non-type decl in a few cases where it
1198   // seems likely a type is wanted instead of the non-type that was found.
1199   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1200   if ((NextToken.is(tok::identifier) ||
1201        (NextIsOp &&
1202         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1203       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1204     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1205     DiagnoseUseOfDecl(Type, NameLoc);
1206     return BuildTypeFor(Type, *Result.begin());
1207   }
1208 
1209   // If we already know which single declaration is referenced, just annotate
1210   // that declaration directly. Defer resolving even non-overloaded class
1211   // member accesses, as we need to defer certain access checks until we know
1212   // the context.
1213   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1214   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1215     return NameClassification::NonType(Result.getRepresentativeDecl());
1216 
1217   // Otherwise, this is an overload set that we will need to resolve later.
1218   Result.suppressDiagnostics();
1219   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1220       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1221       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1222       Result.begin(), Result.end()));
1223 }
1224 
1225 ExprResult
1226 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1227                                              SourceLocation NameLoc) {
1228   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1229   CXXScopeSpec SS;
1230   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1231   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1232 }
1233 
1234 ExprResult
1235 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1236                                             IdentifierInfo *Name,
1237                                             SourceLocation NameLoc,
1238                                             bool IsAddressOfOperand) {
1239   DeclarationNameInfo NameInfo(Name, NameLoc);
1240   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1241                                     NameInfo, IsAddressOfOperand,
1242                                     /*TemplateArgs=*/nullptr);
1243 }
1244 
1245 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1246                                               NamedDecl *Found,
1247                                               SourceLocation NameLoc,
1248                                               const Token &NextToken) {
1249   if (getCurMethodDecl() && SS.isEmpty())
1250     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1251       return BuildIvarRefExpr(S, NameLoc, Ivar);
1252 
1253   // Reconstruct the lookup result.
1254   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1255   Result.addDecl(Found);
1256   Result.resolveKind();
1257 
1258   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1259   return BuildDeclarationNameExpr(SS, Result, ADL);
1260 }
1261 
1262 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1263   // For an implicit class member access, transform the result into a member
1264   // access expression if necessary.
1265   auto *ULE = cast<UnresolvedLookupExpr>(E);
1266   if ((*ULE->decls_begin())->isCXXClassMember()) {
1267     CXXScopeSpec SS;
1268     SS.Adopt(ULE->getQualifierLoc());
1269 
1270     // Reconstruct the lookup result.
1271     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1272                         LookupOrdinaryName);
1273     Result.setNamingClass(ULE->getNamingClass());
1274     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1275       Result.addDecl(*I, I.getAccess());
1276     Result.resolveKind();
1277     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1278                                            nullptr, S);
1279   }
1280 
1281   // Otherwise, this is already in the form we needed, and no further checks
1282   // are necessary.
1283   return ULE;
1284 }
1285 
1286 Sema::TemplateNameKindForDiagnostics
1287 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1288   auto *TD = Name.getAsTemplateDecl();
1289   if (!TD)
1290     return TemplateNameKindForDiagnostics::DependentTemplate;
1291   if (isa<ClassTemplateDecl>(TD))
1292     return TemplateNameKindForDiagnostics::ClassTemplate;
1293   if (isa<FunctionTemplateDecl>(TD))
1294     return TemplateNameKindForDiagnostics::FunctionTemplate;
1295   if (isa<VarTemplateDecl>(TD))
1296     return TemplateNameKindForDiagnostics::VarTemplate;
1297   if (isa<TypeAliasTemplateDecl>(TD))
1298     return TemplateNameKindForDiagnostics::AliasTemplate;
1299   if (isa<TemplateTemplateParmDecl>(TD))
1300     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1301   if (isa<ConceptDecl>(TD))
1302     return TemplateNameKindForDiagnostics::Concept;
1303   return TemplateNameKindForDiagnostics::DependentTemplate;
1304 }
1305 
1306 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1307   assert(DC->getLexicalParent() == CurContext &&
1308       "The next DeclContext should be lexically contained in the current one.");
1309   CurContext = DC;
1310   S->setEntity(DC);
1311 }
1312 
1313 void Sema::PopDeclContext() {
1314   assert(CurContext && "DeclContext imbalance!");
1315 
1316   CurContext = CurContext->getLexicalParent();
1317   assert(CurContext && "Popped translation unit!");
1318 }
1319 
1320 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1321                                                                     Decl *D) {
1322   // Unlike PushDeclContext, the context to which we return is not necessarily
1323   // the containing DC of TD, because the new context will be some pre-existing
1324   // TagDecl definition instead of a fresh one.
1325   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1326   CurContext = cast<TagDecl>(D)->getDefinition();
1327   assert(CurContext && "skipping definition of undefined tag");
1328   // Start lookups from the parent of the current context; we don't want to look
1329   // into the pre-existing complete definition.
1330   S->setEntity(CurContext->getLookupParent());
1331   return Result;
1332 }
1333 
1334 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1335   CurContext = static_cast<decltype(CurContext)>(Context);
1336 }
1337 
1338 /// EnterDeclaratorContext - Used when we must lookup names in the context
1339 /// of a declarator's nested name specifier.
1340 ///
1341 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1342   // C++0x [basic.lookup.unqual]p13:
1343   //   A name used in the definition of a static data member of class
1344   //   X (after the qualified-id of the static member) is looked up as
1345   //   if the name was used in a member function of X.
1346   // C++0x [basic.lookup.unqual]p14:
1347   //   If a variable member of a namespace is defined outside of the
1348   //   scope of its namespace then any name used in the definition of
1349   //   the variable member (after the declarator-id) is looked up as
1350   //   if the definition of the variable member occurred in its
1351   //   namespace.
1352   // Both of these imply that we should push a scope whose context
1353   // is the semantic context of the declaration.  We can't use
1354   // PushDeclContext here because that context is not necessarily
1355   // lexically contained in the current context.  Fortunately,
1356   // the containing scope should have the appropriate information.
1357 
1358   assert(!S->getEntity() && "scope already has entity");
1359 
1360 #ifndef NDEBUG
1361   Scope *Ancestor = S->getParent();
1362   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1363   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1364 #endif
1365 
1366   CurContext = DC;
1367   S->setEntity(DC);
1368 
1369   if (S->getParent()->isTemplateParamScope()) {
1370     // Also set the corresponding entities for all immediately-enclosing
1371     // template parameter scopes.
1372     EnterTemplatedContext(S->getParent(), DC);
1373   }
1374 }
1375 
1376 void Sema::ExitDeclaratorContext(Scope *S) {
1377   assert(S->getEntity() == CurContext && "Context imbalance!");
1378 
1379   // Switch back to the lexical context.  The safety of this is
1380   // enforced by an assert in EnterDeclaratorContext.
1381   Scope *Ancestor = S->getParent();
1382   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1383   CurContext = Ancestor->getEntity();
1384 
1385   // We don't need to do anything with the scope, which is going to
1386   // disappear.
1387 }
1388 
1389 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1390   assert(S->isTemplateParamScope() &&
1391          "expected to be initializing a template parameter scope");
1392 
1393   // C++20 [temp.local]p7:
1394   //   In the definition of a member of a class template that appears outside
1395   //   of the class template definition, the name of a member of the class
1396   //   template hides the name of a template-parameter of any enclosing class
1397   //   templates (but not a template-parameter of the member if the member is a
1398   //   class or function template).
1399   // C++20 [temp.local]p9:
1400   //   In the definition of a class template or in the definition of a member
1401   //   of such a template that appears outside of the template definition, for
1402   //   each non-dependent base class (13.8.2.1), if the name of the base class
1403   //   or the name of a member of the base class is the same as the name of a
1404   //   template-parameter, the base class name or member name hides the
1405   //   template-parameter name (6.4.10).
1406   //
1407   // This means that a template parameter scope should be searched immediately
1408   // after searching the DeclContext for which it is a template parameter
1409   // scope. For example, for
1410   //   template<typename T> template<typename U> template<typename V>
1411   //     void N::A<T>::B<U>::f(...)
1412   // we search V then B<U> (and base classes) then U then A<T> (and base
1413   // classes) then T then N then ::.
1414   unsigned ScopeDepth = getTemplateDepth(S);
1415   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1416     DeclContext *SearchDCAfterScope = DC;
1417     for (; DC; DC = DC->getLookupParent()) {
1418       if (const TemplateParameterList *TPL =
1419               cast<Decl>(DC)->getDescribedTemplateParams()) {
1420         unsigned DCDepth = TPL->getDepth() + 1;
1421         if (DCDepth > ScopeDepth)
1422           continue;
1423         if (ScopeDepth == DCDepth)
1424           SearchDCAfterScope = DC = DC->getLookupParent();
1425         break;
1426       }
1427     }
1428     S->setLookupEntity(SearchDCAfterScope);
1429   }
1430 }
1431 
1432 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1433   // We assume that the caller has already called
1434   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1435   FunctionDecl *FD = D->getAsFunction();
1436   if (!FD)
1437     return;
1438 
1439   // Same implementation as PushDeclContext, but enters the context
1440   // from the lexical parent, rather than the top-level class.
1441   assert(CurContext == FD->getLexicalParent() &&
1442     "The next DeclContext should be lexically contained in the current one.");
1443   CurContext = FD;
1444   S->setEntity(CurContext);
1445 
1446   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1447     ParmVarDecl *Param = FD->getParamDecl(P);
1448     // If the parameter has an identifier, then add it to the scope
1449     if (Param->getIdentifier()) {
1450       S->AddDecl(Param);
1451       IdResolver.AddDecl(Param);
1452     }
1453   }
1454 }
1455 
1456 void Sema::ActOnExitFunctionContext() {
1457   // Same implementation as PopDeclContext, but returns to the lexical parent,
1458   // rather than the top-level class.
1459   assert(CurContext && "DeclContext imbalance!");
1460   CurContext = CurContext->getLexicalParent();
1461   assert(CurContext && "Popped translation unit!");
1462 }
1463 
1464 /// Determine whether overloading is allowed for a new function
1465 /// declaration considering prior declarations of the same name.
1466 ///
1467 /// This routine determines whether overloading is possible, not
1468 /// whether a new declaration actually overloads a previous one.
1469 /// It will return true in C++ (where overloads are alway permitted)
1470 /// or, as a C extension, when either the new declaration or a
1471 /// previous one is declared with the 'overloadable' attribute.
1472 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1473                                        ASTContext &Context,
1474                                        const FunctionDecl *New) {
1475   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1476     return true;
1477 
1478   // Multiversion function declarations are not overloads in the
1479   // usual sense of that term, but lookup will report that an
1480   // overload set was found if more than one multiversion function
1481   // declaration is present for the same name. It is therefore
1482   // inadequate to assume that some prior declaration(s) had
1483   // the overloadable attribute; checking is required. Since one
1484   // declaration is permitted to omit the attribute, it is necessary
1485   // to check at least two; hence the 'any_of' check below. Note that
1486   // the overloadable attribute is implicitly added to declarations
1487   // that were required to have it but did not.
1488   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1489     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1490       return ND->hasAttr<OverloadableAttr>();
1491     });
1492   } else if (Previous.getResultKind() == LookupResult::Found)
1493     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1494 
1495   return false;
1496 }
1497 
1498 /// Add this decl to the scope shadowed decl chains.
1499 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1500   // Move up the scope chain until we find the nearest enclosing
1501   // non-transparent context. The declaration will be introduced into this
1502   // scope.
1503   while (S->getEntity() && S->getEntity()->isTransparentContext())
1504     S = S->getParent();
1505 
1506   // Add scoped declarations into their context, so that they can be
1507   // found later. Declarations without a context won't be inserted
1508   // into any context.
1509   if (AddToContext)
1510     CurContext->addDecl(D);
1511 
1512   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1513   // are function-local declarations.
1514   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1515     return;
1516 
1517   // Template instantiations should also not be pushed into scope.
1518   if (isa<FunctionDecl>(D) &&
1519       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1520     return;
1521 
1522   // If this replaces anything in the current scope,
1523   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1524                                IEnd = IdResolver.end();
1525   for (; I != IEnd; ++I) {
1526     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1527       S->RemoveDecl(*I);
1528       IdResolver.RemoveDecl(*I);
1529 
1530       // Should only need to replace one decl.
1531       break;
1532     }
1533   }
1534 
1535   S->AddDecl(D);
1536 
1537   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1538     // Implicitly-generated labels may end up getting generated in an order that
1539     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1540     // the label at the appropriate place in the identifier chain.
1541     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1542       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1543       if (IDC == CurContext) {
1544         if (!S->isDeclScope(*I))
1545           continue;
1546       } else if (IDC->Encloses(CurContext))
1547         break;
1548     }
1549 
1550     IdResolver.InsertDeclAfter(I, D);
1551   } else {
1552     IdResolver.AddDecl(D);
1553   }
1554   warnOnReservedIdentifier(D);
1555 }
1556 
1557 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1558                          bool AllowInlineNamespace) {
1559   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1560 }
1561 
1562 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1563   DeclContext *TargetDC = DC->getPrimaryContext();
1564   do {
1565     if (DeclContext *ScopeDC = S->getEntity())
1566       if (ScopeDC->getPrimaryContext() == TargetDC)
1567         return S;
1568   } while ((S = S->getParent()));
1569 
1570   return nullptr;
1571 }
1572 
1573 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1574                                             DeclContext*,
1575                                             ASTContext&);
1576 
1577 /// Filters out lookup results that don't fall within the given scope
1578 /// as determined by isDeclInScope.
1579 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1580                                 bool ConsiderLinkage,
1581                                 bool AllowInlineNamespace) {
1582   LookupResult::Filter F = R.makeFilter();
1583   while (F.hasNext()) {
1584     NamedDecl *D = F.next();
1585 
1586     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1587       continue;
1588 
1589     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1590       continue;
1591 
1592     F.erase();
1593   }
1594 
1595   F.done();
1596 }
1597 
1598 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1599 /// have compatible owning modules.
1600 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1601   // [module.interface]p7:
1602   // A declaration is attached to a module as follows:
1603   // - If the declaration is a non-dependent friend declaration that nominates a
1604   // function with a declarator-id that is a qualified-id or template-id or that
1605   // nominates a class other than with an elaborated-type-specifier with neither
1606   // a nested-name-specifier nor a simple-template-id, it is attached to the
1607   // module to which the friend is attached ([basic.link]).
1608   if (New->getFriendObjectKind() &&
1609       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1610     New->setLocalOwningModule(Old->getOwningModule());
1611     makeMergedDefinitionVisible(New);
1612     return false;
1613   }
1614 
1615   Module *NewM = New->getOwningModule();
1616   Module *OldM = Old->getOwningModule();
1617 
1618   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1619     NewM = NewM->Parent;
1620   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1621     OldM = OldM->Parent;
1622 
1623   // If we have a decl in a module partition, it is part of the containing
1624   // module (which is the only thing that can be importing it).
1625   if (NewM && OldM &&
1626       (OldM->Kind == Module::ModulePartitionInterface ||
1627        OldM->Kind == Module::ModulePartitionImplementation)) {
1628     return false;
1629   }
1630 
1631   if (NewM == OldM)
1632     return false;
1633 
1634   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1635   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1636   if (NewIsModuleInterface || OldIsModuleInterface) {
1637     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1638     //   if a declaration of D [...] appears in the purview of a module, all
1639     //   other such declarations shall appear in the purview of the same module
1640     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1641       << New
1642       << NewIsModuleInterface
1643       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1644       << OldIsModuleInterface
1645       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1646     Diag(Old->getLocation(), diag::note_previous_declaration);
1647     New->setInvalidDecl();
1648     return true;
1649   }
1650 
1651   return false;
1652 }
1653 
1654 // [module.interface]p6:
1655 // A redeclaration of an entity X is implicitly exported if X was introduced by
1656 // an exported declaration; otherwise it shall not be exported.
1657 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1658   // [module.interface]p1:
1659   // An export-declaration shall inhabit a namespace scope.
1660   //
1661   // So it is meaningless to talk about redeclaration which is not at namespace
1662   // scope.
1663   if (!New->getLexicalDeclContext()
1664            ->getNonTransparentContext()
1665            ->isFileContext() ||
1666       !Old->getLexicalDeclContext()
1667            ->getNonTransparentContext()
1668            ->isFileContext())
1669     return false;
1670 
1671   bool IsNewExported = New->isInExportDeclContext();
1672   bool IsOldExported = Old->isInExportDeclContext();
1673 
1674   // It should be irrevelant if both of them are not exported.
1675   if (!IsNewExported && !IsOldExported)
1676     return false;
1677 
1678   if (IsOldExported)
1679     return false;
1680 
1681   assert(IsNewExported);
1682 
1683   auto Lk = Old->getFormalLinkage();
1684   int S = 0;
1685   if (Lk == Linkage::InternalLinkage)
1686     S = 1;
1687   else if (Lk == Linkage::ModuleLinkage)
1688     S = 2;
1689   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1690   Diag(Old->getLocation(), diag::note_previous_declaration);
1691   return true;
1692 }
1693 
1694 // A wrapper function for checking the semantic restrictions of
1695 // a redeclaration within a module.
1696 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1697   if (CheckRedeclarationModuleOwnership(New, Old))
1698     return true;
1699 
1700   if (CheckRedeclarationExported(New, Old))
1701     return true;
1702 
1703   return false;
1704 }
1705 
1706 static bool isUsingDecl(NamedDecl *D) {
1707   return isa<UsingShadowDecl>(D) ||
1708          isa<UnresolvedUsingTypenameDecl>(D) ||
1709          isa<UnresolvedUsingValueDecl>(D);
1710 }
1711 
1712 /// Removes using shadow declarations from the lookup results.
1713 static void RemoveUsingDecls(LookupResult &R) {
1714   LookupResult::Filter F = R.makeFilter();
1715   while (F.hasNext())
1716     if (isUsingDecl(F.next()))
1717       F.erase();
1718 
1719   F.done();
1720 }
1721 
1722 /// Check for this common pattern:
1723 /// @code
1724 /// class S {
1725 ///   S(const S&); // DO NOT IMPLEMENT
1726 ///   void operator=(const S&); // DO NOT IMPLEMENT
1727 /// };
1728 /// @endcode
1729 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1730   // FIXME: Should check for private access too but access is set after we get
1731   // the decl here.
1732   if (D->doesThisDeclarationHaveABody())
1733     return false;
1734 
1735   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1736     return CD->isCopyConstructor();
1737   return D->isCopyAssignmentOperator();
1738 }
1739 
1740 // We need this to handle
1741 //
1742 // typedef struct {
1743 //   void *foo() { return 0; }
1744 // } A;
1745 //
1746 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1747 // for example. If 'A', foo will have external linkage. If we have '*A',
1748 // foo will have no linkage. Since we can't know until we get to the end
1749 // of the typedef, this function finds out if D might have non-external linkage.
1750 // Callers should verify at the end of the TU if it D has external linkage or
1751 // not.
1752 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1753   const DeclContext *DC = D->getDeclContext();
1754   while (!DC->isTranslationUnit()) {
1755     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1756       if (!RD->hasNameForLinkage())
1757         return true;
1758     }
1759     DC = DC->getParent();
1760   }
1761 
1762   return !D->isExternallyVisible();
1763 }
1764 
1765 // FIXME: This needs to be refactored; some other isInMainFile users want
1766 // these semantics.
1767 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1768   if (S.TUKind != TU_Complete)
1769     return false;
1770   return S.SourceMgr.isInMainFile(Loc);
1771 }
1772 
1773 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1774   assert(D);
1775 
1776   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1777     return false;
1778 
1779   // Ignore all entities declared within templates, and out-of-line definitions
1780   // of members of class templates.
1781   if (D->getDeclContext()->isDependentContext() ||
1782       D->getLexicalDeclContext()->isDependentContext())
1783     return false;
1784 
1785   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1786     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1787       return false;
1788     // A non-out-of-line declaration of a member specialization was implicitly
1789     // instantiated; it's the out-of-line declaration that we're interested in.
1790     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1791         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1792       return false;
1793 
1794     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1795       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1796         return false;
1797     } else {
1798       // 'static inline' functions are defined in headers; don't warn.
1799       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1800         return false;
1801     }
1802 
1803     if (FD->doesThisDeclarationHaveABody() &&
1804         Context.DeclMustBeEmitted(FD))
1805       return false;
1806   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1807     // Constants and utility variables are defined in headers with internal
1808     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1809     // like "inline".)
1810     if (!isMainFileLoc(*this, VD->getLocation()))
1811       return false;
1812 
1813     if (Context.DeclMustBeEmitted(VD))
1814       return false;
1815 
1816     if (VD->isStaticDataMember() &&
1817         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1818       return false;
1819     if (VD->isStaticDataMember() &&
1820         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1821         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1822       return false;
1823 
1824     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1825       return false;
1826   } else {
1827     return false;
1828   }
1829 
1830   // Only warn for unused decls internal to the translation unit.
1831   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1832   // for inline functions defined in the main source file, for instance.
1833   return mightHaveNonExternalLinkage(D);
1834 }
1835 
1836 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1837   if (!D)
1838     return;
1839 
1840   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1841     const FunctionDecl *First = FD->getFirstDecl();
1842     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1843       return; // First should already be in the vector.
1844   }
1845 
1846   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1847     const VarDecl *First = VD->getFirstDecl();
1848     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1849       return; // First should already be in the vector.
1850   }
1851 
1852   if (ShouldWarnIfUnusedFileScopedDecl(D))
1853     UnusedFileScopedDecls.push_back(D);
1854 }
1855 
1856 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1857   if (D->isInvalidDecl())
1858     return false;
1859 
1860   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1861     // For a decomposition declaration, warn if none of the bindings are
1862     // referenced, instead of if the variable itself is referenced (which
1863     // it is, by the bindings' expressions).
1864     for (auto *BD : DD->bindings())
1865       if (BD->isReferenced())
1866         return false;
1867   } else if (!D->getDeclName()) {
1868     return false;
1869   } else if (D->isReferenced() || D->isUsed()) {
1870     return false;
1871   }
1872 
1873   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1874     return false;
1875 
1876   if (isa<LabelDecl>(D))
1877     return true;
1878 
1879   // Except for labels, we only care about unused decls that are local to
1880   // functions.
1881   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1882   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1883     // For dependent types, the diagnostic is deferred.
1884     WithinFunction =
1885         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1886   if (!WithinFunction)
1887     return false;
1888 
1889   if (isa<TypedefNameDecl>(D))
1890     return true;
1891 
1892   // White-list anything that isn't a local variable.
1893   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1894     return false;
1895 
1896   // Types of valid local variables should be complete, so this should succeed.
1897   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1898 
1899     const Expr *Init = VD->getInit();
1900     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1901       Init = Cleanups->getSubExpr();
1902 
1903     const auto *Ty = VD->getType().getTypePtr();
1904 
1905     // Only look at the outermost level of typedef.
1906     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1907       // Allow anything marked with __attribute__((unused)).
1908       if (TT->getDecl()->hasAttr<UnusedAttr>())
1909         return false;
1910     }
1911 
1912     // Warn for reference variables whose initializtion performs lifetime
1913     // extension.
1914     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1915       if (MTE->getExtendingDecl()) {
1916         Ty = VD->getType().getNonReferenceType().getTypePtr();
1917         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1918       }
1919     }
1920 
1921     // If we failed to complete the type for some reason, or if the type is
1922     // dependent, don't diagnose the variable.
1923     if (Ty->isIncompleteType() || Ty->isDependentType())
1924       return false;
1925 
1926     // Look at the element type to ensure that the warning behaviour is
1927     // consistent for both scalars and arrays.
1928     Ty = Ty->getBaseElementTypeUnsafe();
1929 
1930     if (const TagType *TT = Ty->getAs<TagType>()) {
1931       const TagDecl *Tag = TT->getDecl();
1932       if (Tag->hasAttr<UnusedAttr>())
1933         return false;
1934 
1935       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1936         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1937           return false;
1938 
1939         if (Init) {
1940           const CXXConstructExpr *Construct =
1941             dyn_cast<CXXConstructExpr>(Init);
1942           if (Construct && !Construct->isElidable()) {
1943             CXXConstructorDecl *CD = Construct->getConstructor();
1944             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1945                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1946               return false;
1947           }
1948 
1949           // Suppress the warning if we don't know how this is constructed, and
1950           // it could possibly be non-trivial constructor.
1951           if (Init->isTypeDependent()) {
1952             for (const CXXConstructorDecl *Ctor : RD->ctors())
1953               if (!Ctor->isTrivial())
1954                 return false;
1955           }
1956 
1957           // Suppress the warning if the constructor is unresolved because
1958           // its arguments are dependent.
1959           if (isa<CXXUnresolvedConstructExpr>(Init))
1960             return false;
1961         }
1962       }
1963     }
1964 
1965     // TODO: __attribute__((unused)) templates?
1966   }
1967 
1968   return true;
1969 }
1970 
1971 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1972                                      FixItHint &Hint) {
1973   if (isa<LabelDecl>(D)) {
1974     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1975         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1976         true);
1977     if (AfterColon.isInvalid())
1978       return;
1979     Hint = FixItHint::CreateRemoval(
1980         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1981   }
1982 }
1983 
1984 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1985   if (D->getTypeForDecl()->isDependentType())
1986     return;
1987 
1988   for (auto *TmpD : D->decls()) {
1989     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1990       DiagnoseUnusedDecl(T);
1991     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1992       DiagnoseUnusedNestedTypedefs(R);
1993   }
1994 }
1995 
1996 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1997 /// unless they are marked attr(unused).
1998 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1999   if (!ShouldDiagnoseUnusedDecl(D))
2000     return;
2001 
2002   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2003     // typedefs can be referenced later on, so the diagnostics are emitted
2004     // at end-of-translation-unit.
2005     UnusedLocalTypedefNameCandidates.insert(TD);
2006     return;
2007   }
2008 
2009   FixItHint Hint;
2010   GenerateFixForUnusedDecl(D, Context, Hint);
2011 
2012   unsigned DiagID;
2013   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2014     DiagID = diag::warn_unused_exception_param;
2015   else if (isa<LabelDecl>(D))
2016     DiagID = diag::warn_unused_label;
2017   else
2018     DiagID = diag::warn_unused_variable;
2019 
2020   Diag(D->getLocation(), DiagID) << D << Hint;
2021 }
2022 
2023 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2024   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2025   // it's not really unused.
2026   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2027       VD->hasAttr<CleanupAttr>())
2028     return;
2029 
2030   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2031 
2032   if (Ty->isReferenceType() || Ty->isDependentType())
2033     return;
2034 
2035   if (const TagType *TT = Ty->getAs<TagType>()) {
2036     const TagDecl *Tag = TT->getDecl();
2037     if (Tag->hasAttr<UnusedAttr>())
2038       return;
2039     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2040     // mimic gcc's behavior.
2041     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2042       if (!RD->hasAttr<WarnUnusedAttr>())
2043         return;
2044     }
2045   }
2046 
2047   // Don't warn about __block Objective-C pointer variables, as they might
2048   // be assigned in the block but not used elsewhere for the purpose of lifetime
2049   // extension.
2050   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2051     return;
2052 
2053   // Don't warn about Objective-C pointer variables with precise lifetime
2054   // semantics; they can be used to ensure ARC releases the object at a known
2055   // time, which may mean assignment but no other references.
2056   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2057     return;
2058 
2059   auto iter = RefsMinusAssignments.find(VD);
2060   if (iter == RefsMinusAssignments.end())
2061     return;
2062 
2063   assert(iter->getSecond() >= 0 &&
2064          "Found a negative number of references to a VarDecl");
2065   if (iter->getSecond() != 0)
2066     return;
2067   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2068                                          : diag::warn_unused_but_set_variable;
2069   Diag(VD->getLocation(), DiagID) << VD;
2070 }
2071 
2072 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2073   // Verify that we have no forward references left.  If so, there was a goto
2074   // or address of a label taken, but no definition of it.  Label fwd
2075   // definitions are indicated with a null substmt which is also not a resolved
2076   // MS inline assembly label name.
2077   bool Diagnose = false;
2078   if (L->isMSAsmLabel())
2079     Diagnose = !L->isResolvedMSAsmLabel();
2080   else
2081     Diagnose = L->getStmt() == nullptr;
2082   if (Diagnose)
2083     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2084 }
2085 
2086 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2087   S->mergeNRVOIntoParent();
2088 
2089   if (S->decl_empty()) return;
2090   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2091          "Scope shouldn't contain decls!");
2092 
2093   for (auto *TmpD : S->decls()) {
2094     assert(TmpD && "This decl didn't get pushed??");
2095 
2096     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2097     NamedDecl *D = cast<NamedDecl>(TmpD);
2098 
2099     // Diagnose unused variables in this scope.
2100     if (!S->hasUnrecoverableErrorOccurred()) {
2101       DiagnoseUnusedDecl(D);
2102       if (const auto *RD = dyn_cast<RecordDecl>(D))
2103         DiagnoseUnusedNestedTypedefs(RD);
2104       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2105         DiagnoseUnusedButSetDecl(VD);
2106         RefsMinusAssignments.erase(VD);
2107       }
2108     }
2109 
2110     if (!D->getDeclName()) continue;
2111 
2112     // If this was a forward reference to a label, verify it was defined.
2113     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2114       CheckPoppedLabel(LD, *this);
2115 
2116     // Remove this name from our lexical scope, and warn on it if we haven't
2117     // already.
2118     IdResolver.RemoveDecl(D);
2119     auto ShadowI = ShadowingDecls.find(D);
2120     if (ShadowI != ShadowingDecls.end()) {
2121       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2122         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2123             << D << FD << FD->getParent();
2124         Diag(FD->getLocation(), diag::note_previous_declaration);
2125       }
2126       ShadowingDecls.erase(ShadowI);
2127     }
2128   }
2129 }
2130 
2131 /// Look for an Objective-C class in the translation unit.
2132 ///
2133 /// \param Id The name of the Objective-C class we're looking for. If
2134 /// typo-correction fixes this name, the Id will be updated
2135 /// to the fixed name.
2136 ///
2137 /// \param IdLoc The location of the name in the translation unit.
2138 ///
2139 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2140 /// if there is no class with the given name.
2141 ///
2142 /// \returns The declaration of the named Objective-C class, or NULL if the
2143 /// class could not be found.
2144 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2145                                               SourceLocation IdLoc,
2146                                               bool DoTypoCorrection) {
2147   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2148   // creation from this context.
2149   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2150 
2151   if (!IDecl && DoTypoCorrection) {
2152     // Perform typo correction at the given location, but only if we
2153     // find an Objective-C class name.
2154     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2155     if (TypoCorrection C =
2156             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2157                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2158       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2159       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2160       Id = IDecl->getIdentifier();
2161     }
2162   }
2163   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2164   // This routine must always return a class definition, if any.
2165   if (Def && Def->getDefinition())
2166       Def = Def->getDefinition();
2167   return Def;
2168 }
2169 
2170 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2171 /// from S, where a non-field would be declared. This routine copes
2172 /// with the difference between C and C++ scoping rules in structs and
2173 /// unions. For example, the following code is well-formed in C but
2174 /// ill-formed in C++:
2175 /// @code
2176 /// struct S6 {
2177 ///   enum { BAR } e;
2178 /// };
2179 ///
2180 /// void test_S6() {
2181 ///   struct S6 a;
2182 ///   a.e = BAR;
2183 /// }
2184 /// @endcode
2185 /// For the declaration of BAR, this routine will return a different
2186 /// scope. The scope S will be the scope of the unnamed enumeration
2187 /// within S6. In C++, this routine will return the scope associated
2188 /// with S6, because the enumeration's scope is a transparent
2189 /// context but structures can contain non-field names. In C, this
2190 /// routine will return the translation unit scope, since the
2191 /// enumeration's scope is a transparent context and structures cannot
2192 /// contain non-field names.
2193 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2194   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2195          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2196          (S->isClassScope() && !getLangOpts().CPlusPlus))
2197     S = S->getParent();
2198   return S;
2199 }
2200 
2201 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2202                                ASTContext::GetBuiltinTypeError Error) {
2203   switch (Error) {
2204   case ASTContext::GE_None:
2205     return "";
2206   case ASTContext::GE_Missing_type:
2207     return BuiltinInfo.getHeaderName(ID);
2208   case ASTContext::GE_Missing_stdio:
2209     return "stdio.h";
2210   case ASTContext::GE_Missing_setjmp:
2211     return "setjmp.h";
2212   case ASTContext::GE_Missing_ucontext:
2213     return "ucontext.h";
2214   }
2215   llvm_unreachable("unhandled error kind");
2216 }
2217 
2218 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2219                                   unsigned ID, SourceLocation Loc) {
2220   DeclContext *Parent = Context.getTranslationUnitDecl();
2221 
2222   if (getLangOpts().CPlusPlus) {
2223     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2224         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2225     CLinkageDecl->setImplicit();
2226     Parent->addDecl(CLinkageDecl);
2227     Parent = CLinkageDecl;
2228   }
2229 
2230   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2231                                            /*TInfo=*/nullptr, SC_Extern,
2232                                            getCurFPFeatures().isFPConstrained(),
2233                                            false, Type->isFunctionProtoType());
2234   New->setImplicit();
2235   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2236 
2237   // Create Decl objects for each parameter, adding them to the
2238   // FunctionDecl.
2239   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2240     SmallVector<ParmVarDecl *, 16> Params;
2241     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2242       ParmVarDecl *parm = ParmVarDecl::Create(
2243           Context, New, SourceLocation(), SourceLocation(), nullptr,
2244           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2245       parm->setScopeInfo(0, i);
2246       Params.push_back(parm);
2247     }
2248     New->setParams(Params);
2249   }
2250 
2251   AddKnownFunctionAttributes(New);
2252   return New;
2253 }
2254 
2255 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2256 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2257 /// if we're creating this built-in in anticipation of redeclaring the
2258 /// built-in.
2259 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2260                                      Scope *S, bool ForRedeclaration,
2261                                      SourceLocation Loc) {
2262   LookupNecessaryTypesForBuiltin(S, ID);
2263 
2264   ASTContext::GetBuiltinTypeError Error;
2265   QualType R = Context.GetBuiltinType(ID, Error);
2266   if (Error) {
2267     if (!ForRedeclaration)
2268       return nullptr;
2269 
2270     // If we have a builtin without an associated type we should not emit a
2271     // warning when we were not able to find a type for it.
2272     if (Error == ASTContext::GE_Missing_type ||
2273         Context.BuiltinInfo.allowTypeMismatch(ID))
2274       return nullptr;
2275 
2276     // If we could not find a type for setjmp it is because the jmp_buf type was
2277     // not defined prior to the setjmp declaration.
2278     if (Error == ASTContext::GE_Missing_setjmp) {
2279       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2280           << Context.BuiltinInfo.getName(ID);
2281       return nullptr;
2282     }
2283 
2284     // Generally, we emit a warning that the declaration requires the
2285     // appropriate header.
2286     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2287         << getHeaderName(Context.BuiltinInfo, ID, Error)
2288         << Context.BuiltinInfo.getName(ID);
2289     return nullptr;
2290   }
2291 
2292   if (!ForRedeclaration &&
2293       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2294        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2295     Diag(Loc, diag::ext_implicit_lib_function_decl)
2296         << Context.BuiltinInfo.getName(ID) << R;
2297     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2298       Diag(Loc, diag::note_include_header_or_declare)
2299           << Header << Context.BuiltinInfo.getName(ID);
2300   }
2301 
2302   if (R.isNull())
2303     return nullptr;
2304 
2305   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2306   RegisterLocallyScopedExternCDecl(New, S);
2307 
2308   // TUScope is the translation-unit scope to insert this function into.
2309   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2310   // relate Scopes to DeclContexts, and probably eliminate CurContext
2311   // entirely, but we're not there yet.
2312   DeclContext *SavedContext = CurContext;
2313   CurContext = New->getDeclContext();
2314   PushOnScopeChains(New, TUScope);
2315   CurContext = SavedContext;
2316   return New;
2317 }
2318 
2319 /// Typedef declarations don't have linkage, but they still denote the same
2320 /// entity if their types are the same.
2321 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2322 /// isSameEntity.
2323 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2324                                                      TypedefNameDecl *Decl,
2325                                                      LookupResult &Previous) {
2326   // This is only interesting when modules are enabled.
2327   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2328     return;
2329 
2330   // Empty sets are uninteresting.
2331   if (Previous.empty())
2332     return;
2333 
2334   LookupResult::Filter Filter = Previous.makeFilter();
2335   while (Filter.hasNext()) {
2336     NamedDecl *Old = Filter.next();
2337 
2338     // Non-hidden declarations are never ignored.
2339     if (S.isVisible(Old))
2340       continue;
2341 
2342     // Declarations of the same entity are not ignored, even if they have
2343     // different linkages.
2344     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2345       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2346                                 Decl->getUnderlyingType()))
2347         continue;
2348 
2349       // If both declarations give a tag declaration a typedef name for linkage
2350       // purposes, then they declare the same entity.
2351       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2352           Decl->getAnonDeclWithTypedefName())
2353         continue;
2354     }
2355 
2356     Filter.erase();
2357   }
2358 
2359   Filter.done();
2360 }
2361 
2362 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2363   QualType OldType;
2364   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2365     OldType = OldTypedef->getUnderlyingType();
2366   else
2367     OldType = Context.getTypeDeclType(Old);
2368   QualType NewType = New->getUnderlyingType();
2369 
2370   if (NewType->isVariablyModifiedType()) {
2371     // Must not redefine a typedef with a variably-modified type.
2372     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2373     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2374       << Kind << NewType;
2375     if (Old->getLocation().isValid())
2376       notePreviousDefinition(Old, New->getLocation());
2377     New->setInvalidDecl();
2378     return true;
2379   }
2380 
2381   if (OldType != NewType &&
2382       !OldType->isDependentType() &&
2383       !NewType->isDependentType() &&
2384       !Context.hasSameType(OldType, NewType)) {
2385     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2386     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2387       << Kind << NewType << OldType;
2388     if (Old->getLocation().isValid())
2389       notePreviousDefinition(Old, New->getLocation());
2390     New->setInvalidDecl();
2391     return true;
2392   }
2393   return false;
2394 }
2395 
2396 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2397 /// same name and scope as a previous declaration 'Old'.  Figure out
2398 /// how to resolve this situation, merging decls or emitting
2399 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2400 ///
2401 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2402                                 LookupResult &OldDecls) {
2403   // If the new decl is known invalid already, don't bother doing any
2404   // merging checks.
2405   if (New->isInvalidDecl()) return;
2406 
2407   // Allow multiple definitions for ObjC built-in typedefs.
2408   // FIXME: Verify the underlying types are equivalent!
2409   if (getLangOpts().ObjC) {
2410     const IdentifierInfo *TypeID = New->getIdentifier();
2411     switch (TypeID->getLength()) {
2412     default: break;
2413     case 2:
2414       {
2415         if (!TypeID->isStr("id"))
2416           break;
2417         QualType T = New->getUnderlyingType();
2418         if (!T->isPointerType())
2419           break;
2420         if (!T->isVoidPointerType()) {
2421           QualType PT = T->castAs<PointerType>()->getPointeeType();
2422           if (!PT->isStructureType())
2423             break;
2424         }
2425         Context.setObjCIdRedefinitionType(T);
2426         // Install the built-in type for 'id', ignoring the current definition.
2427         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2428         return;
2429       }
2430     case 5:
2431       if (!TypeID->isStr("Class"))
2432         break;
2433       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2434       // Install the built-in type for 'Class', ignoring the current definition.
2435       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2436       return;
2437     case 3:
2438       if (!TypeID->isStr("SEL"))
2439         break;
2440       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2441       // Install the built-in type for 'SEL', ignoring the current definition.
2442       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2443       return;
2444     }
2445     // Fall through - the typedef name was not a builtin type.
2446   }
2447 
2448   // Verify the old decl was also a type.
2449   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2450   if (!Old) {
2451     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2452       << New->getDeclName();
2453 
2454     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2455     if (OldD->getLocation().isValid())
2456       notePreviousDefinition(OldD, New->getLocation());
2457 
2458     return New->setInvalidDecl();
2459   }
2460 
2461   // If the old declaration is invalid, just give up here.
2462   if (Old->isInvalidDecl())
2463     return New->setInvalidDecl();
2464 
2465   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2466     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2467     auto *NewTag = New->getAnonDeclWithTypedefName();
2468     NamedDecl *Hidden = nullptr;
2469     if (OldTag && NewTag &&
2470         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2471         !hasVisibleDefinition(OldTag, &Hidden)) {
2472       // There is a definition of this tag, but it is not visible. Use it
2473       // instead of our tag.
2474       New->setTypeForDecl(OldTD->getTypeForDecl());
2475       if (OldTD->isModed())
2476         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2477                                     OldTD->getUnderlyingType());
2478       else
2479         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2480 
2481       // Make the old tag definition visible.
2482       makeMergedDefinitionVisible(Hidden);
2483 
2484       // If this was an unscoped enumeration, yank all of its enumerators
2485       // out of the scope.
2486       if (isa<EnumDecl>(NewTag)) {
2487         Scope *EnumScope = getNonFieldDeclScope(S);
2488         for (auto *D : NewTag->decls()) {
2489           auto *ED = cast<EnumConstantDecl>(D);
2490           assert(EnumScope->isDeclScope(ED));
2491           EnumScope->RemoveDecl(ED);
2492           IdResolver.RemoveDecl(ED);
2493           ED->getLexicalDeclContext()->removeDecl(ED);
2494         }
2495       }
2496     }
2497   }
2498 
2499   // If the typedef types are not identical, reject them in all languages and
2500   // with any extensions enabled.
2501   if (isIncompatibleTypedef(Old, New))
2502     return;
2503 
2504   // The types match.  Link up the redeclaration chain and merge attributes if
2505   // the old declaration was a typedef.
2506   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2507     New->setPreviousDecl(Typedef);
2508     mergeDeclAttributes(New, Old);
2509   }
2510 
2511   if (getLangOpts().MicrosoftExt)
2512     return;
2513 
2514   if (getLangOpts().CPlusPlus) {
2515     // C++ [dcl.typedef]p2:
2516     //   In a given non-class scope, a typedef specifier can be used to
2517     //   redefine the name of any type declared in that scope to refer
2518     //   to the type to which it already refers.
2519     if (!isa<CXXRecordDecl>(CurContext))
2520       return;
2521 
2522     // C++0x [dcl.typedef]p4:
2523     //   In a given class scope, a typedef specifier can be used to redefine
2524     //   any class-name declared in that scope that is not also a typedef-name
2525     //   to refer to the type to which it already refers.
2526     //
2527     // This wording came in via DR424, which was a correction to the
2528     // wording in DR56, which accidentally banned code like:
2529     //
2530     //   struct S {
2531     //     typedef struct A { } A;
2532     //   };
2533     //
2534     // in the C++03 standard. We implement the C++0x semantics, which
2535     // allow the above but disallow
2536     //
2537     //   struct S {
2538     //     typedef int I;
2539     //     typedef int I;
2540     //   };
2541     //
2542     // since that was the intent of DR56.
2543     if (!isa<TypedefNameDecl>(Old))
2544       return;
2545 
2546     Diag(New->getLocation(), diag::err_redefinition)
2547       << New->getDeclName();
2548     notePreviousDefinition(Old, New->getLocation());
2549     return New->setInvalidDecl();
2550   }
2551 
2552   // Modules always permit redefinition of typedefs, as does C11.
2553   if (getLangOpts().Modules || getLangOpts().C11)
2554     return;
2555 
2556   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2557   // is normally mapped to an error, but can be controlled with
2558   // -Wtypedef-redefinition.  If either the original or the redefinition is
2559   // in a system header, don't emit this for compatibility with GCC.
2560   if (getDiagnostics().getSuppressSystemWarnings() &&
2561       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2562       (Old->isImplicit() ||
2563        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2564        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2565     return;
2566 
2567   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2568     << New->getDeclName();
2569   notePreviousDefinition(Old, New->getLocation());
2570 }
2571 
2572 /// DeclhasAttr - returns true if decl Declaration already has the target
2573 /// attribute.
2574 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2575   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2576   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2577   for (const auto *i : D->attrs())
2578     if (i->getKind() == A->getKind()) {
2579       if (Ann) {
2580         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2581           return true;
2582         continue;
2583       }
2584       // FIXME: Don't hardcode this check
2585       if (OA && isa<OwnershipAttr>(i))
2586         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2587       return true;
2588     }
2589 
2590   return false;
2591 }
2592 
2593 static bool isAttributeTargetADefinition(Decl *D) {
2594   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2595     return VD->isThisDeclarationADefinition();
2596   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2597     return TD->isCompleteDefinition() || TD->isBeingDefined();
2598   return true;
2599 }
2600 
2601 /// Merge alignment attributes from \p Old to \p New, taking into account the
2602 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2603 ///
2604 /// \return \c true if any attributes were added to \p New.
2605 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2606   // Look for alignas attributes on Old, and pick out whichever attribute
2607   // specifies the strictest alignment requirement.
2608   AlignedAttr *OldAlignasAttr = nullptr;
2609   AlignedAttr *OldStrictestAlignAttr = nullptr;
2610   unsigned OldAlign = 0;
2611   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2612     // FIXME: We have no way of representing inherited dependent alignments
2613     // in a case like:
2614     //   template<int A, int B> struct alignas(A) X;
2615     //   template<int A, int B> struct alignas(B) X {};
2616     // For now, we just ignore any alignas attributes which are not on the
2617     // definition in such a case.
2618     if (I->isAlignmentDependent())
2619       return false;
2620 
2621     if (I->isAlignas())
2622       OldAlignasAttr = I;
2623 
2624     unsigned Align = I->getAlignment(S.Context);
2625     if (Align > OldAlign) {
2626       OldAlign = Align;
2627       OldStrictestAlignAttr = I;
2628     }
2629   }
2630 
2631   // Look for alignas attributes on New.
2632   AlignedAttr *NewAlignasAttr = nullptr;
2633   unsigned NewAlign = 0;
2634   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2635     if (I->isAlignmentDependent())
2636       return false;
2637 
2638     if (I->isAlignas())
2639       NewAlignasAttr = I;
2640 
2641     unsigned Align = I->getAlignment(S.Context);
2642     if (Align > NewAlign)
2643       NewAlign = Align;
2644   }
2645 
2646   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2647     // Both declarations have 'alignas' attributes. We require them to match.
2648     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2649     // fall short. (If two declarations both have alignas, they must both match
2650     // every definition, and so must match each other if there is a definition.)
2651 
2652     // If either declaration only contains 'alignas(0)' specifiers, then it
2653     // specifies the natural alignment for the type.
2654     if (OldAlign == 0 || NewAlign == 0) {
2655       QualType Ty;
2656       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2657         Ty = VD->getType();
2658       else
2659         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2660 
2661       if (OldAlign == 0)
2662         OldAlign = S.Context.getTypeAlign(Ty);
2663       if (NewAlign == 0)
2664         NewAlign = S.Context.getTypeAlign(Ty);
2665     }
2666 
2667     if (OldAlign != NewAlign) {
2668       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2669         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2670         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2671       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2672     }
2673   }
2674 
2675   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2676     // C++11 [dcl.align]p6:
2677     //   if any declaration of an entity has an alignment-specifier,
2678     //   every defining declaration of that entity shall specify an
2679     //   equivalent alignment.
2680     // C11 6.7.5/7:
2681     //   If the definition of an object does not have an alignment
2682     //   specifier, any other declaration of that object shall also
2683     //   have no alignment specifier.
2684     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2685       << OldAlignasAttr;
2686     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2687       << OldAlignasAttr;
2688   }
2689 
2690   bool AnyAdded = false;
2691 
2692   // Ensure we have an attribute representing the strictest alignment.
2693   if (OldAlign > NewAlign) {
2694     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2695     Clone->setInherited(true);
2696     New->addAttr(Clone);
2697     AnyAdded = true;
2698   }
2699 
2700   // Ensure we have an alignas attribute if the old declaration had one.
2701   if (OldAlignasAttr && !NewAlignasAttr &&
2702       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2703     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2704     Clone->setInherited(true);
2705     New->addAttr(Clone);
2706     AnyAdded = true;
2707   }
2708 
2709   return AnyAdded;
2710 }
2711 
2712 #define WANT_DECL_MERGE_LOGIC
2713 #include "clang/Sema/AttrParsedAttrImpl.inc"
2714 #undef WANT_DECL_MERGE_LOGIC
2715 
2716 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2717                                const InheritableAttr *Attr,
2718                                Sema::AvailabilityMergeKind AMK) {
2719   // Diagnose any mutual exclusions between the attribute that we want to add
2720   // and attributes that already exist on the declaration.
2721   if (!DiagnoseMutualExclusions(S, D, Attr))
2722     return false;
2723 
2724   // This function copies an attribute Attr from a previous declaration to the
2725   // new declaration D if the new declaration doesn't itself have that attribute
2726   // yet or if that attribute allows duplicates.
2727   // If you're adding a new attribute that requires logic different from
2728   // "use explicit attribute on decl if present, else use attribute from
2729   // previous decl", for example if the attribute needs to be consistent
2730   // between redeclarations, you need to call a custom merge function here.
2731   InheritableAttr *NewAttr = nullptr;
2732   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2733     NewAttr = S.mergeAvailabilityAttr(
2734         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2735         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2736         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2737         AA->getPriority());
2738   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2739     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2740   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2741     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2742   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2743     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2744   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2745     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2746   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2747     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2748   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2749     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2750                                 FA->getFirstArg());
2751   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2752     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2753   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2754     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2755   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2756     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2757                                        IA->getInheritanceModel());
2758   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2759     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2760                                       &S.Context.Idents.get(AA->getSpelling()));
2761   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2762            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2763             isa<CUDAGlobalAttr>(Attr))) {
2764     // CUDA target attributes are part of function signature for
2765     // overloading purposes and must not be merged.
2766     return false;
2767   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2768     NewAttr = S.mergeMinSizeAttr(D, *MA);
2769   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2770     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2771   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2772     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2773   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2774     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2775   else if (isa<AlignedAttr>(Attr))
2776     // AlignedAttrs are handled separately, because we need to handle all
2777     // such attributes on a declaration at the same time.
2778     NewAttr = nullptr;
2779   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2780            (AMK == Sema::AMK_Override ||
2781             AMK == Sema::AMK_ProtocolImplementation ||
2782             AMK == Sema::AMK_OptionalProtocolImplementation))
2783     NewAttr = nullptr;
2784   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2785     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2786   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2787     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2788   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2789     NewAttr = S.mergeImportNameAttr(D, *INA);
2790   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2791     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2792   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2793     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2794   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2795     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2796   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2797     NewAttr =
2798         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2799   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2800     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2801 
2802   if (NewAttr) {
2803     NewAttr->setInherited(true);
2804     D->addAttr(NewAttr);
2805     if (isa<MSInheritanceAttr>(NewAttr))
2806       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2807     return true;
2808   }
2809 
2810   return false;
2811 }
2812 
2813 static const NamedDecl *getDefinition(const Decl *D) {
2814   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2815     return TD->getDefinition();
2816   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2817     const VarDecl *Def = VD->getDefinition();
2818     if (Def)
2819       return Def;
2820     return VD->getActingDefinition();
2821   }
2822   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2823     const FunctionDecl *Def = nullptr;
2824     if (FD->isDefined(Def, true))
2825       return Def;
2826   }
2827   return nullptr;
2828 }
2829 
2830 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2831   for (const auto *Attribute : D->attrs())
2832     if (Attribute->getKind() == Kind)
2833       return true;
2834   return false;
2835 }
2836 
2837 /// checkNewAttributesAfterDef - If we already have a definition, check that
2838 /// there are no new attributes in this declaration.
2839 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2840   if (!New->hasAttrs())
2841     return;
2842 
2843   const NamedDecl *Def = getDefinition(Old);
2844   if (!Def || Def == New)
2845     return;
2846 
2847   AttrVec &NewAttributes = New->getAttrs();
2848   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2849     const Attr *NewAttribute = NewAttributes[I];
2850 
2851     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2852       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2853         Sema::SkipBodyInfo SkipBody;
2854         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2855 
2856         // If we're skipping this definition, drop the "alias" attribute.
2857         if (SkipBody.ShouldSkip) {
2858           NewAttributes.erase(NewAttributes.begin() + I);
2859           --E;
2860           continue;
2861         }
2862       } else {
2863         VarDecl *VD = cast<VarDecl>(New);
2864         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2865                                 VarDecl::TentativeDefinition
2866                             ? diag::err_alias_after_tentative
2867                             : diag::err_redefinition;
2868         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2869         if (Diag == diag::err_redefinition)
2870           S.notePreviousDefinition(Def, VD->getLocation());
2871         else
2872           S.Diag(Def->getLocation(), diag::note_previous_definition);
2873         VD->setInvalidDecl();
2874       }
2875       ++I;
2876       continue;
2877     }
2878 
2879     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2880       // Tentative definitions are only interesting for the alias check above.
2881       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2882         ++I;
2883         continue;
2884       }
2885     }
2886 
2887     if (hasAttribute(Def, NewAttribute->getKind())) {
2888       ++I;
2889       continue; // regular attr merging will take care of validating this.
2890     }
2891 
2892     if (isa<C11NoReturnAttr>(NewAttribute)) {
2893       // C's _Noreturn is allowed to be added to a function after it is defined.
2894       ++I;
2895       continue;
2896     } else if (isa<UuidAttr>(NewAttribute)) {
2897       // msvc will allow a subsequent definition to add an uuid to a class
2898       ++I;
2899       continue;
2900     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2901       if (AA->isAlignas()) {
2902         // C++11 [dcl.align]p6:
2903         //   if any declaration of an entity has an alignment-specifier,
2904         //   every defining declaration of that entity shall specify an
2905         //   equivalent alignment.
2906         // C11 6.7.5/7:
2907         //   If the definition of an object does not have an alignment
2908         //   specifier, any other declaration of that object shall also
2909         //   have no alignment specifier.
2910         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2911           << AA;
2912         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2913           << AA;
2914         NewAttributes.erase(NewAttributes.begin() + I);
2915         --E;
2916         continue;
2917       }
2918     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2919       // If there is a C definition followed by a redeclaration with this
2920       // attribute then there are two different definitions. In C++, prefer the
2921       // standard diagnostics.
2922       if (!S.getLangOpts().CPlusPlus) {
2923         S.Diag(NewAttribute->getLocation(),
2924                diag::err_loader_uninitialized_redeclaration);
2925         S.Diag(Def->getLocation(), diag::note_previous_definition);
2926         NewAttributes.erase(NewAttributes.begin() + I);
2927         --E;
2928         continue;
2929       }
2930     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2931                cast<VarDecl>(New)->isInline() &&
2932                !cast<VarDecl>(New)->isInlineSpecified()) {
2933       // Don't warn about applying selectany to implicitly inline variables.
2934       // Older compilers and language modes would require the use of selectany
2935       // to make such variables inline, and it would have no effect if we
2936       // honored it.
2937       ++I;
2938       continue;
2939     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2940       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2941       // declarations after defintions.
2942       ++I;
2943       continue;
2944     }
2945 
2946     S.Diag(NewAttribute->getLocation(),
2947            diag::warn_attribute_precede_definition);
2948     S.Diag(Def->getLocation(), diag::note_previous_definition);
2949     NewAttributes.erase(NewAttributes.begin() + I);
2950     --E;
2951   }
2952 }
2953 
2954 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2955                                      const ConstInitAttr *CIAttr,
2956                                      bool AttrBeforeInit) {
2957   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2958 
2959   // Figure out a good way to write this specifier on the old declaration.
2960   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2961   // enough of the attribute list spelling information to extract that without
2962   // heroics.
2963   std::string SuitableSpelling;
2964   if (S.getLangOpts().CPlusPlus20)
2965     SuitableSpelling = std::string(
2966         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2967   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2968     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2969         InsertLoc, {tok::l_square, tok::l_square,
2970                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2971                     S.PP.getIdentifierInfo("require_constant_initialization"),
2972                     tok::r_square, tok::r_square}));
2973   if (SuitableSpelling.empty())
2974     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2975         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2976                     S.PP.getIdentifierInfo("require_constant_initialization"),
2977                     tok::r_paren, tok::r_paren}));
2978   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2979     SuitableSpelling = "constinit";
2980   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2981     SuitableSpelling = "[[clang::require_constant_initialization]]";
2982   if (SuitableSpelling.empty())
2983     SuitableSpelling = "__attribute__((require_constant_initialization))";
2984   SuitableSpelling += " ";
2985 
2986   if (AttrBeforeInit) {
2987     // extern constinit int a;
2988     // int a = 0; // error (missing 'constinit'), accepted as extension
2989     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2990     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2991         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2992     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2993   } else {
2994     // int a = 0;
2995     // constinit extern int a; // error (missing 'constinit')
2996     S.Diag(CIAttr->getLocation(),
2997            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2998                                  : diag::warn_require_const_init_added_too_late)
2999         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3000     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3001         << CIAttr->isConstinit()
3002         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3003   }
3004 }
3005 
3006 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3007 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3008                                AvailabilityMergeKind AMK) {
3009   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3010     UsedAttr *NewAttr = OldAttr->clone(Context);
3011     NewAttr->setInherited(true);
3012     New->addAttr(NewAttr);
3013   }
3014   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3015     RetainAttr *NewAttr = OldAttr->clone(Context);
3016     NewAttr->setInherited(true);
3017     New->addAttr(NewAttr);
3018   }
3019 
3020   if (!Old->hasAttrs() && !New->hasAttrs())
3021     return;
3022 
3023   // [dcl.constinit]p1:
3024   //   If the [constinit] specifier is applied to any declaration of a
3025   //   variable, it shall be applied to the initializing declaration.
3026   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3027   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3028   if (bool(OldConstInit) != bool(NewConstInit)) {
3029     const auto *OldVD = cast<VarDecl>(Old);
3030     auto *NewVD = cast<VarDecl>(New);
3031 
3032     // Find the initializing declaration. Note that we might not have linked
3033     // the new declaration into the redeclaration chain yet.
3034     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3035     if (!InitDecl &&
3036         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3037       InitDecl = NewVD;
3038 
3039     if (InitDecl == NewVD) {
3040       // This is the initializing declaration. If it would inherit 'constinit',
3041       // that's ill-formed. (Note that we do not apply this to the attribute
3042       // form).
3043       if (OldConstInit && OldConstInit->isConstinit())
3044         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3045                                  /*AttrBeforeInit=*/true);
3046     } else if (NewConstInit) {
3047       // This is the first time we've been told that this declaration should
3048       // have a constant initializer. If we already saw the initializing
3049       // declaration, this is too late.
3050       if (InitDecl && InitDecl != NewVD) {
3051         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3052                                  /*AttrBeforeInit=*/false);
3053         NewVD->dropAttr<ConstInitAttr>();
3054       }
3055     }
3056   }
3057 
3058   // Attributes declared post-definition are currently ignored.
3059   checkNewAttributesAfterDef(*this, New, Old);
3060 
3061   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3062     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3063       if (!OldA->isEquivalent(NewA)) {
3064         // This redeclaration changes __asm__ label.
3065         Diag(New->getLocation(), diag::err_different_asm_label);
3066         Diag(OldA->getLocation(), diag::note_previous_declaration);
3067       }
3068     } else if (Old->isUsed()) {
3069       // This redeclaration adds an __asm__ label to a declaration that has
3070       // already been ODR-used.
3071       Diag(New->getLocation(), diag::err_late_asm_label_name)
3072         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3073     }
3074   }
3075 
3076   // Re-declaration cannot add abi_tag's.
3077   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3078     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3079       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3080         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3081           Diag(NewAbiTagAttr->getLocation(),
3082                diag::err_new_abi_tag_on_redeclaration)
3083               << NewTag;
3084           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3085         }
3086       }
3087     } else {
3088       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3089       Diag(Old->getLocation(), diag::note_previous_declaration);
3090     }
3091   }
3092 
3093   // This redeclaration adds a section attribute.
3094   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3095     if (auto *VD = dyn_cast<VarDecl>(New)) {
3096       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3097         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3098         Diag(Old->getLocation(), diag::note_previous_declaration);
3099       }
3100     }
3101   }
3102 
3103   // Redeclaration adds code-seg attribute.
3104   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3105   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3106       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3107     Diag(New->getLocation(), diag::warn_mismatched_section)
3108          << 0 /*codeseg*/;
3109     Diag(Old->getLocation(), diag::note_previous_declaration);
3110   }
3111 
3112   if (!Old->hasAttrs())
3113     return;
3114 
3115   bool foundAny = New->hasAttrs();
3116 
3117   // Ensure that any moving of objects within the allocated map is done before
3118   // we process them.
3119   if (!foundAny) New->setAttrs(AttrVec());
3120 
3121   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3122     // Ignore deprecated/unavailable/availability attributes if requested.
3123     AvailabilityMergeKind LocalAMK = AMK_None;
3124     if (isa<DeprecatedAttr>(I) ||
3125         isa<UnavailableAttr>(I) ||
3126         isa<AvailabilityAttr>(I)) {
3127       switch (AMK) {
3128       case AMK_None:
3129         continue;
3130 
3131       case AMK_Redeclaration:
3132       case AMK_Override:
3133       case AMK_ProtocolImplementation:
3134       case AMK_OptionalProtocolImplementation:
3135         LocalAMK = AMK;
3136         break;
3137       }
3138     }
3139 
3140     // Already handled.
3141     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3142       continue;
3143 
3144     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3145       foundAny = true;
3146   }
3147 
3148   if (mergeAlignedAttrs(*this, New, Old))
3149     foundAny = true;
3150 
3151   if (!foundAny) New->dropAttrs();
3152 }
3153 
3154 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3155 /// to the new one.
3156 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3157                                      const ParmVarDecl *oldDecl,
3158                                      Sema &S) {
3159   // C++11 [dcl.attr.depend]p2:
3160   //   The first declaration of a function shall specify the
3161   //   carries_dependency attribute for its declarator-id if any declaration
3162   //   of the function specifies the carries_dependency attribute.
3163   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3164   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3165     S.Diag(CDA->getLocation(),
3166            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3167     // Find the first declaration of the parameter.
3168     // FIXME: Should we build redeclaration chains for function parameters?
3169     const FunctionDecl *FirstFD =
3170       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3171     const ParmVarDecl *FirstVD =
3172       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3173     S.Diag(FirstVD->getLocation(),
3174            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3175   }
3176 
3177   if (!oldDecl->hasAttrs())
3178     return;
3179 
3180   bool foundAny = newDecl->hasAttrs();
3181 
3182   // Ensure that any moving of objects within the allocated map is
3183   // done before we process them.
3184   if (!foundAny) newDecl->setAttrs(AttrVec());
3185 
3186   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3187     if (!DeclHasAttr(newDecl, I)) {
3188       InheritableAttr *newAttr =
3189         cast<InheritableParamAttr>(I->clone(S.Context));
3190       newAttr->setInherited(true);
3191       newDecl->addAttr(newAttr);
3192       foundAny = true;
3193     }
3194   }
3195 
3196   if (!foundAny) newDecl->dropAttrs();
3197 }
3198 
3199 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3200                                 const ParmVarDecl *OldParam,
3201                                 Sema &S) {
3202   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3203     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3204       if (*Oldnullability != *Newnullability) {
3205         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3206           << DiagNullabilityKind(
3207                *Newnullability,
3208                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3209                 != 0))
3210           << DiagNullabilityKind(
3211                *Oldnullability,
3212                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3213                 != 0));
3214         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3215       }
3216     } else {
3217       QualType NewT = NewParam->getType();
3218       NewT = S.Context.getAttributedType(
3219                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3220                          NewT, NewT);
3221       NewParam->setType(NewT);
3222     }
3223   }
3224 }
3225 
3226 namespace {
3227 
3228 /// Used in MergeFunctionDecl to keep track of function parameters in
3229 /// C.
3230 struct GNUCompatibleParamWarning {
3231   ParmVarDecl *OldParm;
3232   ParmVarDecl *NewParm;
3233   QualType PromotedType;
3234 };
3235 
3236 } // end anonymous namespace
3237 
3238 // Determine whether the previous declaration was a definition, implicit
3239 // declaration, or a declaration.
3240 template <typename T>
3241 static std::pair<diag::kind, SourceLocation>
3242 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3243   diag::kind PrevDiag;
3244   SourceLocation OldLocation = Old->getLocation();
3245   if (Old->isThisDeclarationADefinition())
3246     PrevDiag = diag::note_previous_definition;
3247   else if (Old->isImplicit()) {
3248     PrevDiag = diag::note_previous_implicit_declaration;
3249     if (OldLocation.isInvalid())
3250       OldLocation = New->getLocation();
3251   } else
3252     PrevDiag = diag::note_previous_declaration;
3253   return std::make_pair(PrevDiag, OldLocation);
3254 }
3255 
3256 /// canRedefineFunction - checks if a function can be redefined. Currently,
3257 /// only extern inline functions can be redefined, and even then only in
3258 /// GNU89 mode.
3259 static bool canRedefineFunction(const FunctionDecl *FD,
3260                                 const LangOptions& LangOpts) {
3261   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3262           !LangOpts.CPlusPlus &&
3263           FD->isInlineSpecified() &&
3264           FD->getStorageClass() == SC_Extern);
3265 }
3266 
3267 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3268   const AttributedType *AT = T->getAs<AttributedType>();
3269   while (AT && !AT->isCallingConv())
3270     AT = AT->getModifiedType()->getAs<AttributedType>();
3271   return AT;
3272 }
3273 
3274 template <typename T>
3275 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3276   const DeclContext *DC = Old->getDeclContext();
3277   if (DC->isRecord())
3278     return false;
3279 
3280   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3281   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3282     return true;
3283   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3284     return true;
3285   return false;
3286 }
3287 
3288 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3289 static bool isExternC(VarTemplateDecl *) { return false; }
3290 static bool isExternC(FunctionTemplateDecl *) { return false; }
3291 
3292 /// Check whether a redeclaration of an entity introduced by a
3293 /// using-declaration is valid, given that we know it's not an overload
3294 /// (nor a hidden tag declaration).
3295 template<typename ExpectedDecl>
3296 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3297                                    ExpectedDecl *New) {
3298   // C++11 [basic.scope.declarative]p4:
3299   //   Given a set of declarations in a single declarative region, each of
3300   //   which specifies the same unqualified name,
3301   //   -- they shall all refer to the same entity, or all refer to functions
3302   //      and function templates; or
3303   //   -- exactly one declaration shall declare a class name or enumeration
3304   //      name that is not a typedef name and the other declarations shall all
3305   //      refer to the same variable or enumerator, or all refer to functions
3306   //      and function templates; in this case the class name or enumeration
3307   //      name is hidden (3.3.10).
3308 
3309   // C++11 [namespace.udecl]p14:
3310   //   If a function declaration in namespace scope or block scope has the
3311   //   same name and the same parameter-type-list as a function introduced
3312   //   by a using-declaration, and the declarations do not declare the same
3313   //   function, the program is ill-formed.
3314 
3315   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3316   if (Old &&
3317       !Old->getDeclContext()->getRedeclContext()->Equals(
3318           New->getDeclContext()->getRedeclContext()) &&
3319       !(isExternC(Old) && isExternC(New)))
3320     Old = nullptr;
3321 
3322   if (!Old) {
3323     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3324     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3325     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3326     return true;
3327   }
3328   return false;
3329 }
3330 
3331 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3332                                             const FunctionDecl *B) {
3333   assert(A->getNumParams() == B->getNumParams());
3334 
3335   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3336     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3337     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3338     if (AttrA == AttrB)
3339       return true;
3340     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3341            AttrA->isDynamic() == AttrB->isDynamic();
3342   };
3343 
3344   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3345 }
3346 
3347 /// If necessary, adjust the semantic declaration context for a qualified
3348 /// declaration to name the correct inline namespace within the qualifier.
3349 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3350                                                DeclaratorDecl *OldD) {
3351   // The only case where we need to update the DeclContext is when
3352   // redeclaration lookup for a qualified name finds a declaration
3353   // in an inline namespace within the context named by the qualifier:
3354   //
3355   //   inline namespace N { int f(); }
3356   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3357   //
3358   // For unqualified declarations, the semantic context *can* change
3359   // along the redeclaration chain (for local extern declarations,
3360   // extern "C" declarations, and friend declarations in particular).
3361   if (!NewD->getQualifier())
3362     return;
3363 
3364   // NewD is probably already in the right context.
3365   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3366   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3367   if (NamedDC->Equals(SemaDC))
3368     return;
3369 
3370   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3371           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3372          "unexpected context for redeclaration");
3373 
3374   auto *LexDC = NewD->getLexicalDeclContext();
3375   auto FixSemaDC = [=](NamedDecl *D) {
3376     if (!D)
3377       return;
3378     D->setDeclContext(SemaDC);
3379     D->setLexicalDeclContext(LexDC);
3380   };
3381 
3382   FixSemaDC(NewD);
3383   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3384     FixSemaDC(FD->getDescribedFunctionTemplate());
3385   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3386     FixSemaDC(VD->getDescribedVarTemplate());
3387 }
3388 
3389 /// MergeFunctionDecl - We just parsed a function 'New' from
3390 /// declarator D which has the same name and scope as a previous
3391 /// declaration 'Old'.  Figure out how to resolve this situation,
3392 /// merging decls or emitting diagnostics as appropriate.
3393 ///
3394 /// In C++, New and Old must be declarations that are not
3395 /// overloaded. Use IsOverload to determine whether New and Old are
3396 /// overloaded, and to select the Old declaration that New should be
3397 /// merged with.
3398 ///
3399 /// Returns true if there was an error, false otherwise.
3400 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3401                              Scope *S, bool MergeTypeWithOld) {
3402   // Verify the old decl was also a function.
3403   FunctionDecl *Old = OldD->getAsFunction();
3404   if (!Old) {
3405     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3406       if (New->getFriendObjectKind()) {
3407         Diag(New->getLocation(), diag::err_using_decl_friend);
3408         Diag(Shadow->getTargetDecl()->getLocation(),
3409              diag::note_using_decl_target);
3410         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3411             << 0;
3412         return true;
3413       }
3414 
3415       // Check whether the two declarations might declare the same function or
3416       // function template.
3417       if (FunctionTemplateDecl *NewTemplate =
3418               New->getDescribedFunctionTemplate()) {
3419         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3420                                                          NewTemplate))
3421           return true;
3422         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3423                          ->getAsFunction();
3424       } else {
3425         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3426           return true;
3427         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3428       }
3429     } else {
3430       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3431         << New->getDeclName();
3432       notePreviousDefinition(OldD, New->getLocation());
3433       return true;
3434     }
3435   }
3436 
3437   // If the old declaration was found in an inline namespace and the new
3438   // declaration was qualified, update the DeclContext to match.
3439   adjustDeclContextForDeclaratorDecl(New, Old);
3440 
3441   // If the old declaration is invalid, just give up here.
3442   if (Old->isInvalidDecl())
3443     return true;
3444 
3445   // Disallow redeclaration of some builtins.
3446   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3447     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3448     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3449         << Old << Old->getType();
3450     return true;
3451   }
3452 
3453   diag::kind PrevDiag;
3454   SourceLocation OldLocation;
3455   std::tie(PrevDiag, OldLocation) =
3456       getNoteDiagForInvalidRedeclaration(Old, New);
3457 
3458   // Don't complain about this if we're in GNU89 mode and the old function
3459   // is an extern inline function.
3460   // Don't complain about specializations. They are not supposed to have
3461   // storage classes.
3462   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3463       New->getStorageClass() == SC_Static &&
3464       Old->hasExternalFormalLinkage() &&
3465       !New->getTemplateSpecializationInfo() &&
3466       !canRedefineFunction(Old, getLangOpts())) {
3467     if (getLangOpts().MicrosoftExt) {
3468       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3469       Diag(OldLocation, PrevDiag);
3470     } else {
3471       Diag(New->getLocation(), diag::err_static_non_static) << New;
3472       Diag(OldLocation, PrevDiag);
3473       return true;
3474     }
3475   }
3476 
3477   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3478     if (!Old->hasAttr<InternalLinkageAttr>()) {
3479       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3480           << ILA;
3481       Diag(Old->getLocation(), diag::note_previous_declaration);
3482       New->dropAttr<InternalLinkageAttr>();
3483     }
3484 
3485   if (auto *EA = New->getAttr<ErrorAttr>()) {
3486     if (!Old->hasAttr<ErrorAttr>()) {
3487       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3488       Diag(Old->getLocation(), diag::note_previous_declaration);
3489       New->dropAttr<ErrorAttr>();
3490     }
3491   }
3492 
3493   if (CheckRedeclarationInModule(New, Old))
3494     return true;
3495 
3496   if (!getLangOpts().CPlusPlus) {
3497     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3498     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3499       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3500         << New << OldOvl;
3501 
3502       // Try our best to find a decl that actually has the overloadable
3503       // attribute for the note. In most cases (e.g. programs with only one
3504       // broken declaration/definition), this won't matter.
3505       //
3506       // FIXME: We could do this if we juggled some extra state in
3507       // OverloadableAttr, rather than just removing it.
3508       const Decl *DiagOld = Old;
3509       if (OldOvl) {
3510         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3511           const auto *A = D->getAttr<OverloadableAttr>();
3512           return A && !A->isImplicit();
3513         });
3514         // If we've implicitly added *all* of the overloadable attrs to this
3515         // chain, emitting a "previous redecl" note is pointless.
3516         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3517       }
3518 
3519       if (DiagOld)
3520         Diag(DiagOld->getLocation(),
3521              diag::note_attribute_overloadable_prev_overload)
3522           << OldOvl;
3523 
3524       if (OldOvl)
3525         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3526       else
3527         New->dropAttr<OverloadableAttr>();
3528     }
3529   }
3530 
3531   // If a function is first declared with a calling convention, but is later
3532   // declared or defined without one, all following decls assume the calling
3533   // convention of the first.
3534   //
3535   // It's OK if a function is first declared without a calling convention,
3536   // but is later declared or defined with the default calling convention.
3537   //
3538   // To test if either decl has an explicit calling convention, we look for
3539   // AttributedType sugar nodes on the type as written.  If they are missing or
3540   // were canonicalized away, we assume the calling convention was implicit.
3541   //
3542   // Note also that we DO NOT return at this point, because we still have
3543   // other tests to run.
3544   QualType OldQType = Context.getCanonicalType(Old->getType());
3545   QualType NewQType = Context.getCanonicalType(New->getType());
3546   const FunctionType *OldType = cast<FunctionType>(OldQType);
3547   const FunctionType *NewType = cast<FunctionType>(NewQType);
3548   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3549   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3550   bool RequiresAdjustment = false;
3551 
3552   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3553     FunctionDecl *First = Old->getFirstDecl();
3554     const FunctionType *FT =
3555         First->getType().getCanonicalType()->castAs<FunctionType>();
3556     FunctionType::ExtInfo FI = FT->getExtInfo();
3557     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3558     if (!NewCCExplicit) {
3559       // Inherit the CC from the previous declaration if it was specified
3560       // there but not here.
3561       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3562       RequiresAdjustment = true;
3563     } else if (Old->getBuiltinID()) {
3564       // Builtin attribute isn't propagated to the new one yet at this point,
3565       // so we check if the old one is a builtin.
3566 
3567       // Calling Conventions on a Builtin aren't really useful and setting a
3568       // default calling convention and cdecl'ing some builtin redeclarations is
3569       // common, so warn and ignore the calling convention on the redeclaration.
3570       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3571           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3572           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3573       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3574       RequiresAdjustment = true;
3575     } else {
3576       // Calling conventions aren't compatible, so complain.
3577       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3578       Diag(New->getLocation(), diag::err_cconv_change)
3579         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3580         << !FirstCCExplicit
3581         << (!FirstCCExplicit ? "" :
3582             FunctionType::getNameForCallConv(FI.getCC()));
3583 
3584       // Put the note on the first decl, since it is the one that matters.
3585       Diag(First->getLocation(), diag::note_previous_declaration);
3586       return true;
3587     }
3588   }
3589 
3590   // FIXME: diagnose the other way around?
3591   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3592     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3593     RequiresAdjustment = true;
3594   }
3595 
3596   // Merge regparm attribute.
3597   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3598       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3599     if (NewTypeInfo.getHasRegParm()) {
3600       Diag(New->getLocation(), diag::err_regparm_mismatch)
3601         << NewType->getRegParmType()
3602         << OldType->getRegParmType();
3603       Diag(OldLocation, diag::note_previous_declaration);
3604       return true;
3605     }
3606 
3607     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3608     RequiresAdjustment = true;
3609   }
3610 
3611   // Merge ns_returns_retained attribute.
3612   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3613     if (NewTypeInfo.getProducesResult()) {
3614       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3615           << "'ns_returns_retained'";
3616       Diag(OldLocation, diag::note_previous_declaration);
3617       return true;
3618     }
3619 
3620     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3621     RequiresAdjustment = true;
3622   }
3623 
3624   if (OldTypeInfo.getNoCallerSavedRegs() !=
3625       NewTypeInfo.getNoCallerSavedRegs()) {
3626     if (NewTypeInfo.getNoCallerSavedRegs()) {
3627       AnyX86NoCallerSavedRegistersAttr *Attr =
3628         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3629       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3630       Diag(OldLocation, diag::note_previous_declaration);
3631       return true;
3632     }
3633 
3634     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3635     RequiresAdjustment = true;
3636   }
3637 
3638   if (RequiresAdjustment) {
3639     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3640     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3641     New->setType(QualType(AdjustedType, 0));
3642     NewQType = Context.getCanonicalType(New->getType());
3643   }
3644 
3645   // If this redeclaration makes the function inline, we may need to add it to
3646   // UndefinedButUsed.
3647   if (!Old->isInlined() && New->isInlined() &&
3648       !New->hasAttr<GNUInlineAttr>() &&
3649       !getLangOpts().GNUInline &&
3650       Old->isUsed(false) &&
3651       !Old->isDefined() && !New->isThisDeclarationADefinition())
3652     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3653                                            SourceLocation()));
3654 
3655   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3656   // about it.
3657   if (New->hasAttr<GNUInlineAttr>() &&
3658       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3659     UndefinedButUsed.erase(Old->getCanonicalDecl());
3660   }
3661 
3662   // If pass_object_size params don't match up perfectly, this isn't a valid
3663   // redeclaration.
3664   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3665       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3666     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3667         << New->getDeclName();
3668     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3669     return true;
3670   }
3671 
3672   if (getLangOpts().CPlusPlus) {
3673     // C++1z [over.load]p2
3674     //   Certain function declarations cannot be overloaded:
3675     //     -- Function declarations that differ only in the return type,
3676     //        the exception specification, or both cannot be overloaded.
3677 
3678     // Check the exception specifications match. This may recompute the type of
3679     // both Old and New if it resolved exception specifications, so grab the
3680     // types again after this. Because this updates the type, we do this before
3681     // any of the other checks below, which may update the "de facto" NewQType
3682     // but do not necessarily update the type of New.
3683     if (CheckEquivalentExceptionSpec(Old, New))
3684       return true;
3685     OldQType = Context.getCanonicalType(Old->getType());
3686     NewQType = Context.getCanonicalType(New->getType());
3687 
3688     // Go back to the type source info to compare the declared return types,
3689     // per C++1y [dcl.type.auto]p13:
3690     //   Redeclarations or specializations of a function or function template
3691     //   with a declared return type that uses a placeholder type shall also
3692     //   use that placeholder, not a deduced type.
3693     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3694     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3695     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3696         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3697                                        OldDeclaredReturnType)) {
3698       QualType ResQT;
3699       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3700           OldDeclaredReturnType->isObjCObjectPointerType())
3701         // FIXME: This does the wrong thing for a deduced return type.
3702         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3703       if (ResQT.isNull()) {
3704         if (New->isCXXClassMember() && New->isOutOfLine())
3705           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3706               << New << New->getReturnTypeSourceRange();
3707         else
3708           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3709               << New->getReturnTypeSourceRange();
3710         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3711                                     << Old->getReturnTypeSourceRange();
3712         return true;
3713       }
3714       else
3715         NewQType = ResQT;
3716     }
3717 
3718     QualType OldReturnType = OldType->getReturnType();
3719     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3720     if (OldReturnType != NewReturnType) {
3721       // If this function has a deduced return type and has already been
3722       // defined, copy the deduced value from the old declaration.
3723       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3724       if (OldAT && OldAT->isDeduced()) {
3725         QualType DT = OldAT->getDeducedType();
3726         if (DT.isNull()) {
3727           New->setType(SubstAutoTypeDependent(New->getType()));
3728           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3729         } else {
3730           New->setType(SubstAutoType(New->getType(), DT));
3731           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3732         }
3733       }
3734     }
3735 
3736     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3737     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3738     if (OldMethod && NewMethod) {
3739       // Preserve triviality.
3740       NewMethod->setTrivial(OldMethod->isTrivial());
3741 
3742       // MSVC allows explicit template specialization at class scope:
3743       // 2 CXXMethodDecls referring to the same function will be injected.
3744       // We don't want a redeclaration error.
3745       bool IsClassScopeExplicitSpecialization =
3746                               OldMethod->isFunctionTemplateSpecialization() &&
3747                               NewMethod->isFunctionTemplateSpecialization();
3748       bool isFriend = NewMethod->getFriendObjectKind();
3749 
3750       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3751           !IsClassScopeExplicitSpecialization) {
3752         //    -- Member function declarations with the same name and the
3753         //       same parameter types cannot be overloaded if any of them
3754         //       is a static member function declaration.
3755         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3756           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3757           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3758           return true;
3759         }
3760 
3761         // C++ [class.mem]p1:
3762         //   [...] A member shall not be declared twice in the
3763         //   member-specification, except that a nested class or member
3764         //   class template can be declared and then later defined.
3765         if (!inTemplateInstantiation()) {
3766           unsigned NewDiag;
3767           if (isa<CXXConstructorDecl>(OldMethod))
3768             NewDiag = diag::err_constructor_redeclared;
3769           else if (isa<CXXDestructorDecl>(NewMethod))
3770             NewDiag = diag::err_destructor_redeclared;
3771           else if (isa<CXXConversionDecl>(NewMethod))
3772             NewDiag = diag::err_conv_function_redeclared;
3773           else
3774             NewDiag = diag::err_member_redeclared;
3775 
3776           Diag(New->getLocation(), NewDiag);
3777         } else {
3778           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3779             << New << New->getType();
3780         }
3781         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3782         return true;
3783 
3784       // Complain if this is an explicit declaration of a special
3785       // member that was initially declared implicitly.
3786       //
3787       // As an exception, it's okay to befriend such methods in order
3788       // to permit the implicit constructor/destructor/operator calls.
3789       } else if (OldMethod->isImplicit()) {
3790         if (isFriend) {
3791           NewMethod->setImplicit();
3792         } else {
3793           Diag(NewMethod->getLocation(),
3794                diag::err_definition_of_implicitly_declared_member)
3795             << New << getSpecialMember(OldMethod);
3796           return true;
3797         }
3798       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3799         Diag(NewMethod->getLocation(),
3800              diag::err_definition_of_explicitly_defaulted_member)
3801           << getSpecialMember(OldMethod);
3802         return true;
3803       }
3804     }
3805 
3806     // C++11 [dcl.attr.noreturn]p1:
3807     //   The first declaration of a function shall specify the noreturn
3808     //   attribute if any declaration of that function specifies the noreturn
3809     //   attribute.
3810     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3811       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3812         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3813             << NRA;
3814         Diag(Old->getLocation(), diag::note_previous_declaration);
3815       }
3816 
3817     // C++11 [dcl.attr.depend]p2:
3818     //   The first declaration of a function shall specify the
3819     //   carries_dependency attribute for its declarator-id if any declaration
3820     //   of the function specifies the carries_dependency attribute.
3821     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3822     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3823       Diag(CDA->getLocation(),
3824            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3825       Diag(Old->getFirstDecl()->getLocation(),
3826            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3827     }
3828 
3829     // (C++98 8.3.5p3):
3830     //   All declarations for a function shall agree exactly in both the
3831     //   return type and the parameter-type-list.
3832     // We also want to respect all the extended bits except noreturn.
3833 
3834     // noreturn should now match unless the old type info didn't have it.
3835     QualType OldQTypeForComparison = OldQType;
3836     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3837       auto *OldType = OldQType->castAs<FunctionProtoType>();
3838       const FunctionType *OldTypeForComparison
3839         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3840       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3841       assert(OldQTypeForComparison.isCanonical());
3842     }
3843 
3844     if (haveIncompatibleLanguageLinkages(Old, New)) {
3845       // As a special case, retain the language linkage from previous
3846       // declarations of a friend function as an extension.
3847       //
3848       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3849       // and is useful because there's otherwise no way to specify language
3850       // linkage within class scope.
3851       //
3852       // Check cautiously as the friend object kind isn't yet complete.
3853       if (New->getFriendObjectKind() != Decl::FOK_None) {
3854         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3855         Diag(OldLocation, PrevDiag);
3856       } else {
3857         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3858         Diag(OldLocation, PrevDiag);
3859         return true;
3860       }
3861     }
3862 
3863     // If the function types are compatible, merge the declarations. Ignore the
3864     // exception specifier because it was already checked above in
3865     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3866     // about incompatible types under -fms-compatibility.
3867     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3868                                                          NewQType))
3869       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3870 
3871     // If the types are imprecise (due to dependent constructs in friends or
3872     // local extern declarations), it's OK if they differ. We'll check again
3873     // during instantiation.
3874     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3875       return false;
3876 
3877     // Fall through for conflicting redeclarations and redefinitions.
3878   }
3879 
3880   // C: Function types need to be compatible, not identical. This handles
3881   // duplicate function decls like "void f(int); void f(enum X);" properly.
3882   if (!getLangOpts().CPlusPlus) {
3883     // If we are merging two functions where only one of them has a prototype,
3884     // we may have enough information to decide to issue a diagnostic that the
3885     // function without a protoype will change behavior in C2x. This handles
3886     // cases like:
3887     //   void i(); void i(int j);
3888     //   void i(int j); void i();
3889     //   void i(); void i(int j) {}
3890     // See ActOnFinishFunctionBody() for other cases of the behavior change
3891     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3892     // type without a prototype.
3893     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3894         !New->isImplicit() && !Old->isImplicit()) {
3895       const FunctionDecl *WithProto, *WithoutProto;
3896       if (New->hasWrittenPrototype()) {
3897         WithProto = New;
3898         WithoutProto = Old;
3899       } else {
3900         WithProto = Old;
3901         WithoutProto = New;
3902       }
3903 
3904       if (WithProto->getNumParams() != 0) {
3905         // The function definition has parameters, so this will change
3906         // behavior in C2x.
3907         //
3908         // If we already warned about about the function without a prototype
3909         // being deprecated, add a note that it also changes behavior. If we
3910         // didn't warn about it being deprecated (because the diagnostic is
3911         // not enabled), warn now that it is deprecated and changes behavior.
3912         bool AddNote = false;
3913         if (Diags.isIgnored(diag::warn_strict_prototypes,
3914                             WithoutProto->getLocation())) {
3915           if (WithoutProto->getBuiltinID() == 0 &&
3916               !WithoutProto->isImplicit() &&
3917               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3918                                                   WithProto->getLocation())) {
3919             PartialDiagnostic PD =
3920                 PDiag(diag::warn_non_prototype_changes_behavior);
3921             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3922               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3923                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3924             }
3925             Diag(WithoutProto->getLocation(), PD);
3926           }
3927         } else {
3928           AddNote = true;
3929         }
3930 
3931         // Because the function with a prototype has parameters but a previous
3932         // declaration had none, the function with the prototype will also
3933         // change behavior in C2x.
3934         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3935           if (SourceMgr.isBeforeInTranslationUnit(
3936                   WithProto->getLocation(), WithoutProto->getLocation())) {
3937             // If the function with the prototype comes before the function
3938             // without the prototype, we only want to diagnose the one without
3939             // the prototype.
3940             Diag(WithoutProto->getLocation(),
3941                  diag::warn_non_prototype_changes_behavior);
3942           } else {
3943             // Otherwise, diagnose the one with the prototype, and potentially
3944             // attach a note to the one without a prototype if needed.
3945             Diag(WithProto->getLocation(),
3946                  diag::warn_non_prototype_changes_behavior);
3947             if (AddNote && WithoutProto->getBuiltinID() == 0)
3948               Diag(WithoutProto->getLocation(),
3949                    diag::note_func_decl_changes_behavior);
3950           }
3951         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3952                    !WithoutProto->isImplicit()) {
3953           // If we were supposed to add a note but the function with a
3954           // prototype is a builtin or was implicitly declared, which means we
3955           // have nothing to attach the note to, so we issue a warning instead.
3956           Diag(WithoutProto->getLocation(),
3957                diag::warn_non_prototype_changes_behavior);
3958         }
3959       }
3960     }
3961 
3962     if (Context.typesAreCompatible(OldQType, NewQType)) {
3963       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3964       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3965       const FunctionProtoType *OldProto = nullptr;
3966       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3967           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3968         // The old declaration provided a function prototype, but the
3969         // new declaration does not. Merge in the prototype.
3970         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3971         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3972         NewQType =
3973             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3974                                     OldProto->getExtProtoInfo());
3975         New->setType(NewQType);
3976         New->setHasInheritedPrototype();
3977 
3978         // Synthesize parameters with the same types.
3979         SmallVector<ParmVarDecl *, 16> Params;
3980         for (const auto &ParamType : OldProto->param_types()) {
3981           ParmVarDecl *Param = ParmVarDecl::Create(
3982               Context, New, SourceLocation(), SourceLocation(), nullptr,
3983               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
3984           Param->setScopeInfo(0, Params.size());
3985           Param->setImplicit();
3986           Params.push_back(Param);
3987         }
3988 
3989         New->setParams(Params);
3990       }
3991 
3992       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3993     }
3994   }
3995 
3996   // Check if the function types are compatible when pointer size address
3997   // spaces are ignored.
3998   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3999     return false;
4000 
4001   // GNU C permits a K&R definition to follow a prototype declaration
4002   // if the declared types of the parameters in the K&R definition
4003   // match the types in the prototype declaration, even when the
4004   // promoted types of the parameters from the K&R definition differ
4005   // from the types in the prototype. GCC then keeps the types from
4006   // the prototype.
4007   //
4008   // If a variadic prototype is followed by a non-variadic K&R definition,
4009   // the K&R definition becomes variadic.  This is sort of an edge case, but
4010   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4011   // C99 6.9.1p8.
4012   if (!getLangOpts().CPlusPlus &&
4013       Old->hasPrototype() && !New->hasPrototype() &&
4014       New->getType()->getAs<FunctionProtoType>() &&
4015       Old->getNumParams() == New->getNumParams()) {
4016     SmallVector<QualType, 16> ArgTypes;
4017     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4018     const FunctionProtoType *OldProto
4019       = Old->getType()->getAs<FunctionProtoType>();
4020     const FunctionProtoType *NewProto
4021       = New->getType()->getAs<FunctionProtoType>();
4022 
4023     // Determine whether this is the GNU C extension.
4024     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4025                                                NewProto->getReturnType());
4026     bool LooseCompatible = !MergedReturn.isNull();
4027     for (unsigned Idx = 0, End = Old->getNumParams();
4028          LooseCompatible && Idx != End; ++Idx) {
4029       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4030       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4031       if (Context.typesAreCompatible(OldParm->getType(),
4032                                      NewProto->getParamType(Idx))) {
4033         ArgTypes.push_back(NewParm->getType());
4034       } else if (Context.typesAreCompatible(OldParm->getType(),
4035                                             NewParm->getType(),
4036                                             /*CompareUnqualified=*/true)) {
4037         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4038                                            NewProto->getParamType(Idx) };
4039         Warnings.push_back(Warn);
4040         ArgTypes.push_back(NewParm->getType());
4041       } else
4042         LooseCompatible = false;
4043     }
4044 
4045     if (LooseCompatible) {
4046       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4047         Diag(Warnings[Warn].NewParm->getLocation(),
4048              diag::ext_param_promoted_not_compatible_with_prototype)
4049           << Warnings[Warn].PromotedType
4050           << Warnings[Warn].OldParm->getType();
4051         if (Warnings[Warn].OldParm->getLocation().isValid())
4052           Diag(Warnings[Warn].OldParm->getLocation(),
4053                diag::note_previous_declaration);
4054       }
4055 
4056       if (MergeTypeWithOld)
4057         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4058                                              OldProto->getExtProtoInfo()));
4059       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4060     }
4061 
4062     // Fall through to diagnose conflicting types.
4063   }
4064 
4065   // A function that has already been declared has been redeclared or
4066   // defined with a different type; show an appropriate diagnostic.
4067 
4068   // If the previous declaration was an implicitly-generated builtin
4069   // declaration, then at the very least we should use a specialized note.
4070   unsigned BuiltinID;
4071   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4072     // If it's actually a library-defined builtin function like 'malloc'
4073     // or 'printf', just warn about the incompatible redeclaration.
4074     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4075       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4076       Diag(OldLocation, diag::note_previous_builtin_declaration)
4077         << Old << Old->getType();
4078       return false;
4079     }
4080 
4081     PrevDiag = diag::note_previous_builtin_declaration;
4082   }
4083 
4084   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4085   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4086   return true;
4087 }
4088 
4089 /// Completes the merge of two function declarations that are
4090 /// known to be compatible.
4091 ///
4092 /// This routine handles the merging of attributes and other
4093 /// properties of function declarations from the old declaration to
4094 /// the new declaration, once we know that New is in fact a
4095 /// redeclaration of Old.
4096 ///
4097 /// \returns false
4098 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4099                                         Scope *S, bool MergeTypeWithOld) {
4100   // Merge the attributes
4101   mergeDeclAttributes(New, Old);
4102 
4103   // Merge "pure" flag.
4104   if (Old->isPure())
4105     New->setPure();
4106 
4107   // Merge "used" flag.
4108   if (Old->getMostRecentDecl()->isUsed(false))
4109     New->setIsUsed();
4110 
4111   // Merge attributes from the parameters.  These can mismatch with K&R
4112   // declarations.
4113   if (New->getNumParams() == Old->getNumParams())
4114       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4115         ParmVarDecl *NewParam = New->getParamDecl(i);
4116         ParmVarDecl *OldParam = Old->getParamDecl(i);
4117         mergeParamDeclAttributes(NewParam, OldParam, *this);
4118         mergeParamDeclTypes(NewParam, OldParam, *this);
4119       }
4120 
4121   if (getLangOpts().CPlusPlus)
4122     return MergeCXXFunctionDecl(New, Old, S);
4123 
4124   // Merge the function types so the we get the composite types for the return
4125   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4126   // was visible.
4127   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4128   if (!Merged.isNull() && MergeTypeWithOld)
4129     New->setType(Merged);
4130 
4131   return false;
4132 }
4133 
4134 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4135                                 ObjCMethodDecl *oldMethod) {
4136   // Merge the attributes, including deprecated/unavailable
4137   AvailabilityMergeKind MergeKind =
4138       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4139           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4140                                      : AMK_ProtocolImplementation)
4141           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4142                                                            : AMK_Override;
4143 
4144   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4145 
4146   // Merge attributes from the parameters.
4147   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4148                                        oe = oldMethod->param_end();
4149   for (ObjCMethodDecl::param_iterator
4150          ni = newMethod->param_begin(), ne = newMethod->param_end();
4151        ni != ne && oi != oe; ++ni, ++oi)
4152     mergeParamDeclAttributes(*ni, *oi, *this);
4153 
4154   CheckObjCMethodOverride(newMethod, oldMethod);
4155 }
4156 
4157 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4158   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4159 
4160   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4161          ? diag::err_redefinition_different_type
4162          : diag::err_redeclaration_different_type)
4163     << New->getDeclName() << New->getType() << Old->getType();
4164 
4165   diag::kind PrevDiag;
4166   SourceLocation OldLocation;
4167   std::tie(PrevDiag, OldLocation)
4168     = getNoteDiagForInvalidRedeclaration(Old, New);
4169   S.Diag(OldLocation, PrevDiag);
4170   New->setInvalidDecl();
4171 }
4172 
4173 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4174 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4175 /// emitting diagnostics as appropriate.
4176 ///
4177 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4178 /// to here in AddInitializerToDecl. We can't check them before the initializer
4179 /// is attached.
4180 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4181                              bool MergeTypeWithOld) {
4182   if (New->isInvalidDecl() || Old->isInvalidDecl())
4183     return;
4184 
4185   QualType MergedT;
4186   if (getLangOpts().CPlusPlus) {
4187     if (New->getType()->isUndeducedType()) {
4188       // We don't know what the new type is until the initializer is attached.
4189       return;
4190     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4191       // These could still be something that needs exception specs checked.
4192       return MergeVarDeclExceptionSpecs(New, Old);
4193     }
4194     // C++ [basic.link]p10:
4195     //   [...] the types specified by all declarations referring to a given
4196     //   object or function shall be identical, except that declarations for an
4197     //   array object can specify array types that differ by the presence or
4198     //   absence of a major array bound (8.3.4).
4199     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4200       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4201       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4202 
4203       // We are merging a variable declaration New into Old. If it has an array
4204       // bound, and that bound differs from Old's bound, we should diagnose the
4205       // mismatch.
4206       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4207         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4208              PrevVD = PrevVD->getPreviousDecl()) {
4209           QualType PrevVDTy = PrevVD->getType();
4210           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4211             continue;
4212 
4213           if (!Context.hasSameType(New->getType(), PrevVDTy))
4214             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4215         }
4216       }
4217 
4218       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4219         if (Context.hasSameType(OldArray->getElementType(),
4220                                 NewArray->getElementType()))
4221           MergedT = New->getType();
4222       }
4223       // FIXME: Check visibility. New is hidden but has a complete type. If New
4224       // has no array bound, it should not inherit one from Old, if Old is not
4225       // visible.
4226       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4227         if (Context.hasSameType(OldArray->getElementType(),
4228                                 NewArray->getElementType()))
4229           MergedT = Old->getType();
4230       }
4231     }
4232     else if (New->getType()->isObjCObjectPointerType() &&
4233                Old->getType()->isObjCObjectPointerType()) {
4234       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4235                                               Old->getType());
4236     }
4237   } else {
4238     // C 6.2.7p2:
4239     //   All declarations that refer to the same object or function shall have
4240     //   compatible type.
4241     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4242   }
4243   if (MergedT.isNull()) {
4244     // It's OK if we couldn't merge types if either type is dependent, for a
4245     // block-scope variable. In other cases (static data members of class
4246     // templates, variable templates, ...), we require the types to be
4247     // equivalent.
4248     // FIXME: The C++ standard doesn't say anything about this.
4249     if ((New->getType()->isDependentType() ||
4250          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4251       // If the old type was dependent, we can't merge with it, so the new type
4252       // becomes dependent for now. We'll reproduce the original type when we
4253       // instantiate the TypeSourceInfo for the variable.
4254       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4255         New->setType(Context.DependentTy);
4256       return;
4257     }
4258     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4259   }
4260 
4261   // Don't actually update the type on the new declaration if the old
4262   // declaration was an extern declaration in a different scope.
4263   if (MergeTypeWithOld)
4264     New->setType(MergedT);
4265 }
4266 
4267 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4268                                   LookupResult &Previous) {
4269   // C11 6.2.7p4:
4270   //   For an identifier with internal or external linkage declared
4271   //   in a scope in which a prior declaration of that identifier is
4272   //   visible, if the prior declaration specifies internal or
4273   //   external linkage, the type of the identifier at the later
4274   //   declaration becomes the composite type.
4275   //
4276   // If the variable isn't visible, we do not merge with its type.
4277   if (Previous.isShadowed())
4278     return false;
4279 
4280   if (S.getLangOpts().CPlusPlus) {
4281     // C++11 [dcl.array]p3:
4282     //   If there is a preceding declaration of the entity in the same
4283     //   scope in which the bound was specified, an omitted array bound
4284     //   is taken to be the same as in that earlier declaration.
4285     return NewVD->isPreviousDeclInSameBlockScope() ||
4286            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4287             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4288   } else {
4289     // If the old declaration was function-local, don't merge with its
4290     // type unless we're in the same function.
4291     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4292            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4293   }
4294 }
4295 
4296 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4297 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4298 /// situation, merging decls or emitting diagnostics as appropriate.
4299 ///
4300 /// Tentative definition rules (C99 6.9.2p2) are checked by
4301 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4302 /// definitions here, since the initializer hasn't been attached.
4303 ///
4304 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4305   // If the new decl is already invalid, don't do any other checking.
4306   if (New->isInvalidDecl())
4307     return;
4308 
4309   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4310     return;
4311 
4312   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4313 
4314   // Verify the old decl was also a variable or variable template.
4315   VarDecl *Old = nullptr;
4316   VarTemplateDecl *OldTemplate = nullptr;
4317   if (Previous.isSingleResult()) {
4318     if (NewTemplate) {
4319       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4320       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4321 
4322       if (auto *Shadow =
4323               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4324         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4325           return New->setInvalidDecl();
4326     } else {
4327       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4328 
4329       if (auto *Shadow =
4330               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4331         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4332           return New->setInvalidDecl();
4333     }
4334   }
4335   if (!Old) {
4336     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4337         << New->getDeclName();
4338     notePreviousDefinition(Previous.getRepresentativeDecl(),
4339                            New->getLocation());
4340     return New->setInvalidDecl();
4341   }
4342 
4343   // If the old declaration was found in an inline namespace and the new
4344   // declaration was qualified, update the DeclContext to match.
4345   adjustDeclContextForDeclaratorDecl(New, Old);
4346 
4347   // Ensure the template parameters are compatible.
4348   if (NewTemplate &&
4349       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4350                                       OldTemplate->getTemplateParameters(),
4351                                       /*Complain=*/true, TPL_TemplateMatch))
4352     return New->setInvalidDecl();
4353 
4354   // C++ [class.mem]p1:
4355   //   A member shall not be declared twice in the member-specification [...]
4356   //
4357   // Here, we need only consider static data members.
4358   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4359     Diag(New->getLocation(), diag::err_duplicate_member)
4360       << New->getIdentifier();
4361     Diag(Old->getLocation(), diag::note_previous_declaration);
4362     New->setInvalidDecl();
4363   }
4364 
4365   mergeDeclAttributes(New, Old);
4366   // Warn if an already-declared variable is made a weak_import in a subsequent
4367   // declaration
4368   if (New->hasAttr<WeakImportAttr>() &&
4369       Old->getStorageClass() == SC_None &&
4370       !Old->hasAttr<WeakImportAttr>()) {
4371     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4372     Diag(Old->getLocation(), diag::note_previous_declaration);
4373     // Remove weak_import attribute on new declaration.
4374     New->dropAttr<WeakImportAttr>();
4375   }
4376 
4377   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4378     if (!Old->hasAttr<InternalLinkageAttr>()) {
4379       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4380           << ILA;
4381       Diag(Old->getLocation(), diag::note_previous_declaration);
4382       New->dropAttr<InternalLinkageAttr>();
4383     }
4384 
4385   // Merge the types.
4386   VarDecl *MostRecent = Old->getMostRecentDecl();
4387   if (MostRecent != Old) {
4388     MergeVarDeclTypes(New, MostRecent,
4389                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4390     if (New->isInvalidDecl())
4391       return;
4392   }
4393 
4394   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4395   if (New->isInvalidDecl())
4396     return;
4397 
4398   diag::kind PrevDiag;
4399   SourceLocation OldLocation;
4400   std::tie(PrevDiag, OldLocation) =
4401       getNoteDiagForInvalidRedeclaration(Old, New);
4402 
4403   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4404   if (New->getStorageClass() == SC_Static &&
4405       !New->isStaticDataMember() &&
4406       Old->hasExternalFormalLinkage()) {
4407     if (getLangOpts().MicrosoftExt) {
4408       Diag(New->getLocation(), diag::ext_static_non_static)
4409           << New->getDeclName();
4410       Diag(OldLocation, PrevDiag);
4411     } else {
4412       Diag(New->getLocation(), diag::err_static_non_static)
4413           << New->getDeclName();
4414       Diag(OldLocation, PrevDiag);
4415       return New->setInvalidDecl();
4416     }
4417   }
4418   // C99 6.2.2p4:
4419   //   For an identifier declared with the storage-class specifier
4420   //   extern in a scope in which a prior declaration of that
4421   //   identifier is visible,23) if the prior declaration specifies
4422   //   internal or external linkage, the linkage of the identifier at
4423   //   the later declaration is the same as the linkage specified at
4424   //   the prior declaration. If no prior declaration is visible, or
4425   //   if the prior declaration specifies no linkage, then the
4426   //   identifier has external linkage.
4427   if (New->hasExternalStorage() && Old->hasLinkage())
4428     /* Okay */;
4429   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4430            !New->isStaticDataMember() &&
4431            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4432     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4433     Diag(OldLocation, PrevDiag);
4434     return New->setInvalidDecl();
4435   }
4436 
4437   // Check if extern is followed by non-extern and vice-versa.
4438   if (New->hasExternalStorage() &&
4439       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4440     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4441     Diag(OldLocation, PrevDiag);
4442     return New->setInvalidDecl();
4443   }
4444   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4445       !New->hasExternalStorage()) {
4446     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4447     Diag(OldLocation, PrevDiag);
4448     return New->setInvalidDecl();
4449   }
4450 
4451   if (CheckRedeclarationInModule(New, Old))
4452     return;
4453 
4454   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4455 
4456   // FIXME: The test for external storage here seems wrong? We still
4457   // need to check for mismatches.
4458   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4459       // Don't complain about out-of-line definitions of static members.
4460       !(Old->getLexicalDeclContext()->isRecord() &&
4461         !New->getLexicalDeclContext()->isRecord())) {
4462     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4463     Diag(OldLocation, PrevDiag);
4464     return New->setInvalidDecl();
4465   }
4466 
4467   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4468     if (VarDecl *Def = Old->getDefinition()) {
4469       // C++1z [dcl.fcn.spec]p4:
4470       //   If the definition of a variable appears in a translation unit before
4471       //   its first declaration as inline, the program is ill-formed.
4472       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4473       Diag(Def->getLocation(), diag::note_previous_definition);
4474     }
4475   }
4476 
4477   // If this redeclaration makes the variable inline, we may need to add it to
4478   // UndefinedButUsed.
4479   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4480       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4481     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4482                                            SourceLocation()));
4483 
4484   if (New->getTLSKind() != Old->getTLSKind()) {
4485     if (!Old->getTLSKind()) {
4486       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4487       Diag(OldLocation, PrevDiag);
4488     } else if (!New->getTLSKind()) {
4489       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4490       Diag(OldLocation, PrevDiag);
4491     } else {
4492       // Do not allow redeclaration to change the variable between requiring
4493       // static and dynamic initialization.
4494       // FIXME: GCC allows this, but uses the TLS keyword on the first
4495       // declaration to determine the kind. Do we need to be compatible here?
4496       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4497         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4498       Diag(OldLocation, PrevDiag);
4499     }
4500   }
4501 
4502   // C++ doesn't have tentative definitions, so go right ahead and check here.
4503   if (getLangOpts().CPlusPlus &&
4504       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4505     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4506         Old->getCanonicalDecl()->isConstexpr()) {
4507       // This definition won't be a definition any more once it's been merged.
4508       Diag(New->getLocation(),
4509            diag::warn_deprecated_redundant_constexpr_static_def);
4510     } else if (VarDecl *Def = Old->getDefinition()) {
4511       if (checkVarDeclRedefinition(Def, New))
4512         return;
4513     }
4514   }
4515 
4516   if (haveIncompatibleLanguageLinkages(Old, New)) {
4517     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4518     Diag(OldLocation, PrevDiag);
4519     New->setInvalidDecl();
4520     return;
4521   }
4522 
4523   // Merge "used" flag.
4524   if (Old->getMostRecentDecl()->isUsed(false))
4525     New->setIsUsed();
4526 
4527   // Keep a chain of previous declarations.
4528   New->setPreviousDecl(Old);
4529   if (NewTemplate)
4530     NewTemplate->setPreviousDecl(OldTemplate);
4531 
4532   // Inherit access appropriately.
4533   New->setAccess(Old->getAccess());
4534   if (NewTemplate)
4535     NewTemplate->setAccess(New->getAccess());
4536 
4537   if (Old->isInline())
4538     New->setImplicitlyInline();
4539 }
4540 
4541 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4542   SourceManager &SrcMgr = getSourceManager();
4543   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4544   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4545   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4546   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4547   auto &HSI = PP.getHeaderSearchInfo();
4548   StringRef HdrFilename =
4549       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4550 
4551   auto noteFromModuleOrInclude = [&](Module *Mod,
4552                                      SourceLocation IncLoc) -> bool {
4553     // Redefinition errors with modules are common with non modular mapped
4554     // headers, example: a non-modular header H in module A that also gets
4555     // included directly in a TU. Pointing twice to the same header/definition
4556     // is confusing, try to get better diagnostics when modules is on.
4557     if (IncLoc.isValid()) {
4558       if (Mod) {
4559         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4560             << HdrFilename.str() << Mod->getFullModuleName();
4561         if (!Mod->DefinitionLoc.isInvalid())
4562           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4563               << Mod->getFullModuleName();
4564       } else {
4565         Diag(IncLoc, diag::note_redefinition_include_same_file)
4566             << HdrFilename.str();
4567       }
4568       return true;
4569     }
4570 
4571     return false;
4572   };
4573 
4574   // Is it the same file and same offset? Provide more information on why
4575   // this leads to a redefinition error.
4576   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4577     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4578     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4579     bool EmittedDiag =
4580         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4581     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4582 
4583     // If the header has no guards, emit a note suggesting one.
4584     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4585       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4586 
4587     if (EmittedDiag)
4588       return;
4589   }
4590 
4591   // Redefinition coming from different files or couldn't do better above.
4592   if (Old->getLocation().isValid())
4593     Diag(Old->getLocation(), diag::note_previous_definition);
4594 }
4595 
4596 /// We've just determined that \p Old and \p New both appear to be definitions
4597 /// of the same variable. Either diagnose or fix the problem.
4598 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4599   if (!hasVisibleDefinition(Old) &&
4600       (New->getFormalLinkage() == InternalLinkage ||
4601        New->isInline() ||
4602        New->getDescribedVarTemplate() ||
4603        New->getNumTemplateParameterLists() ||
4604        New->getDeclContext()->isDependentContext())) {
4605     // The previous definition is hidden, and multiple definitions are
4606     // permitted (in separate TUs). Demote this to a declaration.
4607     New->demoteThisDefinitionToDeclaration();
4608 
4609     // Make the canonical definition visible.
4610     if (auto *OldTD = Old->getDescribedVarTemplate())
4611       makeMergedDefinitionVisible(OldTD);
4612     makeMergedDefinitionVisible(Old);
4613     return false;
4614   } else {
4615     Diag(New->getLocation(), diag::err_redefinition) << New;
4616     notePreviousDefinition(Old, New->getLocation());
4617     New->setInvalidDecl();
4618     return true;
4619   }
4620 }
4621 
4622 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4623 /// no declarator (e.g. "struct foo;") is parsed.
4624 Decl *
4625 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4626                                  RecordDecl *&AnonRecord) {
4627   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4628                                     AnonRecord);
4629 }
4630 
4631 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4632 // disambiguate entities defined in different scopes.
4633 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4634 // compatibility.
4635 // We will pick our mangling number depending on which version of MSVC is being
4636 // targeted.
4637 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4638   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4639              ? S->getMSCurManglingNumber()
4640              : S->getMSLastManglingNumber();
4641 }
4642 
4643 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4644   if (!Context.getLangOpts().CPlusPlus)
4645     return;
4646 
4647   if (isa<CXXRecordDecl>(Tag->getParent())) {
4648     // If this tag is the direct child of a class, number it if
4649     // it is anonymous.
4650     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4651       return;
4652     MangleNumberingContext &MCtx =
4653         Context.getManglingNumberContext(Tag->getParent());
4654     Context.setManglingNumber(
4655         Tag, MCtx.getManglingNumber(
4656                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4657     return;
4658   }
4659 
4660   // If this tag isn't a direct child of a class, number it if it is local.
4661   MangleNumberingContext *MCtx;
4662   Decl *ManglingContextDecl;
4663   std::tie(MCtx, ManglingContextDecl) =
4664       getCurrentMangleNumberContext(Tag->getDeclContext());
4665   if (MCtx) {
4666     Context.setManglingNumber(
4667         Tag, MCtx->getManglingNumber(
4668                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4669   }
4670 }
4671 
4672 namespace {
4673 struct NonCLikeKind {
4674   enum {
4675     None,
4676     BaseClass,
4677     DefaultMemberInit,
4678     Lambda,
4679     Friend,
4680     OtherMember,
4681     Invalid,
4682   } Kind = None;
4683   SourceRange Range;
4684 
4685   explicit operator bool() { return Kind != None; }
4686 };
4687 }
4688 
4689 /// Determine whether a class is C-like, according to the rules of C++
4690 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4691 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4692   if (RD->isInvalidDecl())
4693     return {NonCLikeKind::Invalid, {}};
4694 
4695   // C++ [dcl.typedef]p9: [P1766R1]
4696   //   An unnamed class with a typedef name for linkage purposes shall not
4697   //
4698   //    -- have any base classes
4699   if (RD->getNumBases())
4700     return {NonCLikeKind::BaseClass,
4701             SourceRange(RD->bases_begin()->getBeginLoc(),
4702                         RD->bases_end()[-1].getEndLoc())};
4703   bool Invalid = false;
4704   for (Decl *D : RD->decls()) {
4705     // Don't complain about things we already diagnosed.
4706     if (D->isInvalidDecl()) {
4707       Invalid = true;
4708       continue;
4709     }
4710 
4711     //  -- have any [...] default member initializers
4712     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4713       if (FD->hasInClassInitializer()) {
4714         auto *Init = FD->getInClassInitializer();
4715         return {NonCLikeKind::DefaultMemberInit,
4716                 Init ? Init->getSourceRange() : D->getSourceRange()};
4717       }
4718       continue;
4719     }
4720 
4721     // FIXME: We don't allow friend declarations. This violates the wording of
4722     // P1766, but not the intent.
4723     if (isa<FriendDecl>(D))
4724       return {NonCLikeKind::Friend, D->getSourceRange()};
4725 
4726     //  -- declare any members other than non-static data members, member
4727     //     enumerations, or member classes,
4728     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4729         isa<EnumDecl>(D))
4730       continue;
4731     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4732     if (!MemberRD) {
4733       if (D->isImplicit())
4734         continue;
4735       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4736     }
4737 
4738     //  -- contain a lambda-expression,
4739     if (MemberRD->isLambda())
4740       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4741 
4742     //  and all member classes shall also satisfy these requirements
4743     //  (recursively).
4744     if (MemberRD->isThisDeclarationADefinition()) {
4745       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4746         return Kind;
4747     }
4748   }
4749 
4750   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4751 }
4752 
4753 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4754                                         TypedefNameDecl *NewTD) {
4755   if (TagFromDeclSpec->isInvalidDecl())
4756     return;
4757 
4758   // Do nothing if the tag already has a name for linkage purposes.
4759   if (TagFromDeclSpec->hasNameForLinkage())
4760     return;
4761 
4762   // A well-formed anonymous tag must always be a TUK_Definition.
4763   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4764 
4765   // The type must match the tag exactly;  no qualifiers allowed.
4766   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4767                            Context.getTagDeclType(TagFromDeclSpec))) {
4768     if (getLangOpts().CPlusPlus)
4769       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4770     return;
4771   }
4772 
4773   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4774   //   An unnamed class with a typedef name for linkage purposes shall [be
4775   //   C-like].
4776   //
4777   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4778   // shouldn't happen, but there are constructs that the language rule doesn't
4779   // disallow for which we can't reasonably avoid computing linkage early.
4780   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4781   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4782                              : NonCLikeKind();
4783   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4784   if (NonCLike || ChangesLinkage) {
4785     if (NonCLike.Kind == NonCLikeKind::Invalid)
4786       return;
4787 
4788     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4789     if (ChangesLinkage) {
4790       // If the linkage changes, we can't accept this as an extension.
4791       if (NonCLike.Kind == NonCLikeKind::None)
4792         DiagID = diag::err_typedef_changes_linkage;
4793       else
4794         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4795     }
4796 
4797     SourceLocation FixitLoc =
4798         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4799     llvm::SmallString<40> TextToInsert;
4800     TextToInsert += ' ';
4801     TextToInsert += NewTD->getIdentifier()->getName();
4802 
4803     Diag(FixitLoc, DiagID)
4804       << isa<TypeAliasDecl>(NewTD)
4805       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4806     if (NonCLike.Kind != NonCLikeKind::None) {
4807       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4808         << NonCLike.Kind - 1 << NonCLike.Range;
4809     }
4810     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4811       << NewTD << isa<TypeAliasDecl>(NewTD);
4812 
4813     if (ChangesLinkage)
4814       return;
4815   }
4816 
4817   // Otherwise, set this as the anon-decl typedef for the tag.
4818   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4819 }
4820 
4821 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4822   switch (T) {
4823   case DeclSpec::TST_class:
4824     return 0;
4825   case DeclSpec::TST_struct:
4826     return 1;
4827   case DeclSpec::TST_interface:
4828     return 2;
4829   case DeclSpec::TST_union:
4830     return 3;
4831   case DeclSpec::TST_enum:
4832     return 4;
4833   default:
4834     llvm_unreachable("unexpected type specifier");
4835   }
4836 }
4837 
4838 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4839 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4840 /// parameters to cope with template friend declarations.
4841 Decl *
4842 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4843                                  MultiTemplateParamsArg TemplateParams,
4844                                  bool IsExplicitInstantiation,
4845                                  RecordDecl *&AnonRecord) {
4846   Decl *TagD = nullptr;
4847   TagDecl *Tag = nullptr;
4848   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4849       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4850       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4851       DS.getTypeSpecType() == DeclSpec::TST_union ||
4852       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4853     TagD = DS.getRepAsDecl();
4854 
4855     if (!TagD) // We probably had an error
4856       return nullptr;
4857 
4858     // Note that the above type specs guarantee that the
4859     // type rep is a Decl, whereas in many of the others
4860     // it's a Type.
4861     if (isa<TagDecl>(TagD))
4862       Tag = cast<TagDecl>(TagD);
4863     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4864       Tag = CTD->getTemplatedDecl();
4865   }
4866 
4867   if (Tag) {
4868     handleTagNumbering(Tag, S);
4869     Tag->setFreeStanding();
4870     if (Tag->isInvalidDecl())
4871       return Tag;
4872   }
4873 
4874   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4875     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4876     // or incomplete types shall not be restrict-qualified."
4877     if (TypeQuals & DeclSpec::TQ_restrict)
4878       Diag(DS.getRestrictSpecLoc(),
4879            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4880            << DS.getSourceRange();
4881   }
4882 
4883   if (DS.isInlineSpecified())
4884     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4885         << getLangOpts().CPlusPlus17;
4886 
4887   if (DS.hasConstexprSpecifier()) {
4888     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4889     // and definitions of functions and variables.
4890     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4891     // the declaration of a function or function template
4892     if (Tag)
4893       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4894           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4895           << static_cast<int>(DS.getConstexprSpecifier());
4896     else
4897       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4898           << static_cast<int>(DS.getConstexprSpecifier());
4899     // Don't emit warnings after this error.
4900     return TagD;
4901   }
4902 
4903   DiagnoseFunctionSpecifiers(DS);
4904 
4905   if (DS.isFriendSpecified()) {
4906     // If we're dealing with a decl but not a TagDecl, assume that
4907     // whatever routines created it handled the friendship aspect.
4908     if (TagD && !Tag)
4909       return nullptr;
4910     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4911   }
4912 
4913   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4914   bool IsExplicitSpecialization =
4915     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4916   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4917       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4918       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4919     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4920     // nested-name-specifier unless it is an explicit instantiation
4921     // or an explicit specialization.
4922     //
4923     // FIXME: We allow class template partial specializations here too, per the
4924     // obvious intent of DR1819.
4925     //
4926     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4927     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4928         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4929     return nullptr;
4930   }
4931 
4932   // Track whether this decl-specifier declares anything.
4933   bool DeclaresAnything = true;
4934 
4935   // Handle anonymous struct definitions.
4936   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4937     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4938         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4939       if (getLangOpts().CPlusPlus ||
4940           Record->getDeclContext()->isRecord()) {
4941         // If CurContext is a DeclContext that can contain statements,
4942         // RecursiveASTVisitor won't visit the decls that
4943         // BuildAnonymousStructOrUnion() will put into CurContext.
4944         // Also store them here so that they can be part of the
4945         // DeclStmt that gets created in this case.
4946         // FIXME: Also return the IndirectFieldDecls created by
4947         // BuildAnonymousStructOr union, for the same reason?
4948         if (CurContext->isFunctionOrMethod())
4949           AnonRecord = Record;
4950         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4951                                            Context.getPrintingPolicy());
4952       }
4953 
4954       DeclaresAnything = false;
4955     }
4956   }
4957 
4958   // C11 6.7.2.1p2:
4959   //   A struct-declaration that does not declare an anonymous structure or
4960   //   anonymous union shall contain a struct-declarator-list.
4961   //
4962   // This rule also existed in C89 and C99; the grammar for struct-declaration
4963   // did not permit a struct-declaration without a struct-declarator-list.
4964   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4965       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4966     // Check for Microsoft C extension: anonymous struct/union member.
4967     // Handle 2 kinds of anonymous struct/union:
4968     //   struct STRUCT;
4969     //   union UNION;
4970     // and
4971     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4972     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4973     if ((Tag && Tag->getDeclName()) ||
4974         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4975       RecordDecl *Record = nullptr;
4976       if (Tag)
4977         Record = dyn_cast<RecordDecl>(Tag);
4978       else if (const RecordType *RT =
4979                    DS.getRepAsType().get()->getAsStructureType())
4980         Record = RT->getDecl();
4981       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4982         Record = UT->getDecl();
4983 
4984       if (Record && getLangOpts().MicrosoftExt) {
4985         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4986             << Record->isUnion() << DS.getSourceRange();
4987         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4988       }
4989 
4990       DeclaresAnything = false;
4991     }
4992   }
4993 
4994   // Skip all the checks below if we have a type error.
4995   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4996       (TagD && TagD->isInvalidDecl()))
4997     return TagD;
4998 
4999   if (getLangOpts().CPlusPlus &&
5000       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5001     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5002       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5003           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5004         DeclaresAnything = false;
5005 
5006   if (!DS.isMissingDeclaratorOk()) {
5007     // Customize diagnostic for a typedef missing a name.
5008     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5009       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5010           << DS.getSourceRange();
5011     else
5012       DeclaresAnything = false;
5013   }
5014 
5015   if (DS.isModulePrivateSpecified() &&
5016       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5017     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5018       << Tag->getTagKind()
5019       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5020 
5021   ActOnDocumentableDecl(TagD);
5022 
5023   // C 6.7/2:
5024   //   A declaration [...] shall declare at least a declarator [...], a tag,
5025   //   or the members of an enumeration.
5026   // C++ [dcl.dcl]p3:
5027   //   [If there are no declarators], and except for the declaration of an
5028   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5029   //   names into the program, or shall redeclare a name introduced by a
5030   //   previous declaration.
5031   if (!DeclaresAnything) {
5032     // In C, we allow this as a (popular) extension / bug. Don't bother
5033     // producing further diagnostics for redundant qualifiers after this.
5034     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5035                                ? diag::err_no_declarators
5036                                : diag::ext_no_declarators)
5037         << DS.getSourceRange();
5038     return TagD;
5039   }
5040 
5041   // C++ [dcl.stc]p1:
5042   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5043   //   init-declarator-list of the declaration shall not be empty.
5044   // C++ [dcl.fct.spec]p1:
5045   //   If a cv-qualifier appears in a decl-specifier-seq, the
5046   //   init-declarator-list of the declaration shall not be empty.
5047   //
5048   // Spurious qualifiers here appear to be valid in C.
5049   unsigned DiagID = diag::warn_standalone_specifier;
5050   if (getLangOpts().CPlusPlus)
5051     DiagID = diag::ext_standalone_specifier;
5052 
5053   // Note that a linkage-specification sets a storage class, but
5054   // 'extern "C" struct foo;' is actually valid and not theoretically
5055   // useless.
5056   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5057     if (SCS == DeclSpec::SCS_mutable)
5058       // Since mutable is not a viable storage class specifier in C, there is
5059       // no reason to treat it as an extension. Instead, diagnose as an error.
5060       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5061     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5062       Diag(DS.getStorageClassSpecLoc(), DiagID)
5063         << DeclSpec::getSpecifierName(SCS);
5064   }
5065 
5066   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5067     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5068       << DeclSpec::getSpecifierName(TSCS);
5069   if (DS.getTypeQualifiers()) {
5070     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5071       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5072     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5073       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5074     // Restrict is covered above.
5075     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5076       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5077     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5078       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5079   }
5080 
5081   // Warn about ignored type attributes, for example:
5082   // __attribute__((aligned)) struct A;
5083   // Attributes should be placed after tag to apply to type declaration.
5084   if (!DS.getAttributes().empty()) {
5085     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5086     if (TypeSpecType == DeclSpec::TST_class ||
5087         TypeSpecType == DeclSpec::TST_struct ||
5088         TypeSpecType == DeclSpec::TST_interface ||
5089         TypeSpecType == DeclSpec::TST_union ||
5090         TypeSpecType == DeclSpec::TST_enum) {
5091       for (const ParsedAttr &AL : DS.getAttributes())
5092         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5093             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5094     }
5095   }
5096 
5097   return TagD;
5098 }
5099 
5100 /// We are trying to inject an anonymous member into the given scope;
5101 /// check if there's an existing declaration that can't be overloaded.
5102 ///
5103 /// \return true if this is a forbidden redeclaration
5104 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5105                                          Scope *S,
5106                                          DeclContext *Owner,
5107                                          DeclarationName Name,
5108                                          SourceLocation NameLoc,
5109                                          bool IsUnion) {
5110   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5111                  Sema::ForVisibleRedeclaration);
5112   if (!SemaRef.LookupName(R, S)) return false;
5113 
5114   // Pick a representative declaration.
5115   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5116   assert(PrevDecl && "Expected a non-null Decl");
5117 
5118   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5119     return false;
5120 
5121   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5122     << IsUnion << Name;
5123   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5124 
5125   return true;
5126 }
5127 
5128 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5129 /// anonymous struct or union AnonRecord into the owning context Owner
5130 /// and scope S. This routine will be invoked just after we realize
5131 /// that an unnamed union or struct is actually an anonymous union or
5132 /// struct, e.g.,
5133 ///
5134 /// @code
5135 /// union {
5136 ///   int i;
5137 ///   float f;
5138 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5139 ///    // f into the surrounding scope.x
5140 /// @endcode
5141 ///
5142 /// This routine is recursive, injecting the names of nested anonymous
5143 /// structs/unions into the owning context and scope as well.
5144 static bool
5145 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5146                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5147                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5148   bool Invalid = false;
5149 
5150   // Look every FieldDecl and IndirectFieldDecl with a name.
5151   for (auto *D : AnonRecord->decls()) {
5152     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5153         cast<NamedDecl>(D)->getDeclName()) {
5154       ValueDecl *VD = cast<ValueDecl>(D);
5155       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5156                                        VD->getLocation(),
5157                                        AnonRecord->isUnion())) {
5158         // C++ [class.union]p2:
5159         //   The names of the members of an anonymous union shall be
5160         //   distinct from the names of any other entity in the
5161         //   scope in which the anonymous union is declared.
5162         Invalid = true;
5163       } else {
5164         // C++ [class.union]p2:
5165         //   For the purpose of name lookup, after the anonymous union
5166         //   definition, the members of the anonymous union are
5167         //   considered to have been defined in the scope in which the
5168         //   anonymous union is declared.
5169         unsigned OldChainingSize = Chaining.size();
5170         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5171           Chaining.append(IF->chain_begin(), IF->chain_end());
5172         else
5173           Chaining.push_back(VD);
5174 
5175         assert(Chaining.size() >= 2);
5176         NamedDecl **NamedChain =
5177           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5178         for (unsigned i = 0; i < Chaining.size(); i++)
5179           NamedChain[i] = Chaining[i];
5180 
5181         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5182             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5183             VD->getType(), {NamedChain, Chaining.size()});
5184 
5185         for (const auto *Attr : VD->attrs())
5186           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5187 
5188         IndirectField->setAccess(AS);
5189         IndirectField->setImplicit();
5190         SemaRef.PushOnScopeChains(IndirectField, S);
5191 
5192         // That includes picking up the appropriate access specifier.
5193         if (AS != AS_none) IndirectField->setAccess(AS);
5194 
5195         Chaining.resize(OldChainingSize);
5196       }
5197     }
5198   }
5199 
5200   return Invalid;
5201 }
5202 
5203 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5204 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5205 /// illegal input values are mapped to SC_None.
5206 static StorageClass
5207 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5208   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5209   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5210          "Parser allowed 'typedef' as storage class VarDecl.");
5211   switch (StorageClassSpec) {
5212   case DeclSpec::SCS_unspecified:    return SC_None;
5213   case DeclSpec::SCS_extern:
5214     if (DS.isExternInLinkageSpec())
5215       return SC_None;
5216     return SC_Extern;
5217   case DeclSpec::SCS_static:         return SC_Static;
5218   case DeclSpec::SCS_auto:           return SC_Auto;
5219   case DeclSpec::SCS_register:       return SC_Register;
5220   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5221     // Illegal SCSs map to None: error reporting is up to the caller.
5222   case DeclSpec::SCS_mutable:        // Fall through.
5223   case DeclSpec::SCS_typedef:        return SC_None;
5224   }
5225   llvm_unreachable("unknown storage class specifier");
5226 }
5227 
5228 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5229   assert(Record->hasInClassInitializer());
5230 
5231   for (const auto *I : Record->decls()) {
5232     const auto *FD = dyn_cast<FieldDecl>(I);
5233     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5234       FD = IFD->getAnonField();
5235     if (FD && FD->hasInClassInitializer())
5236       return FD->getLocation();
5237   }
5238 
5239   llvm_unreachable("couldn't find in-class initializer");
5240 }
5241 
5242 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5243                                       SourceLocation DefaultInitLoc) {
5244   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5245     return;
5246 
5247   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5248   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5249 }
5250 
5251 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5252                                       CXXRecordDecl *AnonUnion) {
5253   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5254     return;
5255 
5256   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5257 }
5258 
5259 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5260 /// anonymous structure or union. Anonymous unions are a C++ feature
5261 /// (C++ [class.union]) and a C11 feature; anonymous structures
5262 /// are a C11 feature and GNU C++ extension.
5263 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5264                                         AccessSpecifier AS,
5265                                         RecordDecl *Record,
5266                                         const PrintingPolicy &Policy) {
5267   DeclContext *Owner = Record->getDeclContext();
5268 
5269   // Diagnose whether this anonymous struct/union is an extension.
5270   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5271     Diag(Record->getLocation(), diag::ext_anonymous_union);
5272   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5273     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5274   else if (!Record->isUnion() && !getLangOpts().C11)
5275     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5276 
5277   // C and C++ require different kinds of checks for anonymous
5278   // structs/unions.
5279   bool Invalid = false;
5280   if (getLangOpts().CPlusPlus) {
5281     const char *PrevSpec = nullptr;
5282     if (Record->isUnion()) {
5283       // C++ [class.union]p6:
5284       // C++17 [class.union.anon]p2:
5285       //   Anonymous unions declared in a named namespace or in the
5286       //   global namespace shall be declared static.
5287       unsigned DiagID;
5288       DeclContext *OwnerScope = Owner->getRedeclContext();
5289       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5290           (OwnerScope->isTranslationUnit() ||
5291            (OwnerScope->isNamespace() &&
5292             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5293         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5294           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5295 
5296         // Recover by adding 'static'.
5297         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5298                                PrevSpec, DiagID, Policy);
5299       }
5300       // C++ [class.union]p6:
5301       //   A storage class is not allowed in a declaration of an
5302       //   anonymous union in a class scope.
5303       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5304                isa<RecordDecl>(Owner)) {
5305         Diag(DS.getStorageClassSpecLoc(),
5306              diag::err_anonymous_union_with_storage_spec)
5307           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5308 
5309         // Recover by removing the storage specifier.
5310         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5311                                SourceLocation(),
5312                                PrevSpec, DiagID, Context.getPrintingPolicy());
5313       }
5314     }
5315 
5316     // Ignore const/volatile/restrict qualifiers.
5317     if (DS.getTypeQualifiers()) {
5318       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5319         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5320           << Record->isUnion() << "const"
5321           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5322       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5323         Diag(DS.getVolatileSpecLoc(),
5324              diag::ext_anonymous_struct_union_qualified)
5325           << Record->isUnion() << "volatile"
5326           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5327       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5328         Diag(DS.getRestrictSpecLoc(),
5329              diag::ext_anonymous_struct_union_qualified)
5330           << Record->isUnion() << "restrict"
5331           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5332       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5333         Diag(DS.getAtomicSpecLoc(),
5334              diag::ext_anonymous_struct_union_qualified)
5335           << Record->isUnion() << "_Atomic"
5336           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5337       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5338         Diag(DS.getUnalignedSpecLoc(),
5339              diag::ext_anonymous_struct_union_qualified)
5340           << Record->isUnion() << "__unaligned"
5341           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5342 
5343       DS.ClearTypeQualifiers();
5344     }
5345 
5346     // C++ [class.union]p2:
5347     //   The member-specification of an anonymous union shall only
5348     //   define non-static data members. [Note: nested types and
5349     //   functions cannot be declared within an anonymous union. ]
5350     for (auto *Mem : Record->decls()) {
5351       // Ignore invalid declarations; we already diagnosed them.
5352       if (Mem->isInvalidDecl())
5353         continue;
5354 
5355       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5356         // C++ [class.union]p3:
5357         //   An anonymous union shall not have private or protected
5358         //   members (clause 11).
5359         assert(FD->getAccess() != AS_none);
5360         if (FD->getAccess() != AS_public) {
5361           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5362             << Record->isUnion() << (FD->getAccess() == AS_protected);
5363           Invalid = true;
5364         }
5365 
5366         // C++ [class.union]p1
5367         //   An object of a class with a non-trivial constructor, a non-trivial
5368         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5369         //   assignment operator cannot be a member of a union, nor can an
5370         //   array of such objects.
5371         if (CheckNontrivialField(FD))
5372           Invalid = true;
5373       } else if (Mem->isImplicit()) {
5374         // Any implicit members are fine.
5375       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5376         // This is a type that showed up in an
5377         // elaborated-type-specifier inside the anonymous struct or
5378         // union, but which actually declares a type outside of the
5379         // anonymous struct or union. It's okay.
5380       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5381         if (!MemRecord->isAnonymousStructOrUnion() &&
5382             MemRecord->getDeclName()) {
5383           // Visual C++ allows type definition in anonymous struct or union.
5384           if (getLangOpts().MicrosoftExt)
5385             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5386               << Record->isUnion();
5387           else {
5388             // This is a nested type declaration.
5389             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5390               << Record->isUnion();
5391             Invalid = true;
5392           }
5393         } else {
5394           // This is an anonymous type definition within another anonymous type.
5395           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5396           // not part of standard C++.
5397           Diag(MemRecord->getLocation(),
5398                diag::ext_anonymous_record_with_anonymous_type)
5399             << Record->isUnion();
5400         }
5401       } else if (isa<AccessSpecDecl>(Mem)) {
5402         // Any access specifier is fine.
5403       } else if (isa<StaticAssertDecl>(Mem)) {
5404         // In C++1z, static_assert declarations are also fine.
5405       } else {
5406         // We have something that isn't a non-static data
5407         // member. Complain about it.
5408         unsigned DK = diag::err_anonymous_record_bad_member;
5409         if (isa<TypeDecl>(Mem))
5410           DK = diag::err_anonymous_record_with_type;
5411         else if (isa<FunctionDecl>(Mem))
5412           DK = diag::err_anonymous_record_with_function;
5413         else if (isa<VarDecl>(Mem))
5414           DK = diag::err_anonymous_record_with_static;
5415 
5416         // Visual C++ allows type definition in anonymous struct or union.
5417         if (getLangOpts().MicrosoftExt &&
5418             DK == diag::err_anonymous_record_with_type)
5419           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5420             << Record->isUnion();
5421         else {
5422           Diag(Mem->getLocation(), DK) << Record->isUnion();
5423           Invalid = true;
5424         }
5425       }
5426     }
5427 
5428     // C++11 [class.union]p8 (DR1460):
5429     //   At most one variant member of a union may have a
5430     //   brace-or-equal-initializer.
5431     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5432         Owner->isRecord())
5433       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5434                                 cast<CXXRecordDecl>(Record));
5435   }
5436 
5437   if (!Record->isUnion() && !Owner->isRecord()) {
5438     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5439       << getLangOpts().CPlusPlus;
5440     Invalid = true;
5441   }
5442 
5443   // C++ [dcl.dcl]p3:
5444   //   [If there are no declarators], and except for the declaration of an
5445   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5446   //   names into the program
5447   // C++ [class.mem]p2:
5448   //   each such member-declaration shall either declare at least one member
5449   //   name of the class or declare at least one unnamed bit-field
5450   //
5451   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5452   if (getLangOpts().CPlusPlus && Record->field_empty())
5453     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5454 
5455   // Mock up a declarator.
5456   Declarator Dc(DS, DeclaratorContext::Member);
5457   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5458   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5459 
5460   // Create a declaration for this anonymous struct/union.
5461   NamedDecl *Anon = nullptr;
5462   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5463     Anon = FieldDecl::Create(
5464         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5465         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5466         /*BitWidth=*/nullptr, /*Mutable=*/false,
5467         /*InitStyle=*/ICIS_NoInit);
5468     Anon->setAccess(AS);
5469     ProcessDeclAttributes(S, Anon, Dc);
5470 
5471     if (getLangOpts().CPlusPlus)
5472       FieldCollector->Add(cast<FieldDecl>(Anon));
5473   } else {
5474     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5475     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5476     if (SCSpec == DeclSpec::SCS_mutable) {
5477       // mutable can only appear on non-static class members, so it's always
5478       // an error here
5479       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5480       Invalid = true;
5481       SC = SC_None;
5482     }
5483 
5484     assert(DS.getAttributes().empty() && "No attribute expected");
5485     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5486                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5487                            Context.getTypeDeclType(Record), TInfo, SC);
5488 
5489     // Default-initialize the implicit variable. This initialization will be
5490     // trivial in almost all cases, except if a union member has an in-class
5491     // initializer:
5492     //   union { int n = 0; };
5493     ActOnUninitializedDecl(Anon);
5494   }
5495   Anon->setImplicit();
5496 
5497   // Mark this as an anonymous struct/union type.
5498   Record->setAnonymousStructOrUnion(true);
5499 
5500   // Add the anonymous struct/union object to the current
5501   // context. We'll be referencing this object when we refer to one of
5502   // its members.
5503   Owner->addDecl(Anon);
5504 
5505   // Inject the members of the anonymous struct/union into the owning
5506   // context and into the identifier resolver chain for name lookup
5507   // purposes.
5508   SmallVector<NamedDecl*, 2> Chain;
5509   Chain.push_back(Anon);
5510 
5511   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5512     Invalid = true;
5513 
5514   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5515     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5516       MangleNumberingContext *MCtx;
5517       Decl *ManglingContextDecl;
5518       std::tie(MCtx, ManglingContextDecl) =
5519           getCurrentMangleNumberContext(NewVD->getDeclContext());
5520       if (MCtx) {
5521         Context.setManglingNumber(
5522             NewVD, MCtx->getManglingNumber(
5523                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5524         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5525       }
5526     }
5527   }
5528 
5529   if (Invalid)
5530     Anon->setInvalidDecl();
5531 
5532   return Anon;
5533 }
5534 
5535 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5536 /// Microsoft C anonymous structure.
5537 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5538 /// Example:
5539 ///
5540 /// struct A { int a; };
5541 /// struct B { struct A; int b; };
5542 ///
5543 /// void foo() {
5544 ///   B var;
5545 ///   var.a = 3;
5546 /// }
5547 ///
5548 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5549                                            RecordDecl *Record) {
5550   assert(Record && "expected a record!");
5551 
5552   // Mock up a declarator.
5553   Declarator Dc(DS, DeclaratorContext::TypeName);
5554   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5555   assert(TInfo && "couldn't build declarator info for anonymous struct");
5556 
5557   auto *ParentDecl = cast<RecordDecl>(CurContext);
5558   QualType RecTy = Context.getTypeDeclType(Record);
5559 
5560   // Create a declaration for this anonymous struct.
5561   NamedDecl *Anon =
5562       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5563                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5564                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5565                         /*InitStyle=*/ICIS_NoInit);
5566   Anon->setImplicit();
5567 
5568   // Add the anonymous struct object to the current context.
5569   CurContext->addDecl(Anon);
5570 
5571   // Inject the members of the anonymous struct into the current
5572   // context and into the identifier resolver chain for name lookup
5573   // purposes.
5574   SmallVector<NamedDecl*, 2> Chain;
5575   Chain.push_back(Anon);
5576 
5577   RecordDecl *RecordDef = Record->getDefinition();
5578   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5579                                diag::err_field_incomplete_or_sizeless) ||
5580       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5581                                           AS_none, Chain)) {
5582     Anon->setInvalidDecl();
5583     ParentDecl->setInvalidDecl();
5584   }
5585 
5586   return Anon;
5587 }
5588 
5589 /// GetNameForDeclarator - Determine the full declaration name for the
5590 /// given Declarator.
5591 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5592   return GetNameFromUnqualifiedId(D.getName());
5593 }
5594 
5595 /// Retrieves the declaration name from a parsed unqualified-id.
5596 DeclarationNameInfo
5597 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5598   DeclarationNameInfo NameInfo;
5599   NameInfo.setLoc(Name.StartLocation);
5600 
5601   switch (Name.getKind()) {
5602 
5603   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5604   case UnqualifiedIdKind::IK_Identifier:
5605     NameInfo.setName(Name.Identifier);
5606     return NameInfo;
5607 
5608   case UnqualifiedIdKind::IK_DeductionGuideName: {
5609     // C++ [temp.deduct.guide]p3:
5610     //   The simple-template-id shall name a class template specialization.
5611     //   The template-name shall be the same identifier as the template-name
5612     //   of the simple-template-id.
5613     // These together intend to imply that the template-name shall name a
5614     // class template.
5615     // FIXME: template<typename T> struct X {};
5616     //        template<typename T> using Y = X<T>;
5617     //        Y(int) -> Y<int>;
5618     //   satisfies these rules but does not name a class template.
5619     TemplateName TN = Name.TemplateName.get().get();
5620     auto *Template = TN.getAsTemplateDecl();
5621     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5622       Diag(Name.StartLocation,
5623            diag::err_deduction_guide_name_not_class_template)
5624         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5625       if (Template)
5626         Diag(Template->getLocation(), diag::note_template_decl_here);
5627       return DeclarationNameInfo();
5628     }
5629 
5630     NameInfo.setName(
5631         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5632     return NameInfo;
5633   }
5634 
5635   case UnqualifiedIdKind::IK_OperatorFunctionId:
5636     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5637                                            Name.OperatorFunctionId.Operator));
5638     NameInfo.setCXXOperatorNameRange(SourceRange(
5639         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5640     return NameInfo;
5641 
5642   case UnqualifiedIdKind::IK_LiteralOperatorId:
5643     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5644                                                            Name.Identifier));
5645     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5646     return NameInfo;
5647 
5648   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5649     TypeSourceInfo *TInfo;
5650     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5651     if (Ty.isNull())
5652       return DeclarationNameInfo();
5653     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5654                                                Context.getCanonicalType(Ty)));
5655     NameInfo.setNamedTypeInfo(TInfo);
5656     return NameInfo;
5657   }
5658 
5659   case UnqualifiedIdKind::IK_ConstructorName: {
5660     TypeSourceInfo *TInfo;
5661     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5662     if (Ty.isNull())
5663       return DeclarationNameInfo();
5664     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5665                                               Context.getCanonicalType(Ty)));
5666     NameInfo.setNamedTypeInfo(TInfo);
5667     return NameInfo;
5668   }
5669 
5670   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5671     // In well-formed code, we can only have a constructor
5672     // template-id that refers to the current context, so go there
5673     // to find the actual type being constructed.
5674     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5675     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5676       return DeclarationNameInfo();
5677 
5678     // Determine the type of the class being constructed.
5679     QualType CurClassType = Context.getTypeDeclType(CurClass);
5680 
5681     // FIXME: Check two things: that the template-id names the same type as
5682     // CurClassType, and that the template-id does not occur when the name
5683     // was qualified.
5684 
5685     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5686                                     Context.getCanonicalType(CurClassType)));
5687     // FIXME: should we retrieve TypeSourceInfo?
5688     NameInfo.setNamedTypeInfo(nullptr);
5689     return NameInfo;
5690   }
5691 
5692   case UnqualifiedIdKind::IK_DestructorName: {
5693     TypeSourceInfo *TInfo;
5694     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5695     if (Ty.isNull())
5696       return DeclarationNameInfo();
5697     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5698                                               Context.getCanonicalType(Ty)));
5699     NameInfo.setNamedTypeInfo(TInfo);
5700     return NameInfo;
5701   }
5702 
5703   case UnqualifiedIdKind::IK_TemplateId: {
5704     TemplateName TName = Name.TemplateId->Template.get();
5705     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5706     return Context.getNameForTemplate(TName, TNameLoc);
5707   }
5708 
5709   } // switch (Name.getKind())
5710 
5711   llvm_unreachable("Unknown name kind");
5712 }
5713 
5714 static QualType getCoreType(QualType Ty) {
5715   do {
5716     if (Ty->isPointerType() || Ty->isReferenceType())
5717       Ty = Ty->getPointeeType();
5718     else if (Ty->isArrayType())
5719       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5720     else
5721       return Ty.withoutLocalFastQualifiers();
5722   } while (true);
5723 }
5724 
5725 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5726 /// and Definition have "nearly" matching parameters. This heuristic is
5727 /// used to improve diagnostics in the case where an out-of-line function
5728 /// definition doesn't match any declaration within the class or namespace.
5729 /// Also sets Params to the list of indices to the parameters that differ
5730 /// between the declaration and the definition. If hasSimilarParameters
5731 /// returns true and Params is empty, then all of the parameters match.
5732 static bool hasSimilarParameters(ASTContext &Context,
5733                                      FunctionDecl *Declaration,
5734                                      FunctionDecl *Definition,
5735                                      SmallVectorImpl<unsigned> &Params) {
5736   Params.clear();
5737   if (Declaration->param_size() != Definition->param_size())
5738     return false;
5739   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5740     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5741     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5742 
5743     // The parameter types are identical
5744     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5745       continue;
5746 
5747     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5748     QualType DefParamBaseTy = getCoreType(DefParamTy);
5749     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5750     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5751 
5752     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5753         (DeclTyName && DeclTyName == DefTyName))
5754       Params.push_back(Idx);
5755     else  // The two parameters aren't even close
5756       return false;
5757   }
5758 
5759   return true;
5760 }
5761 
5762 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5763 /// declarator needs to be rebuilt in the current instantiation.
5764 /// Any bits of declarator which appear before the name are valid for
5765 /// consideration here.  That's specifically the type in the decl spec
5766 /// and the base type in any member-pointer chunks.
5767 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5768                                                     DeclarationName Name) {
5769   // The types we specifically need to rebuild are:
5770   //   - typenames, typeofs, and decltypes
5771   //   - types which will become injected class names
5772   // Of course, we also need to rebuild any type referencing such a
5773   // type.  It's safest to just say "dependent", but we call out a
5774   // few cases here.
5775 
5776   DeclSpec &DS = D.getMutableDeclSpec();
5777   switch (DS.getTypeSpecType()) {
5778   case DeclSpec::TST_typename:
5779   case DeclSpec::TST_typeofType:
5780   case DeclSpec::TST_underlyingType:
5781   case DeclSpec::TST_atomic: {
5782     // Grab the type from the parser.
5783     TypeSourceInfo *TSI = nullptr;
5784     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5785     if (T.isNull() || !T->isInstantiationDependentType()) break;
5786 
5787     // Make sure there's a type source info.  This isn't really much
5788     // of a waste; most dependent types should have type source info
5789     // attached already.
5790     if (!TSI)
5791       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5792 
5793     // Rebuild the type in the current instantiation.
5794     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5795     if (!TSI) return true;
5796 
5797     // Store the new type back in the decl spec.
5798     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5799     DS.UpdateTypeRep(LocType);
5800     break;
5801   }
5802 
5803   case DeclSpec::TST_decltype:
5804   case DeclSpec::TST_typeofExpr: {
5805     Expr *E = DS.getRepAsExpr();
5806     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5807     if (Result.isInvalid()) return true;
5808     DS.UpdateExprRep(Result.get());
5809     break;
5810   }
5811 
5812   default:
5813     // Nothing to do for these decl specs.
5814     break;
5815   }
5816 
5817   // It doesn't matter what order we do this in.
5818   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5819     DeclaratorChunk &Chunk = D.getTypeObject(I);
5820 
5821     // The only type information in the declarator which can come
5822     // before the declaration name is the base type of a member
5823     // pointer.
5824     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5825       continue;
5826 
5827     // Rebuild the scope specifier in-place.
5828     CXXScopeSpec &SS = Chunk.Mem.Scope();
5829     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5830       return true;
5831   }
5832 
5833   return false;
5834 }
5835 
5836 /// Returns true if the declaration is declared in a system header or from a
5837 /// system macro.
5838 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5839   return SM.isInSystemHeader(D->getLocation()) ||
5840          SM.isInSystemMacro(D->getLocation());
5841 }
5842 
5843 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5844   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5845   // of system decl.
5846   if (D->getPreviousDecl() || D->isImplicit())
5847     return;
5848   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5849   if (Status != ReservedIdentifierStatus::NotReserved &&
5850       !isFromSystemHeader(Context.getSourceManager(), D)) {
5851     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5852         << D << static_cast<int>(Status);
5853   }
5854 }
5855 
5856 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5857   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5858   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5859 
5860   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5861       Dcl && Dcl->getDeclContext()->isFileContext())
5862     Dcl->setTopLevelDeclInObjCContainer();
5863 
5864   return Dcl;
5865 }
5866 
5867 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5868 ///   If T is the name of a class, then each of the following shall have a
5869 ///   name different from T:
5870 ///     - every static data member of class T;
5871 ///     - every member function of class T
5872 ///     - every member of class T that is itself a type;
5873 /// \returns true if the declaration name violates these rules.
5874 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5875                                    DeclarationNameInfo NameInfo) {
5876   DeclarationName Name = NameInfo.getName();
5877 
5878   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5879   while (Record && Record->isAnonymousStructOrUnion())
5880     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5881   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5882     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5883     return true;
5884   }
5885 
5886   return false;
5887 }
5888 
5889 /// Diagnose a declaration whose declarator-id has the given
5890 /// nested-name-specifier.
5891 ///
5892 /// \param SS The nested-name-specifier of the declarator-id.
5893 ///
5894 /// \param DC The declaration context to which the nested-name-specifier
5895 /// resolves.
5896 ///
5897 /// \param Name The name of the entity being declared.
5898 ///
5899 /// \param Loc The location of the name of the entity being declared.
5900 ///
5901 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5902 /// we're declaring an explicit / partial specialization / instantiation.
5903 ///
5904 /// \returns true if we cannot safely recover from this error, false otherwise.
5905 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5906                                         DeclarationName Name,
5907                                         SourceLocation Loc, bool IsTemplateId) {
5908   DeclContext *Cur = CurContext;
5909   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5910     Cur = Cur->getParent();
5911 
5912   // If the user provided a superfluous scope specifier that refers back to the
5913   // class in which the entity is already declared, diagnose and ignore it.
5914   //
5915   // class X {
5916   //   void X::f();
5917   // };
5918   //
5919   // Note, it was once ill-formed to give redundant qualification in all
5920   // contexts, but that rule was removed by DR482.
5921   if (Cur->Equals(DC)) {
5922     if (Cur->isRecord()) {
5923       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5924                                       : diag::err_member_extra_qualification)
5925         << Name << FixItHint::CreateRemoval(SS.getRange());
5926       SS.clear();
5927     } else {
5928       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5929     }
5930     return false;
5931   }
5932 
5933   // Check whether the qualifying scope encloses the scope of the original
5934   // declaration. For a template-id, we perform the checks in
5935   // CheckTemplateSpecializationScope.
5936   if (!Cur->Encloses(DC) && !IsTemplateId) {
5937     if (Cur->isRecord())
5938       Diag(Loc, diag::err_member_qualification)
5939         << Name << SS.getRange();
5940     else if (isa<TranslationUnitDecl>(DC))
5941       Diag(Loc, diag::err_invalid_declarator_global_scope)
5942         << Name << SS.getRange();
5943     else if (isa<FunctionDecl>(Cur))
5944       Diag(Loc, diag::err_invalid_declarator_in_function)
5945         << Name << SS.getRange();
5946     else if (isa<BlockDecl>(Cur))
5947       Diag(Loc, diag::err_invalid_declarator_in_block)
5948         << Name << SS.getRange();
5949     else if (isa<ExportDecl>(Cur)) {
5950       if (!isa<NamespaceDecl>(DC))
5951         Diag(Loc, diag::err_export_non_namespace_scope_name)
5952             << Name << SS.getRange();
5953       else
5954         // The cases that DC is not NamespaceDecl should be handled in
5955         // CheckRedeclarationExported.
5956         return false;
5957     } else
5958       Diag(Loc, diag::err_invalid_declarator_scope)
5959       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5960 
5961     return true;
5962   }
5963 
5964   if (Cur->isRecord()) {
5965     // Cannot qualify members within a class.
5966     Diag(Loc, diag::err_member_qualification)
5967       << Name << SS.getRange();
5968     SS.clear();
5969 
5970     // C++ constructors and destructors with incorrect scopes can break
5971     // our AST invariants by having the wrong underlying types. If
5972     // that's the case, then drop this declaration entirely.
5973     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5974          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5975         !Context.hasSameType(Name.getCXXNameType(),
5976                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5977       return true;
5978 
5979     return false;
5980   }
5981 
5982   // C++11 [dcl.meaning]p1:
5983   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5984   //   not begin with a decltype-specifer"
5985   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5986   while (SpecLoc.getPrefix())
5987     SpecLoc = SpecLoc.getPrefix();
5988   if (isa_and_nonnull<DecltypeType>(
5989           SpecLoc.getNestedNameSpecifier()->getAsType()))
5990     Diag(Loc, diag::err_decltype_in_declarator)
5991       << SpecLoc.getTypeLoc().getSourceRange();
5992 
5993   return false;
5994 }
5995 
5996 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5997                                   MultiTemplateParamsArg TemplateParamLists) {
5998   // TODO: consider using NameInfo for diagnostic.
5999   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6000   DeclarationName Name = NameInfo.getName();
6001 
6002   // All of these full declarators require an identifier.  If it doesn't have
6003   // one, the ParsedFreeStandingDeclSpec action should be used.
6004   if (D.isDecompositionDeclarator()) {
6005     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6006   } else if (!Name) {
6007     if (!D.isInvalidType())  // Reject this if we think it is valid.
6008       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6009           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6010     return nullptr;
6011   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6012     return nullptr;
6013 
6014   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6015   // we find one that is.
6016   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6017          (S->getFlags() & Scope::TemplateParamScope) != 0)
6018     S = S->getParent();
6019 
6020   DeclContext *DC = CurContext;
6021   if (D.getCXXScopeSpec().isInvalid())
6022     D.setInvalidType();
6023   else if (D.getCXXScopeSpec().isSet()) {
6024     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6025                                         UPPC_DeclarationQualifier))
6026       return nullptr;
6027 
6028     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6029     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6030     if (!DC || isa<EnumDecl>(DC)) {
6031       // If we could not compute the declaration context, it's because the
6032       // declaration context is dependent but does not refer to a class,
6033       // class template, or class template partial specialization. Complain
6034       // and return early, to avoid the coming semantic disaster.
6035       Diag(D.getIdentifierLoc(),
6036            diag::err_template_qualified_declarator_no_match)
6037         << D.getCXXScopeSpec().getScopeRep()
6038         << D.getCXXScopeSpec().getRange();
6039       return nullptr;
6040     }
6041     bool IsDependentContext = DC->isDependentContext();
6042 
6043     if (!IsDependentContext &&
6044         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6045       return nullptr;
6046 
6047     // If a class is incomplete, do not parse entities inside it.
6048     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6049       Diag(D.getIdentifierLoc(),
6050            diag::err_member_def_undefined_record)
6051         << Name << DC << D.getCXXScopeSpec().getRange();
6052       return nullptr;
6053     }
6054     if (!D.getDeclSpec().isFriendSpecified()) {
6055       if (diagnoseQualifiedDeclaration(
6056               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6057               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6058         if (DC->isRecord())
6059           return nullptr;
6060 
6061         D.setInvalidType();
6062       }
6063     }
6064 
6065     // Check whether we need to rebuild the type of the given
6066     // declaration in the current instantiation.
6067     if (EnteringContext && IsDependentContext &&
6068         TemplateParamLists.size() != 0) {
6069       ContextRAII SavedContext(*this, DC);
6070       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6071         D.setInvalidType();
6072     }
6073   }
6074 
6075   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6076   QualType R = TInfo->getType();
6077 
6078   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6079                                       UPPC_DeclarationType))
6080     D.setInvalidType();
6081 
6082   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6083                         forRedeclarationInCurContext());
6084 
6085   // See if this is a redefinition of a variable in the same scope.
6086   if (!D.getCXXScopeSpec().isSet()) {
6087     bool IsLinkageLookup = false;
6088     bool CreateBuiltins = false;
6089 
6090     // If the declaration we're planning to build will be a function
6091     // or object with linkage, then look for another declaration with
6092     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6093     //
6094     // If the declaration we're planning to build will be declared with
6095     // external linkage in the translation unit, create any builtin with
6096     // the same name.
6097     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6098       /* Do nothing*/;
6099     else if (CurContext->isFunctionOrMethod() &&
6100              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6101               R->isFunctionType())) {
6102       IsLinkageLookup = true;
6103       CreateBuiltins =
6104           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6105     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6106                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6107       CreateBuiltins = true;
6108 
6109     if (IsLinkageLookup) {
6110       Previous.clear(LookupRedeclarationWithLinkage);
6111       Previous.setRedeclarationKind(ForExternalRedeclaration);
6112     }
6113 
6114     LookupName(Previous, S, CreateBuiltins);
6115   } else { // Something like "int foo::x;"
6116     LookupQualifiedName(Previous, DC);
6117 
6118     // C++ [dcl.meaning]p1:
6119     //   When the declarator-id is qualified, the declaration shall refer to a
6120     //  previously declared member of the class or namespace to which the
6121     //  qualifier refers (or, in the case of a namespace, of an element of the
6122     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6123     //  thereof; [...]
6124     //
6125     // Note that we already checked the context above, and that we do not have
6126     // enough information to make sure that Previous contains the declaration
6127     // we want to match. For example, given:
6128     //
6129     //   class X {
6130     //     void f();
6131     //     void f(float);
6132     //   };
6133     //
6134     //   void X::f(int) { } // ill-formed
6135     //
6136     // In this case, Previous will point to the overload set
6137     // containing the two f's declared in X, but neither of them
6138     // matches.
6139 
6140     // C++ [dcl.meaning]p1:
6141     //   [...] the member shall not merely have been introduced by a
6142     //   using-declaration in the scope of the class or namespace nominated by
6143     //   the nested-name-specifier of the declarator-id.
6144     RemoveUsingDecls(Previous);
6145   }
6146 
6147   if (Previous.isSingleResult() &&
6148       Previous.getFoundDecl()->isTemplateParameter()) {
6149     // Maybe we will complain about the shadowed template parameter.
6150     if (!D.isInvalidType())
6151       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6152                                       Previous.getFoundDecl());
6153 
6154     // Just pretend that we didn't see the previous declaration.
6155     Previous.clear();
6156   }
6157 
6158   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6159     // Forget that the previous declaration is the injected-class-name.
6160     Previous.clear();
6161 
6162   // In C++, the previous declaration we find might be a tag type
6163   // (class or enum). In this case, the new declaration will hide the
6164   // tag type. Note that this applies to functions, function templates, and
6165   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6166   if (Previous.isSingleTagDecl() &&
6167       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6168       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6169     Previous.clear();
6170 
6171   // Check that there are no default arguments other than in the parameters
6172   // of a function declaration (C++ only).
6173   if (getLangOpts().CPlusPlus)
6174     CheckExtraCXXDefaultArguments(D);
6175 
6176   NamedDecl *New;
6177 
6178   bool AddToScope = true;
6179   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6180     if (TemplateParamLists.size()) {
6181       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6182       return nullptr;
6183     }
6184 
6185     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6186   } else if (R->isFunctionType()) {
6187     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6188                                   TemplateParamLists,
6189                                   AddToScope);
6190   } else {
6191     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6192                                   AddToScope);
6193   }
6194 
6195   if (!New)
6196     return nullptr;
6197 
6198   // If this has an identifier and is not a function template specialization,
6199   // add it to the scope stack.
6200   if (New->getDeclName() && AddToScope)
6201     PushOnScopeChains(New, S);
6202 
6203   if (isInOpenMPDeclareTargetContext())
6204     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6205 
6206   return New;
6207 }
6208 
6209 /// Helper method to turn variable array types into constant array
6210 /// types in certain situations which would otherwise be errors (for
6211 /// GCC compatibility).
6212 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6213                                                     ASTContext &Context,
6214                                                     bool &SizeIsNegative,
6215                                                     llvm::APSInt &Oversized) {
6216   // This method tries to turn a variable array into a constant
6217   // array even when the size isn't an ICE.  This is necessary
6218   // for compatibility with code that depends on gcc's buggy
6219   // constant expression folding, like struct {char x[(int)(char*)2];}
6220   SizeIsNegative = false;
6221   Oversized = 0;
6222 
6223   if (T->isDependentType())
6224     return QualType();
6225 
6226   QualifierCollector Qs;
6227   const Type *Ty = Qs.strip(T);
6228 
6229   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6230     QualType Pointee = PTy->getPointeeType();
6231     QualType FixedType =
6232         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6233                                             Oversized);
6234     if (FixedType.isNull()) return FixedType;
6235     FixedType = Context.getPointerType(FixedType);
6236     return Qs.apply(Context, FixedType);
6237   }
6238   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6239     QualType Inner = PTy->getInnerType();
6240     QualType FixedType =
6241         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6242                                             Oversized);
6243     if (FixedType.isNull()) return FixedType;
6244     FixedType = Context.getParenType(FixedType);
6245     return Qs.apply(Context, FixedType);
6246   }
6247 
6248   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6249   if (!VLATy)
6250     return QualType();
6251 
6252   QualType ElemTy = VLATy->getElementType();
6253   if (ElemTy->isVariablyModifiedType()) {
6254     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6255                                                  SizeIsNegative, Oversized);
6256     if (ElemTy.isNull())
6257       return QualType();
6258   }
6259 
6260   Expr::EvalResult Result;
6261   if (!VLATy->getSizeExpr() ||
6262       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6263     return QualType();
6264 
6265   llvm::APSInt Res = Result.Val.getInt();
6266 
6267   // Check whether the array size is negative.
6268   if (Res.isSigned() && Res.isNegative()) {
6269     SizeIsNegative = true;
6270     return QualType();
6271   }
6272 
6273   // Check whether the array is too large to be addressed.
6274   unsigned ActiveSizeBits =
6275       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6276        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6277           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6278           : Res.getActiveBits();
6279   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6280     Oversized = Res;
6281     return QualType();
6282   }
6283 
6284   QualType FoldedArrayType = Context.getConstantArrayType(
6285       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6286   return Qs.apply(Context, FoldedArrayType);
6287 }
6288 
6289 static void
6290 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6291   SrcTL = SrcTL.getUnqualifiedLoc();
6292   DstTL = DstTL.getUnqualifiedLoc();
6293   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6294     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6295     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6296                                       DstPTL.getPointeeLoc());
6297     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6298     return;
6299   }
6300   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6301     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6302     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6303                                       DstPTL.getInnerLoc());
6304     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6305     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6306     return;
6307   }
6308   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6309   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6310   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6311   TypeLoc DstElemTL = DstATL.getElementLoc();
6312   if (VariableArrayTypeLoc SrcElemATL =
6313           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6314     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6315     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6316   } else {
6317     DstElemTL.initializeFullCopy(SrcElemTL);
6318   }
6319   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6320   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6321   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6322 }
6323 
6324 /// Helper method to turn variable array types into constant array
6325 /// types in certain situations which would otherwise be errors (for
6326 /// GCC compatibility).
6327 static TypeSourceInfo*
6328 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6329                                               ASTContext &Context,
6330                                               bool &SizeIsNegative,
6331                                               llvm::APSInt &Oversized) {
6332   QualType FixedTy
6333     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6334                                           SizeIsNegative, Oversized);
6335   if (FixedTy.isNull())
6336     return nullptr;
6337   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6338   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6339                                     FixedTInfo->getTypeLoc());
6340   return FixedTInfo;
6341 }
6342 
6343 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6344 /// true if we were successful.
6345 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6346                                            QualType &T, SourceLocation Loc,
6347                                            unsigned FailedFoldDiagID) {
6348   bool SizeIsNegative;
6349   llvm::APSInt Oversized;
6350   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6351       TInfo, Context, SizeIsNegative, Oversized);
6352   if (FixedTInfo) {
6353     Diag(Loc, diag::ext_vla_folded_to_constant);
6354     TInfo = FixedTInfo;
6355     T = FixedTInfo->getType();
6356     return true;
6357   }
6358 
6359   if (SizeIsNegative)
6360     Diag(Loc, diag::err_typecheck_negative_array_size);
6361   else if (Oversized.getBoolValue())
6362     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6363   else if (FailedFoldDiagID)
6364     Diag(Loc, FailedFoldDiagID);
6365   return false;
6366 }
6367 
6368 /// Register the given locally-scoped extern "C" declaration so
6369 /// that it can be found later for redeclarations. We include any extern "C"
6370 /// declaration that is not visible in the translation unit here, not just
6371 /// function-scope declarations.
6372 void
6373 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6374   if (!getLangOpts().CPlusPlus &&
6375       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6376     // Don't need to track declarations in the TU in C.
6377     return;
6378 
6379   // Note that we have a locally-scoped external with this name.
6380   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6381 }
6382 
6383 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6384   // FIXME: We can have multiple results via __attribute__((overloadable)).
6385   auto Result = Context.getExternCContextDecl()->lookup(Name);
6386   return Result.empty() ? nullptr : *Result.begin();
6387 }
6388 
6389 /// Diagnose function specifiers on a declaration of an identifier that
6390 /// does not identify a function.
6391 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6392   // FIXME: We should probably indicate the identifier in question to avoid
6393   // confusion for constructs like "virtual int a(), b;"
6394   if (DS.isVirtualSpecified())
6395     Diag(DS.getVirtualSpecLoc(),
6396          diag::err_virtual_non_function);
6397 
6398   if (DS.hasExplicitSpecifier())
6399     Diag(DS.getExplicitSpecLoc(),
6400          diag::err_explicit_non_function);
6401 
6402   if (DS.isNoreturnSpecified())
6403     Diag(DS.getNoreturnSpecLoc(),
6404          diag::err_noreturn_non_function);
6405 }
6406 
6407 NamedDecl*
6408 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6409                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6410   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6411   if (D.getCXXScopeSpec().isSet()) {
6412     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6413       << D.getCXXScopeSpec().getRange();
6414     D.setInvalidType();
6415     // Pretend we didn't see the scope specifier.
6416     DC = CurContext;
6417     Previous.clear();
6418   }
6419 
6420   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6421 
6422   if (D.getDeclSpec().isInlineSpecified())
6423     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6424         << getLangOpts().CPlusPlus17;
6425   if (D.getDeclSpec().hasConstexprSpecifier())
6426     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6427         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6428 
6429   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6430     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6431       Diag(D.getName().StartLocation,
6432            diag::err_deduction_guide_invalid_specifier)
6433           << "typedef";
6434     else
6435       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6436           << D.getName().getSourceRange();
6437     return nullptr;
6438   }
6439 
6440   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6441   if (!NewTD) return nullptr;
6442 
6443   // Handle attributes prior to checking for duplicates in MergeVarDecl
6444   ProcessDeclAttributes(S, NewTD, D);
6445 
6446   CheckTypedefForVariablyModifiedType(S, NewTD);
6447 
6448   bool Redeclaration = D.isRedeclaration();
6449   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6450   D.setRedeclaration(Redeclaration);
6451   return ND;
6452 }
6453 
6454 void
6455 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6456   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6457   // then it shall have block scope.
6458   // Note that variably modified types must be fixed before merging the decl so
6459   // that redeclarations will match.
6460   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6461   QualType T = TInfo->getType();
6462   if (T->isVariablyModifiedType()) {
6463     setFunctionHasBranchProtectedScope();
6464 
6465     if (S->getFnParent() == nullptr) {
6466       bool SizeIsNegative;
6467       llvm::APSInt Oversized;
6468       TypeSourceInfo *FixedTInfo =
6469         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6470                                                       SizeIsNegative,
6471                                                       Oversized);
6472       if (FixedTInfo) {
6473         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6474         NewTD->setTypeSourceInfo(FixedTInfo);
6475       } else {
6476         if (SizeIsNegative)
6477           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6478         else if (T->isVariableArrayType())
6479           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6480         else if (Oversized.getBoolValue())
6481           Diag(NewTD->getLocation(), diag::err_array_too_large)
6482             << toString(Oversized, 10);
6483         else
6484           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6485         NewTD->setInvalidDecl();
6486       }
6487     }
6488   }
6489 }
6490 
6491 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6492 /// declares a typedef-name, either using the 'typedef' type specifier or via
6493 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6494 NamedDecl*
6495 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6496                            LookupResult &Previous, bool &Redeclaration) {
6497 
6498   // Find the shadowed declaration before filtering for scope.
6499   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6500 
6501   // Merge the decl with the existing one if appropriate. If the decl is
6502   // in an outer scope, it isn't the same thing.
6503   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6504                        /*AllowInlineNamespace*/false);
6505   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6506   if (!Previous.empty()) {
6507     Redeclaration = true;
6508     MergeTypedefNameDecl(S, NewTD, Previous);
6509   } else {
6510     inferGslPointerAttribute(NewTD);
6511   }
6512 
6513   if (ShadowedDecl && !Redeclaration)
6514     CheckShadow(NewTD, ShadowedDecl, Previous);
6515 
6516   // If this is the C FILE type, notify the AST context.
6517   if (IdentifierInfo *II = NewTD->getIdentifier())
6518     if (!NewTD->isInvalidDecl() &&
6519         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6520       if (II->isStr("FILE"))
6521         Context.setFILEDecl(NewTD);
6522       else if (II->isStr("jmp_buf"))
6523         Context.setjmp_bufDecl(NewTD);
6524       else if (II->isStr("sigjmp_buf"))
6525         Context.setsigjmp_bufDecl(NewTD);
6526       else if (II->isStr("ucontext_t"))
6527         Context.setucontext_tDecl(NewTD);
6528     }
6529 
6530   return NewTD;
6531 }
6532 
6533 /// Determines whether the given declaration is an out-of-scope
6534 /// previous declaration.
6535 ///
6536 /// This routine should be invoked when name lookup has found a
6537 /// previous declaration (PrevDecl) that is not in the scope where a
6538 /// new declaration by the same name is being introduced. If the new
6539 /// declaration occurs in a local scope, previous declarations with
6540 /// linkage may still be considered previous declarations (C99
6541 /// 6.2.2p4-5, C++ [basic.link]p6).
6542 ///
6543 /// \param PrevDecl the previous declaration found by name
6544 /// lookup
6545 ///
6546 /// \param DC the context in which the new declaration is being
6547 /// declared.
6548 ///
6549 /// \returns true if PrevDecl is an out-of-scope previous declaration
6550 /// for a new delcaration with the same name.
6551 static bool
6552 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6553                                 ASTContext &Context) {
6554   if (!PrevDecl)
6555     return false;
6556 
6557   if (!PrevDecl->hasLinkage())
6558     return false;
6559 
6560   if (Context.getLangOpts().CPlusPlus) {
6561     // C++ [basic.link]p6:
6562     //   If there is a visible declaration of an entity with linkage
6563     //   having the same name and type, ignoring entities declared
6564     //   outside the innermost enclosing namespace scope, the block
6565     //   scope declaration declares that same entity and receives the
6566     //   linkage of the previous declaration.
6567     DeclContext *OuterContext = DC->getRedeclContext();
6568     if (!OuterContext->isFunctionOrMethod())
6569       // This rule only applies to block-scope declarations.
6570       return false;
6571 
6572     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6573     if (PrevOuterContext->isRecord())
6574       // We found a member function: ignore it.
6575       return false;
6576 
6577     // Find the innermost enclosing namespace for the new and
6578     // previous declarations.
6579     OuterContext = OuterContext->getEnclosingNamespaceContext();
6580     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6581 
6582     // The previous declaration is in a different namespace, so it
6583     // isn't the same function.
6584     if (!OuterContext->Equals(PrevOuterContext))
6585       return false;
6586   }
6587 
6588   return true;
6589 }
6590 
6591 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6592   CXXScopeSpec &SS = D.getCXXScopeSpec();
6593   if (!SS.isSet()) return;
6594   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6595 }
6596 
6597 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6598   QualType type = decl->getType();
6599   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6600   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6601     // Various kinds of declaration aren't allowed to be __autoreleasing.
6602     unsigned kind = -1U;
6603     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6604       if (var->hasAttr<BlocksAttr>())
6605         kind = 0; // __block
6606       else if (!var->hasLocalStorage())
6607         kind = 1; // global
6608     } else if (isa<ObjCIvarDecl>(decl)) {
6609       kind = 3; // ivar
6610     } else if (isa<FieldDecl>(decl)) {
6611       kind = 2; // field
6612     }
6613 
6614     if (kind != -1U) {
6615       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6616         << kind;
6617     }
6618   } else if (lifetime == Qualifiers::OCL_None) {
6619     // Try to infer lifetime.
6620     if (!type->isObjCLifetimeType())
6621       return false;
6622 
6623     lifetime = type->getObjCARCImplicitLifetime();
6624     type = Context.getLifetimeQualifiedType(type, lifetime);
6625     decl->setType(type);
6626   }
6627 
6628   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6629     // Thread-local variables cannot have lifetime.
6630     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6631         var->getTLSKind()) {
6632       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6633         << var->getType();
6634       return true;
6635     }
6636   }
6637 
6638   return false;
6639 }
6640 
6641 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6642   if (Decl->getType().hasAddressSpace())
6643     return;
6644   if (Decl->getType()->isDependentType())
6645     return;
6646   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6647     QualType Type = Var->getType();
6648     if (Type->isSamplerT() || Type->isVoidType())
6649       return;
6650     LangAS ImplAS = LangAS::opencl_private;
6651     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6652     // __opencl_c_program_scope_global_variables feature, the address space
6653     // for a variable at program scope or a static or extern variable inside
6654     // a function are inferred to be __global.
6655     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6656         Var->hasGlobalStorage())
6657       ImplAS = LangAS::opencl_global;
6658     // If the original type from a decayed type is an array type and that array
6659     // type has no address space yet, deduce it now.
6660     if (auto DT = dyn_cast<DecayedType>(Type)) {
6661       auto OrigTy = DT->getOriginalType();
6662       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6663         // Add the address space to the original array type and then propagate
6664         // that to the element type through `getAsArrayType`.
6665         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6666         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6667         // Re-generate the decayed type.
6668         Type = Context.getDecayedType(OrigTy);
6669       }
6670     }
6671     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6672     // Apply any qualifiers (including address space) from the array type to
6673     // the element type. This implements C99 6.7.3p8: "If the specification of
6674     // an array type includes any type qualifiers, the element type is so
6675     // qualified, not the array type."
6676     if (Type->isArrayType())
6677       Type = QualType(Context.getAsArrayType(Type), 0);
6678     Decl->setType(Type);
6679   }
6680 }
6681 
6682 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6683   // Ensure that an auto decl is deduced otherwise the checks below might cache
6684   // the wrong linkage.
6685   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6686 
6687   // 'weak' only applies to declarations with external linkage.
6688   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6689     if (!ND.isExternallyVisible()) {
6690       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6691       ND.dropAttr<WeakAttr>();
6692     }
6693   }
6694   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6695     if (ND.isExternallyVisible()) {
6696       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6697       ND.dropAttr<WeakRefAttr>();
6698       ND.dropAttr<AliasAttr>();
6699     }
6700   }
6701 
6702   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6703     if (VD->hasInit()) {
6704       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6705         assert(VD->isThisDeclarationADefinition() &&
6706                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6707         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6708         VD->dropAttr<AliasAttr>();
6709       }
6710     }
6711   }
6712 
6713   // 'selectany' only applies to externally visible variable declarations.
6714   // It does not apply to functions.
6715   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6716     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6717       S.Diag(Attr->getLocation(),
6718              diag::err_attribute_selectany_non_extern_data);
6719       ND.dropAttr<SelectAnyAttr>();
6720     }
6721   }
6722 
6723   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6724     auto *VD = dyn_cast<VarDecl>(&ND);
6725     bool IsAnonymousNS = false;
6726     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6727     if (VD) {
6728       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6729       while (NS && !IsAnonymousNS) {
6730         IsAnonymousNS = NS->isAnonymousNamespace();
6731         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6732       }
6733     }
6734     // dll attributes require external linkage. Static locals may have external
6735     // linkage but still cannot be explicitly imported or exported.
6736     // In Microsoft mode, a variable defined in anonymous namespace must have
6737     // external linkage in order to be exported.
6738     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6739     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6740         (!AnonNSInMicrosoftMode &&
6741          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6742       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6743         << &ND << Attr;
6744       ND.setInvalidDecl();
6745     }
6746   }
6747 
6748   // Check the attributes on the function type, if any.
6749   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6750     // Don't declare this variable in the second operand of the for-statement;
6751     // GCC miscompiles that by ending its lifetime before evaluating the
6752     // third operand. See gcc.gnu.org/PR86769.
6753     AttributedTypeLoc ATL;
6754     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6755          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6756          TL = ATL.getModifiedLoc()) {
6757       // The [[lifetimebound]] attribute can be applied to the implicit object
6758       // parameter of a non-static member function (other than a ctor or dtor)
6759       // by applying it to the function type.
6760       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6761         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6762         if (!MD || MD->isStatic()) {
6763           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6764               << !MD << A->getRange();
6765         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6766           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6767               << isa<CXXDestructorDecl>(MD) << A->getRange();
6768         }
6769       }
6770     }
6771   }
6772 }
6773 
6774 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6775                                            NamedDecl *NewDecl,
6776                                            bool IsSpecialization,
6777                                            bool IsDefinition) {
6778   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6779     return;
6780 
6781   bool IsTemplate = false;
6782   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6783     OldDecl = OldTD->getTemplatedDecl();
6784     IsTemplate = true;
6785     if (!IsSpecialization)
6786       IsDefinition = false;
6787   }
6788   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6789     NewDecl = NewTD->getTemplatedDecl();
6790     IsTemplate = true;
6791   }
6792 
6793   if (!OldDecl || !NewDecl)
6794     return;
6795 
6796   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6797   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6798   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6799   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6800 
6801   // dllimport and dllexport are inheritable attributes so we have to exclude
6802   // inherited attribute instances.
6803   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6804                     (NewExportAttr && !NewExportAttr->isInherited());
6805 
6806   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6807   // the only exception being explicit specializations.
6808   // Implicitly generated declarations are also excluded for now because there
6809   // is no other way to switch these to use dllimport or dllexport.
6810   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6811 
6812   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6813     // Allow with a warning for free functions and global variables.
6814     bool JustWarn = false;
6815     if (!OldDecl->isCXXClassMember()) {
6816       auto *VD = dyn_cast<VarDecl>(OldDecl);
6817       if (VD && !VD->getDescribedVarTemplate())
6818         JustWarn = true;
6819       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6820       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6821         JustWarn = true;
6822     }
6823 
6824     // We cannot change a declaration that's been used because IR has already
6825     // been emitted. Dllimported functions will still work though (modulo
6826     // address equality) as they can use the thunk.
6827     if (OldDecl->isUsed())
6828       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6829         JustWarn = false;
6830 
6831     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6832                                : diag::err_attribute_dll_redeclaration;
6833     S.Diag(NewDecl->getLocation(), DiagID)
6834         << NewDecl
6835         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6836     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6837     if (!JustWarn) {
6838       NewDecl->setInvalidDecl();
6839       return;
6840     }
6841   }
6842 
6843   // A redeclaration is not allowed to drop a dllimport attribute, the only
6844   // exceptions being inline function definitions (except for function
6845   // templates), local extern declarations, qualified friend declarations or
6846   // special MSVC extension: in the last case, the declaration is treated as if
6847   // it were marked dllexport.
6848   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6849   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6850   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6851     // Ignore static data because out-of-line definitions are diagnosed
6852     // separately.
6853     IsStaticDataMember = VD->isStaticDataMember();
6854     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6855                    VarDecl::DeclarationOnly;
6856   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6857     IsInline = FD->isInlined();
6858     IsQualifiedFriend = FD->getQualifier() &&
6859                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6860   }
6861 
6862   if (OldImportAttr && !HasNewAttr &&
6863       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6864       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6865     if (IsMicrosoftABI && IsDefinition) {
6866       S.Diag(NewDecl->getLocation(),
6867              diag::warn_redeclaration_without_import_attribute)
6868           << NewDecl;
6869       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6870       NewDecl->dropAttr<DLLImportAttr>();
6871       NewDecl->addAttr(
6872           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6873     } else {
6874       S.Diag(NewDecl->getLocation(),
6875              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6876           << NewDecl << OldImportAttr;
6877       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6878       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6879       OldDecl->dropAttr<DLLImportAttr>();
6880       NewDecl->dropAttr<DLLImportAttr>();
6881     }
6882   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6883     // In MinGW, seeing a function declared inline drops the dllimport
6884     // attribute.
6885     OldDecl->dropAttr<DLLImportAttr>();
6886     NewDecl->dropAttr<DLLImportAttr>();
6887     S.Diag(NewDecl->getLocation(),
6888            diag::warn_dllimport_dropped_from_inline_function)
6889         << NewDecl << OldImportAttr;
6890   }
6891 
6892   // A specialization of a class template member function is processed here
6893   // since it's a redeclaration. If the parent class is dllexport, the
6894   // specialization inherits that attribute. This doesn't happen automatically
6895   // since the parent class isn't instantiated until later.
6896   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6897     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6898         !NewImportAttr && !NewExportAttr) {
6899       if (const DLLExportAttr *ParentExportAttr =
6900               MD->getParent()->getAttr<DLLExportAttr>()) {
6901         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6902         NewAttr->setInherited(true);
6903         NewDecl->addAttr(NewAttr);
6904       }
6905     }
6906   }
6907 }
6908 
6909 /// Given that we are within the definition of the given function,
6910 /// will that definition behave like C99's 'inline', where the
6911 /// definition is discarded except for optimization purposes?
6912 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6913   // Try to avoid calling GetGVALinkageForFunction.
6914 
6915   // All cases of this require the 'inline' keyword.
6916   if (!FD->isInlined()) return false;
6917 
6918   // This is only possible in C++ with the gnu_inline attribute.
6919   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6920     return false;
6921 
6922   // Okay, go ahead and call the relatively-more-expensive function.
6923   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6924 }
6925 
6926 /// Determine whether a variable is extern "C" prior to attaching
6927 /// an initializer. We can't just call isExternC() here, because that
6928 /// will also compute and cache whether the declaration is externally
6929 /// visible, which might change when we attach the initializer.
6930 ///
6931 /// This can only be used if the declaration is known to not be a
6932 /// redeclaration of an internal linkage declaration.
6933 ///
6934 /// For instance:
6935 ///
6936 ///   auto x = []{};
6937 ///
6938 /// Attaching the initializer here makes this declaration not externally
6939 /// visible, because its type has internal linkage.
6940 ///
6941 /// FIXME: This is a hack.
6942 template<typename T>
6943 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6944   if (S.getLangOpts().CPlusPlus) {
6945     // In C++, the overloadable attribute negates the effects of extern "C".
6946     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6947       return false;
6948 
6949     // So do CUDA's host/device attributes.
6950     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6951                                  D->template hasAttr<CUDAHostAttr>()))
6952       return false;
6953   }
6954   return D->isExternC();
6955 }
6956 
6957 static bool shouldConsiderLinkage(const VarDecl *VD) {
6958   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6959   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6960       isa<OMPDeclareMapperDecl>(DC))
6961     return VD->hasExternalStorage();
6962   if (DC->isFileContext())
6963     return true;
6964   if (DC->isRecord())
6965     return false;
6966   if (isa<RequiresExprBodyDecl>(DC))
6967     return false;
6968   llvm_unreachable("Unexpected context");
6969 }
6970 
6971 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6972   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6973   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6974       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6975     return true;
6976   if (DC->isRecord())
6977     return false;
6978   llvm_unreachable("Unexpected context");
6979 }
6980 
6981 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6982                           ParsedAttr::Kind Kind) {
6983   // Check decl attributes on the DeclSpec.
6984   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6985     return true;
6986 
6987   // Walk the declarator structure, checking decl attributes that were in a type
6988   // position to the decl itself.
6989   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6990     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6991       return true;
6992   }
6993 
6994   // Finally, check attributes on the decl itself.
6995   return PD.getAttributes().hasAttribute(Kind);
6996 }
6997 
6998 /// Adjust the \c DeclContext for a function or variable that might be a
6999 /// function-local external declaration.
7000 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7001   if (!DC->isFunctionOrMethod())
7002     return false;
7003 
7004   // If this is a local extern function or variable declared within a function
7005   // template, don't add it into the enclosing namespace scope until it is
7006   // instantiated; it might have a dependent type right now.
7007   if (DC->isDependentContext())
7008     return true;
7009 
7010   // C++11 [basic.link]p7:
7011   //   When a block scope declaration of an entity with linkage is not found to
7012   //   refer to some other declaration, then that entity is a member of the
7013   //   innermost enclosing namespace.
7014   //
7015   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7016   // semantically-enclosing namespace, not a lexically-enclosing one.
7017   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7018     DC = DC->getParent();
7019   return true;
7020 }
7021 
7022 /// Returns true if given declaration has external C language linkage.
7023 static bool isDeclExternC(const Decl *D) {
7024   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7025     return FD->isExternC();
7026   if (const auto *VD = dyn_cast<VarDecl>(D))
7027     return VD->isExternC();
7028 
7029   llvm_unreachable("Unknown type of decl!");
7030 }
7031 
7032 /// Returns true if there hasn't been any invalid type diagnosed.
7033 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7034   DeclContext *DC = NewVD->getDeclContext();
7035   QualType R = NewVD->getType();
7036 
7037   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7038   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7039   // argument.
7040   if (R->isImageType() || R->isPipeType()) {
7041     Se.Diag(NewVD->getLocation(),
7042             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7043         << R;
7044     NewVD->setInvalidDecl();
7045     return false;
7046   }
7047 
7048   // OpenCL v1.2 s6.9.r:
7049   // The event type cannot be used to declare a program scope variable.
7050   // OpenCL v2.0 s6.9.q:
7051   // The clk_event_t and reserve_id_t types cannot be declared in program
7052   // scope.
7053   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7054     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7055       Se.Diag(NewVD->getLocation(),
7056               diag::err_invalid_type_for_program_scope_var)
7057           << R;
7058       NewVD->setInvalidDecl();
7059       return false;
7060     }
7061   }
7062 
7063   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7064   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7065                                                Se.getLangOpts())) {
7066     QualType NR = R.getCanonicalType();
7067     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7068            NR->isReferenceType()) {
7069       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7070           NR->isFunctionReferenceType()) {
7071         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7072             << NR->isReferenceType();
7073         NewVD->setInvalidDecl();
7074         return false;
7075       }
7076       NR = NR->getPointeeType();
7077     }
7078   }
7079 
7080   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7081                                                Se.getLangOpts())) {
7082     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7083     // half array type (unless the cl_khr_fp16 extension is enabled).
7084     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7085       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7086       NewVD->setInvalidDecl();
7087       return false;
7088     }
7089   }
7090 
7091   // OpenCL v1.2 s6.9.r:
7092   // The event type cannot be used with the __local, __constant and __global
7093   // address space qualifiers.
7094   if (R->isEventT()) {
7095     if (R.getAddressSpace() != LangAS::opencl_private) {
7096       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7097       NewVD->setInvalidDecl();
7098       return false;
7099     }
7100   }
7101 
7102   if (R->isSamplerT()) {
7103     // OpenCL v1.2 s6.9.b p4:
7104     // The sampler type cannot be used with the __local and __global address
7105     // space qualifiers.
7106     if (R.getAddressSpace() == LangAS::opencl_local ||
7107         R.getAddressSpace() == LangAS::opencl_global) {
7108       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7109       NewVD->setInvalidDecl();
7110     }
7111 
7112     // OpenCL v1.2 s6.12.14.1:
7113     // A global sampler must be declared with either the constant address
7114     // space qualifier or with the const qualifier.
7115     if (DC->isTranslationUnit() &&
7116         !(R.getAddressSpace() == LangAS::opencl_constant ||
7117           R.isConstQualified())) {
7118       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7119       NewVD->setInvalidDecl();
7120     }
7121     if (NewVD->isInvalidDecl())
7122       return false;
7123   }
7124 
7125   return true;
7126 }
7127 
7128 template <typename AttrTy>
7129 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7130   const TypedefNameDecl *TND = TT->getDecl();
7131   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7132     AttrTy *Clone = Attribute->clone(S.Context);
7133     Clone->setInherited(true);
7134     D->addAttr(Clone);
7135   }
7136 }
7137 
7138 NamedDecl *Sema::ActOnVariableDeclarator(
7139     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7140     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7141     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7142   QualType R = TInfo->getType();
7143   DeclarationName Name = GetNameForDeclarator(D).getName();
7144 
7145   IdentifierInfo *II = Name.getAsIdentifierInfo();
7146 
7147   if (D.isDecompositionDeclarator()) {
7148     // Take the name of the first declarator as our name for diagnostic
7149     // purposes.
7150     auto &Decomp = D.getDecompositionDeclarator();
7151     if (!Decomp.bindings().empty()) {
7152       II = Decomp.bindings()[0].Name;
7153       Name = II;
7154     }
7155   } else if (!II) {
7156     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7157     return nullptr;
7158   }
7159 
7160 
7161   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7162   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7163 
7164   // dllimport globals without explicit storage class are treated as extern. We
7165   // have to change the storage class this early to get the right DeclContext.
7166   if (SC == SC_None && !DC->isRecord() &&
7167       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7168       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7169     SC = SC_Extern;
7170 
7171   DeclContext *OriginalDC = DC;
7172   bool IsLocalExternDecl = SC == SC_Extern &&
7173                            adjustContextForLocalExternDecl(DC);
7174 
7175   if (SCSpec == DeclSpec::SCS_mutable) {
7176     // mutable can only appear on non-static class members, so it's always
7177     // an error here
7178     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7179     D.setInvalidType();
7180     SC = SC_None;
7181   }
7182 
7183   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7184       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7185                               D.getDeclSpec().getStorageClassSpecLoc())) {
7186     // In C++11, the 'register' storage class specifier is deprecated.
7187     // Suppress the warning in system macros, it's used in macros in some
7188     // popular C system headers, such as in glibc's htonl() macro.
7189     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7190          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7191                                    : diag::warn_deprecated_register)
7192       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7193   }
7194 
7195   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7196 
7197   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7198     // C99 6.9p2: The storage-class specifiers auto and register shall not
7199     // appear in the declaration specifiers in an external declaration.
7200     // Global Register+Asm is a GNU extension we support.
7201     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7202       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7203       D.setInvalidType();
7204     }
7205   }
7206 
7207   // If this variable has a VLA type and an initializer, try to
7208   // fold to a constant-sized type. This is otherwise invalid.
7209   if (D.hasInitializer() && R->isVariableArrayType())
7210     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7211                                     /*DiagID=*/0);
7212 
7213   bool IsMemberSpecialization = false;
7214   bool IsVariableTemplateSpecialization = false;
7215   bool IsPartialSpecialization = false;
7216   bool IsVariableTemplate = false;
7217   VarDecl *NewVD = nullptr;
7218   VarTemplateDecl *NewTemplate = nullptr;
7219   TemplateParameterList *TemplateParams = nullptr;
7220   if (!getLangOpts().CPlusPlus) {
7221     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7222                             II, R, TInfo, SC);
7223 
7224     if (R->getContainedDeducedType())
7225       ParsingInitForAutoVars.insert(NewVD);
7226 
7227     if (D.isInvalidType())
7228       NewVD->setInvalidDecl();
7229 
7230     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7231         NewVD->hasLocalStorage())
7232       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7233                             NTCUC_AutoVar, NTCUK_Destruct);
7234   } else {
7235     bool Invalid = false;
7236 
7237     if (DC->isRecord() && !CurContext->isRecord()) {
7238       // This is an out-of-line definition of a static data member.
7239       switch (SC) {
7240       case SC_None:
7241         break;
7242       case SC_Static:
7243         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7244              diag::err_static_out_of_line)
7245           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7246         break;
7247       case SC_Auto:
7248       case SC_Register:
7249       case SC_Extern:
7250         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7251         // to names of variables declared in a block or to function parameters.
7252         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7253         // of class members
7254 
7255         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7256              diag::err_storage_class_for_static_member)
7257           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7258         break;
7259       case SC_PrivateExtern:
7260         llvm_unreachable("C storage class in c++!");
7261       }
7262     }
7263 
7264     if (SC == SC_Static && CurContext->isRecord()) {
7265       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7266         // Walk up the enclosing DeclContexts to check for any that are
7267         // incompatible with static data members.
7268         const DeclContext *FunctionOrMethod = nullptr;
7269         const CXXRecordDecl *AnonStruct = nullptr;
7270         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7271           if (Ctxt->isFunctionOrMethod()) {
7272             FunctionOrMethod = Ctxt;
7273             break;
7274           }
7275           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7276           if (ParentDecl && !ParentDecl->getDeclName()) {
7277             AnonStruct = ParentDecl;
7278             break;
7279           }
7280         }
7281         if (FunctionOrMethod) {
7282           // C++ [class.static.data]p5: A local class shall not have static data
7283           // members.
7284           Diag(D.getIdentifierLoc(),
7285                diag::err_static_data_member_not_allowed_in_local_class)
7286             << Name << RD->getDeclName() << RD->getTagKind();
7287         } else if (AnonStruct) {
7288           // C++ [class.static.data]p4: Unnamed classes and classes contained
7289           // directly or indirectly within unnamed classes shall not contain
7290           // static data members.
7291           Diag(D.getIdentifierLoc(),
7292                diag::err_static_data_member_not_allowed_in_anon_struct)
7293             << Name << AnonStruct->getTagKind();
7294           Invalid = true;
7295         } else if (RD->isUnion()) {
7296           // C++98 [class.union]p1: If a union contains a static data member,
7297           // the program is ill-formed. C++11 drops this restriction.
7298           Diag(D.getIdentifierLoc(),
7299                getLangOpts().CPlusPlus11
7300                  ? diag::warn_cxx98_compat_static_data_member_in_union
7301                  : diag::ext_static_data_member_in_union) << Name;
7302         }
7303       }
7304     }
7305 
7306     // Match up the template parameter lists with the scope specifier, then
7307     // determine whether we have a template or a template specialization.
7308     bool InvalidScope = false;
7309     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7310         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7311         D.getCXXScopeSpec(),
7312         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7313             ? D.getName().TemplateId
7314             : nullptr,
7315         TemplateParamLists,
7316         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7317     Invalid |= InvalidScope;
7318 
7319     if (TemplateParams) {
7320       if (!TemplateParams->size() &&
7321           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7322         // There is an extraneous 'template<>' for this variable. Complain
7323         // about it, but allow the declaration of the variable.
7324         Diag(TemplateParams->getTemplateLoc(),
7325              diag::err_template_variable_noparams)
7326           << II
7327           << SourceRange(TemplateParams->getTemplateLoc(),
7328                          TemplateParams->getRAngleLoc());
7329         TemplateParams = nullptr;
7330       } else {
7331         // Check that we can declare a template here.
7332         if (CheckTemplateDeclScope(S, TemplateParams))
7333           return nullptr;
7334 
7335         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7336           // This is an explicit specialization or a partial specialization.
7337           IsVariableTemplateSpecialization = true;
7338           IsPartialSpecialization = TemplateParams->size() > 0;
7339         } else { // if (TemplateParams->size() > 0)
7340           // This is a template declaration.
7341           IsVariableTemplate = true;
7342 
7343           // Only C++1y supports variable templates (N3651).
7344           Diag(D.getIdentifierLoc(),
7345                getLangOpts().CPlusPlus14
7346                    ? diag::warn_cxx11_compat_variable_template
7347                    : diag::ext_variable_template);
7348         }
7349       }
7350     } else {
7351       // Check that we can declare a member specialization here.
7352       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7353           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7354         return nullptr;
7355       assert((Invalid ||
7356               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7357              "should have a 'template<>' for this decl");
7358     }
7359 
7360     if (IsVariableTemplateSpecialization) {
7361       SourceLocation TemplateKWLoc =
7362           TemplateParamLists.size() > 0
7363               ? TemplateParamLists[0]->getTemplateLoc()
7364               : SourceLocation();
7365       DeclResult Res = ActOnVarTemplateSpecialization(
7366           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7367           IsPartialSpecialization);
7368       if (Res.isInvalid())
7369         return nullptr;
7370       NewVD = cast<VarDecl>(Res.get());
7371       AddToScope = false;
7372     } else if (D.isDecompositionDeclarator()) {
7373       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7374                                         D.getIdentifierLoc(), R, TInfo, SC,
7375                                         Bindings);
7376     } else
7377       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7378                               D.getIdentifierLoc(), II, R, TInfo, SC);
7379 
7380     // If this is supposed to be a variable template, create it as such.
7381     if (IsVariableTemplate) {
7382       NewTemplate =
7383           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7384                                   TemplateParams, NewVD);
7385       NewVD->setDescribedVarTemplate(NewTemplate);
7386     }
7387 
7388     // If this decl has an auto type in need of deduction, make a note of the
7389     // Decl so we can diagnose uses of it in its own initializer.
7390     if (R->getContainedDeducedType())
7391       ParsingInitForAutoVars.insert(NewVD);
7392 
7393     if (D.isInvalidType() || Invalid) {
7394       NewVD->setInvalidDecl();
7395       if (NewTemplate)
7396         NewTemplate->setInvalidDecl();
7397     }
7398 
7399     SetNestedNameSpecifier(*this, NewVD, D);
7400 
7401     // If we have any template parameter lists that don't directly belong to
7402     // the variable (matching the scope specifier), store them.
7403     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7404     if (TemplateParamLists.size() > VDTemplateParamLists)
7405       NewVD->setTemplateParameterListsInfo(
7406           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7407   }
7408 
7409   if (D.getDeclSpec().isInlineSpecified()) {
7410     if (!getLangOpts().CPlusPlus) {
7411       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7412           << 0;
7413     } else if (CurContext->isFunctionOrMethod()) {
7414       // 'inline' is not allowed on block scope variable declaration.
7415       Diag(D.getDeclSpec().getInlineSpecLoc(),
7416            diag::err_inline_declaration_block_scope) << Name
7417         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7418     } else {
7419       Diag(D.getDeclSpec().getInlineSpecLoc(),
7420            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7421                                      : diag::ext_inline_variable);
7422       NewVD->setInlineSpecified();
7423     }
7424   }
7425 
7426   // Set the lexical context. If the declarator has a C++ scope specifier, the
7427   // lexical context will be different from the semantic context.
7428   NewVD->setLexicalDeclContext(CurContext);
7429   if (NewTemplate)
7430     NewTemplate->setLexicalDeclContext(CurContext);
7431 
7432   if (IsLocalExternDecl) {
7433     if (D.isDecompositionDeclarator())
7434       for (auto *B : Bindings)
7435         B->setLocalExternDecl();
7436     else
7437       NewVD->setLocalExternDecl();
7438   }
7439 
7440   bool EmitTLSUnsupportedError = false;
7441   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7442     // C++11 [dcl.stc]p4:
7443     //   When thread_local is applied to a variable of block scope the
7444     //   storage-class-specifier static is implied if it does not appear
7445     //   explicitly.
7446     // Core issue: 'static' is not implied if the variable is declared
7447     //   'extern'.
7448     if (NewVD->hasLocalStorage() &&
7449         (SCSpec != DeclSpec::SCS_unspecified ||
7450          TSCS != DeclSpec::TSCS_thread_local ||
7451          !DC->isFunctionOrMethod()))
7452       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7453            diag::err_thread_non_global)
7454         << DeclSpec::getSpecifierName(TSCS);
7455     else if (!Context.getTargetInfo().isTLSSupported()) {
7456       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7457           getLangOpts().SYCLIsDevice) {
7458         // Postpone error emission until we've collected attributes required to
7459         // figure out whether it's a host or device variable and whether the
7460         // error should be ignored.
7461         EmitTLSUnsupportedError = true;
7462         // We still need to mark the variable as TLS so it shows up in AST with
7463         // proper storage class for other tools to use even if we're not going
7464         // to emit any code for it.
7465         NewVD->setTSCSpec(TSCS);
7466       } else
7467         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7468              diag::err_thread_unsupported);
7469     } else
7470       NewVD->setTSCSpec(TSCS);
7471   }
7472 
7473   switch (D.getDeclSpec().getConstexprSpecifier()) {
7474   case ConstexprSpecKind::Unspecified:
7475     break;
7476 
7477   case ConstexprSpecKind::Consteval:
7478     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7479          diag::err_constexpr_wrong_decl_kind)
7480         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7481     LLVM_FALLTHROUGH;
7482 
7483   case ConstexprSpecKind::Constexpr:
7484     NewVD->setConstexpr(true);
7485     // C++1z [dcl.spec.constexpr]p1:
7486     //   A static data member declared with the constexpr specifier is
7487     //   implicitly an inline variable.
7488     if (NewVD->isStaticDataMember() &&
7489         (getLangOpts().CPlusPlus17 ||
7490          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7491       NewVD->setImplicitlyInline();
7492     break;
7493 
7494   case ConstexprSpecKind::Constinit:
7495     if (!NewVD->hasGlobalStorage())
7496       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7497            diag::err_constinit_local_variable);
7498     else
7499       NewVD->addAttr(ConstInitAttr::Create(
7500           Context, D.getDeclSpec().getConstexprSpecLoc(),
7501           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7502     break;
7503   }
7504 
7505   // C99 6.7.4p3
7506   //   An inline definition of a function with external linkage shall
7507   //   not contain a definition of a modifiable object with static or
7508   //   thread storage duration...
7509   // We only apply this when the function is required to be defined
7510   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7511   // that a local variable with thread storage duration still has to
7512   // be marked 'static'.  Also note that it's possible to get these
7513   // semantics in C++ using __attribute__((gnu_inline)).
7514   if (SC == SC_Static && S->getFnParent() != nullptr &&
7515       !NewVD->getType().isConstQualified()) {
7516     FunctionDecl *CurFD = getCurFunctionDecl();
7517     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7518       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7519            diag::warn_static_local_in_extern_inline);
7520       MaybeSuggestAddingStaticToDecl(CurFD);
7521     }
7522   }
7523 
7524   if (D.getDeclSpec().isModulePrivateSpecified()) {
7525     if (IsVariableTemplateSpecialization)
7526       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7527           << (IsPartialSpecialization ? 1 : 0)
7528           << FixItHint::CreateRemoval(
7529                  D.getDeclSpec().getModulePrivateSpecLoc());
7530     else if (IsMemberSpecialization)
7531       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7532         << 2
7533         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7534     else if (NewVD->hasLocalStorage())
7535       Diag(NewVD->getLocation(), diag::err_module_private_local)
7536           << 0 << NewVD
7537           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7538           << FixItHint::CreateRemoval(
7539                  D.getDeclSpec().getModulePrivateSpecLoc());
7540     else {
7541       NewVD->setModulePrivate();
7542       if (NewTemplate)
7543         NewTemplate->setModulePrivate();
7544       for (auto *B : Bindings)
7545         B->setModulePrivate();
7546     }
7547   }
7548 
7549   if (getLangOpts().OpenCL) {
7550     deduceOpenCLAddressSpace(NewVD);
7551 
7552     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7553     if (TSC != TSCS_unspecified) {
7554       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7555            diag::err_opencl_unknown_type_specifier)
7556           << getLangOpts().getOpenCLVersionString()
7557           << DeclSpec::getSpecifierName(TSC) << 1;
7558       NewVD->setInvalidDecl();
7559     }
7560   }
7561 
7562   // Handle attributes prior to checking for duplicates in MergeVarDecl
7563   ProcessDeclAttributes(S, NewVD, D);
7564 
7565   // FIXME: This is probably the wrong location to be doing this and we should
7566   // probably be doing this for more attributes (especially for function
7567   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7568   // the code to copy attributes would be generated by TableGen.
7569   if (R->isFunctionPointerType())
7570     if (const auto *TT = R->getAs<TypedefType>())
7571       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7572 
7573   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7574       getLangOpts().SYCLIsDevice) {
7575     if (EmitTLSUnsupportedError &&
7576         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7577          (getLangOpts().OpenMPIsDevice &&
7578           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7579       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7580            diag::err_thread_unsupported);
7581 
7582     if (EmitTLSUnsupportedError &&
7583         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7584       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7585     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7586     // storage [duration]."
7587     if (SC == SC_None && S->getFnParent() != nullptr &&
7588         (NewVD->hasAttr<CUDASharedAttr>() ||
7589          NewVD->hasAttr<CUDAConstantAttr>())) {
7590       NewVD->setStorageClass(SC_Static);
7591     }
7592   }
7593 
7594   // Ensure that dllimport globals without explicit storage class are treated as
7595   // extern. The storage class is set above using parsed attributes. Now we can
7596   // check the VarDecl itself.
7597   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7598          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7599          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7600 
7601   // In auto-retain/release, infer strong retension for variables of
7602   // retainable type.
7603   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7604     NewVD->setInvalidDecl();
7605 
7606   // Handle GNU asm-label extension (encoded as an attribute).
7607   if (Expr *E = (Expr*)D.getAsmLabel()) {
7608     // The parser guarantees this is a string.
7609     StringLiteral *SE = cast<StringLiteral>(E);
7610     StringRef Label = SE->getString();
7611     if (S->getFnParent() != nullptr) {
7612       switch (SC) {
7613       case SC_None:
7614       case SC_Auto:
7615         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7616         break;
7617       case SC_Register:
7618         // Local Named register
7619         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7620             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7621           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7622         break;
7623       case SC_Static:
7624       case SC_Extern:
7625       case SC_PrivateExtern:
7626         break;
7627       }
7628     } else if (SC == SC_Register) {
7629       // Global Named register
7630       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7631         const auto &TI = Context.getTargetInfo();
7632         bool HasSizeMismatch;
7633 
7634         if (!TI.isValidGCCRegisterName(Label))
7635           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7636         else if (!TI.validateGlobalRegisterVariable(Label,
7637                                                     Context.getTypeSize(R),
7638                                                     HasSizeMismatch))
7639           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7640         else if (HasSizeMismatch)
7641           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7642       }
7643 
7644       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7645         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7646         NewVD->setInvalidDecl(true);
7647       }
7648     }
7649 
7650     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7651                                         /*IsLiteralLabel=*/true,
7652                                         SE->getStrTokenLoc(0)));
7653   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7654     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7655       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7656     if (I != ExtnameUndeclaredIdentifiers.end()) {
7657       if (isDeclExternC(NewVD)) {
7658         NewVD->addAttr(I->second);
7659         ExtnameUndeclaredIdentifiers.erase(I);
7660       } else
7661         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7662             << /*Variable*/1 << NewVD;
7663     }
7664   }
7665 
7666   // Find the shadowed declaration before filtering for scope.
7667   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7668                                 ? getShadowedDeclaration(NewVD, Previous)
7669                                 : nullptr;
7670 
7671   // Don't consider existing declarations that are in a different
7672   // scope and are out-of-semantic-context declarations (if the new
7673   // declaration has linkage).
7674   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7675                        D.getCXXScopeSpec().isNotEmpty() ||
7676                        IsMemberSpecialization ||
7677                        IsVariableTemplateSpecialization);
7678 
7679   // Check whether the previous declaration is in the same block scope. This
7680   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7681   if (getLangOpts().CPlusPlus &&
7682       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7683     NewVD->setPreviousDeclInSameBlockScope(
7684         Previous.isSingleResult() && !Previous.isShadowed() &&
7685         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7686 
7687   if (!getLangOpts().CPlusPlus) {
7688     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7689   } else {
7690     // If this is an explicit specialization of a static data member, check it.
7691     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7692         CheckMemberSpecialization(NewVD, Previous))
7693       NewVD->setInvalidDecl();
7694 
7695     // Merge the decl with the existing one if appropriate.
7696     if (!Previous.empty()) {
7697       if (Previous.isSingleResult() &&
7698           isa<FieldDecl>(Previous.getFoundDecl()) &&
7699           D.getCXXScopeSpec().isSet()) {
7700         // The user tried to define a non-static data member
7701         // out-of-line (C++ [dcl.meaning]p1).
7702         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7703           << D.getCXXScopeSpec().getRange();
7704         Previous.clear();
7705         NewVD->setInvalidDecl();
7706       }
7707     } else if (D.getCXXScopeSpec().isSet()) {
7708       // No previous declaration in the qualifying scope.
7709       Diag(D.getIdentifierLoc(), diag::err_no_member)
7710         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7711         << D.getCXXScopeSpec().getRange();
7712       NewVD->setInvalidDecl();
7713     }
7714 
7715     if (!IsVariableTemplateSpecialization)
7716       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7717 
7718     if (NewTemplate) {
7719       VarTemplateDecl *PrevVarTemplate =
7720           NewVD->getPreviousDecl()
7721               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7722               : nullptr;
7723 
7724       // Check the template parameter list of this declaration, possibly
7725       // merging in the template parameter list from the previous variable
7726       // template declaration.
7727       if (CheckTemplateParameterList(
7728               TemplateParams,
7729               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7730                               : nullptr,
7731               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7732                DC->isDependentContext())
7733                   ? TPC_ClassTemplateMember
7734                   : TPC_VarTemplate))
7735         NewVD->setInvalidDecl();
7736 
7737       // If we are providing an explicit specialization of a static variable
7738       // template, make a note of that.
7739       if (PrevVarTemplate &&
7740           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7741         PrevVarTemplate->setMemberSpecialization();
7742     }
7743   }
7744 
7745   // Diagnose shadowed variables iff this isn't a redeclaration.
7746   if (ShadowedDecl && !D.isRedeclaration())
7747     CheckShadow(NewVD, ShadowedDecl, Previous);
7748 
7749   ProcessPragmaWeak(S, NewVD);
7750 
7751   // If this is the first declaration of an extern C variable, update
7752   // the map of such variables.
7753   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7754       isIncompleteDeclExternC(*this, NewVD))
7755     RegisterLocallyScopedExternCDecl(NewVD, S);
7756 
7757   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7758     MangleNumberingContext *MCtx;
7759     Decl *ManglingContextDecl;
7760     std::tie(MCtx, ManglingContextDecl) =
7761         getCurrentMangleNumberContext(NewVD->getDeclContext());
7762     if (MCtx) {
7763       Context.setManglingNumber(
7764           NewVD, MCtx->getManglingNumber(
7765                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7766       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7767     }
7768   }
7769 
7770   // Special handling of variable named 'main'.
7771   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7772       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7773       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7774 
7775     // C++ [basic.start.main]p3
7776     // A program that declares a variable main at global scope is ill-formed.
7777     if (getLangOpts().CPlusPlus)
7778       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7779 
7780     // In C, and external-linkage variable named main results in undefined
7781     // behavior.
7782     else if (NewVD->hasExternalFormalLinkage())
7783       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7784   }
7785 
7786   if (D.isRedeclaration() && !Previous.empty()) {
7787     NamedDecl *Prev = Previous.getRepresentativeDecl();
7788     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7789                                    D.isFunctionDefinition());
7790   }
7791 
7792   if (NewTemplate) {
7793     if (NewVD->isInvalidDecl())
7794       NewTemplate->setInvalidDecl();
7795     ActOnDocumentableDecl(NewTemplate);
7796     return NewTemplate;
7797   }
7798 
7799   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7800     CompleteMemberSpecialization(NewVD, Previous);
7801 
7802   return NewVD;
7803 }
7804 
7805 /// Enum describing the %select options in diag::warn_decl_shadow.
7806 enum ShadowedDeclKind {
7807   SDK_Local,
7808   SDK_Global,
7809   SDK_StaticMember,
7810   SDK_Field,
7811   SDK_Typedef,
7812   SDK_Using,
7813   SDK_StructuredBinding
7814 };
7815 
7816 /// Determine what kind of declaration we're shadowing.
7817 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7818                                                 const DeclContext *OldDC) {
7819   if (isa<TypeAliasDecl>(ShadowedDecl))
7820     return SDK_Using;
7821   else if (isa<TypedefDecl>(ShadowedDecl))
7822     return SDK_Typedef;
7823   else if (isa<BindingDecl>(ShadowedDecl))
7824     return SDK_StructuredBinding;
7825   else if (isa<RecordDecl>(OldDC))
7826     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7827 
7828   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7829 }
7830 
7831 /// Return the location of the capture if the given lambda captures the given
7832 /// variable \p VD, or an invalid source location otherwise.
7833 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7834                                          const VarDecl *VD) {
7835   for (const Capture &Capture : LSI->Captures) {
7836     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7837       return Capture.getLocation();
7838   }
7839   return SourceLocation();
7840 }
7841 
7842 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7843                                      const LookupResult &R) {
7844   // Only diagnose if we're shadowing an unambiguous field or variable.
7845   if (R.getResultKind() != LookupResult::Found)
7846     return false;
7847 
7848   // Return false if warning is ignored.
7849   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7850 }
7851 
7852 /// Return the declaration shadowed by the given variable \p D, or null
7853 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7854 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7855                                         const LookupResult &R) {
7856   if (!shouldWarnIfShadowedDecl(Diags, R))
7857     return nullptr;
7858 
7859   // Don't diagnose declarations at file scope.
7860   if (D->hasGlobalStorage())
7861     return nullptr;
7862 
7863   NamedDecl *ShadowedDecl = R.getFoundDecl();
7864   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7865                                                             : nullptr;
7866 }
7867 
7868 /// Return the declaration shadowed by the given typedef \p D, or null
7869 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7870 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7871                                         const LookupResult &R) {
7872   // Don't warn if typedef declaration is part of a class
7873   if (D->getDeclContext()->isRecord())
7874     return nullptr;
7875 
7876   if (!shouldWarnIfShadowedDecl(Diags, R))
7877     return nullptr;
7878 
7879   NamedDecl *ShadowedDecl = R.getFoundDecl();
7880   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7881 }
7882 
7883 /// Return the declaration shadowed by the given variable \p D, or null
7884 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7885 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7886                                         const LookupResult &R) {
7887   if (!shouldWarnIfShadowedDecl(Diags, R))
7888     return nullptr;
7889 
7890   NamedDecl *ShadowedDecl = R.getFoundDecl();
7891   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7892                                                             : nullptr;
7893 }
7894 
7895 /// Diagnose variable or built-in function shadowing.  Implements
7896 /// -Wshadow.
7897 ///
7898 /// This method is called whenever a VarDecl is added to a "useful"
7899 /// scope.
7900 ///
7901 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7902 /// \param R the lookup of the name
7903 ///
7904 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7905                        const LookupResult &R) {
7906   DeclContext *NewDC = D->getDeclContext();
7907 
7908   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7909     // Fields are not shadowed by variables in C++ static methods.
7910     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7911       if (MD->isStatic())
7912         return;
7913 
7914     // Fields shadowed by constructor parameters are a special case. Usually
7915     // the constructor initializes the field with the parameter.
7916     if (isa<CXXConstructorDecl>(NewDC))
7917       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7918         // Remember that this was shadowed so we can either warn about its
7919         // modification or its existence depending on warning settings.
7920         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7921         return;
7922       }
7923   }
7924 
7925   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7926     if (shadowedVar->isExternC()) {
7927       // For shadowing external vars, make sure that we point to the global
7928       // declaration, not a locally scoped extern declaration.
7929       for (auto I : shadowedVar->redecls())
7930         if (I->isFileVarDecl()) {
7931           ShadowedDecl = I;
7932           break;
7933         }
7934     }
7935 
7936   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7937 
7938   unsigned WarningDiag = diag::warn_decl_shadow;
7939   SourceLocation CaptureLoc;
7940   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7941       isa<CXXMethodDecl>(NewDC)) {
7942     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7943       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7944         if (RD->getLambdaCaptureDefault() == LCD_None) {
7945           // Try to avoid warnings for lambdas with an explicit capture list.
7946           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7947           // Warn only when the lambda captures the shadowed decl explicitly.
7948           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7949           if (CaptureLoc.isInvalid())
7950             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7951         } else {
7952           // Remember that this was shadowed so we can avoid the warning if the
7953           // shadowed decl isn't captured and the warning settings allow it.
7954           cast<LambdaScopeInfo>(getCurFunction())
7955               ->ShadowingDecls.push_back(
7956                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7957           return;
7958         }
7959       }
7960 
7961       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7962         // A variable can't shadow a local variable in an enclosing scope, if
7963         // they are separated by a non-capturing declaration context.
7964         for (DeclContext *ParentDC = NewDC;
7965              ParentDC && !ParentDC->Equals(OldDC);
7966              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7967           // Only block literals, captured statements, and lambda expressions
7968           // can capture; other scopes don't.
7969           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7970               !isLambdaCallOperator(ParentDC)) {
7971             return;
7972           }
7973         }
7974       }
7975     }
7976   }
7977 
7978   // Only warn about certain kinds of shadowing for class members.
7979   if (NewDC && NewDC->isRecord()) {
7980     // In particular, don't warn about shadowing non-class members.
7981     if (!OldDC->isRecord())
7982       return;
7983 
7984     // TODO: should we warn about static data members shadowing
7985     // static data members from base classes?
7986 
7987     // TODO: don't diagnose for inaccessible shadowed members.
7988     // This is hard to do perfectly because we might friend the
7989     // shadowing context, but that's just a false negative.
7990   }
7991 
7992 
7993   DeclarationName Name = R.getLookupName();
7994 
7995   // Emit warning and note.
7996   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7997   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7998   if (!CaptureLoc.isInvalid())
7999     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8000         << Name << /*explicitly*/ 1;
8001   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8002 }
8003 
8004 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8005 /// when these variables are captured by the lambda.
8006 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8007   for (const auto &Shadow : LSI->ShadowingDecls) {
8008     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8009     // Try to avoid the warning when the shadowed decl isn't captured.
8010     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8011     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8012     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8013                                        ? diag::warn_decl_shadow_uncaptured_local
8014                                        : diag::warn_decl_shadow)
8015         << Shadow.VD->getDeclName()
8016         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8017     if (!CaptureLoc.isInvalid())
8018       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8019           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8020     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8021   }
8022 }
8023 
8024 /// Check -Wshadow without the advantage of a previous lookup.
8025 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8026   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8027     return;
8028 
8029   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8030                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8031   LookupName(R, S);
8032   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8033     CheckShadow(D, ShadowedDecl, R);
8034 }
8035 
8036 /// Check if 'E', which is an expression that is about to be modified, refers
8037 /// to a constructor parameter that shadows a field.
8038 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8039   // Quickly ignore expressions that can't be shadowing ctor parameters.
8040   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8041     return;
8042   E = E->IgnoreParenImpCasts();
8043   auto *DRE = dyn_cast<DeclRefExpr>(E);
8044   if (!DRE)
8045     return;
8046   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8047   auto I = ShadowingDecls.find(D);
8048   if (I == ShadowingDecls.end())
8049     return;
8050   const NamedDecl *ShadowedDecl = I->second;
8051   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8052   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8053   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8054   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8055 
8056   // Avoid issuing multiple warnings about the same decl.
8057   ShadowingDecls.erase(I);
8058 }
8059 
8060 /// Check for conflict between this global or extern "C" declaration and
8061 /// previous global or extern "C" declarations. This is only used in C++.
8062 template<typename T>
8063 static bool checkGlobalOrExternCConflict(
8064     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8065   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8066   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8067 
8068   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8069     // The common case: this global doesn't conflict with any extern "C"
8070     // declaration.
8071     return false;
8072   }
8073 
8074   if (Prev) {
8075     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8076       // Both the old and new declarations have C language linkage. This is a
8077       // redeclaration.
8078       Previous.clear();
8079       Previous.addDecl(Prev);
8080       return true;
8081     }
8082 
8083     // This is a global, non-extern "C" declaration, and there is a previous
8084     // non-global extern "C" declaration. Diagnose if this is a variable
8085     // declaration.
8086     if (!isa<VarDecl>(ND))
8087       return false;
8088   } else {
8089     // The declaration is extern "C". Check for any declaration in the
8090     // translation unit which might conflict.
8091     if (IsGlobal) {
8092       // We have already performed the lookup into the translation unit.
8093       IsGlobal = false;
8094       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8095            I != E; ++I) {
8096         if (isa<VarDecl>(*I)) {
8097           Prev = *I;
8098           break;
8099         }
8100       }
8101     } else {
8102       DeclContext::lookup_result R =
8103           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8104       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8105            I != E; ++I) {
8106         if (isa<VarDecl>(*I)) {
8107           Prev = *I;
8108           break;
8109         }
8110         // FIXME: If we have any other entity with this name in global scope,
8111         // the declaration is ill-formed, but that is a defect: it breaks the
8112         // 'stat' hack, for instance. Only variables can have mangled name
8113         // clashes with extern "C" declarations, so only they deserve a
8114         // diagnostic.
8115       }
8116     }
8117 
8118     if (!Prev)
8119       return false;
8120   }
8121 
8122   // Use the first declaration's location to ensure we point at something which
8123   // is lexically inside an extern "C" linkage-spec.
8124   assert(Prev && "should have found a previous declaration to diagnose");
8125   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8126     Prev = FD->getFirstDecl();
8127   else
8128     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8129 
8130   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8131     << IsGlobal << ND;
8132   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8133     << IsGlobal;
8134   return false;
8135 }
8136 
8137 /// Apply special rules for handling extern "C" declarations. Returns \c true
8138 /// if we have found that this is a redeclaration of some prior entity.
8139 ///
8140 /// Per C++ [dcl.link]p6:
8141 ///   Two declarations [for a function or variable] with C language linkage
8142 ///   with the same name that appear in different scopes refer to the same
8143 ///   [entity]. An entity with C language linkage shall not be declared with
8144 ///   the same name as an entity in global scope.
8145 template<typename T>
8146 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8147                                                   LookupResult &Previous) {
8148   if (!S.getLangOpts().CPlusPlus) {
8149     // In C, when declaring a global variable, look for a corresponding 'extern'
8150     // variable declared in function scope. We don't need this in C++, because
8151     // we find local extern decls in the surrounding file-scope DeclContext.
8152     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8153       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8154         Previous.clear();
8155         Previous.addDecl(Prev);
8156         return true;
8157       }
8158     }
8159     return false;
8160   }
8161 
8162   // A declaration in the translation unit can conflict with an extern "C"
8163   // declaration.
8164   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8165     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8166 
8167   // An extern "C" declaration can conflict with a declaration in the
8168   // translation unit or can be a redeclaration of an extern "C" declaration
8169   // in another scope.
8170   if (isIncompleteDeclExternC(S,ND))
8171     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8172 
8173   // Neither global nor extern "C": nothing to do.
8174   return false;
8175 }
8176 
8177 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8178   // If the decl is already known invalid, don't check it.
8179   if (NewVD->isInvalidDecl())
8180     return;
8181 
8182   QualType T = NewVD->getType();
8183 
8184   // Defer checking an 'auto' type until its initializer is attached.
8185   if (T->isUndeducedType())
8186     return;
8187 
8188   if (NewVD->hasAttrs())
8189     CheckAlignasUnderalignment(NewVD);
8190 
8191   if (T->isObjCObjectType()) {
8192     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8193       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8194     T = Context.getObjCObjectPointerType(T);
8195     NewVD->setType(T);
8196   }
8197 
8198   // Emit an error if an address space was applied to decl with local storage.
8199   // This includes arrays of objects with address space qualifiers, but not
8200   // automatic variables that point to other address spaces.
8201   // ISO/IEC TR 18037 S5.1.2
8202   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8203       T.getAddressSpace() != LangAS::Default) {
8204     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8205     NewVD->setInvalidDecl();
8206     return;
8207   }
8208 
8209   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8210   // scope.
8211   if (getLangOpts().OpenCLVersion == 120 &&
8212       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8213                                             getLangOpts()) &&
8214       NewVD->isStaticLocal()) {
8215     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8216     NewVD->setInvalidDecl();
8217     return;
8218   }
8219 
8220   if (getLangOpts().OpenCL) {
8221     if (!diagnoseOpenCLTypes(*this, NewVD))
8222       return;
8223 
8224     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8225     if (NewVD->hasAttr<BlocksAttr>()) {
8226       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8227       return;
8228     }
8229 
8230     if (T->isBlockPointerType()) {
8231       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8232       // can't use 'extern' storage class.
8233       if (!T.isConstQualified()) {
8234         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8235             << 0 /*const*/;
8236         NewVD->setInvalidDecl();
8237         return;
8238       }
8239       if (NewVD->hasExternalStorage()) {
8240         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8241         NewVD->setInvalidDecl();
8242         return;
8243       }
8244     }
8245 
8246     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8247     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8248         NewVD->hasExternalStorage()) {
8249       if (!T->isSamplerT() && !T->isDependentType() &&
8250           !(T.getAddressSpace() == LangAS::opencl_constant ||
8251             (T.getAddressSpace() == LangAS::opencl_global &&
8252              getOpenCLOptions().areProgramScopeVariablesSupported(
8253                  getLangOpts())))) {
8254         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8255         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8256           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8257               << Scope << "global or constant";
8258         else
8259           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8260               << Scope << "constant";
8261         NewVD->setInvalidDecl();
8262         return;
8263       }
8264     } else {
8265       if (T.getAddressSpace() == LangAS::opencl_global) {
8266         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8267             << 1 /*is any function*/ << "global";
8268         NewVD->setInvalidDecl();
8269         return;
8270       }
8271       if (T.getAddressSpace() == LangAS::opencl_constant ||
8272           T.getAddressSpace() == LangAS::opencl_local) {
8273         FunctionDecl *FD = getCurFunctionDecl();
8274         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8275         // in functions.
8276         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8277           if (T.getAddressSpace() == LangAS::opencl_constant)
8278             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8279                 << 0 /*non-kernel only*/ << "constant";
8280           else
8281             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8282                 << 0 /*non-kernel only*/ << "local";
8283           NewVD->setInvalidDecl();
8284           return;
8285         }
8286         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8287         // in the outermost scope of a kernel function.
8288         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8289           if (!getCurScope()->isFunctionScope()) {
8290             if (T.getAddressSpace() == LangAS::opencl_constant)
8291               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8292                   << "constant";
8293             else
8294               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8295                   << "local";
8296             NewVD->setInvalidDecl();
8297             return;
8298           }
8299         }
8300       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8301                  // If we are parsing a template we didn't deduce an addr
8302                  // space yet.
8303                  T.getAddressSpace() != LangAS::Default) {
8304         // Do not allow other address spaces on automatic variable.
8305         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8306         NewVD->setInvalidDecl();
8307         return;
8308       }
8309     }
8310   }
8311 
8312   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8313       && !NewVD->hasAttr<BlocksAttr>()) {
8314     if (getLangOpts().getGC() != LangOptions::NonGC)
8315       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8316     else {
8317       assert(!getLangOpts().ObjCAutoRefCount);
8318       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8319     }
8320   }
8321 
8322   bool isVM = T->isVariablyModifiedType();
8323   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8324       NewVD->hasAttr<BlocksAttr>())
8325     setFunctionHasBranchProtectedScope();
8326 
8327   if ((isVM && NewVD->hasLinkage()) ||
8328       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8329     bool SizeIsNegative;
8330     llvm::APSInt Oversized;
8331     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8332         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8333     QualType FixedT;
8334     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8335       FixedT = FixedTInfo->getType();
8336     else if (FixedTInfo) {
8337       // Type and type-as-written are canonically different. We need to fix up
8338       // both types separately.
8339       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8340                                                    Oversized);
8341     }
8342     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8343       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8344       // FIXME: This won't give the correct result for
8345       // int a[10][n];
8346       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8347 
8348       if (NewVD->isFileVarDecl())
8349         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8350         << SizeRange;
8351       else if (NewVD->isStaticLocal())
8352         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8353         << SizeRange;
8354       else
8355         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8356         << SizeRange;
8357       NewVD->setInvalidDecl();
8358       return;
8359     }
8360 
8361     if (!FixedTInfo) {
8362       if (NewVD->isFileVarDecl())
8363         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8364       else
8365         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8366       NewVD->setInvalidDecl();
8367       return;
8368     }
8369 
8370     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8371     NewVD->setType(FixedT);
8372     NewVD->setTypeSourceInfo(FixedTInfo);
8373   }
8374 
8375   if (T->isVoidType()) {
8376     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8377     //                    of objects and functions.
8378     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8379       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8380         << T;
8381       NewVD->setInvalidDecl();
8382       return;
8383     }
8384   }
8385 
8386   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8387     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8388     NewVD->setInvalidDecl();
8389     return;
8390   }
8391 
8392   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8393     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8394     NewVD->setInvalidDecl();
8395     return;
8396   }
8397 
8398   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8399     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8400     NewVD->setInvalidDecl();
8401     return;
8402   }
8403 
8404   if (NewVD->isConstexpr() && !T->isDependentType() &&
8405       RequireLiteralType(NewVD->getLocation(), T,
8406                          diag::err_constexpr_var_non_literal)) {
8407     NewVD->setInvalidDecl();
8408     return;
8409   }
8410 
8411   // PPC MMA non-pointer types are not allowed as non-local variable types.
8412   if (Context.getTargetInfo().getTriple().isPPC64() &&
8413       !NewVD->isLocalVarDecl() &&
8414       CheckPPCMMAType(T, NewVD->getLocation())) {
8415     NewVD->setInvalidDecl();
8416     return;
8417   }
8418 }
8419 
8420 /// Perform semantic checking on a newly-created variable
8421 /// declaration.
8422 ///
8423 /// This routine performs all of the type-checking required for a
8424 /// variable declaration once it has been built. It is used both to
8425 /// check variables after they have been parsed and their declarators
8426 /// have been translated into a declaration, and to check variables
8427 /// that have been instantiated from a template.
8428 ///
8429 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8430 ///
8431 /// Returns true if the variable declaration is a redeclaration.
8432 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8433   CheckVariableDeclarationType(NewVD);
8434 
8435   // If the decl is already known invalid, don't check it.
8436   if (NewVD->isInvalidDecl())
8437     return false;
8438 
8439   // If we did not find anything by this name, look for a non-visible
8440   // extern "C" declaration with the same name.
8441   if (Previous.empty() &&
8442       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8443     Previous.setShadowed();
8444 
8445   if (!Previous.empty()) {
8446     MergeVarDecl(NewVD, Previous);
8447     return true;
8448   }
8449   return false;
8450 }
8451 
8452 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8453 /// and if so, check that it's a valid override and remember it.
8454 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8455   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8456 
8457   // Look for methods in base classes that this method might override.
8458   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8459                      /*DetectVirtual=*/false);
8460   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8461     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8462     DeclarationName Name = MD->getDeclName();
8463 
8464     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8465       // We really want to find the base class destructor here.
8466       QualType T = Context.getTypeDeclType(BaseRecord);
8467       CanQualType CT = Context.getCanonicalType(T);
8468       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8469     }
8470 
8471     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8472       CXXMethodDecl *BaseMD =
8473           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8474       if (!BaseMD || !BaseMD->isVirtual() ||
8475           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8476                      /*ConsiderCudaAttrs=*/true,
8477                      // C++2a [class.virtual]p2 does not consider requires
8478                      // clauses when overriding.
8479                      /*ConsiderRequiresClauses=*/false))
8480         continue;
8481 
8482       if (Overridden.insert(BaseMD).second) {
8483         MD->addOverriddenMethod(BaseMD);
8484         CheckOverridingFunctionReturnType(MD, BaseMD);
8485         CheckOverridingFunctionAttributes(MD, BaseMD);
8486         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8487         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8488       }
8489 
8490       // A method can only override one function from each base class. We
8491       // don't track indirectly overridden methods from bases of bases.
8492       return true;
8493     }
8494 
8495     return false;
8496   };
8497 
8498   DC->lookupInBases(VisitBase, Paths);
8499   return !Overridden.empty();
8500 }
8501 
8502 namespace {
8503   // Struct for holding all of the extra arguments needed by
8504   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8505   struct ActOnFDArgs {
8506     Scope *S;
8507     Declarator &D;
8508     MultiTemplateParamsArg TemplateParamLists;
8509     bool AddToScope;
8510   };
8511 } // end anonymous namespace
8512 
8513 namespace {
8514 
8515 // Callback to only accept typo corrections that have a non-zero edit distance.
8516 // Also only accept corrections that have the same parent decl.
8517 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8518  public:
8519   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8520                             CXXRecordDecl *Parent)
8521       : Context(Context), OriginalFD(TypoFD),
8522         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8523 
8524   bool ValidateCandidate(const TypoCorrection &candidate) override {
8525     if (candidate.getEditDistance() == 0)
8526       return false;
8527 
8528     SmallVector<unsigned, 1> MismatchedParams;
8529     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8530                                           CDeclEnd = candidate.end();
8531          CDecl != CDeclEnd; ++CDecl) {
8532       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8533 
8534       if (FD && !FD->hasBody() &&
8535           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8536         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8537           CXXRecordDecl *Parent = MD->getParent();
8538           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8539             return true;
8540         } else if (!ExpectedParent) {
8541           return true;
8542         }
8543       }
8544     }
8545 
8546     return false;
8547   }
8548 
8549   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8550     return std::make_unique<DifferentNameValidatorCCC>(*this);
8551   }
8552 
8553  private:
8554   ASTContext &Context;
8555   FunctionDecl *OriginalFD;
8556   CXXRecordDecl *ExpectedParent;
8557 };
8558 
8559 } // end anonymous namespace
8560 
8561 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8562   TypoCorrectedFunctionDefinitions.insert(F);
8563 }
8564 
8565 /// Generate diagnostics for an invalid function redeclaration.
8566 ///
8567 /// This routine handles generating the diagnostic messages for an invalid
8568 /// function redeclaration, including finding possible similar declarations
8569 /// or performing typo correction if there are no previous declarations with
8570 /// the same name.
8571 ///
8572 /// Returns a NamedDecl iff typo correction was performed and substituting in
8573 /// the new declaration name does not cause new errors.
8574 static NamedDecl *DiagnoseInvalidRedeclaration(
8575     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8576     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8577   DeclarationName Name = NewFD->getDeclName();
8578   DeclContext *NewDC = NewFD->getDeclContext();
8579   SmallVector<unsigned, 1> MismatchedParams;
8580   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8581   TypoCorrection Correction;
8582   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8583   unsigned DiagMsg =
8584     IsLocalFriend ? diag::err_no_matching_local_friend :
8585     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8586     diag::err_member_decl_does_not_match;
8587   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8588                     IsLocalFriend ? Sema::LookupLocalFriendName
8589                                   : Sema::LookupOrdinaryName,
8590                     Sema::ForVisibleRedeclaration);
8591 
8592   NewFD->setInvalidDecl();
8593   if (IsLocalFriend)
8594     SemaRef.LookupName(Prev, S);
8595   else
8596     SemaRef.LookupQualifiedName(Prev, NewDC);
8597   assert(!Prev.isAmbiguous() &&
8598          "Cannot have an ambiguity in previous-declaration lookup");
8599   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8600   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8601                                 MD ? MD->getParent() : nullptr);
8602   if (!Prev.empty()) {
8603     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8604          Func != FuncEnd; ++Func) {
8605       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8606       if (FD &&
8607           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8608         // Add 1 to the index so that 0 can mean the mismatch didn't
8609         // involve a parameter
8610         unsigned ParamNum =
8611             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8612         NearMatches.push_back(std::make_pair(FD, ParamNum));
8613       }
8614     }
8615   // If the qualified name lookup yielded nothing, try typo correction
8616   } else if ((Correction = SemaRef.CorrectTypo(
8617                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8618                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8619                   IsLocalFriend ? nullptr : NewDC))) {
8620     // Set up everything for the call to ActOnFunctionDeclarator
8621     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8622                               ExtraArgs.D.getIdentifierLoc());
8623     Previous.clear();
8624     Previous.setLookupName(Correction.getCorrection());
8625     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8626                                     CDeclEnd = Correction.end();
8627          CDecl != CDeclEnd; ++CDecl) {
8628       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8629       if (FD && !FD->hasBody() &&
8630           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8631         Previous.addDecl(FD);
8632       }
8633     }
8634     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8635 
8636     NamedDecl *Result;
8637     // Retry building the function declaration with the new previous
8638     // declarations, and with errors suppressed.
8639     {
8640       // Trap errors.
8641       Sema::SFINAETrap Trap(SemaRef);
8642 
8643       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8644       // pieces need to verify the typo-corrected C++ declaration and hopefully
8645       // eliminate the need for the parameter pack ExtraArgs.
8646       Result = SemaRef.ActOnFunctionDeclarator(
8647           ExtraArgs.S, ExtraArgs.D,
8648           Correction.getCorrectionDecl()->getDeclContext(),
8649           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8650           ExtraArgs.AddToScope);
8651 
8652       if (Trap.hasErrorOccurred())
8653         Result = nullptr;
8654     }
8655 
8656     if (Result) {
8657       // Determine which correction we picked.
8658       Decl *Canonical = Result->getCanonicalDecl();
8659       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8660            I != E; ++I)
8661         if ((*I)->getCanonicalDecl() == Canonical)
8662           Correction.setCorrectionDecl(*I);
8663 
8664       // Let Sema know about the correction.
8665       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8666       SemaRef.diagnoseTypo(
8667           Correction,
8668           SemaRef.PDiag(IsLocalFriend
8669                           ? diag::err_no_matching_local_friend_suggest
8670                           : diag::err_member_decl_does_not_match_suggest)
8671             << Name << NewDC << IsDefinition);
8672       return Result;
8673     }
8674 
8675     // Pretend the typo correction never occurred
8676     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8677                               ExtraArgs.D.getIdentifierLoc());
8678     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8679     Previous.clear();
8680     Previous.setLookupName(Name);
8681   }
8682 
8683   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8684       << Name << NewDC << IsDefinition << NewFD->getLocation();
8685 
8686   bool NewFDisConst = false;
8687   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8688     NewFDisConst = NewMD->isConst();
8689 
8690   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8691        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8692        NearMatch != NearMatchEnd; ++NearMatch) {
8693     FunctionDecl *FD = NearMatch->first;
8694     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8695     bool FDisConst = MD && MD->isConst();
8696     bool IsMember = MD || !IsLocalFriend;
8697 
8698     // FIXME: These notes are poorly worded for the local friend case.
8699     if (unsigned Idx = NearMatch->second) {
8700       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8701       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8702       if (Loc.isInvalid()) Loc = FD->getLocation();
8703       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8704                                  : diag::note_local_decl_close_param_match)
8705         << Idx << FDParam->getType()
8706         << NewFD->getParamDecl(Idx - 1)->getType();
8707     } else if (FDisConst != NewFDisConst) {
8708       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8709           << NewFDisConst << FD->getSourceRange().getEnd()
8710           << (NewFDisConst
8711                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8712                                                  .getConstQualifierLoc())
8713                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8714                                                    .getRParenLoc()
8715                                                    .getLocWithOffset(1),
8716                                                " const"));
8717     } else
8718       SemaRef.Diag(FD->getLocation(),
8719                    IsMember ? diag::note_member_def_close_match
8720                             : diag::note_local_decl_close_match);
8721   }
8722   return nullptr;
8723 }
8724 
8725 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8726   switch (D.getDeclSpec().getStorageClassSpec()) {
8727   default: llvm_unreachable("Unknown storage class!");
8728   case DeclSpec::SCS_auto:
8729   case DeclSpec::SCS_register:
8730   case DeclSpec::SCS_mutable:
8731     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8732                  diag::err_typecheck_sclass_func);
8733     D.getMutableDeclSpec().ClearStorageClassSpecs();
8734     D.setInvalidType();
8735     break;
8736   case DeclSpec::SCS_unspecified: break;
8737   case DeclSpec::SCS_extern:
8738     if (D.getDeclSpec().isExternInLinkageSpec())
8739       return SC_None;
8740     return SC_Extern;
8741   case DeclSpec::SCS_static: {
8742     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8743       // C99 6.7.1p5:
8744       //   The declaration of an identifier for a function that has
8745       //   block scope shall have no explicit storage-class specifier
8746       //   other than extern
8747       // See also (C++ [dcl.stc]p4).
8748       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8749                    diag::err_static_block_func);
8750       break;
8751     } else
8752       return SC_Static;
8753   }
8754   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8755   }
8756 
8757   // No explicit storage class has already been returned
8758   return SC_None;
8759 }
8760 
8761 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8762                                            DeclContext *DC, QualType &R,
8763                                            TypeSourceInfo *TInfo,
8764                                            StorageClass SC,
8765                                            bool &IsVirtualOkay) {
8766   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8767   DeclarationName Name = NameInfo.getName();
8768 
8769   FunctionDecl *NewFD = nullptr;
8770   bool isInline = D.getDeclSpec().isInlineSpecified();
8771 
8772   if (!SemaRef.getLangOpts().CPlusPlus) {
8773     // Determine whether the function was written with a
8774     // prototype. This true when:
8775     //   - there is a prototype in the declarator, or
8776     //   - the type R of the function is some kind of typedef or other non-
8777     //     attributed reference to a type name (which eventually refers to a
8778     //     function type).
8779     bool HasPrototype =
8780       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8781       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8782 
8783     NewFD = FunctionDecl::Create(
8784         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8785         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8786         ConstexprSpecKind::Unspecified,
8787         /*TrailingRequiresClause=*/nullptr);
8788     if (D.isInvalidType())
8789       NewFD->setInvalidDecl();
8790 
8791     return NewFD;
8792   }
8793 
8794   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8795 
8796   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8797   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8798     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8799                  diag::err_constexpr_wrong_decl_kind)
8800         << static_cast<int>(ConstexprKind);
8801     ConstexprKind = ConstexprSpecKind::Unspecified;
8802     D.getMutableDeclSpec().ClearConstexprSpec();
8803   }
8804   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8805 
8806   // Check that the return type is not an abstract class type.
8807   // For record types, this is done by the AbstractClassUsageDiagnoser once
8808   // the class has been completely parsed.
8809   if (!DC->isRecord() &&
8810       SemaRef.RequireNonAbstractType(
8811           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8812           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8813     D.setInvalidType();
8814 
8815   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8816     // This is a C++ constructor declaration.
8817     assert(DC->isRecord() &&
8818            "Constructors can only be declared in a member context");
8819 
8820     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8821     return CXXConstructorDecl::Create(
8822         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8823         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8824         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8825         InheritedConstructor(), TrailingRequiresClause);
8826 
8827   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8828     // This is a C++ destructor declaration.
8829     if (DC->isRecord()) {
8830       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8831       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8832       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8833           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8834           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8835           /*isImplicitlyDeclared=*/false, ConstexprKind,
8836           TrailingRequiresClause);
8837 
8838       // If the destructor needs an implicit exception specification, set it
8839       // now. FIXME: It'd be nice to be able to create the right type to start
8840       // with, but the type needs to reference the destructor declaration.
8841       if (SemaRef.getLangOpts().CPlusPlus11)
8842         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8843 
8844       IsVirtualOkay = true;
8845       return NewDD;
8846 
8847     } else {
8848       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8849       D.setInvalidType();
8850 
8851       // Create a FunctionDecl to satisfy the function definition parsing
8852       // code path.
8853       return FunctionDecl::Create(
8854           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8855           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8856           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8857     }
8858 
8859   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8860     if (!DC->isRecord()) {
8861       SemaRef.Diag(D.getIdentifierLoc(),
8862            diag::err_conv_function_not_member);
8863       return nullptr;
8864     }
8865 
8866     SemaRef.CheckConversionDeclarator(D, R, SC);
8867     if (D.isInvalidType())
8868       return nullptr;
8869 
8870     IsVirtualOkay = true;
8871     return CXXConversionDecl::Create(
8872         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8873         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8874         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8875         TrailingRequiresClause);
8876 
8877   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8878     if (TrailingRequiresClause)
8879       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8880                    diag::err_trailing_requires_clause_on_deduction_guide)
8881           << TrailingRequiresClause->getSourceRange();
8882     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8883 
8884     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8885                                          ExplicitSpecifier, NameInfo, R, TInfo,
8886                                          D.getEndLoc());
8887   } else if (DC->isRecord()) {
8888     // If the name of the function is the same as the name of the record,
8889     // then this must be an invalid constructor that has a return type.
8890     // (The parser checks for a return type and makes the declarator a
8891     // constructor if it has no return type).
8892     if (Name.getAsIdentifierInfo() &&
8893         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8894       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8895         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8896         << SourceRange(D.getIdentifierLoc());
8897       return nullptr;
8898     }
8899 
8900     // This is a C++ method declaration.
8901     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8902         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8903         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8904         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8905     IsVirtualOkay = !Ret->isStatic();
8906     return Ret;
8907   } else {
8908     bool isFriend =
8909         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8910     if (!isFriend && SemaRef.CurContext->isRecord())
8911       return nullptr;
8912 
8913     // Determine whether the function was written with a
8914     // prototype. This true when:
8915     //   - we're in C++ (where every function has a prototype),
8916     return FunctionDecl::Create(
8917         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8918         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8919         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8920   }
8921 }
8922 
8923 enum OpenCLParamType {
8924   ValidKernelParam,
8925   PtrPtrKernelParam,
8926   PtrKernelParam,
8927   InvalidAddrSpacePtrKernelParam,
8928   InvalidKernelParam,
8929   RecordKernelParam
8930 };
8931 
8932 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8933   // Size dependent types are just typedefs to normal integer types
8934   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8935   // integers other than by their names.
8936   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8937 
8938   // Remove typedefs one by one until we reach a typedef
8939   // for a size dependent type.
8940   QualType DesugaredTy = Ty;
8941   do {
8942     ArrayRef<StringRef> Names(SizeTypeNames);
8943     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8944     if (Names.end() != Match)
8945       return true;
8946 
8947     Ty = DesugaredTy;
8948     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8949   } while (DesugaredTy != Ty);
8950 
8951   return false;
8952 }
8953 
8954 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8955   if (PT->isDependentType())
8956     return InvalidKernelParam;
8957 
8958   if (PT->isPointerType() || PT->isReferenceType()) {
8959     QualType PointeeType = PT->getPointeeType();
8960     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8961         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8962         PointeeType.getAddressSpace() == LangAS::Default)
8963       return InvalidAddrSpacePtrKernelParam;
8964 
8965     if (PointeeType->isPointerType()) {
8966       // This is a pointer to pointer parameter.
8967       // Recursively check inner type.
8968       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8969       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8970           ParamKind == InvalidKernelParam)
8971         return ParamKind;
8972 
8973       return PtrPtrKernelParam;
8974     }
8975 
8976     // C++ for OpenCL v1.0 s2.4:
8977     // Moreover the types used in parameters of the kernel functions must be:
8978     // Standard layout types for pointer parameters. The same applies to
8979     // reference if an implementation supports them in kernel parameters.
8980     if (S.getLangOpts().OpenCLCPlusPlus &&
8981         !S.getOpenCLOptions().isAvailableOption(
8982             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8983         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8984         !PointeeType->isStandardLayoutType())
8985       return InvalidKernelParam;
8986 
8987     return PtrKernelParam;
8988   }
8989 
8990   // OpenCL v1.2 s6.9.k:
8991   // Arguments to kernel functions in a program cannot be declared with the
8992   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8993   // uintptr_t or a struct and/or union that contain fields declared to be one
8994   // of these built-in scalar types.
8995   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8996     return InvalidKernelParam;
8997 
8998   if (PT->isImageType())
8999     return PtrKernelParam;
9000 
9001   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9002     return InvalidKernelParam;
9003 
9004   // OpenCL extension spec v1.2 s9.5:
9005   // This extension adds support for half scalar and vector types as built-in
9006   // types that can be used for arithmetic operations, conversions etc.
9007   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9008       PT->isHalfType())
9009     return InvalidKernelParam;
9010 
9011   // Look into an array argument to check if it has a forbidden type.
9012   if (PT->isArrayType()) {
9013     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9014     // Call ourself to check an underlying type of an array. Since the
9015     // getPointeeOrArrayElementType returns an innermost type which is not an
9016     // array, this recursive call only happens once.
9017     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9018   }
9019 
9020   // C++ for OpenCL v1.0 s2.4:
9021   // Moreover the types used in parameters of the kernel functions must be:
9022   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9023   // types) for parameters passed by value;
9024   if (S.getLangOpts().OpenCLCPlusPlus &&
9025       !S.getOpenCLOptions().isAvailableOption(
9026           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9027       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9028     return InvalidKernelParam;
9029 
9030   if (PT->isRecordType())
9031     return RecordKernelParam;
9032 
9033   return ValidKernelParam;
9034 }
9035 
9036 static void checkIsValidOpenCLKernelParameter(
9037   Sema &S,
9038   Declarator &D,
9039   ParmVarDecl *Param,
9040   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9041   QualType PT = Param->getType();
9042 
9043   // Cache the valid types we encounter to avoid rechecking structs that are
9044   // used again
9045   if (ValidTypes.count(PT.getTypePtr()))
9046     return;
9047 
9048   switch (getOpenCLKernelParameterType(S, PT)) {
9049   case PtrPtrKernelParam:
9050     // OpenCL v3.0 s6.11.a:
9051     // A kernel function argument cannot be declared as a pointer to a pointer
9052     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9053     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9054       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9055       D.setInvalidType();
9056       return;
9057     }
9058 
9059     ValidTypes.insert(PT.getTypePtr());
9060     return;
9061 
9062   case InvalidAddrSpacePtrKernelParam:
9063     // OpenCL v1.0 s6.5:
9064     // __kernel function arguments declared to be a pointer of a type can point
9065     // to one of the following address spaces only : __global, __local or
9066     // __constant.
9067     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9068     D.setInvalidType();
9069     return;
9070 
9071     // OpenCL v1.2 s6.9.k:
9072     // Arguments to kernel functions in a program cannot be declared with the
9073     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9074     // uintptr_t or a struct and/or union that contain fields declared to be
9075     // one of these built-in scalar types.
9076 
9077   case InvalidKernelParam:
9078     // OpenCL v1.2 s6.8 n:
9079     // A kernel function argument cannot be declared
9080     // of event_t type.
9081     // Do not diagnose half type since it is diagnosed as invalid argument
9082     // type for any function elsewhere.
9083     if (!PT->isHalfType()) {
9084       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9085 
9086       // Explain what typedefs are involved.
9087       const TypedefType *Typedef = nullptr;
9088       while ((Typedef = PT->getAs<TypedefType>())) {
9089         SourceLocation Loc = Typedef->getDecl()->getLocation();
9090         // SourceLocation may be invalid for a built-in type.
9091         if (Loc.isValid())
9092           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9093         PT = Typedef->desugar();
9094       }
9095     }
9096 
9097     D.setInvalidType();
9098     return;
9099 
9100   case PtrKernelParam:
9101   case ValidKernelParam:
9102     ValidTypes.insert(PT.getTypePtr());
9103     return;
9104 
9105   case RecordKernelParam:
9106     break;
9107   }
9108 
9109   // Track nested structs we will inspect
9110   SmallVector<const Decl *, 4> VisitStack;
9111 
9112   // Track where we are in the nested structs. Items will migrate from
9113   // VisitStack to HistoryStack as we do the DFS for bad field.
9114   SmallVector<const FieldDecl *, 4> HistoryStack;
9115   HistoryStack.push_back(nullptr);
9116 
9117   // At this point we already handled everything except of a RecordType or
9118   // an ArrayType of a RecordType.
9119   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9120   const RecordType *RecTy =
9121       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9122   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9123 
9124   VisitStack.push_back(RecTy->getDecl());
9125   assert(VisitStack.back() && "First decl null?");
9126 
9127   do {
9128     const Decl *Next = VisitStack.pop_back_val();
9129     if (!Next) {
9130       assert(!HistoryStack.empty());
9131       // Found a marker, we have gone up a level
9132       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9133         ValidTypes.insert(Hist->getType().getTypePtr());
9134 
9135       continue;
9136     }
9137 
9138     // Adds everything except the original parameter declaration (which is not a
9139     // field itself) to the history stack.
9140     const RecordDecl *RD;
9141     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9142       HistoryStack.push_back(Field);
9143 
9144       QualType FieldTy = Field->getType();
9145       // Other field types (known to be valid or invalid) are handled while we
9146       // walk around RecordDecl::fields().
9147       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9148              "Unexpected type.");
9149       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9150 
9151       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9152     } else {
9153       RD = cast<RecordDecl>(Next);
9154     }
9155 
9156     // Add a null marker so we know when we've gone back up a level
9157     VisitStack.push_back(nullptr);
9158 
9159     for (const auto *FD : RD->fields()) {
9160       QualType QT = FD->getType();
9161 
9162       if (ValidTypes.count(QT.getTypePtr()))
9163         continue;
9164 
9165       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9166       if (ParamType == ValidKernelParam)
9167         continue;
9168 
9169       if (ParamType == RecordKernelParam) {
9170         VisitStack.push_back(FD);
9171         continue;
9172       }
9173 
9174       // OpenCL v1.2 s6.9.p:
9175       // Arguments to kernel functions that are declared to be a struct or union
9176       // do not allow OpenCL objects to be passed as elements of the struct or
9177       // union.
9178       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9179           ParamType == InvalidAddrSpacePtrKernelParam) {
9180         S.Diag(Param->getLocation(),
9181                diag::err_record_with_pointers_kernel_param)
9182           << PT->isUnionType()
9183           << PT;
9184       } else {
9185         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9186       }
9187 
9188       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9189           << OrigRecDecl->getDeclName();
9190 
9191       // We have an error, now let's go back up through history and show where
9192       // the offending field came from
9193       for (ArrayRef<const FieldDecl *>::const_iterator
9194                I = HistoryStack.begin() + 1,
9195                E = HistoryStack.end();
9196            I != E; ++I) {
9197         const FieldDecl *OuterField = *I;
9198         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9199           << OuterField->getType();
9200       }
9201 
9202       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9203         << QT->isPointerType()
9204         << QT;
9205       D.setInvalidType();
9206       return;
9207     }
9208   } while (!VisitStack.empty());
9209 }
9210 
9211 /// Find the DeclContext in which a tag is implicitly declared if we see an
9212 /// elaborated type specifier in the specified context, and lookup finds
9213 /// nothing.
9214 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9215   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9216     DC = DC->getParent();
9217   return DC;
9218 }
9219 
9220 /// Find the Scope in which a tag is implicitly declared if we see an
9221 /// elaborated type specifier in the specified context, and lookup finds
9222 /// nothing.
9223 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9224   while (S->isClassScope() ||
9225          (LangOpts.CPlusPlus &&
9226           S->isFunctionPrototypeScope()) ||
9227          ((S->getFlags() & Scope::DeclScope) == 0) ||
9228          (S->getEntity() && S->getEntity()->isTransparentContext()))
9229     S = S->getParent();
9230   return S;
9231 }
9232 
9233 NamedDecl*
9234 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9235                               TypeSourceInfo *TInfo, LookupResult &Previous,
9236                               MultiTemplateParamsArg TemplateParamListsRef,
9237                               bool &AddToScope) {
9238   QualType R = TInfo->getType();
9239 
9240   assert(R->isFunctionType());
9241   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9242     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9243 
9244   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9245   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9246   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9247     if (!TemplateParamLists.empty() &&
9248         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9249       TemplateParamLists.back() = Invented;
9250     else
9251       TemplateParamLists.push_back(Invented);
9252   }
9253 
9254   // TODO: consider using NameInfo for diagnostic.
9255   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9256   DeclarationName Name = NameInfo.getName();
9257   StorageClass SC = getFunctionStorageClass(*this, D);
9258 
9259   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9260     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9261          diag::err_invalid_thread)
9262       << DeclSpec::getSpecifierName(TSCS);
9263 
9264   if (D.isFirstDeclarationOfMember())
9265     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9266                            D.getIdentifierLoc());
9267 
9268   bool isFriend = false;
9269   FunctionTemplateDecl *FunctionTemplate = nullptr;
9270   bool isMemberSpecialization = false;
9271   bool isFunctionTemplateSpecialization = false;
9272 
9273   bool isDependentClassScopeExplicitSpecialization = false;
9274   bool HasExplicitTemplateArgs = false;
9275   TemplateArgumentListInfo TemplateArgs;
9276 
9277   bool isVirtualOkay = false;
9278 
9279   DeclContext *OriginalDC = DC;
9280   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9281 
9282   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9283                                               isVirtualOkay);
9284   if (!NewFD) return nullptr;
9285 
9286   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9287     NewFD->setTopLevelDeclInObjCContainer();
9288 
9289   // Set the lexical context. If this is a function-scope declaration, or has a
9290   // C++ scope specifier, or is the object of a friend declaration, the lexical
9291   // context will be different from the semantic context.
9292   NewFD->setLexicalDeclContext(CurContext);
9293 
9294   if (IsLocalExternDecl)
9295     NewFD->setLocalExternDecl();
9296 
9297   if (getLangOpts().CPlusPlus) {
9298     bool isInline = D.getDeclSpec().isInlineSpecified();
9299     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9300     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9301     isFriend = D.getDeclSpec().isFriendSpecified();
9302     if (isFriend && !isInline && D.isFunctionDefinition()) {
9303       // C++ [class.friend]p5
9304       //   A function can be defined in a friend declaration of a
9305       //   class . . . . Such a function is implicitly inline.
9306       NewFD->setImplicitlyInline();
9307     }
9308 
9309     // If this is a method defined in an __interface, and is not a constructor
9310     // or an overloaded operator, then set the pure flag (isVirtual will already
9311     // return true).
9312     if (const CXXRecordDecl *Parent =
9313           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9314       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9315         NewFD->setPure(true);
9316 
9317       // C++ [class.union]p2
9318       //   A union can have member functions, but not virtual functions.
9319       if (isVirtual && Parent->isUnion()) {
9320         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9321         NewFD->setInvalidDecl();
9322       }
9323       if ((Parent->isClass() || Parent->isStruct()) &&
9324           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9325           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9326           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9327         if (auto *Def = Parent->getDefinition())
9328           Def->setInitMethod(true);
9329       }
9330     }
9331 
9332     SetNestedNameSpecifier(*this, NewFD, D);
9333     isMemberSpecialization = false;
9334     isFunctionTemplateSpecialization = false;
9335     if (D.isInvalidType())
9336       NewFD->setInvalidDecl();
9337 
9338     // Match up the template parameter lists with the scope specifier, then
9339     // determine whether we have a template or a template specialization.
9340     bool Invalid = false;
9341     TemplateParameterList *TemplateParams =
9342         MatchTemplateParametersToScopeSpecifier(
9343             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9344             D.getCXXScopeSpec(),
9345             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9346                 ? D.getName().TemplateId
9347                 : nullptr,
9348             TemplateParamLists, isFriend, isMemberSpecialization,
9349             Invalid);
9350     if (TemplateParams) {
9351       // Check that we can declare a template here.
9352       if (CheckTemplateDeclScope(S, TemplateParams))
9353         NewFD->setInvalidDecl();
9354 
9355       if (TemplateParams->size() > 0) {
9356         // This is a function template
9357 
9358         // A destructor cannot be a template.
9359         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9360           Diag(NewFD->getLocation(), diag::err_destructor_template);
9361           NewFD->setInvalidDecl();
9362         }
9363 
9364         // If we're adding a template to a dependent context, we may need to
9365         // rebuilding some of the types used within the template parameter list,
9366         // now that we know what the current instantiation is.
9367         if (DC->isDependentContext()) {
9368           ContextRAII SavedContext(*this, DC);
9369           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9370             Invalid = true;
9371         }
9372 
9373         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9374                                                         NewFD->getLocation(),
9375                                                         Name, TemplateParams,
9376                                                         NewFD);
9377         FunctionTemplate->setLexicalDeclContext(CurContext);
9378         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9379 
9380         // For source fidelity, store the other template param lists.
9381         if (TemplateParamLists.size() > 1) {
9382           NewFD->setTemplateParameterListsInfo(Context,
9383               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9384                   .drop_back(1));
9385         }
9386       } else {
9387         // This is a function template specialization.
9388         isFunctionTemplateSpecialization = true;
9389         // For source fidelity, store all the template param lists.
9390         if (TemplateParamLists.size() > 0)
9391           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9392 
9393         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9394         if (isFriend) {
9395           // We want to remove the "template<>", found here.
9396           SourceRange RemoveRange = TemplateParams->getSourceRange();
9397 
9398           // If we remove the template<> and the name is not a
9399           // template-id, we're actually silently creating a problem:
9400           // the friend declaration will refer to an untemplated decl,
9401           // and clearly the user wants a template specialization.  So
9402           // we need to insert '<>' after the name.
9403           SourceLocation InsertLoc;
9404           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9405             InsertLoc = D.getName().getSourceRange().getEnd();
9406             InsertLoc = getLocForEndOfToken(InsertLoc);
9407           }
9408 
9409           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9410             << Name << RemoveRange
9411             << FixItHint::CreateRemoval(RemoveRange)
9412             << FixItHint::CreateInsertion(InsertLoc, "<>");
9413           Invalid = true;
9414         }
9415       }
9416     } else {
9417       // Check that we can declare a template here.
9418       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9419           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9420         NewFD->setInvalidDecl();
9421 
9422       // All template param lists were matched against the scope specifier:
9423       // this is NOT (an explicit specialization of) a template.
9424       if (TemplateParamLists.size() > 0)
9425         // For source fidelity, store all the template param lists.
9426         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9427     }
9428 
9429     if (Invalid) {
9430       NewFD->setInvalidDecl();
9431       if (FunctionTemplate)
9432         FunctionTemplate->setInvalidDecl();
9433     }
9434 
9435     // C++ [dcl.fct.spec]p5:
9436     //   The virtual specifier shall only be used in declarations of
9437     //   nonstatic class member functions that appear within a
9438     //   member-specification of a class declaration; see 10.3.
9439     //
9440     if (isVirtual && !NewFD->isInvalidDecl()) {
9441       if (!isVirtualOkay) {
9442         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9443              diag::err_virtual_non_function);
9444       } else if (!CurContext->isRecord()) {
9445         // 'virtual' was specified outside of the class.
9446         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9447              diag::err_virtual_out_of_class)
9448           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9449       } else if (NewFD->getDescribedFunctionTemplate()) {
9450         // C++ [temp.mem]p3:
9451         //  A member function template shall not be virtual.
9452         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9453              diag::err_virtual_member_function_template)
9454           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9455       } else {
9456         // Okay: Add virtual to the method.
9457         NewFD->setVirtualAsWritten(true);
9458       }
9459 
9460       if (getLangOpts().CPlusPlus14 &&
9461           NewFD->getReturnType()->isUndeducedType())
9462         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9463     }
9464 
9465     if (getLangOpts().CPlusPlus14 &&
9466         (NewFD->isDependentContext() ||
9467          (isFriend && CurContext->isDependentContext())) &&
9468         NewFD->getReturnType()->isUndeducedType()) {
9469       // If the function template is referenced directly (for instance, as a
9470       // member of the current instantiation), pretend it has a dependent type.
9471       // This is not really justified by the standard, but is the only sane
9472       // thing to do.
9473       // FIXME: For a friend function, we have not marked the function as being
9474       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9475       const FunctionProtoType *FPT =
9476           NewFD->getType()->castAs<FunctionProtoType>();
9477       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9478       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9479                                              FPT->getExtProtoInfo()));
9480     }
9481 
9482     // C++ [dcl.fct.spec]p3:
9483     //  The inline specifier shall not appear on a block scope function
9484     //  declaration.
9485     if (isInline && !NewFD->isInvalidDecl()) {
9486       if (CurContext->isFunctionOrMethod()) {
9487         // 'inline' is not allowed on block scope function declaration.
9488         Diag(D.getDeclSpec().getInlineSpecLoc(),
9489              diag::err_inline_declaration_block_scope) << Name
9490           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9491       }
9492     }
9493 
9494     // C++ [dcl.fct.spec]p6:
9495     //  The explicit specifier shall be used only in the declaration of a
9496     //  constructor or conversion function within its class definition;
9497     //  see 12.3.1 and 12.3.2.
9498     if (hasExplicit && !NewFD->isInvalidDecl() &&
9499         !isa<CXXDeductionGuideDecl>(NewFD)) {
9500       if (!CurContext->isRecord()) {
9501         // 'explicit' was specified outside of the class.
9502         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9503              diag::err_explicit_out_of_class)
9504             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9505       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9506                  !isa<CXXConversionDecl>(NewFD)) {
9507         // 'explicit' was specified on a function that wasn't a constructor
9508         // or conversion function.
9509         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9510              diag::err_explicit_non_ctor_or_conv_function)
9511             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9512       }
9513     }
9514 
9515     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9516     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9517       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9518       // are implicitly inline.
9519       NewFD->setImplicitlyInline();
9520 
9521       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9522       // be either constructors or to return a literal type. Therefore,
9523       // destructors cannot be declared constexpr.
9524       if (isa<CXXDestructorDecl>(NewFD) &&
9525           (!getLangOpts().CPlusPlus20 ||
9526            ConstexprKind == ConstexprSpecKind::Consteval)) {
9527         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9528             << static_cast<int>(ConstexprKind);
9529         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9530                                     ? ConstexprSpecKind::Unspecified
9531                                     : ConstexprSpecKind::Constexpr);
9532       }
9533       // C++20 [dcl.constexpr]p2: An allocation function, or a
9534       // deallocation function shall not be declared with the consteval
9535       // specifier.
9536       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9537           (NewFD->getOverloadedOperator() == OO_New ||
9538            NewFD->getOverloadedOperator() == OO_Array_New ||
9539            NewFD->getOverloadedOperator() == OO_Delete ||
9540            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9541         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9542              diag::err_invalid_consteval_decl_kind)
9543             << NewFD;
9544         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9545       }
9546     }
9547 
9548     // If __module_private__ was specified, mark the function accordingly.
9549     if (D.getDeclSpec().isModulePrivateSpecified()) {
9550       if (isFunctionTemplateSpecialization) {
9551         SourceLocation ModulePrivateLoc
9552           = D.getDeclSpec().getModulePrivateSpecLoc();
9553         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9554           << 0
9555           << FixItHint::CreateRemoval(ModulePrivateLoc);
9556       } else {
9557         NewFD->setModulePrivate();
9558         if (FunctionTemplate)
9559           FunctionTemplate->setModulePrivate();
9560       }
9561     }
9562 
9563     if (isFriend) {
9564       if (FunctionTemplate) {
9565         FunctionTemplate->setObjectOfFriendDecl();
9566         FunctionTemplate->setAccess(AS_public);
9567       }
9568       NewFD->setObjectOfFriendDecl();
9569       NewFD->setAccess(AS_public);
9570     }
9571 
9572     // If a function is defined as defaulted or deleted, mark it as such now.
9573     // We'll do the relevant checks on defaulted / deleted functions later.
9574     switch (D.getFunctionDefinitionKind()) {
9575     case FunctionDefinitionKind::Declaration:
9576     case FunctionDefinitionKind::Definition:
9577       break;
9578 
9579     case FunctionDefinitionKind::Defaulted:
9580       NewFD->setDefaulted();
9581       break;
9582 
9583     case FunctionDefinitionKind::Deleted:
9584       NewFD->setDeletedAsWritten();
9585       break;
9586     }
9587 
9588     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9589         D.isFunctionDefinition()) {
9590       // C++ [class.mfct]p2:
9591       //   A member function may be defined (8.4) in its class definition, in
9592       //   which case it is an inline member function (7.1.2)
9593       NewFD->setImplicitlyInline();
9594     }
9595 
9596     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9597         !CurContext->isRecord()) {
9598       // C++ [class.static]p1:
9599       //   A data or function member of a class may be declared static
9600       //   in a class definition, in which case it is a static member of
9601       //   the class.
9602 
9603       // Complain about the 'static' specifier if it's on an out-of-line
9604       // member function definition.
9605 
9606       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9607       // member function template declaration and class member template
9608       // declaration (MSVC versions before 2015), warn about this.
9609       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9610            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9611              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9612            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9613            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9614         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9615     }
9616 
9617     // C++11 [except.spec]p15:
9618     //   A deallocation function with no exception-specification is treated
9619     //   as if it were specified with noexcept(true).
9620     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9621     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9622          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9623         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9624       NewFD->setType(Context.getFunctionType(
9625           FPT->getReturnType(), FPT->getParamTypes(),
9626           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9627   }
9628 
9629   // Filter out previous declarations that don't match the scope.
9630   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9631                        D.getCXXScopeSpec().isNotEmpty() ||
9632                        isMemberSpecialization ||
9633                        isFunctionTemplateSpecialization);
9634 
9635   // Handle GNU asm-label extension (encoded as an attribute).
9636   if (Expr *E = (Expr*) D.getAsmLabel()) {
9637     // The parser guarantees this is a string.
9638     StringLiteral *SE = cast<StringLiteral>(E);
9639     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9640                                         /*IsLiteralLabel=*/true,
9641                                         SE->getStrTokenLoc(0)));
9642   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9643     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9644       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9645     if (I != ExtnameUndeclaredIdentifiers.end()) {
9646       if (isDeclExternC(NewFD)) {
9647         NewFD->addAttr(I->second);
9648         ExtnameUndeclaredIdentifiers.erase(I);
9649       } else
9650         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9651             << /*Variable*/0 << NewFD;
9652     }
9653   }
9654 
9655   // Copy the parameter declarations from the declarator D to the function
9656   // declaration NewFD, if they are available.  First scavenge them into Params.
9657   SmallVector<ParmVarDecl*, 16> Params;
9658   unsigned FTIIdx;
9659   if (D.isFunctionDeclarator(FTIIdx)) {
9660     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9661 
9662     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9663     // function that takes no arguments, not a function that takes a
9664     // single void argument.
9665     // We let through "const void" here because Sema::GetTypeForDeclarator
9666     // already checks for that case.
9667     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9668       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9669         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9670         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9671         Param->setDeclContext(NewFD);
9672         Params.push_back(Param);
9673 
9674         if (Param->isInvalidDecl())
9675           NewFD->setInvalidDecl();
9676       }
9677     }
9678 
9679     if (!getLangOpts().CPlusPlus) {
9680       // In C, find all the tag declarations from the prototype and move them
9681       // into the function DeclContext. Remove them from the surrounding tag
9682       // injection context of the function, which is typically but not always
9683       // the TU.
9684       DeclContext *PrototypeTagContext =
9685           getTagInjectionContext(NewFD->getLexicalDeclContext());
9686       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9687         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9688 
9689         // We don't want to reparent enumerators. Look at their parent enum
9690         // instead.
9691         if (!TD) {
9692           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9693             TD = cast<EnumDecl>(ECD->getDeclContext());
9694         }
9695         if (!TD)
9696           continue;
9697         DeclContext *TagDC = TD->getLexicalDeclContext();
9698         if (!TagDC->containsDecl(TD))
9699           continue;
9700         TagDC->removeDecl(TD);
9701         TD->setDeclContext(NewFD);
9702         NewFD->addDecl(TD);
9703 
9704         // Preserve the lexical DeclContext if it is not the surrounding tag
9705         // injection context of the FD. In this example, the semantic context of
9706         // E will be f and the lexical context will be S, while both the
9707         // semantic and lexical contexts of S will be f:
9708         //   void f(struct S { enum E { a } f; } s);
9709         if (TagDC != PrototypeTagContext)
9710           TD->setLexicalDeclContext(TagDC);
9711       }
9712     }
9713   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9714     // When we're declaring a function with a typedef, typeof, etc as in the
9715     // following example, we'll need to synthesize (unnamed)
9716     // parameters for use in the declaration.
9717     //
9718     // @code
9719     // typedef void fn(int);
9720     // fn f;
9721     // @endcode
9722 
9723     // Synthesize a parameter for each argument type.
9724     for (const auto &AI : FT->param_types()) {
9725       ParmVarDecl *Param =
9726           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9727       Param->setScopeInfo(0, Params.size());
9728       Params.push_back(Param);
9729     }
9730   } else {
9731     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9732            "Should not need args for typedef of non-prototype fn");
9733   }
9734 
9735   // Finally, we know we have the right number of parameters, install them.
9736   NewFD->setParams(Params);
9737 
9738   if (D.getDeclSpec().isNoreturnSpecified())
9739     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9740                                            D.getDeclSpec().getNoreturnSpecLoc(),
9741                                            AttributeCommonInfo::AS_Keyword));
9742 
9743   // Functions returning a variably modified type violate C99 6.7.5.2p2
9744   // because all functions have linkage.
9745   if (!NewFD->isInvalidDecl() &&
9746       NewFD->getReturnType()->isVariablyModifiedType()) {
9747     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9748     NewFD->setInvalidDecl();
9749   }
9750 
9751   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9752   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9753       !NewFD->hasAttr<SectionAttr>())
9754     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9755         Context, PragmaClangTextSection.SectionName,
9756         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9757 
9758   // Apply an implicit SectionAttr if #pragma code_seg is active.
9759   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9760       !NewFD->hasAttr<SectionAttr>()) {
9761     NewFD->addAttr(SectionAttr::CreateImplicit(
9762         Context, CodeSegStack.CurrentValue->getString(),
9763         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9764         SectionAttr::Declspec_allocate));
9765     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9766                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9767                          ASTContext::PSF_Read,
9768                      NewFD))
9769       NewFD->dropAttr<SectionAttr>();
9770   }
9771 
9772   // Apply an implicit CodeSegAttr from class declspec or
9773   // apply an implicit SectionAttr from #pragma code_seg if active.
9774   if (!NewFD->hasAttr<CodeSegAttr>()) {
9775     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9776                                                                  D.isFunctionDefinition())) {
9777       NewFD->addAttr(SAttr);
9778     }
9779   }
9780 
9781   // Handle attributes.
9782   ProcessDeclAttributes(S, NewFD, D);
9783 
9784   if (getLangOpts().OpenCL) {
9785     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9786     // type declaration will generate a compilation error.
9787     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9788     if (AddressSpace != LangAS::Default) {
9789       Diag(NewFD->getLocation(),
9790            diag::err_opencl_return_value_with_address_space);
9791       NewFD->setInvalidDecl();
9792     }
9793   }
9794 
9795   if (!getLangOpts().CPlusPlus) {
9796     // Perform semantic checking on the function declaration.
9797     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9798       CheckMain(NewFD, D.getDeclSpec());
9799 
9800     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9801       CheckMSVCRTEntryPoint(NewFD);
9802 
9803     if (!NewFD->isInvalidDecl())
9804       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9805                                                   isMemberSpecialization));
9806     else if (!Previous.empty())
9807       // Recover gracefully from an invalid redeclaration.
9808       D.setRedeclaration(true);
9809     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9810             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9811            "previous declaration set still overloaded");
9812 
9813     // Diagnose no-prototype function declarations with calling conventions that
9814     // don't support variadic calls. Only do this in C and do it after merging
9815     // possibly prototyped redeclarations.
9816     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9817     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9818       CallingConv CC = FT->getExtInfo().getCC();
9819       if (!supportsVariadicCall(CC)) {
9820         // Windows system headers sometimes accidentally use stdcall without
9821         // (void) parameters, so we relax this to a warning.
9822         int DiagID =
9823             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9824         Diag(NewFD->getLocation(), DiagID)
9825             << FunctionType::getNameForCallConv(CC);
9826       }
9827     }
9828 
9829    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9830        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9831      checkNonTrivialCUnion(NewFD->getReturnType(),
9832                            NewFD->getReturnTypeSourceRange().getBegin(),
9833                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9834   } else {
9835     // C++11 [replacement.functions]p3:
9836     //  The program's definitions shall not be specified as inline.
9837     //
9838     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9839     //
9840     // Suppress the diagnostic if the function is __attribute__((used)), since
9841     // that forces an external definition to be emitted.
9842     if (D.getDeclSpec().isInlineSpecified() &&
9843         NewFD->isReplaceableGlobalAllocationFunction() &&
9844         !NewFD->hasAttr<UsedAttr>())
9845       Diag(D.getDeclSpec().getInlineSpecLoc(),
9846            diag::ext_operator_new_delete_declared_inline)
9847         << NewFD->getDeclName();
9848 
9849     // If the declarator is a template-id, translate the parser's template
9850     // argument list into our AST format.
9851     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9852       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9853       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9854       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9855       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9856                                          TemplateId->NumArgs);
9857       translateTemplateArguments(TemplateArgsPtr,
9858                                  TemplateArgs);
9859 
9860       HasExplicitTemplateArgs = true;
9861 
9862       if (NewFD->isInvalidDecl()) {
9863         HasExplicitTemplateArgs = false;
9864       } else if (FunctionTemplate) {
9865         // Function template with explicit template arguments.
9866         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9867           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9868 
9869         HasExplicitTemplateArgs = false;
9870       } else {
9871         assert((isFunctionTemplateSpecialization ||
9872                 D.getDeclSpec().isFriendSpecified()) &&
9873                "should have a 'template<>' for this decl");
9874         // "friend void foo<>(int);" is an implicit specialization decl.
9875         isFunctionTemplateSpecialization = true;
9876       }
9877     } else if (isFriend && isFunctionTemplateSpecialization) {
9878       // This combination is only possible in a recovery case;  the user
9879       // wrote something like:
9880       //   template <> friend void foo(int);
9881       // which we're recovering from as if the user had written:
9882       //   friend void foo<>(int);
9883       // Go ahead and fake up a template id.
9884       HasExplicitTemplateArgs = true;
9885       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9886       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9887     }
9888 
9889     // We do not add HD attributes to specializations here because
9890     // they may have different constexpr-ness compared to their
9891     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9892     // may end up with different effective targets. Instead, a
9893     // specialization inherits its target attributes from its template
9894     // in the CheckFunctionTemplateSpecialization() call below.
9895     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9896       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9897 
9898     // If it's a friend (and only if it's a friend), it's possible
9899     // that either the specialized function type or the specialized
9900     // template is dependent, and therefore matching will fail.  In
9901     // this case, don't check the specialization yet.
9902     if (isFunctionTemplateSpecialization && isFriend &&
9903         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9904          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9905              TemplateArgs.arguments()))) {
9906       assert(HasExplicitTemplateArgs &&
9907              "friend function specialization without template args");
9908       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9909                                                        Previous))
9910         NewFD->setInvalidDecl();
9911     } else if (isFunctionTemplateSpecialization) {
9912       if (CurContext->isDependentContext() && CurContext->isRecord()
9913           && !isFriend) {
9914         isDependentClassScopeExplicitSpecialization = true;
9915       } else if (!NewFD->isInvalidDecl() &&
9916                  CheckFunctionTemplateSpecialization(
9917                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9918                      Previous))
9919         NewFD->setInvalidDecl();
9920 
9921       // C++ [dcl.stc]p1:
9922       //   A storage-class-specifier shall not be specified in an explicit
9923       //   specialization (14.7.3)
9924       FunctionTemplateSpecializationInfo *Info =
9925           NewFD->getTemplateSpecializationInfo();
9926       if (Info && SC != SC_None) {
9927         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9928           Diag(NewFD->getLocation(),
9929                diag::err_explicit_specialization_inconsistent_storage_class)
9930             << SC
9931             << FixItHint::CreateRemoval(
9932                                       D.getDeclSpec().getStorageClassSpecLoc());
9933 
9934         else
9935           Diag(NewFD->getLocation(),
9936                diag::ext_explicit_specialization_storage_class)
9937             << FixItHint::CreateRemoval(
9938                                       D.getDeclSpec().getStorageClassSpecLoc());
9939       }
9940     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9941       if (CheckMemberSpecialization(NewFD, Previous))
9942           NewFD->setInvalidDecl();
9943     }
9944 
9945     // Perform semantic checking on the function declaration.
9946     if (!isDependentClassScopeExplicitSpecialization) {
9947       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9948         CheckMain(NewFD, D.getDeclSpec());
9949 
9950       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9951         CheckMSVCRTEntryPoint(NewFD);
9952 
9953       if (!NewFD->isInvalidDecl())
9954         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9955                                                     isMemberSpecialization));
9956       else if (!Previous.empty())
9957         // Recover gracefully from an invalid redeclaration.
9958         D.setRedeclaration(true);
9959     }
9960 
9961     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9962             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9963            "previous declaration set still overloaded");
9964 
9965     NamedDecl *PrincipalDecl = (FunctionTemplate
9966                                 ? cast<NamedDecl>(FunctionTemplate)
9967                                 : NewFD);
9968 
9969     if (isFriend && NewFD->getPreviousDecl()) {
9970       AccessSpecifier Access = AS_public;
9971       if (!NewFD->isInvalidDecl())
9972         Access = NewFD->getPreviousDecl()->getAccess();
9973 
9974       NewFD->setAccess(Access);
9975       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9976     }
9977 
9978     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9979         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9980       PrincipalDecl->setNonMemberOperator();
9981 
9982     // If we have a function template, check the template parameter
9983     // list. This will check and merge default template arguments.
9984     if (FunctionTemplate) {
9985       FunctionTemplateDecl *PrevTemplate =
9986                                      FunctionTemplate->getPreviousDecl();
9987       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9988                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9989                                     : nullptr,
9990                             D.getDeclSpec().isFriendSpecified()
9991                               ? (D.isFunctionDefinition()
9992                                    ? TPC_FriendFunctionTemplateDefinition
9993                                    : TPC_FriendFunctionTemplate)
9994                               : (D.getCXXScopeSpec().isSet() &&
9995                                  DC && DC->isRecord() &&
9996                                  DC->isDependentContext())
9997                                   ? TPC_ClassTemplateMember
9998                                   : TPC_FunctionTemplate);
9999     }
10000 
10001     if (NewFD->isInvalidDecl()) {
10002       // Ignore all the rest of this.
10003     } else if (!D.isRedeclaration()) {
10004       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10005                                        AddToScope };
10006       // Fake up an access specifier if it's supposed to be a class member.
10007       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10008         NewFD->setAccess(AS_public);
10009 
10010       // Qualified decls generally require a previous declaration.
10011       if (D.getCXXScopeSpec().isSet()) {
10012         // ...with the major exception of templated-scope or
10013         // dependent-scope friend declarations.
10014 
10015         // TODO: we currently also suppress this check in dependent
10016         // contexts because (1) the parameter depth will be off when
10017         // matching friend templates and (2) we might actually be
10018         // selecting a friend based on a dependent factor.  But there
10019         // are situations where these conditions don't apply and we
10020         // can actually do this check immediately.
10021         //
10022         // Unless the scope is dependent, it's always an error if qualified
10023         // redeclaration lookup found nothing at all. Diagnose that now;
10024         // nothing will diagnose that error later.
10025         if (isFriend &&
10026             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10027              (!Previous.empty() && CurContext->isDependentContext()))) {
10028           // ignore these
10029         } else if (NewFD->isCPUDispatchMultiVersion() ||
10030                    NewFD->isCPUSpecificMultiVersion()) {
10031           // ignore this, we allow the redeclaration behavior here to create new
10032           // versions of the function.
10033         } else {
10034           // The user tried to provide an out-of-line definition for a
10035           // function that is a member of a class or namespace, but there
10036           // was no such member function declared (C++ [class.mfct]p2,
10037           // C++ [namespace.memdef]p2). For example:
10038           //
10039           // class X {
10040           //   void f() const;
10041           // };
10042           //
10043           // void X::f() { } // ill-formed
10044           //
10045           // Complain about this problem, and attempt to suggest close
10046           // matches (e.g., those that differ only in cv-qualifiers and
10047           // whether the parameter types are references).
10048 
10049           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10050                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10051             AddToScope = ExtraArgs.AddToScope;
10052             return Result;
10053           }
10054         }
10055 
10056         // Unqualified local friend declarations are required to resolve
10057         // to something.
10058       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10059         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10060                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10061           AddToScope = ExtraArgs.AddToScope;
10062           return Result;
10063         }
10064       }
10065     } else if (!D.isFunctionDefinition() &&
10066                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10067                !isFriend && !isFunctionTemplateSpecialization &&
10068                !isMemberSpecialization) {
10069       // An out-of-line member function declaration must also be a
10070       // definition (C++ [class.mfct]p2).
10071       // Note that this is not the case for explicit specializations of
10072       // function templates or member functions of class templates, per
10073       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10074       // extension for compatibility with old SWIG code which likes to
10075       // generate them.
10076       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10077         << D.getCXXScopeSpec().getRange();
10078     }
10079   }
10080 
10081   // If this is the first declaration of a library builtin function, add
10082   // attributes as appropriate.
10083   if (!D.isRedeclaration() &&
10084       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10085     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10086       if (unsigned BuiltinID = II->getBuiltinID()) {
10087         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10088           // Validate the type matches unless this builtin is specified as
10089           // matching regardless of its declared type.
10090           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10091             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10092           } else {
10093             ASTContext::GetBuiltinTypeError Error;
10094             LookupNecessaryTypesForBuiltin(S, BuiltinID);
10095             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10096 
10097             if (!Error && !BuiltinType.isNull() &&
10098                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10099                     NewFD->getType(), BuiltinType))
10100               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10101           }
10102         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10103                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10104           // FIXME: We should consider this a builtin only in the std namespace.
10105           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10106         }
10107       }
10108     }
10109   }
10110 
10111   ProcessPragmaWeak(S, NewFD);
10112   checkAttributesAfterMerging(*this, *NewFD);
10113 
10114   AddKnownFunctionAttributes(NewFD);
10115 
10116   if (NewFD->hasAttr<OverloadableAttr>() &&
10117       !NewFD->getType()->getAs<FunctionProtoType>()) {
10118     Diag(NewFD->getLocation(),
10119          diag::err_attribute_overloadable_no_prototype)
10120       << NewFD;
10121 
10122     // Turn this into a variadic function with no parameters.
10123     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10124     FunctionProtoType::ExtProtoInfo EPI(
10125         Context.getDefaultCallingConvention(true, false));
10126     EPI.Variadic = true;
10127     EPI.ExtInfo = FT->getExtInfo();
10128 
10129     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10130     NewFD->setType(R);
10131   }
10132 
10133   // If there's a #pragma GCC visibility in scope, and this isn't a class
10134   // member, set the visibility of this function.
10135   if (!DC->isRecord() && NewFD->isExternallyVisible())
10136     AddPushedVisibilityAttribute(NewFD);
10137 
10138   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10139   // marking the function.
10140   AddCFAuditedAttribute(NewFD);
10141 
10142   // If this is a function definition, check if we have to apply optnone due to
10143   // a pragma.
10144   if(D.isFunctionDefinition())
10145     AddRangeBasedOptnone(NewFD);
10146 
10147   // If this is the first declaration of an extern C variable, update
10148   // the map of such variables.
10149   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10150       isIncompleteDeclExternC(*this, NewFD))
10151     RegisterLocallyScopedExternCDecl(NewFD, S);
10152 
10153   // Set this FunctionDecl's range up to the right paren.
10154   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10155 
10156   if (D.isRedeclaration() && !Previous.empty()) {
10157     NamedDecl *Prev = Previous.getRepresentativeDecl();
10158     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10159                                    isMemberSpecialization ||
10160                                        isFunctionTemplateSpecialization,
10161                                    D.isFunctionDefinition());
10162   }
10163 
10164   if (getLangOpts().CUDA) {
10165     IdentifierInfo *II = NewFD->getIdentifier();
10166     if (II && II->isStr(getCudaConfigureFuncName()) &&
10167         !NewFD->isInvalidDecl() &&
10168         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10169       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10170         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10171             << getCudaConfigureFuncName();
10172       Context.setcudaConfigureCallDecl(NewFD);
10173     }
10174 
10175     // Variadic functions, other than a *declaration* of printf, are not allowed
10176     // in device-side CUDA code, unless someone passed
10177     // -fcuda-allow-variadic-functions.
10178     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10179         (NewFD->hasAttr<CUDADeviceAttr>() ||
10180          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10181         !(II && II->isStr("printf") && NewFD->isExternC() &&
10182           !D.isFunctionDefinition())) {
10183       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10184     }
10185   }
10186 
10187   MarkUnusedFileScopedDecl(NewFD);
10188 
10189 
10190 
10191   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10192     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10193     if (SC == SC_Static) {
10194       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10195       D.setInvalidType();
10196     }
10197 
10198     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10199     if (!NewFD->getReturnType()->isVoidType()) {
10200       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10201       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10202           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10203                                 : FixItHint());
10204       D.setInvalidType();
10205     }
10206 
10207     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10208     for (auto Param : NewFD->parameters())
10209       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10210 
10211     if (getLangOpts().OpenCLCPlusPlus) {
10212       if (DC->isRecord()) {
10213         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10214         D.setInvalidType();
10215       }
10216       if (FunctionTemplate) {
10217         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10218         D.setInvalidType();
10219       }
10220     }
10221   }
10222 
10223   if (getLangOpts().CPlusPlus) {
10224     if (FunctionTemplate) {
10225       if (NewFD->isInvalidDecl())
10226         FunctionTemplate->setInvalidDecl();
10227       return FunctionTemplate;
10228     }
10229 
10230     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10231       CompleteMemberSpecialization(NewFD, Previous);
10232   }
10233 
10234   for (const ParmVarDecl *Param : NewFD->parameters()) {
10235     QualType PT = Param->getType();
10236 
10237     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10238     // types.
10239     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10240       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10241         QualType ElemTy = PipeTy->getElementType();
10242           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10243             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10244             D.setInvalidType();
10245           }
10246       }
10247     }
10248   }
10249 
10250   // Here we have an function template explicit specialization at class scope.
10251   // The actual specialization will be postponed to template instatiation
10252   // time via the ClassScopeFunctionSpecializationDecl node.
10253   if (isDependentClassScopeExplicitSpecialization) {
10254     ClassScopeFunctionSpecializationDecl *NewSpec =
10255                          ClassScopeFunctionSpecializationDecl::Create(
10256                                 Context, CurContext, NewFD->getLocation(),
10257                                 cast<CXXMethodDecl>(NewFD),
10258                                 HasExplicitTemplateArgs, TemplateArgs);
10259     CurContext->addDecl(NewSpec);
10260     AddToScope = false;
10261   }
10262 
10263   // Diagnose availability attributes. Availability cannot be used on functions
10264   // that are run during load/unload.
10265   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10266     if (NewFD->hasAttr<ConstructorAttr>()) {
10267       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10268           << 1;
10269       NewFD->dropAttr<AvailabilityAttr>();
10270     }
10271     if (NewFD->hasAttr<DestructorAttr>()) {
10272       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10273           << 2;
10274       NewFD->dropAttr<AvailabilityAttr>();
10275     }
10276   }
10277 
10278   // Diagnose no_builtin attribute on function declaration that are not a
10279   // definition.
10280   // FIXME: We should really be doing this in
10281   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10282   // the FunctionDecl and at this point of the code
10283   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10284   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10285   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10286     switch (D.getFunctionDefinitionKind()) {
10287     case FunctionDefinitionKind::Defaulted:
10288     case FunctionDefinitionKind::Deleted:
10289       Diag(NBA->getLocation(),
10290            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10291           << NBA->getSpelling();
10292       break;
10293     case FunctionDefinitionKind::Declaration:
10294       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10295           << NBA->getSpelling();
10296       break;
10297     case FunctionDefinitionKind::Definition:
10298       break;
10299     }
10300 
10301   return NewFD;
10302 }
10303 
10304 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10305 /// when __declspec(code_seg) "is applied to a class, all member functions of
10306 /// the class and nested classes -- this includes compiler-generated special
10307 /// member functions -- are put in the specified segment."
10308 /// The actual behavior is a little more complicated. The Microsoft compiler
10309 /// won't check outer classes if there is an active value from #pragma code_seg.
10310 /// The CodeSeg is always applied from the direct parent but only from outer
10311 /// classes when the #pragma code_seg stack is empty. See:
10312 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10313 /// available since MS has removed the page.
10314 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10315   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10316   if (!Method)
10317     return nullptr;
10318   const CXXRecordDecl *Parent = Method->getParent();
10319   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10320     Attr *NewAttr = SAttr->clone(S.getASTContext());
10321     NewAttr->setImplicit(true);
10322     return NewAttr;
10323   }
10324 
10325   // The Microsoft compiler won't check outer classes for the CodeSeg
10326   // when the #pragma code_seg stack is active.
10327   if (S.CodeSegStack.CurrentValue)
10328    return nullptr;
10329 
10330   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10331     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10332       Attr *NewAttr = SAttr->clone(S.getASTContext());
10333       NewAttr->setImplicit(true);
10334       return NewAttr;
10335     }
10336   }
10337   return nullptr;
10338 }
10339 
10340 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10341 /// containing class. Otherwise it will return implicit SectionAttr if the
10342 /// function is a definition and there is an active value on CodeSegStack
10343 /// (from the current #pragma code-seg value).
10344 ///
10345 /// \param FD Function being declared.
10346 /// \param IsDefinition Whether it is a definition or just a declarartion.
10347 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10348 ///          nullptr if no attribute should be added.
10349 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10350                                                        bool IsDefinition) {
10351   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10352     return A;
10353   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10354       CodeSegStack.CurrentValue)
10355     return SectionAttr::CreateImplicit(
10356         getASTContext(), CodeSegStack.CurrentValue->getString(),
10357         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10358         SectionAttr::Declspec_allocate);
10359   return nullptr;
10360 }
10361 
10362 /// Determines if we can perform a correct type check for \p D as a
10363 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10364 /// best-effort check.
10365 ///
10366 /// \param NewD The new declaration.
10367 /// \param OldD The old declaration.
10368 /// \param NewT The portion of the type of the new declaration to check.
10369 /// \param OldT The portion of the type of the old declaration to check.
10370 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10371                                           QualType NewT, QualType OldT) {
10372   if (!NewD->getLexicalDeclContext()->isDependentContext())
10373     return true;
10374 
10375   // For dependently-typed local extern declarations and friends, we can't
10376   // perform a correct type check in general until instantiation:
10377   //
10378   //   int f();
10379   //   template<typename T> void g() { T f(); }
10380   //
10381   // (valid if g() is only instantiated with T = int).
10382   if (NewT->isDependentType() &&
10383       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10384     return false;
10385 
10386   // Similarly, if the previous declaration was a dependent local extern
10387   // declaration, we don't really know its type yet.
10388   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10389     return false;
10390 
10391   return true;
10392 }
10393 
10394 /// Checks if the new declaration declared in dependent context must be
10395 /// put in the same redeclaration chain as the specified declaration.
10396 ///
10397 /// \param D Declaration that is checked.
10398 /// \param PrevDecl Previous declaration found with proper lookup method for the
10399 ///                 same declaration name.
10400 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10401 ///          belongs to.
10402 ///
10403 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10404   if (!D->getLexicalDeclContext()->isDependentContext())
10405     return true;
10406 
10407   // Don't chain dependent friend function definitions until instantiation, to
10408   // permit cases like
10409   //
10410   //   void func();
10411   //   template<typename T> class C1 { friend void func() {} };
10412   //   template<typename T> class C2 { friend void func() {} };
10413   //
10414   // ... which is valid if only one of C1 and C2 is ever instantiated.
10415   //
10416   // FIXME: This need only apply to function definitions. For now, we proxy
10417   // this by checking for a file-scope function. We do not want this to apply
10418   // to friend declarations nominating member functions, because that gets in
10419   // the way of access checks.
10420   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10421     return false;
10422 
10423   auto *VD = dyn_cast<ValueDecl>(D);
10424   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10425   return !VD || !PrevVD ||
10426          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10427                                         PrevVD->getType());
10428 }
10429 
10430 /// Check the target attribute of the function for MultiVersion
10431 /// validity.
10432 ///
10433 /// Returns true if there was an error, false otherwise.
10434 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10435   const auto *TA = FD->getAttr<TargetAttr>();
10436   assert(TA && "MultiVersion Candidate requires a target attribute");
10437   ParsedTargetAttr ParseInfo = TA->parse();
10438   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10439   enum ErrType { Feature = 0, Architecture = 1 };
10440 
10441   if (!ParseInfo.Architecture.empty() &&
10442       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10443     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10444         << Architecture << ParseInfo.Architecture;
10445     return true;
10446   }
10447 
10448   for (const auto &Feat : ParseInfo.Features) {
10449     auto BareFeat = StringRef{Feat}.substr(1);
10450     if (Feat[0] == '-') {
10451       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10452           << Feature << ("no-" + BareFeat).str();
10453       return true;
10454     }
10455 
10456     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10457         !TargetInfo.isValidFeatureName(BareFeat)) {
10458       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10459           << Feature << BareFeat;
10460       return true;
10461     }
10462   }
10463   return false;
10464 }
10465 
10466 // Provide a white-list of attributes that are allowed to be combined with
10467 // multiversion functions.
10468 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10469                                            MultiVersionKind MVKind) {
10470   // Note: this list/diagnosis must match the list in
10471   // checkMultiversionAttributesAllSame.
10472   switch (Kind) {
10473   default:
10474     return false;
10475   case attr::Used:
10476     return MVKind == MultiVersionKind::Target;
10477   case attr::NonNull:
10478   case attr::NoThrow:
10479     return true;
10480   }
10481 }
10482 
10483 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10484                                                  const FunctionDecl *FD,
10485                                                  const FunctionDecl *CausedFD,
10486                                                  MultiVersionKind MVKind) {
10487   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10488     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10489         << static_cast<unsigned>(MVKind) << A;
10490     if (CausedFD)
10491       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10492     return true;
10493   };
10494 
10495   for (const Attr *A : FD->attrs()) {
10496     switch (A->getKind()) {
10497     case attr::CPUDispatch:
10498     case attr::CPUSpecific:
10499       if (MVKind != MultiVersionKind::CPUDispatch &&
10500           MVKind != MultiVersionKind::CPUSpecific)
10501         return Diagnose(S, A);
10502       break;
10503     case attr::Target:
10504       if (MVKind != MultiVersionKind::Target)
10505         return Diagnose(S, A);
10506       break;
10507     case attr::TargetClones:
10508       if (MVKind != MultiVersionKind::TargetClones)
10509         return Diagnose(S, A);
10510       break;
10511     default:
10512       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10513         return Diagnose(S, A);
10514       break;
10515     }
10516   }
10517   return false;
10518 }
10519 
10520 bool Sema::areMultiversionVariantFunctionsCompatible(
10521     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10522     const PartialDiagnostic &NoProtoDiagID,
10523     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10524     const PartialDiagnosticAt &NoSupportDiagIDAt,
10525     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10526     bool ConstexprSupported, bool CLinkageMayDiffer) {
10527   enum DoesntSupport {
10528     FuncTemplates = 0,
10529     VirtFuncs = 1,
10530     DeducedReturn = 2,
10531     Constructors = 3,
10532     Destructors = 4,
10533     DeletedFuncs = 5,
10534     DefaultedFuncs = 6,
10535     ConstexprFuncs = 7,
10536     ConstevalFuncs = 8,
10537     Lambda = 9,
10538   };
10539   enum Different {
10540     CallingConv = 0,
10541     ReturnType = 1,
10542     ConstexprSpec = 2,
10543     InlineSpec = 3,
10544     Linkage = 4,
10545     LanguageLinkage = 5,
10546   };
10547 
10548   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10549       !OldFD->getType()->getAs<FunctionProtoType>()) {
10550     Diag(OldFD->getLocation(), NoProtoDiagID);
10551     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10552     return true;
10553   }
10554 
10555   if (NoProtoDiagID.getDiagID() != 0 &&
10556       !NewFD->getType()->getAs<FunctionProtoType>())
10557     return Diag(NewFD->getLocation(), NoProtoDiagID);
10558 
10559   if (!TemplatesSupported &&
10560       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10561     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10562            << FuncTemplates;
10563 
10564   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10565     if (NewCXXFD->isVirtual())
10566       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10567              << VirtFuncs;
10568 
10569     if (isa<CXXConstructorDecl>(NewCXXFD))
10570       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10571              << Constructors;
10572 
10573     if (isa<CXXDestructorDecl>(NewCXXFD))
10574       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10575              << Destructors;
10576   }
10577 
10578   if (NewFD->isDeleted())
10579     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10580            << DeletedFuncs;
10581 
10582   if (NewFD->isDefaulted())
10583     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10584            << DefaultedFuncs;
10585 
10586   if (!ConstexprSupported && NewFD->isConstexpr())
10587     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10588            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10589 
10590   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10591   const auto *NewType = cast<FunctionType>(NewQType);
10592   QualType NewReturnType = NewType->getReturnType();
10593 
10594   if (NewReturnType->isUndeducedType())
10595     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10596            << DeducedReturn;
10597 
10598   // Ensure the return type is identical.
10599   if (OldFD) {
10600     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10601     const auto *OldType = cast<FunctionType>(OldQType);
10602     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10603     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10604 
10605     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10606       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10607 
10608     QualType OldReturnType = OldType->getReturnType();
10609 
10610     if (OldReturnType != NewReturnType)
10611       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10612 
10613     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10614       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10615 
10616     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10617       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10618 
10619     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10620       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10621 
10622     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10623       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10624 
10625     if (CheckEquivalentExceptionSpec(
10626             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10627             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10628       return true;
10629   }
10630   return false;
10631 }
10632 
10633 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10634                                              const FunctionDecl *NewFD,
10635                                              bool CausesMV,
10636                                              MultiVersionKind MVKind) {
10637   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10638     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10639     if (OldFD)
10640       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10641     return true;
10642   }
10643 
10644   bool IsCPUSpecificCPUDispatchMVKind =
10645       MVKind == MultiVersionKind::CPUDispatch ||
10646       MVKind == MultiVersionKind::CPUSpecific;
10647 
10648   if (CausesMV && OldFD &&
10649       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10650     return true;
10651 
10652   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10653     return true;
10654 
10655   // Only allow transition to MultiVersion if it hasn't been used.
10656   if (OldFD && CausesMV && OldFD->isUsed(false))
10657     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10658 
10659   return S.areMultiversionVariantFunctionsCompatible(
10660       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10661       PartialDiagnosticAt(NewFD->getLocation(),
10662                           S.PDiag(diag::note_multiversioning_caused_here)),
10663       PartialDiagnosticAt(NewFD->getLocation(),
10664                           S.PDiag(diag::err_multiversion_doesnt_support)
10665                               << static_cast<unsigned>(MVKind)),
10666       PartialDiagnosticAt(NewFD->getLocation(),
10667                           S.PDiag(diag::err_multiversion_diff)),
10668       /*TemplatesSupported=*/false,
10669       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10670       /*CLinkageMayDiffer=*/false);
10671 }
10672 
10673 /// Check the validity of a multiversion function declaration that is the
10674 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10675 ///
10676 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10677 ///
10678 /// Returns true if there was an error, false otherwise.
10679 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10680                                            MultiVersionKind MVKind,
10681                                            const TargetAttr *TA) {
10682   assert(MVKind != MultiVersionKind::None &&
10683          "Function lacks multiversion attribute");
10684 
10685   // Target only causes MV if it is default, otherwise this is a normal
10686   // function.
10687   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10688     return false;
10689 
10690   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10691     FD->setInvalidDecl();
10692     return true;
10693   }
10694 
10695   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10696     FD->setInvalidDecl();
10697     return true;
10698   }
10699 
10700   FD->setIsMultiVersion();
10701   return false;
10702 }
10703 
10704 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10705   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10706     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10707       return true;
10708   }
10709 
10710   return false;
10711 }
10712 
10713 static bool CheckTargetCausesMultiVersioning(
10714     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10715     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10716   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10717   ParsedTargetAttr NewParsed = NewTA->parse();
10718   // Sort order doesn't matter, it just needs to be consistent.
10719   llvm::sort(NewParsed.Features);
10720 
10721   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10722   // to change, this is a simple redeclaration.
10723   if (!NewTA->isDefaultVersion() &&
10724       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10725     return false;
10726 
10727   // Otherwise, this decl causes MultiVersioning.
10728   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10729                                        MultiVersionKind::Target)) {
10730     NewFD->setInvalidDecl();
10731     return true;
10732   }
10733 
10734   if (CheckMultiVersionValue(S, NewFD)) {
10735     NewFD->setInvalidDecl();
10736     return true;
10737   }
10738 
10739   // If this is 'default', permit the forward declaration.
10740   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10741     Redeclaration = true;
10742     OldDecl = OldFD;
10743     OldFD->setIsMultiVersion();
10744     NewFD->setIsMultiVersion();
10745     return false;
10746   }
10747 
10748   if (CheckMultiVersionValue(S, OldFD)) {
10749     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10750     NewFD->setInvalidDecl();
10751     return true;
10752   }
10753 
10754   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10755 
10756   if (OldParsed == NewParsed) {
10757     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10758     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10759     NewFD->setInvalidDecl();
10760     return true;
10761   }
10762 
10763   for (const auto *FD : OldFD->redecls()) {
10764     const auto *CurTA = FD->getAttr<TargetAttr>();
10765     // We allow forward declarations before ANY multiversioning attributes, but
10766     // nothing after the fact.
10767     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10768         (!CurTA || CurTA->isInherited())) {
10769       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10770           << 0;
10771       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10772       NewFD->setInvalidDecl();
10773       return true;
10774     }
10775   }
10776 
10777   OldFD->setIsMultiVersion();
10778   NewFD->setIsMultiVersion();
10779   Redeclaration = false;
10780   OldDecl = nullptr;
10781   Previous.clear();
10782   return false;
10783 }
10784 
10785 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10786                                         MultiVersionKind New) {
10787   if (Old == New || Old == MultiVersionKind::None ||
10788       New == MultiVersionKind::None)
10789     return true;
10790 
10791   return (Old == MultiVersionKind::CPUDispatch &&
10792           New == MultiVersionKind::CPUSpecific) ||
10793          (Old == MultiVersionKind::CPUSpecific &&
10794           New == MultiVersionKind::CPUDispatch);
10795 }
10796 
10797 /// Check the validity of a new function declaration being added to an existing
10798 /// multiversioned declaration collection.
10799 static bool CheckMultiVersionAdditionalDecl(
10800     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10801     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10802     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10803     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10804     LookupResult &Previous) {
10805 
10806   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10807   // Disallow mixing of multiversioning types.
10808   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10809     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10810     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10811     NewFD->setInvalidDecl();
10812     return true;
10813   }
10814 
10815   ParsedTargetAttr NewParsed;
10816   if (NewTA) {
10817     NewParsed = NewTA->parse();
10818     llvm::sort(NewParsed.Features);
10819   }
10820 
10821   bool UseMemberUsingDeclRules =
10822       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10823 
10824   bool MayNeedOverloadableChecks =
10825       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10826 
10827   // Next, check ALL non-overloads to see if this is a redeclaration of a
10828   // previous member of the MultiVersion set.
10829   for (NamedDecl *ND : Previous) {
10830     FunctionDecl *CurFD = ND->getAsFunction();
10831     if (!CurFD)
10832       continue;
10833     if (MayNeedOverloadableChecks &&
10834         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10835       continue;
10836 
10837     switch (NewMVKind) {
10838     case MultiVersionKind::None:
10839       assert(OldMVKind == MultiVersionKind::TargetClones &&
10840              "Only target_clones can be omitted in subsequent declarations");
10841       break;
10842     case MultiVersionKind::Target: {
10843       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10844       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10845         NewFD->setIsMultiVersion();
10846         Redeclaration = true;
10847         OldDecl = ND;
10848         return false;
10849       }
10850 
10851       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10852       if (CurParsed == NewParsed) {
10853         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10854         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10855         NewFD->setInvalidDecl();
10856         return true;
10857       }
10858       break;
10859     }
10860     case MultiVersionKind::TargetClones: {
10861       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10862       Redeclaration = true;
10863       OldDecl = CurFD;
10864       NewFD->setIsMultiVersion();
10865 
10866       if (CurClones && NewClones &&
10867           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10868            !std::equal(CurClones->featuresStrs_begin(),
10869                        CurClones->featuresStrs_end(),
10870                        NewClones->featuresStrs_begin()))) {
10871         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10872         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10873         NewFD->setInvalidDecl();
10874         return true;
10875       }
10876 
10877       return false;
10878     }
10879     case MultiVersionKind::CPUSpecific:
10880     case MultiVersionKind::CPUDispatch: {
10881       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10882       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10883       // Handle CPUDispatch/CPUSpecific versions.
10884       // Only 1 CPUDispatch function is allowed, this will make it go through
10885       // the redeclaration errors.
10886       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10887           CurFD->hasAttr<CPUDispatchAttr>()) {
10888         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10889             std::equal(
10890                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10891                 NewCPUDisp->cpus_begin(),
10892                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10893                   return Cur->getName() == New->getName();
10894                 })) {
10895           NewFD->setIsMultiVersion();
10896           Redeclaration = true;
10897           OldDecl = ND;
10898           return false;
10899         }
10900 
10901         // If the declarations don't match, this is an error condition.
10902         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10903         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10904         NewFD->setInvalidDecl();
10905         return true;
10906       }
10907       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10908         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10909             std::equal(
10910                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10911                 NewCPUSpec->cpus_begin(),
10912                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10913                   return Cur->getName() == New->getName();
10914                 })) {
10915           NewFD->setIsMultiVersion();
10916           Redeclaration = true;
10917           OldDecl = ND;
10918           return false;
10919         }
10920 
10921         // Only 1 version of CPUSpecific is allowed for each CPU.
10922         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10923           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10924             if (CurII == NewII) {
10925               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10926                   << NewII;
10927               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10928               NewFD->setInvalidDecl();
10929               return true;
10930             }
10931           }
10932         }
10933       }
10934       break;
10935     }
10936     }
10937   }
10938 
10939   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10940   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10941   // handled in the attribute adding step.
10942   if (NewMVKind == MultiVersionKind::Target &&
10943       CheckMultiVersionValue(S, NewFD)) {
10944     NewFD->setInvalidDecl();
10945     return true;
10946   }
10947 
10948   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10949                                        !OldFD->isMultiVersion(), NewMVKind)) {
10950     NewFD->setInvalidDecl();
10951     return true;
10952   }
10953 
10954   // Permit forward declarations in the case where these two are compatible.
10955   if (!OldFD->isMultiVersion()) {
10956     OldFD->setIsMultiVersion();
10957     NewFD->setIsMultiVersion();
10958     Redeclaration = true;
10959     OldDecl = OldFD;
10960     return false;
10961   }
10962 
10963   NewFD->setIsMultiVersion();
10964   Redeclaration = false;
10965   OldDecl = nullptr;
10966   Previous.clear();
10967   return false;
10968 }
10969 
10970 /// Check the validity of a mulitversion function declaration.
10971 /// Also sets the multiversion'ness' of the function itself.
10972 ///
10973 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10974 ///
10975 /// Returns true if there was an error, false otherwise.
10976 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10977                                       bool &Redeclaration, NamedDecl *&OldDecl,
10978                                       LookupResult &Previous) {
10979   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10980   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10981   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10982   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10983   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
10984 
10985   // Main isn't allowed to become a multiversion function, however it IS
10986   // permitted to have 'main' be marked with the 'target' optimization hint.
10987   if (NewFD->isMain()) {
10988     if (MVKind != MultiVersionKind::None &&
10989         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10990       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10991       NewFD->setInvalidDecl();
10992       return true;
10993     }
10994     return false;
10995   }
10996 
10997   if (!OldDecl || !OldDecl->getAsFunction() ||
10998       OldDecl->getDeclContext()->getRedeclContext() !=
10999           NewFD->getDeclContext()->getRedeclContext()) {
11000     // If there's no previous declaration, AND this isn't attempting to cause
11001     // multiversioning, this isn't an error condition.
11002     if (MVKind == MultiVersionKind::None)
11003       return false;
11004     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11005   }
11006 
11007   FunctionDecl *OldFD = OldDecl->getAsFunction();
11008 
11009   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11010     return false;
11011 
11012   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11013   // for target_clones.
11014   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11015       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11016     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11017         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11018     NewFD->setInvalidDecl();
11019     return true;
11020   }
11021 
11022   if (!OldFD->isMultiVersion()) {
11023     switch (MVKind) {
11024     case MultiVersionKind::Target:
11025       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11026                                               Redeclaration, OldDecl, Previous);
11027     case MultiVersionKind::TargetClones:
11028       if (OldFD->isUsed(false)) {
11029         NewFD->setInvalidDecl();
11030         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11031       }
11032       OldFD->setIsMultiVersion();
11033       break;
11034     case MultiVersionKind::CPUDispatch:
11035     case MultiVersionKind::CPUSpecific:
11036     case MultiVersionKind::None:
11037       break;
11038     }
11039   }
11040 
11041   // At this point, we have a multiversion function decl (in OldFD) AND an
11042   // appropriate attribute in the current function decl.  Resolve that these are
11043   // still compatible with previous declarations.
11044   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11045                                          NewCPUDisp, NewCPUSpec, NewClones,
11046                                          Redeclaration, OldDecl, Previous);
11047 }
11048 
11049 /// Perform semantic checking of a new function declaration.
11050 ///
11051 /// Performs semantic analysis of the new function declaration
11052 /// NewFD. This routine performs all semantic checking that does not
11053 /// require the actual declarator involved in the declaration, and is
11054 /// used both for the declaration of functions as they are parsed
11055 /// (called via ActOnDeclarator) and for the declaration of functions
11056 /// that have been instantiated via C++ template instantiation (called
11057 /// via InstantiateDecl).
11058 ///
11059 /// \param IsMemberSpecialization whether this new function declaration is
11060 /// a member specialization (that replaces any definition provided by the
11061 /// previous declaration).
11062 ///
11063 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11064 ///
11065 /// \returns true if the function declaration is a redeclaration.
11066 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11067                                     LookupResult &Previous,
11068                                     bool IsMemberSpecialization) {
11069   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11070          "Variably modified return types are not handled here");
11071 
11072   // Determine whether the type of this function should be merged with
11073   // a previous visible declaration. This never happens for functions in C++,
11074   // and always happens in C if the previous declaration was visible.
11075   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11076                                !Previous.isShadowed();
11077 
11078   bool Redeclaration = false;
11079   NamedDecl *OldDecl = nullptr;
11080   bool MayNeedOverloadableChecks = false;
11081 
11082   // Merge or overload the declaration with an existing declaration of
11083   // the same name, if appropriate.
11084   if (!Previous.empty()) {
11085     // Determine whether NewFD is an overload of PrevDecl or
11086     // a declaration that requires merging. If it's an overload,
11087     // there's no more work to do here; we'll just add the new
11088     // function to the scope.
11089     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11090       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11091       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11092         Redeclaration = true;
11093         OldDecl = Candidate;
11094       }
11095     } else {
11096       MayNeedOverloadableChecks = true;
11097       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11098                             /*NewIsUsingDecl*/ false)) {
11099       case Ovl_Match:
11100         Redeclaration = true;
11101         break;
11102 
11103       case Ovl_NonFunction:
11104         Redeclaration = true;
11105         break;
11106 
11107       case Ovl_Overload:
11108         Redeclaration = false;
11109         break;
11110       }
11111     }
11112   }
11113 
11114   // Check for a previous extern "C" declaration with this name.
11115   if (!Redeclaration &&
11116       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11117     if (!Previous.empty()) {
11118       // This is an extern "C" declaration with the same name as a previous
11119       // declaration, and thus redeclares that entity...
11120       Redeclaration = true;
11121       OldDecl = Previous.getFoundDecl();
11122       MergeTypeWithPrevious = false;
11123 
11124       // ... except in the presence of __attribute__((overloadable)).
11125       if (OldDecl->hasAttr<OverloadableAttr>() ||
11126           NewFD->hasAttr<OverloadableAttr>()) {
11127         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11128           MayNeedOverloadableChecks = true;
11129           Redeclaration = false;
11130           OldDecl = nullptr;
11131         }
11132       }
11133     }
11134   }
11135 
11136   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11137     return Redeclaration;
11138 
11139   // PPC MMA non-pointer types are not allowed as function return types.
11140   if (Context.getTargetInfo().getTriple().isPPC64() &&
11141       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11142     NewFD->setInvalidDecl();
11143   }
11144 
11145   // C++11 [dcl.constexpr]p8:
11146   //   A constexpr specifier for a non-static member function that is not
11147   //   a constructor declares that member function to be const.
11148   //
11149   // This needs to be delayed until we know whether this is an out-of-line
11150   // definition of a static member function.
11151   //
11152   // This rule is not present in C++1y, so we produce a backwards
11153   // compatibility warning whenever it happens in C++11.
11154   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11155   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11156       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11157       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11158     CXXMethodDecl *OldMD = nullptr;
11159     if (OldDecl)
11160       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11161     if (!OldMD || !OldMD->isStatic()) {
11162       const FunctionProtoType *FPT =
11163         MD->getType()->castAs<FunctionProtoType>();
11164       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11165       EPI.TypeQuals.addConst();
11166       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11167                                           FPT->getParamTypes(), EPI));
11168 
11169       // Warn that we did this, if we're not performing template instantiation.
11170       // In that case, we'll have warned already when the template was defined.
11171       if (!inTemplateInstantiation()) {
11172         SourceLocation AddConstLoc;
11173         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11174                 .IgnoreParens().getAs<FunctionTypeLoc>())
11175           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11176 
11177         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11178           << FixItHint::CreateInsertion(AddConstLoc, " const");
11179       }
11180     }
11181   }
11182 
11183   if (Redeclaration) {
11184     // NewFD and OldDecl represent declarations that need to be
11185     // merged.
11186     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11187       NewFD->setInvalidDecl();
11188       return Redeclaration;
11189     }
11190 
11191     Previous.clear();
11192     Previous.addDecl(OldDecl);
11193 
11194     if (FunctionTemplateDecl *OldTemplateDecl =
11195             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11196       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11197       FunctionTemplateDecl *NewTemplateDecl
11198         = NewFD->getDescribedFunctionTemplate();
11199       assert(NewTemplateDecl && "Template/non-template mismatch");
11200 
11201       // The call to MergeFunctionDecl above may have created some state in
11202       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11203       // can add it as a redeclaration.
11204       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11205 
11206       NewFD->setPreviousDeclaration(OldFD);
11207       if (NewFD->isCXXClassMember()) {
11208         NewFD->setAccess(OldTemplateDecl->getAccess());
11209         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11210       }
11211 
11212       // If this is an explicit specialization of a member that is a function
11213       // template, mark it as a member specialization.
11214       if (IsMemberSpecialization &&
11215           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11216         NewTemplateDecl->setMemberSpecialization();
11217         assert(OldTemplateDecl->isMemberSpecialization());
11218         // Explicit specializations of a member template do not inherit deleted
11219         // status from the parent member template that they are specializing.
11220         if (OldFD->isDeleted()) {
11221           // FIXME: This assert will not hold in the presence of modules.
11222           assert(OldFD->getCanonicalDecl() == OldFD);
11223           // FIXME: We need an update record for this AST mutation.
11224           OldFD->setDeletedAsWritten(false);
11225         }
11226       }
11227 
11228     } else {
11229       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11230         auto *OldFD = cast<FunctionDecl>(OldDecl);
11231         // This needs to happen first so that 'inline' propagates.
11232         NewFD->setPreviousDeclaration(OldFD);
11233         if (NewFD->isCXXClassMember())
11234           NewFD->setAccess(OldFD->getAccess());
11235       }
11236     }
11237   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11238              !NewFD->getAttr<OverloadableAttr>()) {
11239     assert((Previous.empty() ||
11240             llvm::any_of(Previous,
11241                          [](const NamedDecl *ND) {
11242                            return ND->hasAttr<OverloadableAttr>();
11243                          })) &&
11244            "Non-redecls shouldn't happen without overloadable present");
11245 
11246     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11247       const auto *FD = dyn_cast<FunctionDecl>(ND);
11248       return FD && !FD->hasAttr<OverloadableAttr>();
11249     });
11250 
11251     if (OtherUnmarkedIter != Previous.end()) {
11252       Diag(NewFD->getLocation(),
11253            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11254       Diag((*OtherUnmarkedIter)->getLocation(),
11255            diag::note_attribute_overloadable_prev_overload)
11256           << false;
11257 
11258       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11259     }
11260   }
11261 
11262   if (LangOpts.OpenMP)
11263     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11264 
11265   // Semantic checking for this function declaration (in isolation).
11266 
11267   if (getLangOpts().CPlusPlus) {
11268     // C++-specific checks.
11269     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11270       CheckConstructor(Constructor);
11271     } else if (CXXDestructorDecl *Destructor =
11272                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11273       CXXRecordDecl *Record = Destructor->getParent();
11274       QualType ClassType = Context.getTypeDeclType(Record);
11275 
11276       // FIXME: Shouldn't we be able to perform this check even when the class
11277       // type is dependent? Both gcc and edg can handle that.
11278       if (!ClassType->isDependentType()) {
11279         DeclarationName Name
11280           = Context.DeclarationNames.getCXXDestructorName(
11281                                         Context.getCanonicalType(ClassType));
11282         if (NewFD->getDeclName() != Name) {
11283           Diag(NewFD->getLocation(), diag::err_destructor_name);
11284           NewFD->setInvalidDecl();
11285           return Redeclaration;
11286         }
11287       }
11288     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11289       if (auto *TD = Guide->getDescribedFunctionTemplate())
11290         CheckDeductionGuideTemplate(TD);
11291 
11292       // A deduction guide is not on the list of entities that can be
11293       // explicitly specialized.
11294       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11295         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11296             << /*explicit specialization*/ 1;
11297     }
11298 
11299     // Find any virtual functions that this function overrides.
11300     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11301       if (!Method->isFunctionTemplateSpecialization() &&
11302           !Method->getDescribedFunctionTemplate() &&
11303           Method->isCanonicalDecl()) {
11304         AddOverriddenMethods(Method->getParent(), Method);
11305       }
11306       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11307         // C++2a [class.virtual]p6
11308         // A virtual method shall not have a requires-clause.
11309         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11310              diag::err_constrained_virtual_method);
11311 
11312       if (Method->isStatic())
11313         checkThisInStaticMemberFunctionType(Method);
11314     }
11315 
11316     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11317       ActOnConversionDeclarator(Conversion);
11318 
11319     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11320     if (NewFD->isOverloadedOperator() &&
11321         CheckOverloadedOperatorDeclaration(NewFD)) {
11322       NewFD->setInvalidDecl();
11323       return Redeclaration;
11324     }
11325 
11326     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11327     if (NewFD->getLiteralIdentifier() &&
11328         CheckLiteralOperatorDeclaration(NewFD)) {
11329       NewFD->setInvalidDecl();
11330       return Redeclaration;
11331     }
11332 
11333     // In C++, check default arguments now that we have merged decls. Unless
11334     // the lexical context is the class, because in this case this is done
11335     // during delayed parsing anyway.
11336     if (!CurContext->isRecord())
11337       CheckCXXDefaultArguments(NewFD);
11338 
11339     // If this function is declared as being extern "C", then check to see if
11340     // the function returns a UDT (class, struct, or union type) that is not C
11341     // compatible, and if it does, warn the user.
11342     // But, issue any diagnostic on the first declaration only.
11343     if (Previous.empty() && NewFD->isExternC()) {
11344       QualType R = NewFD->getReturnType();
11345       if (R->isIncompleteType() && !R->isVoidType())
11346         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11347             << NewFD << R;
11348       else if (!R.isPODType(Context) && !R->isVoidType() &&
11349                !R->isObjCObjectPointerType())
11350         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11351     }
11352 
11353     // C++1z [dcl.fct]p6:
11354     //   [...] whether the function has a non-throwing exception-specification
11355     //   [is] part of the function type
11356     //
11357     // This results in an ABI break between C++14 and C++17 for functions whose
11358     // declared type includes an exception-specification in a parameter or
11359     // return type. (Exception specifications on the function itself are OK in
11360     // most cases, and exception specifications are not permitted in most other
11361     // contexts where they could make it into a mangling.)
11362     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11363       auto HasNoexcept = [&](QualType T) -> bool {
11364         // Strip off declarator chunks that could be between us and a function
11365         // type. We don't need to look far, exception specifications are very
11366         // restricted prior to C++17.
11367         if (auto *RT = T->getAs<ReferenceType>())
11368           T = RT->getPointeeType();
11369         else if (T->isAnyPointerType())
11370           T = T->getPointeeType();
11371         else if (auto *MPT = T->getAs<MemberPointerType>())
11372           T = MPT->getPointeeType();
11373         if (auto *FPT = T->getAs<FunctionProtoType>())
11374           if (FPT->isNothrow())
11375             return true;
11376         return false;
11377       };
11378 
11379       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11380       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11381       for (QualType T : FPT->param_types())
11382         AnyNoexcept |= HasNoexcept(T);
11383       if (AnyNoexcept)
11384         Diag(NewFD->getLocation(),
11385              diag::warn_cxx17_compat_exception_spec_in_signature)
11386             << NewFD;
11387     }
11388 
11389     if (!Redeclaration && LangOpts.CUDA)
11390       checkCUDATargetOverload(NewFD, Previous);
11391   }
11392   return Redeclaration;
11393 }
11394 
11395 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11396   // C++11 [basic.start.main]p3:
11397   //   A program that [...] declares main to be inline, static or
11398   //   constexpr is ill-formed.
11399   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11400   //   appear in a declaration of main.
11401   // static main is not an error under C99, but we should warn about it.
11402   // We accept _Noreturn main as an extension.
11403   if (FD->getStorageClass() == SC_Static)
11404     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11405          ? diag::err_static_main : diag::warn_static_main)
11406       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11407   if (FD->isInlineSpecified())
11408     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11409       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11410   if (DS.isNoreturnSpecified()) {
11411     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11412     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11413     Diag(NoreturnLoc, diag::ext_noreturn_main);
11414     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11415       << FixItHint::CreateRemoval(NoreturnRange);
11416   }
11417   if (FD->isConstexpr()) {
11418     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11419         << FD->isConsteval()
11420         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11421     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11422   }
11423 
11424   if (getLangOpts().OpenCL) {
11425     Diag(FD->getLocation(), diag::err_opencl_no_main)
11426         << FD->hasAttr<OpenCLKernelAttr>();
11427     FD->setInvalidDecl();
11428     return;
11429   }
11430 
11431   // Functions named main in hlsl are default entries, but don't have specific
11432   // signatures they are required to conform to.
11433   if (getLangOpts().HLSL)
11434     return;
11435 
11436   QualType T = FD->getType();
11437   assert(T->isFunctionType() && "function decl is not of function type");
11438   const FunctionType* FT = T->castAs<FunctionType>();
11439 
11440   // Set default calling convention for main()
11441   if (FT->getCallConv() != CC_C) {
11442     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11443     FD->setType(QualType(FT, 0));
11444     T = Context.getCanonicalType(FD->getType());
11445   }
11446 
11447   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11448     // In C with GNU extensions we allow main() to have non-integer return
11449     // type, but we should warn about the extension, and we disable the
11450     // implicit-return-zero rule.
11451 
11452     // GCC in C mode accepts qualified 'int'.
11453     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11454       FD->setHasImplicitReturnZero(true);
11455     else {
11456       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11457       SourceRange RTRange = FD->getReturnTypeSourceRange();
11458       if (RTRange.isValid())
11459         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11460             << FixItHint::CreateReplacement(RTRange, "int");
11461     }
11462   } else {
11463     // In C and C++, main magically returns 0 if you fall off the end;
11464     // set the flag which tells us that.
11465     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11466 
11467     // All the standards say that main() should return 'int'.
11468     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11469       FD->setHasImplicitReturnZero(true);
11470     else {
11471       // Otherwise, this is just a flat-out error.
11472       SourceRange RTRange = FD->getReturnTypeSourceRange();
11473       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11474           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11475                                 : FixItHint());
11476       FD->setInvalidDecl(true);
11477     }
11478   }
11479 
11480   // Treat protoless main() as nullary.
11481   if (isa<FunctionNoProtoType>(FT)) return;
11482 
11483   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11484   unsigned nparams = FTP->getNumParams();
11485   assert(FD->getNumParams() == nparams);
11486 
11487   bool HasExtraParameters = (nparams > 3);
11488 
11489   if (FTP->isVariadic()) {
11490     Diag(FD->getLocation(), diag::ext_variadic_main);
11491     // FIXME: if we had information about the location of the ellipsis, we
11492     // could add a FixIt hint to remove it as a parameter.
11493   }
11494 
11495   // Darwin passes an undocumented fourth argument of type char**.  If
11496   // other platforms start sprouting these, the logic below will start
11497   // getting shifty.
11498   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11499     HasExtraParameters = false;
11500 
11501   if (HasExtraParameters) {
11502     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11503     FD->setInvalidDecl(true);
11504     nparams = 3;
11505   }
11506 
11507   // FIXME: a lot of the following diagnostics would be improved
11508   // if we had some location information about types.
11509 
11510   QualType CharPP =
11511     Context.getPointerType(Context.getPointerType(Context.CharTy));
11512   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11513 
11514   for (unsigned i = 0; i < nparams; ++i) {
11515     QualType AT = FTP->getParamType(i);
11516 
11517     bool mismatch = true;
11518 
11519     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11520       mismatch = false;
11521     else if (Expected[i] == CharPP) {
11522       // As an extension, the following forms are okay:
11523       //   char const **
11524       //   char const * const *
11525       //   char * const *
11526 
11527       QualifierCollector qs;
11528       const PointerType* PT;
11529       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11530           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11531           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11532                               Context.CharTy)) {
11533         qs.removeConst();
11534         mismatch = !qs.empty();
11535       }
11536     }
11537 
11538     if (mismatch) {
11539       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11540       // TODO: suggest replacing given type with expected type
11541       FD->setInvalidDecl(true);
11542     }
11543   }
11544 
11545   if (nparams == 1 && !FD->isInvalidDecl()) {
11546     Diag(FD->getLocation(), diag::warn_main_one_arg);
11547   }
11548 
11549   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11550     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11551     FD->setInvalidDecl();
11552   }
11553 }
11554 
11555 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11556 
11557   // Default calling convention for main and wmain is __cdecl
11558   if (FD->getName() == "main" || FD->getName() == "wmain")
11559     return false;
11560 
11561   // Default calling convention for MinGW is __cdecl
11562   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11563   if (T.isWindowsGNUEnvironment())
11564     return false;
11565 
11566   // Default calling convention for WinMain, wWinMain and DllMain
11567   // is __stdcall on 32 bit Windows
11568   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11569     return true;
11570 
11571   return false;
11572 }
11573 
11574 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11575   QualType T = FD->getType();
11576   assert(T->isFunctionType() && "function decl is not of function type");
11577   const FunctionType *FT = T->castAs<FunctionType>();
11578 
11579   // Set an implicit return of 'zero' if the function can return some integral,
11580   // enumeration, pointer or nullptr type.
11581   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11582       FT->getReturnType()->isAnyPointerType() ||
11583       FT->getReturnType()->isNullPtrType())
11584     // DllMain is exempt because a return value of zero means it failed.
11585     if (FD->getName() != "DllMain")
11586       FD->setHasImplicitReturnZero(true);
11587 
11588   // Explicity specified calling conventions are applied to MSVC entry points
11589   if (!hasExplicitCallingConv(T)) {
11590     if (isDefaultStdCall(FD, *this)) {
11591       if (FT->getCallConv() != CC_X86StdCall) {
11592         FT = Context.adjustFunctionType(
11593             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11594         FD->setType(QualType(FT, 0));
11595       }
11596     } else if (FT->getCallConv() != CC_C) {
11597       FT = Context.adjustFunctionType(FT,
11598                                       FT->getExtInfo().withCallingConv(CC_C));
11599       FD->setType(QualType(FT, 0));
11600     }
11601   }
11602 
11603   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11604     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11605     FD->setInvalidDecl();
11606   }
11607 }
11608 
11609 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11610   // FIXME: Need strict checking.  In C89, we need to check for
11611   // any assignment, increment, decrement, function-calls, or
11612   // commas outside of a sizeof.  In C99, it's the same list,
11613   // except that the aforementioned are allowed in unevaluated
11614   // expressions.  Everything else falls under the
11615   // "may accept other forms of constant expressions" exception.
11616   //
11617   // Regular C++ code will not end up here (exceptions: language extensions,
11618   // OpenCL C++ etc), so the constant expression rules there don't matter.
11619   if (Init->isValueDependent()) {
11620     assert(Init->containsErrors() &&
11621            "Dependent code should only occur in error-recovery path.");
11622     return true;
11623   }
11624   const Expr *Culprit;
11625   if (Init->isConstantInitializer(Context, false, &Culprit))
11626     return false;
11627   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11628     << Culprit->getSourceRange();
11629   return true;
11630 }
11631 
11632 namespace {
11633   // Visits an initialization expression to see if OrigDecl is evaluated in
11634   // its own initialization and throws a warning if it does.
11635   class SelfReferenceChecker
11636       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11637     Sema &S;
11638     Decl *OrigDecl;
11639     bool isRecordType;
11640     bool isPODType;
11641     bool isReferenceType;
11642 
11643     bool isInitList;
11644     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11645 
11646   public:
11647     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11648 
11649     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11650                                                     S(S), OrigDecl(OrigDecl) {
11651       isPODType = false;
11652       isRecordType = false;
11653       isReferenceType = false;
11654       isInitList = false;
11655       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11656         isPODType = VD->getType().isPODType(S.Context);
11657         isRecordType = VD->getType()->isRecordType();
11658         isReferenceType = VD->getType()->isReferenceType();
11659       }
11660     }
11661 
11662     // For most expressions, just call the visitor.  For initializer lists,
11663     // track the index of the field being initialized since fields are
11664     // initialized in order allowing use of previously initialized fields.
11665     void CheckExpr(Expr *E) {
11666       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11667       if (!InitList) {
11668         Visit(E);
11669         return;
11670       }
11671 
11672       // Track and increment the index here.
11673       isInitList = true;
11674       InitFieldIndex.push_back(0);
11675       for (auto Child : InitList->children()) {
11676         CheckExpr(cast<Expr>(Child));
11677         ++InitFieldIndex.back();
11678       }
11679       InitFieldIndex.pop_back();
11680     }
11681 
11682     // Returns true if MemberExpr is checked and no further checking is needed.
11683     // Returns false if additional checking is required.
11684     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11685       llvm::SmallVector<FieldDecl*, 4> Fields;
11686       Expr *Base = E;
11687       bool ReferenceField = false;
11688 
11689       // Get the field members used.
11690       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11691         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11692         if (!FD)
11693           return false;
11694         Fields.push_back(FD);
11695         if (FD->getType()->isReferenceType())
11696           ReferenceField = true;
11697         Base = ME->getBase()->IgnoreParenImpCasts();
11698       }
11699 
11700       // Keep checking only if the base Decl is the same.
11701       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11702       if (!DRE || DRE->getDecl() != OrigDecl)
11703         return false;
11704 
11705       // A reference field can be bound to an unininitialized field.
11706       if (CheckReference && !ReferenceField)
11707         return true;
11708 
11709       // Convert FieldDecls to their index number.
11710       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11711       for (const FieldDecl *I : llvm::reverse(Fields))
11712         UsedFieldIndex.push_back(I->getFieldIndex());
11713 
11714       // See if a warning is needed by checking the first difference in index
11715       // numbers.  If field being used has index less than the field being
11716       // initialized, then the use is safe.
11717       for (auto UsedIter = UsedFieldIndex.begin(),
11718                 UsedEnd = UsedFieldIndex.end(),
11719                 OrigIter = InitFieldIndex.begin(),
11720                 OrigEnd = InitFieldIndex.end();
11721            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11722         if (*UsedIter < *OrigIter)
11723           return true;
11724         if (*UsedIter > *OrigIter)
11725           break;
11726       }
11727 
11728       // TODO: Add a different warning which will print the field names.
11729       HandleDeclRefExpr(DRE);
11730       return true;
11731     }
11732 
11733     // For most expressions, the cast is directly above the DeclRefExpr.
11734     // For conditional operators, the cast can be outside the conditional
11735     // operator if both expressions are DeclRefExpr's.
11736     void HandleValue(Expr *E) {
11737       E = E->IgnoreParens();
11738       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11739         HandleDeclRefExpr(DRE);
11740         return;
11741       }
11742 
11743       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11744         Visit(CO->getCond());
11745         HandleValue(CO->getTrueExpr());
11746         HandleValue(CO->getFalseExpr());
11747         return;
11748       }
11749 
11750       if (BinaryConditionalOperator *BCO =
11751               dyn_cast<BinaryConditionalOperator>(E)) {
11752         Visit(BCO->getCond());
11753         HandleValue(BCO->getFalseExpr());
11754         return;
11755       }
11756 
11757       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11758         HandleValue(OVE->getSourceExpr());
11759         return;
11760       }
11761 
11762       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11763         if (BO->getOpcode() == BO_Comma) {
11764           Visit(BO->getLHS());
11765           HandleValue(BO->getRHS());
11766           return;
11767         }
11768       }
11769 
11770       if (isa<MemberExpr>(E)) {
11771         if (isInitList) {
11772           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11773                                       false /*CheckReference*/))
11774             return;
11775         }
11776 
11777         Expr *Base = E->IgnoreParenImpCasts();
11778         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11779           // Check for static member variables and don't warn on them.
11780           if (!isa<FieldDecl>(ME->getMemberDecl()))
11781             return;
11782           Base = ME->getBase()->IgnoreParenImpCasts();
11783         }
11784         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11785           HandleDeclRefExpr(DRE);
11786         return;
11787       }
11788 
11789       Visit(E);
11790     }
11791 
11792     // Reference types not handled in HandleValue are handled here since all
11793     // uses of references are bad, not just r-value uses.
11794     void VisitDeclRefExpr(DeclRefExpr *E) {
11795       if (isReferenceType)
11796         HandleDeclRefExpr(E);
11797     }
11798 
11799     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11800       if (E->getCastKind() == CK_LValueToRValue) {
11801         HandleValue(E->getSubExpr());
11802         return;
11803       }
11804 
11805       Inherited::VisitImplicitCastExpr(E);
11806     }
11807 
11808     void VisitMemberExpr(MemberExpr *E) {
11809       if (isInitList) {
11810         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11811           return;
11812       }
11813 
11814       // Don't warn on arrays since they can be treated as pointers.
11815       if (E->getType()->canDecayToPointerType()) return;
11816 
11817       // Warn when a non-static method call is followed by non-static member
11818       // field accesses, which is followed by a DeclRefExpr.
11819       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11820       bool Warn = (MD && !MD->isStatic());
11821       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11822       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11823         if (!isa<FieldDecl>(ME->getMemberDecl()))
11824           Warn = false;
11825         Base = ME->getBase()->IgnoreParenImpCasts();
11826       }
11827 
11828       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11829         if (Warn)
11830           HandleDeclRefExpr(DRE);
11831         return;
11832       }
11833 
11834       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11835       // Visit that expression.
11836       Visit(Base);
11837     }
11838 
11839     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11840       Expr *Callee = E->getCallee();
11841 
11842       if (isa<UnresolvedLookupExpr>(Callee))
11843         return Inherited::VisitCXXOperatorCallExpr(E);
11844 
11845       Visit(Callee);
11846       for (auto Arg: E->arguments())
11847         HandleValue(Arg->IgnoreParenImpCasts());
11848     }
11849 
11850     void VisitUnaryOperator(UnaryOperator *E) {
11851       // For POD record types, addresses of its own members are well-defined.
11852       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11853           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11854         if (!isPODType)
11855           HandleValue(E->getSubExpr());
11856         return;
11857       }
11858 
11859       if (E->isIncrementDecrementOp()) {
11860         HandleValue(E->getSubExpr());
11861         return;
11862       }
11863 
11864       Inherited::VisitUnaryOperator(E);
11865     }
11866 
11867     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11868 
11869     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11870       if (E->getConstructor()->isCopyConstructor()) {
11871         Expr *ArgExpr = E->getArg(0);
11872         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11873           if (ILE->getNumInits() == 1)
11874             ArgExpr = ILE->getInit(0);
11875         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11876           if (ICE->getCastKind() == CK_NoOp)
11877             ArgExpr = ICE->getSubExpr();
11878         HandleValue(ArgExpr);
11879         return;
11880       }
11881       Inherited::VisitCXXConstructExpr(E);
11882     }
11883 
11884     void VisitCallExpr(CallExpr *E) {
11885       // Treat std::move as a use.
11886       if (E->isCallToStdMove()) {
11887         HandleValue(E->getArg(0));
11888         return;
11889       }
11890 
11891       Inherited::VisitCallExpr(E);
11892     }
11893 
11894     void VisitBinaryOperator(BinaryOperator *E) {
11895       if (E->isCompoundAssignmentOp()) {
11896         HandleValue(E->getLHS());
11897         Visit(E->getRHS());
11898         return;
11899       }
11900 
11901       Inherited::VisitBinaryOperator(E);
11902     }
11903 
11904     // A custom visitor for BinaryConditionalOperator is needed because the
11905     // regular visitor would check the condition and true expression separately
11906     // but both point to the same place giving duplicate diagnostics.
11907     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11908       Visit(E->getCond());
11909       Visit(E->getFalseExpr());
11910     }
11911 
11912     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11913       Decl* ReferenceDecl = DRE->getDecl();
11914       if (OrigDecl != ReferenceDecl) return;
11915       unsigned diag;
11916       if (isReferenceType) {
11917         diag = diag::warn_uninit_self_reference_in_reference_init;
11918       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11919         diag = diag::warn_static_self_reference_in_init;
11920       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11921                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11922                  DRE->getDecl()->getType()->isRecordType()) {
11923         diag = diag::warn_uninit_self_reference_in_init;
11924       } else {
11925         // Local variables will be handled by the CFG analysis.
11926         return;
11927       }
11928 
11929       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11930                             S.PDiag(diag)
11931                                 << DRE->getDecl() << OrigDecl->getLocation()
11932                                 << DRE->getSourceRange());
11933     }
11934   };
11935 
11936   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11937   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11938                                  bool DirectInit) {
11939     // Parameters arguments are occassionially constructed with itself,
11940     // for instance, in recursive functions.  Skip them.
11941     if (isa<ParmVarDecl>(OrigDecl))
11942       return;
11943 
11944     E = E->IgnoreParens();
11945 
11946     // Skip checking T a = a where T is not a record or reference type.
11947     // Doing so is a way to silence uninitialized warnings.
11948     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11949       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11950         if (ICE->getCastKind() == CK_LValueToRValue)
11951           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11952             if (DRE->getDecl() == OrigDecl)
11953               return;
11954 
11955     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11956   }
11957 } // end anonymous namespace
11958 
11959 namespace {
11960   // Simple wrapper to add the name of a variable or (if no variable is
11961   // available) a DeclarationName into a diagnostic.
11962   struct VarDeclOrName {
11963     VarDecl *VDecl;
11964     DeclarationName Name;
11965 
11966     friend const Sema::SemaDiagnosticBuilder &
11967     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11968       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11969     }
11970   };
11971 } // end anonymous namespace
11972 
11973 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11974                                             DeclarationName Name, QualType Type,
11975                                             TypeSourceInfo *TSI,
11976                                             SourceRange Range, bool DirectInit,
11977                                             Expr *Init) {
11978   bool IsInitCapture = !VDecl;
11979   assert((!VDecl || !VDecl->isInitCapture()) &&
11980          "init captures are expected to be deduced prior to initialization");
11981 
11982   VarDeclOrName VN{VDecl, Name};
11983 
11984   DeducedType *Deduced = Type->getContainedDeducedType();
11985   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11986 
11987   // C++11 [dcl.spec.auto]p3
11988   if (!Init) {
11989     assert(VDecl && "no init for init capture deduction?");
11990 
11991     // Except for class argument deduction, and then for an initializing
11992     // declaration only, i.e. no static at class scope or extern.
11993     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11994         VDecl->hasExternalStorage() ||
11995         VDecl->isStaticDataMember()) {
11996       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11997         << VDecl->getDeclName() << Type;
11998       return QualType();
11999     }
12000   }
12001 
12002   ArrayRef<Expr*> DeduceInits;
12003   if (Init)
12004     DeduceInits = Init;
12005 
12006   if (DirectInit) {
12007     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12008       DeduceInits = PL->exprs();
12009   }
12010 
12011   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12012     assert(VDecl && "non-auto type for init capture deduction?");
12013     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12014     InitializationKind Kind = InitializationKind::CreateForInit(
12015         VDecl->getLocation(), DirectInit, Init);
12016     // FIXME: Initialization should not be taking a mutable list of inits.
12017     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12018     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12019                                                        InitsCopy);
12020   }
12021 
12022   if (DirectInit) {
12023     if (auto *IL = dyn_cast<InitListExpr>(Init))
12024       DeduceInits = IL->inits();
12025   }
12026 
12027   // Deduction only works if we have exactly one source expression.
12028   if (DeduceInits.empty()) {
12029     // It isn't possible to write this directly, but it is possible to
12030     // end up in this situation with "auto x(some_pack...);"
12031     Diag(Init->getBeginLoc(), IsInitCapture
12032                                   ? diag::err_init_capture_no_expression
12033                                   : diag::err_auto_var_init_no_expression)
12034         << VN << Type << Range;
12035     return QualType();
12036   }
12037 
12038   if (DeduceInits.size() > 1) {
12039     Diag(DeduceInits[1]->getBeginLoc(),
12040          IsInitCapture ? diag::err_init_capture_multiple_expressions
12041                        : diag::err_auto_var_init_multiple_expressions)
12042         << VN << Type << Range;
12043     return QualType();
12044   }
12045 
12046   Expr *DeduceInit = DeduceInits[0];
12047   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12048     Diag(Init->getBeginLoc(), IsInitCapture
12049                                   ? diag::err_init_capture_paren_braces
12050                                   : diag::err_auto_var_init_paren_braces)
12051         << isa<InitListExpr>(Init) << VN << Type << Range;
12052     return QualType();
12053   }
12054 
12055   // Expressions default to 'id' when we're in a debugger.
12056   bool DefaultedAnyToId = false;
12057   if (getLangOpts().DebuggerCastResultToId &&
12058       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12059     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12060     if (Result.isInvalid()) {
12061       return QualType();
12062     }
12063     Init = Result.get();
12064     DefaultedAnyToId = true;
12065   }
12066 
12067   // C++ [dcl.decomp]p1:
12068   //   If the assignment-expression [...] has array type A and no ref-qualifier
12069   //   is present, e has type cv A
12070   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12071       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12072       DeduceInit->getType()->isConstantArrayType())
12073     return Context.getQualifiedType(DeduceInit->getType(),
12074                                     Type.getQualifiers());
12075 
12076   QualType DeducedType;
12077   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12078     if (!IsInitCapture)
12079       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12080     else if (isa<InitListExpr>(Init))
12081       Diag(Range.getBegin(),
12082            diag::err_init_capture_deduction_failure_from_init_list)
12083           << VN
12084           << (DeduceInit->getType().isNull() ? TSI->getType()
12085                                              : DeduceInit->getType())
12086           << DeduceInit->getSourceRange();
12087     else
12088       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12089           << VN << TSI->getType()
12090           << (DeduceInit->getType().isNull() ? TSI->getType()
12091                                              : DeduceInit->getType())
12092           << DeduceInit->getSourceRange();
12093   }
12094 
12095   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12096   // 'id' instead of a specific object type prevents most of our usual
12097   // checks.
12098   // We only want to warn outside of template instantiations, though:
12099   // inside a template, the 'id' could have come from a parameter.
12100   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12101       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12102     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12103     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12104   }
12105 
12106   return DeducedType;
12107 }
12108 
12109 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12110                                          Expr *Init) {
12111   assert(!Init || !Init->containsErrors());
12112   QualType DeducedType = deduceVarTypeFromInitializer(
12113       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12114       VDecl->getSourceRange(), DirectInit, Init);
12115   if (DeducedType.isNull()) {
12116     VDecl->setInvalidDecl();
12117     return true;
12118   }
12119 
12120   VDecl->setType(DeducedType);
12121   assert(VDecl->isLinkageValid());
12122 
12123   // In ARC, infer lifetime.
12124   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12125     VDecl->setInvalidDecl();
12126 
12127   if (getLangOpts().OpenCL)
12128     deduceOpenCLAddressSpace(VDecl);
12129 
12130   // If this is a redeclaration, check that the type we just deduced matches
12131   // the previously declared type.
12132   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12133     // We never need to merge the type, because we cannot form an incomplete
12134     // array of auto, nor deduce such a type.
12135     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12136   }
12137 
12138   // Check the deduced type is valid for a variable declaration.
12139   CheckVariableDeclarationType(VDecl);
12140   return VDecl->isInvalidDecl();
12141 }
12142 
12143 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12144                                               SourceLocation Loc) {
12145   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12146     Init = EWC->getSubExpr();
12147 
12148   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12149     Init = CE->getSubExpr();
12150 
12151   QualType InitType = Init->getType();
12152   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12153           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12154          "shouldn't be called if type doesn't have a non-trivial C struct");
12155   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12156     for (auto I : ILE->inits()) {
12157       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12158           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12159         continue;
12160       SourceLocation SL = I->getExprLoc();
12161       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12162     }
12163     return;
12164   }
12165 
12166   if (isa<ImplicitValueInitExpr>(Init)) {
12167     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12168       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12169                             NTCUK_Init);
12170   } else {
12171     // Assume all other explicit initializers involving copying some existing
12172     // object.
12173     // TODO: ignore any explicit initializers where we can guarantee
12174     // copy-elision.
12175     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12176       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12177   }
12178 }
12179 
12180 namespace {
12181 
12182 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12183   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12184   // in the source code or implicitly by the compiler if it is in a union
12185   // defined in a system header and has non-trivial ObjC ownership
12186   // qualifications. We don't want those fields to participate in determining
12187   // whether the containing union is non-trivial.
12188   return FD->hasAttr<UnavailableAttr>();
12189 }
12190 
12191 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12192     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12193                                     void> {
12194   using Super =
12195       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12196                                     void>;
12197 
12198   DiagNonTrivalCUnionDefaultInitializeVisitor(
12199       QualType OrigTy, SourceLocation OrigLoc,
12200       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12201       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12202 
12203   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12204                      const FieldDecl *FD, bool InNonTrivialUnion) {
12205     if (const auto *AT = S.Context.getAsArrayType(QT))
12206       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12207                                      InNonTrivialUnion);
12208     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12209   }
12210 
12211   void visitARCStrong(QualType QT, const FieldDecl *FD,
12212                       bool InNonTrivialUnion) {
12213     if (InNonTrivialUnion)
12214       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12215           << 1 << 0 << QT << FD->getName();
12216   }
12217 
12218   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12219     if (InNonTrivialUnion)
12220       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12221           << 1 << 0 << QT << FD->getName();
12222   }
12223 
12224   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12225     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12226     if (RD->isUnion()) {
12227       if (OrigLoc.isValid()) {
12228         bool IsUnion = false;
12229         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12230           IsUnion = OrigRD->isUnion();
12231         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12232             << 0 << OrigTy << IsUnion << UseContext;
12233         // Reset OrigLoc so that this diagnostic is emitted only once.
12234         OrigLoc = SourceLocation();
12235       }
12236       InNonTrivialUnion = true;
12237     }
12238 
12239     if (InNonTrivialUnion)
12240       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12241           << 0 << 0 << QT.getUnqualifiedType() << "";
12242 
12243     for (const FieldDecl *FD : RD->fields())
12244       if (!shouldIgnoreForRecordTriviality(FD))
12245         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12246   }
12247 
12248   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12249 
12250   // The non-trivial C union type or the struct/union type that contains a
12251   // non-trivial C union.
12252   QualType OrigTy;
12253   SourceLocation OrigLoc;
12254   Sema::NonTrivialCUnionContext UseContext;
12255   Sema &S;
12256 };
12257 
12258 struct DiagNonTrivalCUnionDestructedTypeVisitor
12259     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12260   using Super =
12261       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12262 
12263   DiagNonTrivalCUnionDestructedTypeVisitor(
12264       QualType OrigTy, SourceLocation OrigLoc,
12265       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12266       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12267 
12268   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12269                      const FieldDecl *FD, bool InNonTrivialUnion) {
12270     if (const auto *AT = S.Context.getAsArrayType(QT))
12271       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12272                                      InNonTrivialUnion);
12273     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12274   }
12275 
12276   void visitARCStrong(QualType QT, const FieldDecl *FD,
12277                       bool InNonTrivialUnion) {
12278     if (InNonTrivialUnion)
12279       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12280           << 1 << 1 << QT << FD->getName();
12281   }
12282 
12283   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12284     if (InNonTrivialUnion)
12285       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12286           << 1 << 1 << QT << FD->getName();
12287   }
12288 
12289   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12290     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12291     if (RD->isUnion()) {
12292       if (OrigLoc.isValid()) {
12293         bool IsUnion = false;
12294         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12295           IsUnion = OrigRD->isUnion();
12296         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12297             << 1 << OrigTy << IsUnion << UseContext;
12298         // Reset OrigLoc so that this diagnostic is emitted only once.
12299         OrigLoc = SourceLocation();
12300       }
12301       InNonTrivialUnion = true;
12302     }
12303 
12304     if (InNonTrivialUnion)
12305       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12306           << 0 << 1 << QT.getUnqualifiedType() << "";
12307 
12308     for (const FieldDecl *FD : RD->fields())
12309       if (!shouldIgnoreForRecordTriviality(FD))
12310         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12311   }
12312 
12313   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12314   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12315                           bool InNonTrivialUnion) {}
12316 
12317   // The non-trivial C union type or the struct/union type that contains a
12318   // non-trivial C union.
12319   QualType OrigTy;
12320   SourceLocation OrigLoc;
12321   Sema::NonTrivialCUnionContext UseContext;
12322   Sema &S;
12323 };
12324 
12325 struct DiagNonTrivalCUnionCopyVisitor
12326     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12327   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12328 
12329   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12330                                  Sema::NonTrivialCUnionContext UseContext,
12331                                  Sema &S)
12332       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12333 
12334   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12335                      const FieldDecl *FD, bool InNonTrivialUnion) {
12336     if (const auto *AT = S.Context.getAsArrayType(QT))
12337       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12338                                      InNonTrivialUnion);
12339     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12340   }
12341 
12342   void visitARCStrong(QualType QT, const FieldDecl *FD,
12343                       bool InNonTrivialUnion) {
12344     if (InNonTrivialUnion)
12345       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12346           << 1 << 2 << QT << FD->getName();
12347   }
12348 
12349   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12350     if (InNonTrivialUnion)
12351       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12352           << 1 << 2 << QT << FD->getName();
12353   }
12354 
12355   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12356     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12357     if (RD->isUnion()) {
12358       if (OrigLoc.isValid()) {
12359         bool IsUnion = false;
12360         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12361           IsUnion = OrigRD->isUnion();
12362         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12363             << 2 << OrigTy << IsUnion << UseContext;
12364         // Reset OrigLoc so that this diagnostic is emitted only once.
12365         OrigLoc = SourceLocation();
12366       }
12367       InNonTrivialUnion = true;
12368     }
12369 
12370     if (InNonTrivialUnion)
12371       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12372           << 0 << 2 << QT.getUnqualifiedType() << "";
12373 
12374     for (const FieldDecl *FD : RD->fields())
12375       if (!shouldIgnoreForRecordTriviality(FD))
12376         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12377   }
12378 
12379   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12380                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12381   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12382   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12383                             bool InNonTrivialUnion) {}
12384 
12385   // The non-trivial C union type or the struct/union type that contains a
12386   // non-trivial C union.
12387   QualType OrigTy;
12388   SourceLocation OrigLoc;
12389   Sema::NonTrivialCUnionContext UseContext;
12390   Sema &S;
12391 };
12392 
12393 } // namespace
12394 
12395 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12396                                  NonTrivialCUnionContext UseContext,
12397                                  unsigned NonTrivialKind) {
12398   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12399           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12400           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12401          "shouldn't be called if type doesn't have a non-trivial C union");
12402 
12403   if ((NonTrivialKind & NTCUK_Init) &&
12404       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12405     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12406         .visit(QT, nullptr, false);
12407   if ((NonTrivialKind & NTCUK_Destruct) &&
12408       QT.hasNonTrivialToPrimitiveDestructCUnion())
12409     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12410         .visit(QT, nullptr, false);
12411   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12412     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12413         .visit(QT, nullptr, false);
12414 }
12415 
12416 /// AddInitializerToDecl - Adds the initializer Init to the
12417 /// declaration dcl. If DirectInit is true, this is C++ direct
12418 /// initialization rather than copy initialization.
12419 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12420   // If there is no declaration, there was an error parsing it.  Just ignore
12421   // the initializer.
12422   if (!RealDecl || RealDecl->isInvalidDecl()) {
12423     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12424     return;
12425   }
12426 
12427   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12428     // Pure-specifiers are handled in ActOnPureSpecifier.
12429     Diag(Method->getLocation(), diag::err_member_function_initialization)
12430       << Method->getDeclName() << Init->getSourceRange();
12431     Method->setInvalidDecl();
12432     return;
12433   }
12434 
12435   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12436   if (!VDecl) {
12437     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12438     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12439     RealDecl->setInvalidDecl();
12440     return;
12441   }
12442 
12443   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12444   if (VDecl->getType()->isUndeducedType()) {
12445     // Attempt typo correction early so that the type of the init expression can
12446     // be deduced based on the chosen correction if the original init contains a
12447     // TypoExpr.
12448     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12449     if (!Res.isUsable()) {
12450       // There are unresolved typos in Init, just drop them.
12451       // FIXME: improve the recovery strategy to preserve the Init.
12452       RealDecl->setInvalidDecl();
12453       return;
12454     }
12455     if (Res.get()->containsErrors()) {
12456       // Invalidate the decl as we don't know the type for recovery-expr yet.
12457       RealDecl->setInvalidDecl();
12458       VDecl->setInit(Res.get());
12459       return;
12460     }
12461     Init = Res.get();
12462 
12463     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12464       return;
12465   }
12466 
12467   // dllimport cannot be used on variable definitions.
12468   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12469     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12470     VDecl->setInvalidDecl();
12471     return;
12472   }
12473 
12474   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12475     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12476     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12477     VDecl->setInvalidDecl();
12478     return;
12479   }
12480 
12481   if (!VDecl->getType()->isDependentType()) {
12482     // A definition must end up with a complete type, which means it must be
12483     // complete with the restriction that an array type might be completed by
12484     // the initializer; note that later code assumes this restriction.
12485     QualType BaseDeclType = VDecl->getType();
12486     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12487       BaseDeclType = Array->getElementType();
12488     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12489                             diag::err_typecheck_decl_incomplete_type)) {
12490       RealDecl->setInvalidDecl();
12491       return;
12492     }
12493 
12494     // The variable can not have an abstract class type.
12495     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12496                                diag::err_abstract_type_in_decl,
12497                                AbstractVariableType))
12498       VDecl->setInvalidDecl();
12499   }
12500 
12501   // If adding the initializer will turn this declaration into a definition,
12502   // and we already have a definition for this variable, diagnose or otherwise
12503   // handle the situation.
12504   if (VarDecl *Def = VDecl->getDefinition())
12505     if (Def != VDecl &&
12506         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12507         !VDecl->isThisDeclarationADemotedDefinition() &&
12508         checkVarDeclRedefinition(Def, VDecl))
12509       return;
12510 
12511   if (getLangOpts().CPlusPlus) {
12512     // C++ [class.static.data]p4
12513     //   If a static data member is of const integral or const
12514     //   enumeration type, its declaration in the class definition can
12515     //   specify a constant-initializer which shall be an integral
12516     //   constant expression (5.19). In that case, the member can appear
12517     //   in integral constant expressions. The member shall still be
12518     //   defined in a namespace scope if it is used in the program and the
12519     //   namespace scope definition shall not contain an initializer.
12520     //
12521     // We already performed a redefinition check above, but for static
12522     // data members we also need to check whether there was an in-class
12523     // declaration with an initializer.
12524     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12525       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12526           << VDecl->getDeclName();
12527       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12528            diag::note_previous_initializer)
12529           << 0;
12530       return;
12531     }
12532 
12533     if (VDecl->hasLocalStorage())
12534       setFunctionHasBranchProtectedScope();
12535 
12536     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12537       VDecl->setInvalidDecl();
12538       return;
12539     }
12540   }
12541 
12542   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12543   // a kernel function cannot be initialized."
12544   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12545     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12546     VDecl->setInvalidDecl();
12547     return;
12548   }
12549 
12550   // The LoaderUninitialized attribute acts as a definition (of undef).
12551   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12552     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12553     VDecl->setInvalidDecl();
12554     return;
12555   }
12556 
12557   // Get the decls type and save a reference for later, since
12558   // CheckInitializerTypes may change it.
12559   QualType DclT = VDecl->getType(), SavT = DclT;
12560 
12561   // Expressions default to 'id' when we're in a debugger
12562   // and we are assigning it to a variable of Objective-C pointer type.
12563   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12564       Init->getType() == Context.UnknownAnyTy) {
12565     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12566     if (Result.isInvalid()) {
12567       VDecl->setInvalidDecl();
12568       return;
12569     }
12570     Init = Result.get();
12571   }
12572 
12573   // Perform the initialization.
12574   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12575   if (!VDecl->isInvalidDecl()) {
12576     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12577     InitializationKind Kind = InitializationKind::CreateForInit(
12578         VDecl->getLocation(), DirectInit, Init);
12579 
12580     MultiExprArg Args = Init;
12581     if (CXXDirectInit)
12582       Args = MultiExprArg(CXXDirectInit->getExprs(),
12583                           CXXDirectInit->getNumExprs());
12584 
12585     // Try to correct any TypoExprs in the initialization arguments.
12586     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12587       ExprResult Res = CorrectDelayedTyposInExpr(
12588           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12589           [this, Entity, Kind](Expr *E) {
12590             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12591             return Init.Failed() ? ExprError() : E;
12592           });
12593       if (Res.isInvalid()) {
12594         VDecl->setInvalidDecl();
12595       } else if (Res.get() != Args[Idx]) {
12596         Args[Idx] = Res.get();
12597       }
12598     }
12599     if (VDecl->isInvalidDecl())
12600       return;
12601 
12602     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12603                                    /*TopLevelOfInitList=*/false,
12604                                    /*TreatUnavailableAsInvalid=*/false);
12605     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12606     if (Result.isInvalid()) {
12607       // If the provided initializer fails to initialize the var decl,
12608       // we attach a recovery expr for better recovery.
12609       auto RecoveryExpr =
12610           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12611       if (RecoveryExpr.get())
12612         VDecl->setInit(RecoveryExpr.get());
12613       return;
12614     }
12615 
12616     Init = Result.getAs<Expr>();
12617   }
12618 
12619   // Check for self-references within variable initializers.
12620   // Variables declared within a function/method body (except for references)
12621   // are handled by a dataflow analysis.
12622   // This is undefined behavior in C++, but valid in C.
12623   if (getLangOpts().CPlusPlus)
12624     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12625         VDecl->getType()->isReferenceType())
12626       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12627 
12628   // If the type changed, it means we had an incomplete type that was
12629   // completed by the initializer. For example:
12630   //   int ary[] = { 1, 3, 5 };
12631   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12632   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12633     VDecl->setType(DclT);
12634 
12635   if (!VDecl->isInvalidDecl()) {
12636     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12637 
12638     if (VDecl->hasAttr<BlocksAttr>())
12639       checkRetainCycles(VDecl, Init);
12640 
12641     // It is safe to assign a weak reference into a strong variable.
12642     // Although this code can still have problems:
12643     //   id x = self.weakProp;
12644     //   id y = self.weakProp;
12645     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12646     // paths through the function. This should be revisited if
12647     // -Wrepeated-use-of-weak is made flow-sensitive.
12648     if (FunctionScopeInfo *FSI = getCurFunction())
12649       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12650            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12651           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12652                            Init->getBeginLoc()))
12653         FSI->markSafeWeakUse(Init);
12654   }
12655 
12656   // The initialization is usually a full-expression.
12657   //
12658   // FIXME: If this is a braced initialization of an aggregate, it is not
12659   // an expression, and each individual field initializer is a separate
12660   // full-expression. For instance, in:
12661   //
12662   //   struct Temp { ~Temp(); };
12663   //   struct S { S(Temp); };
12664   //   struct T { S a, b; } t = { Temp(), Temp() }
12665   //
12666   // we should destroy the first Temp before constructing the second.
12667   ExprResult Result =
12668       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12669                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12670   if (Result.isInvalid()) {
12671     VDecl->setInvalidDecl();
12672     return;
12673   }
12674   Init = Result.get();
12675 
12676   // Attach the initializer to the decl.
12677   VDecl->setInit(Init);
12678 
12679   if (VDecl->isLocalVarDecl()) {
12680     // Don't check the initializer if the declaration is malformed.
12681     if (VDecl->isInvalidDecl()) {
12682       // do nothing
12683 
12684     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12685     // This is true even in C++ for OpenCL.
12686     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12687       CheckForConstantInitializer(Init, DclT);
12688 
12689     // Otherwise, C++ does not restrict the initializer.
12690     } else if (getLangOpts().CPlusPlus) {
12691       // do nothing
12692 
12693     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12694     // static storage duration shall be constant expressions or string literals.
12695     } else if (VDecl->getStorageClass() == SC_Static) {
12696       CheckForConstantInitializer(Init, DclT);
12697 
12698     // C89 is stricter than C99 for aggregate initializers.
12699     // C89 6.5.7p3: All the expressions [...] in an initializer list
12700     // for an object that has aggregate or union type shall be
12701     // constant expressions.
12702     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12703                isa<InitListExpr>(Init)) {
12704       const Expr *Culprit;
12705       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12706         Diag(Culprit->getExprLoc(),
12707              diag::ext_aggregate_init_not_constant)
12708           << Culprit->getSourceRange();
12709       }
12710     }
12711 
12712     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12713       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12714         if (VDecl->hasLocalStorage())
12715           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12716   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12717              VDecl->getLexicalDeclContext()->isRecord()) {
12718     // This is an in-class initialization for a static data member, e.g.,
12719     //
12720     // struct S {
12721     //   static const int value = 17;
12722     // };
12723 
12724     // C++ [class.mem]p4:
12725     //   A member-declarator can contain a constant-initializer only
12726     //   if it declares a static member (9.4) of const integral or
12727     //   const enumeration type, see 9.4.2.
12728     //
12729     // C++11 [class.static.data]p3:
12730     //   If a non-volatile non-inline const static data member is of integral
12731     //   or enumeration type, its declaration in the class definition can
12732     //   specify a brace-or-equal-initializer in which every initializer-clause
12733     //   that is an assignment-expression is a constant expression. A static
12734     //   data member of literal type can be declared in the class definition
12735     //   with the constexpr specifier; if so, its declaration shall specify a
12736     //   brace-or-equal-initializer in which every initializer-clause that is
12737     //   an assignment-expression is a constant expression.
12738 
12739     // Do nothing on dependent types.
12740     if (DclT->isDependentType()) {
12741 
12742     // Allow any 'static constexpr' members, whether or not they are of literal
12743     // type. We separately check that every constexpr variable is of literal
12744     // type.
12745     } else if (VDecl->isConstexpr()) {
12746 
12747     // Require constness.
12748     } else if (!DclT.isConstQualified()) {
12749       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12750         << Init->getSourceRange();
12751       VDecl->setInvalidDecl();
12752 
12753     // We allow integer constant expressions in all cases.
12754     } else if (DclT->isIntegralOrEnumerationType()) {
12755       // Check whether the expression is a constant expression.
12756       SourceLocation Loc;
12757       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12758         // In C++11, a non-constexpr const static data member with an
12759         // in-class initializer cannot be volatile.
12760         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12761       else if (Init->isValueDependent())
12762         ; // Nothing to check.
12763       else if (Init->isIntegerConstantExpr(Context, &Loc))
12764         ; // Ok, it's an ICE!
12765       else if (Init->getType()->isScopedEnumeralType() &&
12766                Init->isCXX11ConstantExpr(Context))
12767         ; // Ok, it is a scoped-enum constant expression.
12768       else if (Init->isEvaluatable(Context)) {
12769         // If we can constant fold the initializer through heroics, accept it,
12770         // but report this as a use of an extension for -pedantic.
12771         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12772           << Init->getSourceRange();
12773       } else {
12774         // Otherwise, this is some crazy unknown case.  Report the issue at the
12775         // location provided by the isIntegerConstantExpr failed check.
12776         Diag(Loc, diag::err_in_class_initializer_non_constant)
12777           << Init->getSourceRange();
12778         VDecl->setInvalidDecl();
12779       }
12780 
12781     // We allow foldable floating-point constants as an extension.
12782     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12783       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12784       // it anyway and provide a fixit to add the 'constexpr'.
12785       if (getLangOpts().CPlusPlus11) {
12786         Diag(VDecl->getLocation(),
12787              diag::ext_in_class_initializer_float_type_cxx11)
12788             << DclT << Init->getSourceRange();
12789         Diag(VDecl->getBeginLoc(),
12790              diag::note_in_class_initializer_float_type_cxx11)
12791             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12792       } else {
12793         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12794           << DclT << Init->getSourceRange();
12795 
12796         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12797           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12798             << Init->getSourceRange();
12799           VDecl->setInvalidDecl();
12800         }
12801       }
12802 
12803     // Suggest adding 'constexpr' in C++11 for literal types.
12804     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12805       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12806           << DclT << Init->getSourceRange()
12807           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12808       VDecl->setConstexpr(true);
12809 
12810     } else {
12811       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12812         << DclT << Init->getSourceRange();
12813       VDecl->setInvalidDecl();
12814     }
12815   } else if (VDecl->isFileVarDecl()) {
12816     // In C, extern is typically used to avoid tentative definitions when
12817     // declaring variables in headers, but adding an intializer makes it a
12818     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12819     // In C++, extern is often used to give implictly static const variables
12820     // external linkage, so don't warn in that case. If selectany is present,
12821     // this might be header code intended for C and C++ inclusion, so apply the
12822     // C++ rules.
12823     if (VDecl->getStorageClass() == SC_Extern &&
12824         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12825          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12826         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12827         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12828       Diag(VDecl->getLocation(), diag::warn_extern_init);
12829 
12830     // In Microsoft C++ mode, a const variable defined in namespace scope has
12831     // external linkage by default if the variable is declared with
12832     // __declspec(dllexport).
12833     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12834         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12835         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12836       VDecl->setStorageClass(SC_Extern);
12837 
12838     // C99 6.7.8p4. All file scoped initializers need to be constant.
12839     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12840       CheckForConstantInitializer(Init, DclT);
12841   }
12842 
12843   QualType InitType = Init->getType();
12844   if (!InitType.isNull() &&
12845       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12846        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12847     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12848 
12849   // We will represent direct-initialization similarly to copy-initialization:
12850   //    int x(1);  -as-> int x = 1;
12851   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12852   //
12853   // Clients that want to distinguish between the two forms, can check for
12854   // direct initializer using VarDecl::getInitStyle().
12855   // A major benefit is that clients that don't particularly care about which
12856   // exactly form was it (like the CodeGen) can handle both cases without
12857   // special case code.
12858 
12859   // C++ 8.5p11:
12860   // The form of initialization (using parentheses or '=') is generally
12861   // insignificant, but does matter when the entity being initialized has a
12862   // class type.
12863   if (CXXDirectInit) {
12864     assert(DirectInit && "Call-style initializer must be direct init.");
12865     VDecl->setInitStyle(VarDecl::CallInit);
12866   } else if (DirectInit) {
12867     // This must be list-initialization. No other way is direct-initialization.
12868     VDecl->setInitStyle(VarDecl::ListInit);
12869   }
12870 
12871   if (LangOpts.OpenMP &&
12872       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12873       VDecl->isFileVarDecl())
12874     DeclsToCheckForDeferredDiags.insert(VDecl);
12875   CheckCompleteVariableDeclaration(VDecl);
12876 }
12877 
12878 /// ActOnInitializerError - Given that there was an error parsing an
12879 /// initializer for the given declaration, try to at least re-establish
12880 /// invariants such as whether a variable's type is either dependent or
12881 /// complete.
12882 void Sema::ActOnInitializerError(Decl *D) {
12883   // Our main concern here is re-establishing invariants like "a
12884   // variable's type is either dependent or complete".
12885   if (!D || D->isInvalidDecl()) return;
12886 
12887   VarDecl *VD = dyn_cast<VarDecl>(D);
12888   if (!VD) return;
12889 
12890   // Bindings are not usable if we can't make sense of the initializer.
12891   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12892     for (auto *BD : DD->bindings())
12893       BD->setInvalidDecl();
12894 
12895   // Auto types are meaningless if we can't make sense of the initializer.
12896   if (VD->getType()->isUndeducedType()) {
12897     D->setInvalidDecl();
12898     return;
12899   }
12900 
12901   QualType Ty = VD->getType();
12902   if (Ty->isDependentType()) return;
12903 
12904   // Require a complete type.
12905   if (RequireCompleteType(VD->getLocation(),
12906                           Context.getBaseElementType(Ty),
12907                           diag::err_typecheck_decl_incomplete_type)) {
12908     VD->setInvalidDecl();
12909     return;
12910   }
12911 
12912   // Require a non-abstract type.
12913   if (RequireNonAbstractType(VD->getLocation(), Ty,
12914                              diag::err_abstract_type_in_decl,
12915                              AbstractVariableType)) {
12916     VD->setInvalidDecl();
12917     return;
12918   }
12919 
12920   // Don't bother complaining about constructors or destructors,
12921   // though.
12922 }
12923 
12924 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12925   // If there is no declaration, there was an error parsing it. Just ignore it.
12926   if (!RealDecl)
12927     return;
12928 
12929   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12930     QualType Type = Var->getType();
12931 
12932     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12933     if (isa<DecompositionDecl>(RealDecl)) {
12934       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12935       Var->setInvalidDecl();
12936       return;
12937     }
12938 
12939     if (Type->isUndeducedType() &&
12940         DeduceVariableDeclarationType(Var, false, nullptr))
12941       return;
12942 
12943     // C++11 [class.static.data]p3: A static data member can be declared with
12944     // the constexpr specifier; if so, its declaration shall specify
12945     // a brace-or-equal-initializer.
12946     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12947     // the definition of a variable [...] or the declaration of a static data
12948     // member.
12949     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12950         !Var->isThisDeclarationADemotedDefinition()) {
12951       if (Var->isStaticDataMember()) {
12952         // C++1z removes the relevant rule; the in-class declaration is always
12953         // a definition there.
12954         if (!getLangOpts().CPlusPlus17 &&
12955             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12956           Diag(Var->getLocation(),
12957                diag::err_constexpr_static_mem_var_requires_init)
12958               << Var;
12959           Var->setInvalidDecl();
12960           return;
12961         }
12962       } else {
12963         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12964         Var->setInvalidDecl();
12965         return;
12966       }
12967     }
12968 
12969     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12970     // be initialized.
12971     if (!Var->isInvalidDecl() &&
12972         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12973         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12974       bool HasConstExprDefaultConstructor = false;
12975       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12976         for (auto *Ctor : RD->ctors()) {
12977           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12978               Ctor->getMethodQualifiers().getAddressSpace() ==
12979                   LangAS::opencl_constant) {
12980             HasConstExprDefaultConstructor = true;
12981           }
12982         }
12983       }
12984       if (!HasConstExprDefaultConstructor) {
12985         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12986         Var->setInvalidDecl();
12987         return;
12988       }
12989     }
12990 
12991     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12992       if (Var->getStorageClass() == SC_Extern) {
12993         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12994             << Var;
12995         Var->setInvalidDecl();
12996         return;
12997       }
12998       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12999                               diag::err_typecheck_decl_incomplete_type)) {
13000         Var->setInvalidDecl();
13001         return;
13002       }
13003       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13004         if (!RD->hasTrivialDefaultConstructor()) {
13005           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13006           Var->setInvalidDecl();
13007           return;
13008         }
13009       }
13010       // The declaration is unitialized, no need for further checks.
13011       return;
13012     }
13013 
13014     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13015     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13016         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13017       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13018                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13019 
13020 
13021     switch (DefKind) {
13022     case VarDecl::Definition:
13023       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13024         break;
13025 
13026       // We have an out-of-line definition of a static data member
13027       // that has an in-class initializer, so we type-check this like
13028       // a declaration.
13029       //
13030       LLVM_FALLTHROUGH;
13031 
13032     case VarDecl::DeclarationOnly:
13033       // It's only a declaration.
13034 
13035       // Block scope. C99 6.7p7: If an identifier for an object is
13036       // declared with no linkage (C99 6.2.2p6), the type for the
13037       // object shall be complete.
13038       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13039           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13040           RequireCompleteType(Var->getLocation(), Type,
13041                               diag::err_typecheck_decl_incomplete_type))
13042         Var->setInvalidDecl();
13043 
13044       // Make sure that the type is not abstract.
13045       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13046           RequireNonAbstractType(Var->getLocation(), Type,
13047                                  diag::err_abstract_type_in_decl,
13048                                  AbstractVariableType))
13049         Var->setInvalidDecl();
13050       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13051           Var->getStorageClass() == SC_PrivateExtern) {
13052         Diag(Var->getLocation(), diag::warn_private_extern);
13053         Diag(Var->getLocation(), diag::note_private_extern);
13054       }
13055 
13056       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13057           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13058         ExternalDeclarations.push_back(Var);
13059 
13060       return;
13061 
13062     case VarDecl::TentativeDefinition:
13063       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13064       // object that has file scope without an initializer, and without a
13065       // storage-class specifier or with the storage-class specifier "static",
13066       // constitutes a tentative definition. Note: A tentative definition with
13067       // external linkage is valid (C99 6.2.2p5).
13068       if (!Var->isInvalidDecl()) {
13069         if (const IncompleteArrayType *ArrayT
13070                                     = Context.getAsIncompleteArrayType(Type)) {
13071           if (RequireCompleteSizedType(
13072                   Var->getLocation(), ArrayT->getElementType(),
13073                   diag::err_array_incomplete_or_sizeless_type))
13074             Var->setInvalidDecl();
13075         } else if (Var->getStorageClass() == SC_Static) {
13076           // C99 6.9.2p3: If the declaration of an identifier for an object is
13077           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13078           // declared type shall not be an incomplete type.
13079           // NOTE: code such as the following
13080           //     static struct s;
13081           //     struct s { int a; };
13082           // is accepted by gcc. Hence here we issue a warning instead of
13083           // an error and we do not invalidate the static declaration.
13084           // NOTE: to avoid multiple warnings, only check the first declaration.
13085           if (Var->isFirstDecl())
13086             RequireCompleteType(Var->getLocation(), Type,
13087                                 diag::ext_typecheck_decl_incomplete_type);
13088         }
13089       }
13090 
13091       // Record the tentative definition; we're done.
13092       if (!Var->isInvalidDecl())
13093         TentativeDefinitions.push_back(Var);
13094       return;
13095     }
13096 
13097     // Provide a specific diagnostic for uninitialized variable
13098     // definitions with incomplete array type.
13099     if (Type->isIncompleteArrayType()) {
13100       Diag(Var->getLocation(),
13101            diag::err_typecheck_incomplete_array_needs_initializer);
13102       Var->setInvalidDecl();
13103       return;
13104     }
13105 
13106     // Provide a specific diagnostic for uninitialized variable
13107     // definitions with reference type.
13108     if (Type->isReferenceType()) {
13109       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13110           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13111       Var->setInvalidDecl();
13112       return;
13113     }
13114 
13115     // Do not attempt to type-check the default initializer for a
13116     // variable with dependent type.
13117     if (Type->isDependentType())
13118       return;
13119 
13120     if (Var->isInvalidDecl())
13121       return;
13122 
13123     if (!Var->hasAttr<AliasAttr>()) {
13124       if (RequireCompleteType(Var->getLocation(),
13125                               Context.getBaseElementType(Type),
13126                               diag::err_typecheck_decl_incomplete_type)) {
13127         Var->setInvalidDecl();
13128         return;
13129       }
13130     } else {
13131       return;
13132     }
13133 
13134     // The variable can not have an abstract class type.
13135     if (RequireNonAbstractType(Var->getLocation(), Type,
13136                                diag::err_abstract_type_in_decl,
13137                                AbstractVariableType)) {
13138       Var->setInvalidDecl();
13139       return;
13140     }
13141 
13142     // Check for jumps past the implicit initializer.  C++0x
13143     // clarifies that this applies to a "variable with automatic
13144     // storage duration", not a "local variable".
13145     // C++11 [stmt.dcl]p3
13146     //   A program that jumps from a point where a variable with automatic
13147     //   storage duration is not in scope to a point where it is in scope is
13148     //   ill-formed unless the variable has scalar type, class type with a
13149     //   trivial default constructor and a trivial destructor, a cv-qualified
13150     //   version of one of these types, or an array of one of the preceding
13151     //   types and is declared without an initializer.
13152     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13153       if (const RecordType *Record
13154             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13155         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13156         // Mark the function (if we're in one) for further checking even if the
13157         // looser rules of C++11 do not require such checks, so that we can
13158         // diagnose incompatibilities with C++98.
13159         if (!CXXRecord->isPOD())
13160           setFunctionHasBranchProtectedScope();
13161       }
13162     }
13163     // In OpenCL, we can't initialize objects in the __local address space,
13164     // even implicitly, so don't synthesize an implicit initializer.
13165     if (getLangOpts().OpenCL &&
13166         Var->getType().getAddressSpace() == LangAS::opencl_local)
13167       return;
13168     // C++03 [dcl.init]p9:
13169     //   If no initializer is specified for an object, and the
13170     //   object is of (possibly cv-qualified) non-POD class type (or
13171     //   array thereof), the object shall be default-initialized; if
13172     //   the object is of const-qualified type, the underlying class
13173     //   type shall have a user-declared default
13174     //   constructor. Otherwise, if no initializer is specified for
13175     //   a non- static object, the object and its subobjects, if
13176     //   any, have an indeterminate initial value); if the object
13177     //   or any of its subobjects are of const-qualified type, the
13178     //   program is ill-formed.
13179     // C++0x [dcl.init]p11:
13180     //   If no initializer is specified for an object, the object is
13181     //   default-initialized; [...].
13182     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13183     InitializationKind Kind
13184       = InitializationKind::CreateDefault(Var->getLocation());
13185 
13186     InitializationSequence InitSeq(*this, Entity, Kind, None);
13187     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13188 
13189     if (Init.get()) {
13190       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13191       // This is important for template substitution.
13192       Var->setInitStyle(VarDecl::CallInit);
13193     } else if (Init.isInvalid()) {
13194       // If default-init fails, attach a recovery-expr initializer to track
13195       // that initialization was attempted and failed.
13196       auto RecoveryExpr =
13197           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13198       if (RecoveryExpr.get())
13199         Var->setInit(RecoveryExpr.get());
13200     }
13201 
13202     CheckCompleteVariableDeclaration(Var);
13203   }
13204 }
13205 
13206 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13207   // If there is no declaration, there was an error parsing it. Ignore it.
13208   if (!D)
13209     return;
13210 
13211   VarDecl *VD = dyn_cast<VarDecl>(D);
13212   if (!VD) {
13213     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13214     D->setInvalidDecl();
13215     return;
13216   }
13217 
13218   VD->setCXXForRangeDecl(true);
13219 
13220   // for-range-declaration cannot be given a storage class specifier.
13221   int Error = -1;
13222   switch (VD->getStorageClass()) {
13223   case SC_None:
13224     break;
13225   case SC_Extern:
13226     Error = 0;
13227     break;
13228   case SC_Static:
13229     Error = 1;
13230     break;
13231   case SC_PrivateExtern:
13232     Error = 2;
13233     break;
13234   case SC_Auto:
13235     Error = 3;
13236     break;
13237   case SC_Register:
13238     Error = 4;
13239     break;
13240   }
13241 
13242   // for-range-declaration cannot be given a storage class specifier con't.
13243   switch (VD->getTSCSpec()) {
13244   case TSCS_thread_local:
13245     Error = 6;
13246     break;
13247   case TSCS___thread:
13248   case TSCS__Thread_local:
13249   case TSCS_unspecified:
13250     break;
13251   }
13252 
13253   if (Error != -1) {
13254     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13255         << VD << Error;
13256     D->setInvalidDecl();
13257   }
13258 }
13259 
13260 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13261                                             IdentifierInfo *Ident,
13262                                             ParsedAttributes &Attrs) {
13263   // C++1y [stmt.iter]p1:
13264   //   A range-based for statement of the form
13265   //      for ( for-range-identifier : for-range-initializer ) statement
13266   //   is equivalent to
13267   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13268   DeclSpec DS(Attrs.getPool().getFactory());
13269 
13270   const char *PrevSpec;
13271   unsigned DiagID;
13272   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13273                      getPrintingPolicy());
13274 
13275   Declarator D(DS, DeclaratorContext::ForInit);
13276   D.SetIdentifier(Ident, IdentLoc);
13277   D.takeAttributes(Attrs);
13278 
13279   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13280                 IdentLoc);
13281   Decl *Var = ActOnDeclarator(S, D);
13282   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13283   FinalizeDeclaration(Var);
13284   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13285                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13286                                                       : IdentLoc);
13287 }
13288 
13289 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13290   if (var->isInvalidDecl()) return;
13291 
13292   MaybeAddCUDAConstantAttr(var);
13293 
13294   if (getLangOpts().OpenCL) {
13295     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13296     // initialiser
13297     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13298         !var->hasInit()) {
13299       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13300           << 1 /*Init*/;
13301       var->setInvalidDecl();
13302       return;
13303     }
13304   }
13305 
13306   // In Objective-C, don't allow jumps past the implicit initialization of a
13307   // local retaining variable.
13308   if (getLangOpts().ObjC &&
13309       var->hasLocalStorage()) {
13310     switch (var->getType().getObjCLifetime()) {
13311     case Qualifiers::OCL_None:
13312     case Qualifiers::OCL_ExplicitNone:
13313     case Qualifiers::OCL_Autoreleasing:
13314       break;
13315 
13316     case Qualifiers::OCL_Weak:
13317     case Qualifiers::OCL_Strong:
13318       setFunctionHasBranchProtectedScope();
13319       break;
13320     }
13321   }
13322 
13323   if (var->hasLocalStorage() &&
13324       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13325     setFunctionHasBranchProtectedScope();
13326 
13327   // Warn about externally-visible variables being defined without a
13328   // prior declaration.  We only want to do this for global
13329   // declarations, but we also specifically need to avoid doing it for
13330   // class members because the linkage of an anonymous class can
13331   // change if it's later given a typedef name.
13332   if (var->isThisDeclarationADefinition() &&
13333       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13334       var->isExternallyVisible() && var->hasLinkage() &&
13335       !var->isInline() && !var->getDescribedVarTemplate() &&
13336       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13337       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13338       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13339                                   var->getLocation())) {
13340     // Find a previous declaration that's not a definition.
13341     VarDecl *prev = var->getPreviousDecl();
13342     while (prev && prev->isThisDeclarationADefinition())
13343       prev = prev->getPreviousDecl();
13344 
13345     if (!prev) {
13346       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13347       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13348           << /* variable */ 0;
13349     }
13350   }
13351 
13352   // Cache the result of checking for constant initialization.
13353   Optional<bool> CacheHasConstInit;
13354   const Expr *CacheCulprit = nullptr;
13355   auto checkConstInit = [&]() mutable {
13356     if (!CacheHasConstInit)
13357       CacheHasConstInit = var->getInit()->isConstantInitializer(
13358             Context, var->getType()->isReferenceType(), &CacheCulprit);
13359     return *CacheHasConstInit;
13360   };
13361 
13362   if (var->getTLSKind() == VarDecl::TLS_Static) {
13363     if (var->getType().isDestructedType()) {
13364       // GNU C++98 edits for __thread, [basic.start.term]p3:
13365       //   The type of an object with thread storage duration shall not
13366       //   have a non-trivial destructor.
13367       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13368       if (getLangOpts().CPlusPlus11)
13369         Diag(var->getLocation(), diag::note_use_thread_local);
13370     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13371       if (!checkConstInit()) {
13372         // GNU C++98 edits for __thread, [basic.start.init]p4:
13373         //   An object of thread storage duration shall not require dynamic
13374         //   initialization.
13375         // FIXME: Need strict checking here.
13376         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13377           << CacheCulprit->getSourceRange();
13378         if (getLangOpts().CPlusPlus11)
13379           Diag(var->getLocation(), diag::note_use_thread_local);
13380       }
13381     }
13382   }
13383 
13384 
13385   if (!var->getType()->isStructureType() && var->hasInit() &&
13386       isa<InitListExpr>(var->getInit())) {
13387     const auto *ILE = cast<InitListExpr>(var->getInit());
13388     unsigned NumInits = ILE->getNumInits();
13389     if (NumInits > 2)
13390       for (unsigned I = 0; I < NumInits; ++I) {
13391         const auto *Init = ILE->getInit(I);
13392         if (!Init)
13393           break;
13394         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13395         if (!SL)
13396           break;
13397 
13398         unsigned NumConcat = SL->getNumConcatenated();
13399         // Diagnose missing comma in string array initialization.
13400         // Do not warn when all the elements in the initializer are concatenated
13401         // together. Do not warn for macros too.
13402         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13403           bool OnlyOneMissingComma = true;
13404           for (unsigned J = I + 1; J < NumInits; ++J) {
13405             const auto *Init = ILE->getInit(J);
13406             if (!Init)
13407               break;
13408             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13409             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13410               OnlyOneMissingComma = false;
13411               break;
13412             }
13413           }
13414 
13415           if (OnlyOneMissingComma) {
13416             SmallVector<FixItHint, 1> Hints;
13417             for (unsigned i = 0; i < NumConcat - 1; ++i)
13418               Hints.push_back(FixItHint::CreateInsertion(
13419                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13420 
13421             Diag(SL->getStrTokenLoc(1),
13422                  diag::warn_concatenated_literal_array_init)
13423                 << Hints;
13424             Diag(SL->getBeginLoc(),
13425                  diag::note_concatenated_string_literal_silence);
13426           }
13427           // In any case, stop now.
13428           break;
13429         }
13430       }
13431   }
13432 
13433 
13434   QualType type = var->getType();
13435 
13436   if (var->hasAttr<BlocksAttr>())
13437     getCurFunction()->addByrefBlockVar(var);
13438 
13439   Expr *Init = var->getInit();
13440   bool GlobalStorage = var->hasGlobalStorage();
13441   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13442   QualType baseType = Context.getBaseElementType(type);
13443   bool HasConstInit = true;
13444 
13445   // Check whether the initializer is sufficiently constant.
13446   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13447       !Init->isValueDependent() &&
13448       (GlobalStorage || var->isConstexpr() ||
13449        var->mightBeUsableInConstantExpressions(Context))) {
13450     // If this variable might have a constant initializer or might be usable in
13451     // constant expressions, check whether or not it actually is now.  We can't
13452     // do this lazily, because the result might depend on things that change
13453     // later, such as which constexpr functions happen to be defined.
13454     SmallVector<PartialDiagnosticAt, 8> Notes;
13455     if (!getLangOpts().CPlusPlus11) {
13456       // Prior to C++11, in contexts where a constant initializer is required,
13457       // the set of valid constant initializers is described by syntactic rules
13458       // in [expr.const]p2-6.
13459       // FIXME: Stricter checking for these rules would be useful for constinit /
13460       // -Wglobal-constructors.
13461       HasConstInit = checkConstInit();
13462 
13463       // Compute and cache the constant value, and remember that we have a
13464       // constant initializer.
13465       if (HasConstInit) {
13466         (void)var->checkForConstantInitialization(Notes);
13467         Notes.clear();
13468       } else if (CacheCulprit) {
13469         Notes.emplace_back(CacheCulprit->getExprLoc(),
13470                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13471         Notes.back().second << CacheCulprit->getSourceRange();
13472       }
13473     } else {
13474       // Evaluate the initializer to see if it's a constant initializer.
13475       HasConstInit = var->checkForConstantInitialization(Notes);
13476     }
13477 
13478     if (HasConstInit) {
13479       // FIXME: Consider replacing the initializer with a ConstantExpr.
13480     } else if (var->isConstexpr()) {
13481       SourceLocation DiagLoc = var->getLocation();
13482       // If the note doesn't add any useful information other than a source
13483       // location, fold it into the primary diagnostic.
13484       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13485                                    diag::note_invalid_subexpr_in_const_expr) {
13486         DiagLoc = Notes[0].first;
13487         Notes.clear();
13488       }
13489       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13490           << var << Init->getSourceRange();
13491       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13492         Diag(Notes[I].first, Notes[I].second);
13493     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13494       auto *Attr = var->getAttr<ConstInitAttr>();
13495       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13496           << Init->getSourceRange();
13497       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13498           << Attr->getRange() << Attr->isConstinit();
13499       for (auto &it : Notes)
13500         Diag(it.first, it.second);
13501     } else if (IsGlobal &&
13502                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13503                                            var->getLocation())) {
13504       // Warn about globals which don't have a constant initializer.  Don't
13505       // warn about globals with a non-trivial destructor because we already
13506       // warned about them.
13507       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13508       if (!(RD && !RD->hasTrivialDestructor())) {
13509         // checkConstInit() here permits trivial default initialization even in
13510         // C++11 onwards, where such an initializer is not a constant initializer
13511         // but nonetheless doesn't require a global constructor.
13512         if (!checkConstInit())
13513           Diag(var->getLocation(), diag::warn_global_constructor)
13514               << Init->getSourceRange();
13515       }
13516     }
13517   }
13518 
13519   // Apply section attributes and pragmas to global variables.
13520   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13521       !inTemplateInstantiation()) {
13522     PragmaStack<StringLiteral *> *Stack = nullptr;
13523     int SectionFlags = ASTContext::PSF_Read;
13524     if (var->getType().isConstQualified()) {
13525       if (HasConstInit)
13526         Stack = &ConstSegStack;
13527       else {
13528         Stack = &BSSSegStack;
13529         SectionFlags |= ASTContext::PSF_Write;
13530       }
13531     } else if (var->hasInit() && HasConstInit) {
13532       Stack = &DataSegStack;
13533       SectionFlags |= ASTContext::PSF_Write;
13534     } else {
13535       Stack = &BSSSegStack;
13536       SectionFlags |= ASTContext::PSF_Write;
13537     }
13538     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13539       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13540         SectionFlags |= ASTContext::PSF_Implicit;
13541       UnifySection(SA->getName(), SectionFlags, var);
13542     } else if (Stack->CurrentValue) {
13543       SectionFlags |= ASTContext::PSF_Implicit;
13544       auto SectionName = Stack->CurrentValue->getString();
13545       var->addAttr(SectionAttr::CreateImplicit(
13546           Context, SectionName, Stack->CurrentPragmaLocation,
13547           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13548       if (UnifySection(SectionName, SectionFlags, var))
13549         var->dropAttr<SectionAttr>();
13550     }
13551 
13552     // Apply the init_seg attribute if this has an initializer.  If the
13553     // initializer turns out to not be dynamic, we'll end up ignoring this
13554     // attribute.
13555     if (CurInitSeg && var->getInit())
13556       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13557                                                CurInitSegLoc,
13558                                                AttributeCommonInfo::AS_Pragma));
13559   }
13560 
13561   // All the following checks are C++ only.
13562   if (!getLangOpts().CPlusPlus) {
13563     // If this variable must be emitted, add it as an initializer for the
13564     // current module.
13565     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13566       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13567     return;
13568   }
13569 
13570   // Require the destructor.
13571   if (!type->isDependentType())
13572     if (const RecordType *recordType = baseType->getAs<RecordType>())
13573       FinalizeVarWithDestructor(var, recordType);
13574 
13575   // If this variable must be emitted, add it as an initializer for the current
13576   // module.
13577   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13578     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13579 
13580   // Build the bindings if this is a structured binding declaration.
13581   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13582     CheckCompleteDecompositionDeclaration(DD);
13583 }
13584 
13585 /// Check if VD needs to be dllexport/dllimport due to being in a
13586 /// dllexport/import function.
13587 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13588   assert(VD->isStaticLocal());
13589 
13590   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13591 
13592   // Find outermost function when VD is in lambda function.
13593   while (FD && !getDLLAttr(FD) &&
13594          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13595          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13596     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13597   }
13598 
13599   if (!FD)
13600     return;
13601 
13602   // Static locals inherit dll attributes from their function.
13603   if (Attr *A = getDLLAttr(FD)) {
13604     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13605     NewAttr->setInherited(true);
13606     VD->addAttr(NewAttr);
13607   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13608     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13609     NewAttr->setInherited(true);
13610     VD->addAttr(NewAttr);
13611 
13612     // Export this function to enforce exporting this static variable even
13613     // if it is not used in this compilation unit.
13614     if (!FD->hasAttr<DLLExportAttr>())
13615       FD->addAttr(NewAttr);
13616 
13617   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13618     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13619     NewAttr->setInherited(true);
13620     VD->addAttr(NewAttr);
13621   }
13622 }
13623 
13624 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13625 /// any semantic actions necessary after any initializer has been attached.
13626 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13627   // Note that we are no longer parsing the initializer for this declaration.
13628   ParsingInitForAutoVars.erase(ThisDecl);
13629 
13630   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13631   if (!VD)
13632     return;
13633 
13634   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13635   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13636       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13637     if (PragmaClangBSSSection.Valid)
13638       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13639           Context, PragmaClangBSSSection.SectionName,
13640           PragmaClangBSSSection.PragmaLocation,
13641           AttributeCommonInfo::AS_Pragma));
13642     if (PragmaClangDataSection.Valid)
13643       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13644           Context, PragmaClangDataSection.SectionName,
13645           PragmaClangDataSection.PragmaLocation,
13646           AttributeCommonInfo::AS_Pragma));
13647     if (PragmaClangRodataSection.Valid)
13648       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13649           Context, PragmaClangRodataSection.SectionName,
13650           PragmaClangRodataSection.PragmaLocation,
13651           AttributeCommonInfo::AS_Pragma));
13652     if (PragmaClangRelroSection.Valid)
13653       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13654           Context, PragmaClangRelroSection.SectionName,
13655           PragmaClangRelroSection.PragmaLocation,
13656           AttributeCommonInfo::AS_Pragma));
13657   }
13658 
13659   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13660     for (auto *BD : DD->bindings()) {
13661       FinalizeDeclaration(BD);
13662     }
13663   }
13664 
13665   checkAttributesAfterMerging(*this, *VD);
13666 
13667   // Perform TLS alignment check here after attributes attached to the variable
13668   // which may affect the alignment have been processed. Only perform the check
13669   // if the target has a maximum TLS alignment (zero means no constraints).
13670   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13671     // Protect the check so that it's not performed on dependent types and
13672     // dependent alignments (we can't determine the alignment in that case).
13673     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13674       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13675       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13676         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13677           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13678           << (unsigned)MaxAlignChars.getQuantity();
13679       }
13680     }
13681   }
13682 
13683   if (VD->isStaticLocal())
13684     CheckStaticLocalForDllExport(VD);
13685 
13686   // Perform check for initializers of device-side global variables.
13687   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13688   // 7.5). We must also apply the same checks to all __shared__
13689   // variables whether they are local or not. CUDA also allows
13690   // constant initializers for __constant__ and __device__ variables.
13691   if (getLangOpts().CUDA)
13692     checkAllowedCUDAInitializer(VD);
13693 
13694   // Grab the dllimport or dllexport attribute off of the VarDecl.
13695   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13696 
13697   // Imported static data members cannot be defined out-of-line.
13698   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13699     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13700         VD->isThisDeclarationADefinition()) {
13701       // We allow definitions of dllimport class template static data members
13702       // with a warning.
13703       CXXRecordDecl *Context =
13704         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13705       bool IsClassTemplateMember =
13706           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13707           Context->getDescribedClassTemplate();
13708 
13709       Diag(VD->getLocation(),
13710            IsClassTemplateMember
13711                ? diag::warn_attribute_dllimport_static_field_definition
13712                : diag::err_attribute_dllimport_static_field_definition);
13713       Diag(IA->getLocation(), diag::note_attribute);
13714       if (!IsClassTemplateMember)
13715         VD->setInvalidDecl();
13716     }
13717   }
13718 
13719   // dllimport/dllexport variables cannot be thread local, their TLS index
13720   // isn't exported with the variable.
13721   if (DLLAttr && VD->getTLSKind()) {
13722     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13723     if (F && getDLLAttr(F)) {
13724       assert(VD->isStaticLocal());
13725       // But if this is a static local in a dlimport/dllexport function, the
13726       // function will never be inlined, which means the var would never be
13727       // imported, so having it marked import/export is safe.
13728     } else {
13729       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13730                                                                     << DLLAttr;
13731       VD->setInvalidDecl();
13732     }
13733   }
13734 
13735   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13736     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13737       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13738           << Attr;
13739       VD->dropAttr<UsedAttr>();
13740     }
13741   }
13742   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13743     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13744       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13745           << Attr;
13746       VD->dropAttr<RetainAttr>();
13747     }
13748   }
13749 
13750   const DeclContext *DC = VD->getDeclContext();
13751   // If there's a #pragma GCC visibility in scope, and this isn't a class
13752   // member, set the visibility of this variable.
13753   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13754     AddPushedVisibilityAttribute(VD);
13755 
13756   // FIXME: Warn on unused var template partial specializations.
13757   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13758     MarkUnusedFileScopedDecl(VD);
13759 
13760   // Now we have parsed the initializer and can update the table of magic
13761   // tag values.
13762   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13763       !VD->getType()->isIntegralOrEnumerationType())
13764     return;
13765 
13766   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13767     const Expr *MagicValueExpr = VD->getInit();
13768     if (!MagicValueExpr) {
13769       continue;
13770     }
13771     Optional<llvm::APSInt> MagicValueInt;
13772     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13773       Diag(I->getRange().getBegin(),
13774            diag::err_type_tag_for_datatype_not_ice)
13775         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13776       continue;
13777     }
13778     if (MagicValueInt->getActiveBits() > 64) {
13779       Diag(I->getRange().getBegin(),
13780            diag::err_type_tag_for_datatype_too_large)
13781         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13782       continue;
13783     }
13784     uint64_t MagicValue = MagicValueInt->getZExtValue();
13785     RegisterTypeTagForDatatype(I->getArgumentKind(),
13786                                MagicValue,
13787                                I->getMatchingCType(),
13788                                I->getLayoutCompatible(),
13789                                I->getMustBeNull());
13790   }
13791 }
13792 
13793 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13794   auto *VD = dyn_cast<VarDecl>(DD);
13795   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13796 }
13797 
13798 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13799                                                    ArrayRef<Decl *> Group) {
13800   SmallVector<Decl*, 8> Decls;
13801 
13802   if (DS.isTypeSpecOwned())
13803     Decls.push_back(DS.getRepAsDecl());
13804 
13805   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13806   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13807   bool DiagnosedMultipleDecomps = false;
13808   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13809   bool DiagnosedNonDeducedAuto = false;
13810 
13811   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13812     if (Decl *D = Group[i]) {
13813       // For declarators, there are some additional syntactic-ish checks we need
13814       // to perform.
13815       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13816         if (!FirstDeclaratorInGroup)
13817           FirstDeclaratorInGroup = DD;
13818         if (!FirstDecompDeclaratorInGroup)
13819           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13820         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13821             !hasDeducedAuto(DD))
13822           FirstNonDeducedAutoInGroup = DD;
13823 
13824         if (FirstDeclaratorInGroup != DD) {
13825           // A decomposition declaration cannot be combined with any other
13826           // declaration in the same group.
13827           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13828             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13829                  diag::err_decomp_decl_not_alone)
13830                 << FirstDeclaratorInGroup->getSourceRange()
13831                 << DD->getSourceRange();
13832             DiagnosedMultipleDecomps = true;
13833           }
13834 
13835           // A declarator that uses 'auto' in any way other than to declare a
13836           // variable with a deduced type cannot be combined with any other
13837           // declarator in the same group.
13838           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13839             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13840                  diag::err_auto_non_deduced_not_alone)
13841                 << FirstNonDeducedAutoInGroup->getType()
13842                        ->hasAutoForTrailingReturnType()
13843                 << FirstDeclaratorInGroup->getSourceRange()
13844                 << DD->getSourceRange();
13845             DiagnosedNonDeducedAuto = true;
13846           }
13847         }
13848       }
13849 
13850       Decls.push_back(D);
13851     }
13852   }
13853 
13854   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13855     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13856       handleTagNumbering(Tag, S);
13857       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13858           getLangOpts().CPlusPlus)
13859         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13860     }
13861   }
13862 
13863   return BuildDeclaratorGroup(Decls);
13864 }
13865 
13866 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13867 /// group, performing any necessary semantic checking.
13868 Sema::DeclGroupPtrTy
13869 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13870   // C++14 [dcl.spec.auto]p7: (DR1347)
13871   //   If the type that replaces the placeholder type is not the same in each
13872   //   deduction, the program is ill-formed.
13873   if (Group.size() > 1) {
13874     QualType Deduced;
13875     VarDecl *DeducedDecl = nullptr;
13876     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13877       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13878       if (!D || D->isInvalidDecl())
13879         break;
13880       DeducedType *DT = D->getType()->getContainedDeducedType();
13881       if (!DT || DT->getDeducedType().isNull())
13882         continue;
13883       if (Deduced.isNull()) {
13884         Deduced = DT->getDeducedType();
13885         DeducedDecl = D;
13886       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13887         auto *AT = dyn_cast<AutoType>(DT);
13888         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13889                         diag::err_auto_different_deductions)
13890                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13891                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13892                    << D->getDeclName();
13893         if (DeducedDecl->hasInit())
13894           Dia << DeducedDecl->getInit()->getSourceRange();
13895         if (D->getInit())
13896           Dia << D->getInit()->getSourceRange();
13897         D->setInvalidDecl();
13898         break;
13899       }
13900     }
13901   }
13902 
13903   ActOnDocumentableDecls(Group);
13904 
13905   return DeclGroupPtrTy::make(
13906       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13907 }
13908 
13909 void Sema::ActOnDocumentableDecl(Decl *D) {
13910   ActOnDocumentableDecls(D);
13911 }
13912 
13913 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13914   // Don't parse the comment if Doxygen diagnostics are ignored.
13915   if (Group.empty() || !Group[0])
13916     return;
13917 
13918   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13919                       Group[0]->getLocation()) &&
13920       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13921                       Group[0]->getLocation()))
13922     return;
13923 
13924   if (Group.size() >= 2) {
13925     // This is a decl group.  Normally it will contain only declarations
13926     // produced from declarator list.  But in case we have any definitions or
13927     // additional declaration references:
13928     //   'typedef struct S {} S;'
13929     //   'typedef struct S *S;'
13930     //   'struct S *pS;'
13931     // FinalizeDeclaratorGroup adds these as separate declarations.
13932     Decl *MaybeTagDecl = Group[0];
13933     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13934       Group = Group.slice(1);
13935     }
13936   }
13937 
13938   // FIMXE: We assume every Decl in the group is in the same file.
13939   // This is false when preprocessor constructs the group from decls in
13940   // different files (e. g. macros or #include).
13941   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13942 }
13943 
13944 /// Common checks for a parameter-declaration that should apply to both function
13945 /// parameters and non-type template parameters.
13946 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13947   // Check that there are no default arguments inside the type of this
13948   // parameter.
13949   if (getLangOpts().CPlusPlus)
13950     CheckExtraCXXDefaultArguments(D);
13951 
13952   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13953   if (D.getCXXScopeSpec().isSet()) {
13954     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13955       << D.getCXXScopeSpec().getRange();
13956   }
13957 
13958   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13959   // simple identifier except [...irrelevant cases...].
13960   switch (D.getName().getKind()) {
13961   case UnqualifiedIdKind::IK_Identifier:
13962     break;
13963 
13964   case UnqualifiedIdKind::IK_OperatorFunctionId:
13965   case UnqualifiedIdKind::IK_ConversionFunctionId:
13966   case UnqualifiedIdKind::IK_LiteralOperatorId:
13967   case UnqualifiedIdKind::IK_ConstructorName:
13968   case UnqualifiedIdKind::IK_DestructorName:
13969   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13970   case UnqualifiedIdKind::IK_DeductionGuideName:
13971     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13972       << GetNameForDeclarator(D).getName();
13973     break;
13974 
13975   case UnqualifiedIdKind::IK_TemplateId:
13976   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13977     // GetNameForDeclarator would not produce a useful name in this case.
13978     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13979     break;
13980   }
13981 }
13982 
13983 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13984 /// to introduce parameters into function prototype scope.
13985 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13986   const DeclSpec &DS = D.getDeclSpec();
13987 
13988   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13989 
13990   // C++03 [dcl.stc]p2 also permits 'auto'.
13991   StorageClass SC = SC_None;
13992   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13993     SC = SC_Register;
13994     // In C++11, the 'register' storage class specifier is deprecated.
13995     // In C++17, it is not allowed, but we tolerate it as an extension.
13996     if (getLangOpts().CPlusPlus11) {
13997       Diag(DS.getStorageClassSpecLoc(),
13998            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13999                                      : diag::warn_deprecated_register)
14000         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14001     }
14002   } else if (getLangOpts().CPlusPlus &&
14003              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14004     SC = SC_Auto;
14005   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14006     Diag(DS.getStorageClassSpecLoc(),
14007          diag::err_invalid_storage_class_in_func_decl);
14008     D.getMutableDeclSpec().ClearStorageClassSpecs();
14009   }
14010 
14011   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14012     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14013       << DeclSpec::getSpecifierName(TSCS);
14014   if (DS.isInlineSpecified())
14015     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14016         << getLangOpts().CPlusPlus17;
14017   if (DS.hasConstexprSpecifier())
14018     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14019         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14020 
14021   DiagnoseFunctionSpecifiers(DS);
14022 
14023   CheckFunctionOrTemplateParamDeclarator(S, D);
14024 
14025   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14026   QualType parmDeclType = TInfo->getType();
14027 
14028   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14029   IdentifierInfo *II = D.getIdentifier();
14030   if (II) {
14031     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14032                    ForVisibleRedeclaration);
14033     LookupName(R, S);
14034     if (R.isSingleResult()) {
14035       NamedDecl *PrevDecl = R.getFoundDecl();
14036       if (PrevDecl->isTemplateParameter()) {
14037         // Maybe we will complain about the shadowed template parameter.
14038         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14039         // Just pretend that we didn't see the previous declaration.
14040         PrevDecl = nullptr;
14041       } else if (S->isDeclScope(PrevDecl)) {
14042         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14043         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14044 
14045         // Recover by removing the name
14046         II = nullptr;
14047         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14048         D.setInvalidType(true);
14049       }
14050     }
14051   }
14052 
14053   // Temporarily put parameter variables in the translation unit, not
14054   // the enclosing context.  This prevents them from accidentally
14055   // looking like class members in C++.
14056   ParmVarDecl *New =
14057       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14058                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14059 
14060   if (D.isInvalidType())
14061     New->setInvalidDecl();
14062 
14063   assert(S->isFunctionPrototypeScope());
14064   assert(S->getFunctionPrototypeDepth() >= 1);
14065   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14066                     S->getNextFunctionPrototypeIndex());
14067 
14068   // Add the parameter declaration into this scope.
14069   S->AddDecl(New);
14070   if (II)
14071     IdResolver.AddDecl(New);
14072 
14073   ProcessDeclAttributes(S, New, D);
14074 
14075   if (D.getDeclSpec().isModulePrivateSpecified())
14076     Diag(New->getLocation(), diag::err_module_private_local)
14077         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14078         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14079 
14080   if (New->hasAttr<BlocksAttr>()) {
14081     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14082   }
14083 
14084   if (getLangOpts().OpenCL)
14085     deduceOpenCLAddressSpace(New);
14086 
14087   return New;
14088 }
14089 
14090 /// Synthesizes a variable for a parameter arising from a
14091 /// typedef.
14092 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14093                                               SourceLocation Loc,
14094                                               QualType T) {
14095   /* FIXME: setting StartLoc == Loc.
14096      Would it be worth to modify callers so as to provide proper source
14097      location for the unnamed parameters, embedding the parameter's type? */
14098   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14099                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14100                                            SC_None, nullptr);
14101   Param->setImplicit();
14102   return Param;
14103 }
14104 
14105 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14106   // Don't diagnose unused-parameter errors in template instantiations; we
14107   // will already have done so in the template itself.
14108   if (inTemplateInstantiation())
14109     return;
14110 
14111   for (const ParmVarDecl *Parameter : Parameters) {
14112     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14113         !Parameter->hasAttr<UnusedAttr>()) {
14114       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14115         << Parameter->getDeclName();
14116     }
14117   }
14118 }
14119 
14120 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14121     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14122   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14123     return;
14124 
14125   // Warn if the return value is pass-by-value and larger than the specified
14126   // threshold.
14127   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14128     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14129     if (Size > LangOpts.NumLargeByValueCopy)
14130       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14131   }
14132 
14133   // Warn if any parameter is pass-by-value and larger than the specified
14134   // threshold.
14135   for (const ParmVarDecl *Parameter : Parameters) {
14136     QualType T = Parameter->getType();
14137     if (T->isDependentType() || !T.isPODType(Context))
14138       continue;
14139     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14140     if (Size > LangOpts.NumLargeByValueCopy)
14141       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14142           << Parameter << Size;
14143   }
14144 }
14145 
14146 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14147                                   SourceLocation NameLoc, IdentifierInfo *Name,
14148                                   QualType T, TypeSourceInfo *TSInfo,
14149                                   StorageClass SC) {
14150   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14151   if (getLangOpts().ObjCAutoRefCount &&
14152       T.getObjCLifetime() == Qualifiers::OCL_None &&
14153       T->isObjCLifetimeType()) {
14154 
14155     Qualifiers::ObjCLifetime lifetime;
14156 
14157     // Special cases for arrays:
14158     //   - if it's const, use __unsafe_unretained
14159     //   - otherwise, it's an error
14160     if (T->isArrayType()) {
14161       if (!T.isConstQualified()) {
14162         if (DelayedDiagnostics.shouldDelayDiagnostics())
14163           DelayedDiagnostics.add(
14164               sema::DelayedDiagnostic::makeForbiddenType(
14165               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14166         else
14167           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14168               << TSInfo->getTypeLoc().getSourceRange();
14169       }
14170       lifetime = Qualifiers::OCL_ExplicitNone;
14171     } else {
14172       lifetime = T->getObjCARCImplicitLifetime();
14173     }
14174     T = Context.getLifetimeQualifiedType(T, lifetime);
14175   }
14176 
14177   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14178                                          Context.getAdjustedParameterType(T),
14179                                          TSInfo, SC, nullptr);
14180 
14181   // Make a note if we created a new pack in the scope of a lambda, so that
14182   // we know that references to that pack must also be expanded within the
14183   // lambda scope.
14184   if (New->isParameterPack())
14185     if (auto *LSI = getEnclosingLambda())
14186       LSI->LocalPacks.push_back(New);
14187 
14188   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14189       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14190     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14191                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14192 
14193   // Parameters can not be abstract class types.
14194   // For record types, this is done by the AbstractClassUsageDiagnoser once
14195   // the class has been completely parsed.
14196   if (!CurContext->isRecord() &&
14197       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14198                              AbstractParamType))
14199     New->setInvalidDecl();
14200 
14201   // Parameter declarators cannot be interface types. All ObjC objects are
14202   // passed by reference.
14203   if (T->isObjCObjectType()) {
14204     SourceLocation TypeEndLoc =
14205         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14206     Diag(NameLoc,
14207          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14208       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14209     T = Context.getObjCObjectPointerType(T);
14210     New->setType(T);
14211   }
14212 
14213   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14214   // duration shall not be qualified by an address-space qualifier."
14215   // Since all parameters have automatic store duration, they can not have
14216   // an address space.
14217   if (T.getAddressSpace() != LangAS::Default &&
14218       // OpenCL allows function arguments declared to be an array of a type
14219       // to be qualified with an address space.
14220       !(getLangOpts().OpenCL &&
14221         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14222     Diag(NameLoc, diag::err_arg_with_address_space);
14223     New->setInvalidDecl();
14224   }
14225 
14226   // PPC MMA non-pointer types are not allowed as function argument types.
14227   if (Context.getTargetInfo().getTriple().isPPC64() &&
14228       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14229     New->setInvalidDecl();
14230   }
14231 
14232   return New;
14233 }
14234 
14235 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14236                                            SourceLocation LocAfterDecls) {
14237   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14238 
14239   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14240   // for a K&R function.
14241   if (!FTI.hasPrototype) {
14242     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14243       --i;
14244       if (FTI.Params[i].Param == nullptr) {
14245         SmallString<256> Code;
14246         llvm::raw_svector_ostream(Code)
14247             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14248         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14249             << FTI.Params[i].Ident
14250             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14251 
14252         // Implicitly declare the argument as type 'int' for lack of a better
14253         // type.
14254         AttributeFactory attrs;
14255         DeclSpec DS(attrs);
14256         const char* PrevSpec; // unused
14257         unsigned DiagID; // unused
14258         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14259                            DiagID, Context.getPrintingPolicy());
14260         // Use the identifier location for the type source range.
14261         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14262         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14263         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14264         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14265         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14266       }
14267     }
14268   }
14269 }
14270 
14271 Decl *
14272 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14273                               MultiTemplateParamsArg TemplateParameterLists,
14274                               SkipBodyInfo *SkipBody) {
14275   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14276   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14277   Scope *ParentScope = FnBodyScope->getParent();
14278 
14279   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14280   // we define a non-templated function definition, we will create a declaration
14281   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14282   // The base function declaration will have the equivalent of an `omp declare
14283   // variant` annotation which specifies the mangled definition as a
14284   // specialization function under the OpenMP context defined as part of the
14285   // `omp begin declare variant`.
14286   SmallVector<FunctionDecl *, 4> Bases;
14287   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14288     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14289         ParentScope, D, TemplateParameterLists, Bases);
14290 
14291   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14292   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14293   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14294 
14295   if (!Bases.empty())
14296     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14297 
14298   return Dcl;
14299 }
14300 
14301 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14302   Consumer.HandleInlineFunctionDefinition(D);
14303 }
14304 
14305 static bool
14306 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14307                                 const FunctionDecl *&PossiblePrototype) {
14308   // Don't warn about invalid declarations.
14309   if (FD->isInvalidDecl())
14310     return false;
14311 
14312   // Or declarations that aren't global.
14313   if (!FD->isGlobal())
14314     return false;
14315 
14316   // Don't warn about C++ member functions.
14317   if (isa<CXXMethodDecl>(FD))
14318     return false;
14319 
14320   // Don't warn about 'main'.
14321   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14322     if (IdentifierInfo *II = FD->getIdentifier())
14323       if (II->isStr("main") || II->isStr("efi_main"))
14324         return false;
14325 
14326   // Don't warn about inline functions.
14327   if (FD->isInlined())
14328     return false;
14329 
14330   // Don't warn about function templates.
14331   if (FD->getDescribedFunctionTemplate())
14332     return false;
14333 
14334   // Don't warn about function template specializations.
14335   if (FD->isFunctionTemplateSpecialization())
14336     return false;
14337 
14338   // Don't warn for OpenCL kernels.
14339   if (FD->hasAttr<OpenCLKernelAttr>())
14340     return false;
14341 
14342   // Don't warn on explicitly deleted functions.
14343   if (FD->isDeleted())
14344     return false;
14345 
14346   // Don't warn on implicitly local functions (such as having local-typed
14347   // parameters).
14348   if (!FD->isExternallyVisible())
14349     return false;
14350 
14351   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14352        Prev; Prev = Prev->getPreviousDecl()) {
14353     // Ignore any declarations that occur in function or method
14354     // scope, because they aren't visible from the header.
14355     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14356       continue;
14357 
14358     PossiblePrototype = Prev;
14359     return Prev->getType()->isFunctionNoProtoType();
14360   }
14361 
14362   return true;
14363 }
14364 
14365 void
14366 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14367                                    const FunctionDecl *EffectiveDefinition,
14368                                    SkipBodyInfo *SkipBody) {
14369   const FunctionDecl *Definition = EffectiveDefinition;
14370   if (!Definition &&
14371       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14372     return;
14373 
14374   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14375     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14376       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14377         // A merged copy of the same function, instantiated as a member of
14378         // the same class, is OK.
14379         if (declaresSameEntity(OrigFD, OrigDef) &&
14380             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14381                                cast<Decl>(FD->getLexicalDeclContext())))
14382           return;
14383       }
14384     }
14385   }
14386 
14387   if (canRedefineFunction(Definition, getLangOpts()))
14388     return;
14389 
14390   // Don't emit an error when this is redefinition of a typo-corrected
14391   // definition.
14392   if (TypoCorrectedFunctionDefinitions.count(Definition))
14393     return;
14394 
14395   // If we don't have a visible definition of the function, and it's inline or
14396   // a template, skip the new definition.
14397   if (SkipBody && !hasVisibleDefinition(Definition) &&
14398       (Definition->getFormalLinkage() == InternalLinkage ||
14399        Definition->isInlined() ||
14400        Definition->getDescribedFunctionTemplate() ||
14401        Definition->getNumTemplateParameterLists())) {
14402     SkipBody->ShouldSkip = true;
14403     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14404     if (auto *TD = Definition->getDescribedFunctionTemplate())
14405       makeMergedDefinitionVisible(TD);
14406     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14407     return;
14408   }
14409 
14410   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14411       Definition->getStorageClass() == SC_Extern)
14412     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14413         << FD << getLangOpts().CPlusPlus;
14414   else
14415     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14416 
14417   Diag(Definition->getLocation(), diag::note_previous_definition);
14418   FD->setInvalidDecl();
14419 }
14420 
14421 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14422                                    Sema &S) {
14423   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14424 
14425   LambdaScopeInfo *LSI = S.PushLambdaScope();
14426   LSI->CallOperator = CallOperator;
14427   LSI->Lambda = LambdaClass;
14428   LSI->ReturnType = CallOperator->getReturnType();
14429   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14430 
14431   if (LCD == LCD_None)
14432     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14433   else if (LCD == LCD_ByCopy)
14434     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14435   else if (LCD == LCD_ByRef)
14436     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14437   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14438 
14439   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14440   LSI->Mutable = !CallOperator->isConst();
14441 
14442   // Add the captures to the LSI so they can be noted as already
14443   // captured within tryCaptureVar.
14444   auto I = LambdaClass->field_begin();
14445   for (const auto &C : LambdaClass->captures()) {
14446     if (C.capturesVariable()) {
14447       VarDecl *VD = C.getCapturedVar();
14448       if (VD->isInitCapture())
14449         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14450       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14451       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14452           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14453           /*EllipsisLoc*/C.isPackExpansion()
14454                          ? C.getEllipsisLoc() : SourceLocation(),
14455           I->getType(), /*Invalid*/false);
14456 
14457     } else if (C.capturesThis()) {
14458       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14459                           C.getCaptureKind() == LCK_StarThis);
14460     } else {
14461       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14462                              I->getType());
14463     }
14464     ++I;
14465   }
14466 }
14467 
14468 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14469                                     SkipBodyInfo *SkipBody) {
14470   if (!D) {
14471     // Parsing the function declaration failed in some way. Push on a fake scope
14472     // anyway so we can try to parse the function body.
14473     PushFunctionScope();
14474     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14475     return D;
14476   }
14477 
14478   FunctionDecl *FD = nullptr;
14479 
14480   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14481     FD = FunTmpl->getTemplatedDecl();
14482   else
14483     FD = cast<FunctionDecl>(D);
14484 
14485   // Do not push if it is a lambda because one is already pushed when building
14486   // the lambda in ActOnStartOfLambdaDefinition().
14487   if (!isLambdaCallOperator(FD))
14488     PushExpressionEvaluationContext(
14489         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14490                           : ExprEvalContexts.back().Context);
14491 
14492   // Check for defining attributes before the check for redefinition.
14493   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14494     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14495     FD->dropAttr<AliasAttr>();
14496     FD->setInvalidDecl();
14497   }
14498   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14499     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14500     FD->dropAttr<IFuncAttr>();
14501     FD->setInvalidDecl();
14502   }
14503 
14504   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14505     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14506         Ctor->isDefaultConstructor() &&
14507         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14508       // If this is an MS ABI dllexport default constructor, instantiate any
14509       // default arguments.
14510       InstantiateDefaultCtorDefaultArgs(Ctor);
14511     }
14512   }
14513 
14514   // See if this is a redefinition. If 'will have body' (or similar) is already
14515   // set, then these checks were already performed when it was set.
14516   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14517       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14518     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14519 
14520     // If we're skipping the body, we're done. Don't enter the scope.
14521     if (SkipBody && SkipBody->ShouldSkip)
14522       return D;
14523   }
14524 
14525   // Mark this function as "will have a body eventually".  This lets users to
14526   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14527   // this function.
14528   FD->setWillHaveBody();
14529 
14530   // If we are instantiating a generic lambda call operator, push
14531   // a LambdaScopeInfo onto the function stack.  But use the information
14532   // that's already been calculated (ActOnLambdaExpr) to prime the current
14533   // LambdaScopeInfo.
14534   // When the template operator is being specialized, the LambdaScopeInfo,
14535   // has to be properly restored so that tryCaptureVariable doesn't try
14536   // and capture any new variables. In addition when calculating potential
14537   // captures during transformation of nested lambdas, it is necessary to
14538   // have the LSI properly restored.
14539   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14540     assert(inTemplateInstantiation() &&
14541            "There should be an active template instantiation on the stack "
14542            "when instantiating a generic lambda!");
14543     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14544   } else {
14545     // Enter a new function scope
14546     PushFunctionScope();
14547   }
14548 
14549   // Builtin functions cannot be defined.
14550   if (unsigned BuiltinID = FD->getBuiltinID()) {
14551     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14552         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14553       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14554       FD->setInvalidDecl();
14555     }
14556   }
14557 
14558   // The return type of a function definition must be complete
14559   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14560   QualType ResultType = FD->getReturnType();
14561   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14562       !FD->isInvalidDecl() &&
14563       RequireCompleteType(FD->getLocation(), ResultType,
14564                           diag::err_func_def_incomplete_result))
14565     FD->setInvalidDecl();
14566 
14567   if (FnBodyScope)
14568     PushDeclContext(FnBodyScope, FD);
14569 
14570   // Check the validity of our function parameters
14571   CheckParmsForFunctionDef(FD->parameters(),
14572                            /*CheckParameterNames=*/true);
14573 
14574   // Add non-parameter declarations already in the function to the current
14575   // scope.
14576   if (FnBodyScope) {
14577     for (Decl *NPD : FD->decls()) {
14578       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14579       if (!NonParmDecl)
14580         continue;
14581       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14582              "parameters should not be in newly created FD yet");
14583 
14584       // If the decl has a name, make it accessible in the current scope.
14585       if (NonParmDecl->getDeclName())
14586         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14587 
14588       // Similarly, dive into enums and fish their constants out, making them
14589       // accessible in this scope.
14590       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14591         for (auto *EI : ED->enumerators())
14592           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14593       }
14594     }
14595   }
14596 
14597   // Introduce our parameters into the function scope
14598   for (auto Param : FD->parameters()) {
14599     Param->setOwningFunction(FD);
14600 
14601     // If this has an identifier, add it to the scope stack.
14602     if (Param->getIdentifier() && FnBodyScope) {
14603       CheckShadow(FnBodyScope, Param);
14604 
14605       PushOnScopeChains(Param, FnBodyScope);
14606     }
14607   }
14608 
14609   // Ensure that the function's exception specification is instantiated.
14610   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14611     ResolveExceptionSpec(D->getLocation(), FPT);
14612 
14613   // dllimport cannot be applied to non-inline function definitions.
14614   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14615       !FD->isTemplateInstantiation()) {
14616     assert(!FD->hasAttr<DLLExportAttr>());
14617     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14618     FD->setInvalidDecl();
14619     return D;
14620   }
14621   // We want to attach documentation to original Decl (which might be
14622   // a function template).
14623   ActOnDocumentableDecl(D);
14624   if (getCurLexicalContext()->isObjCContainer() &&
14625       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14626       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14627     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14628 
14629   return D;
14630 }
14631 
14632 /// Given the set of return statements within a function body,
14633 /// compute the variables that are subject to the named return value
14634 /// optimization.
14635 ///
14636 /// Each of the variables that is subject to the named return value
14637 /// optimization will be marked as NRVO variables in the AST, and any
14638 /// return statement that has a marked NRVO variable as its NRVO candidate can
14639 /// use the named return value optimization.
14640 ///
14641 /// This function applies a very simplistic algorithm for NRVO: if every return
14642 /// statement in the scope of a variable has the same NRVO candidate, that
14643 /// candidate is an NRVO variable.
14644 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14645   ReturnStmt **Returns = Scope->Returns.data();
14646 
14647   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14648     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14649       if (!NRVOCandidate->isNRVOVariable())
14650         Returns[I]->setNRVOCandidate(nullptr);
14651     }
14652   }
14653 }
14654 
14655 bool Sema::canDelayFunctionBody(const Declarator &D) {
14656   // We can't delay parsing the body of a constexpr function template (yet).
14657   if (D.getDeclSpec().hasConstexprSpecifier())
14658     return false;
14659 
14660   // We can't delay parsing the body of a function template with a deduced
14661   // return type (yet).
14662   if (D.getDeclSpec().hasAutoTypeSpec()) {
14663     // If the placeholder introduces a non-deduced trailing return type,
14664     // we can still delay parsing it.
14665     if (D.getNumTypeObjects()) {
14666       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14667       if (Outer.Kind == DeclaratorChunk::Function &&
14668           Outer.Fun.hasTrailingReturnType()) {
14669         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14670         return Ty.isNull() || !Ty->isUndeducedType();
14671       }
14672     }
14673     return false;
14674   }
14675 
14676   return true;
14677 }
14678 
14679 bool Sema::canSkipFunctionBody(Decl *D) {
14680   // We cannot skip the body of a function (or function template) which is
14681   // constexpr, since we may need to evaluate its body in order to parse the
14682   // rest of the file.
14683   // We cannot skip the body of a function with an undeduced return type,
14684   // because any callers of that function need to know the type.
14685   if (const FunctionDecl *FD = D->getAsFunction()) {
14686     if (FD->isConstexpr())
14687       return false;
14688     // We can't simply call Type::isUndeducedType here, because inside template
14689     // auto can be deduced to a dependent type, which is not considered
14690     // "undeduced".
14691     if (FD->getReturnType()->getContainedDeducedType())
14692       return false;
14693   }
14694   return Consumer.shouldSkipFunctionBody(D);
14695 }
14696 
14697 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14698   if (!Decl)
14699     return nullptr;
14700   if (FunctionDecl *FD = Decl->getAsFunction())
14701     FD->setHasSkippedBody();
14702   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14703     MD->setHasSkippedBody();
14704   return Decl;
14705 }
14706 
14707 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14708   return ActOnFinishFunctionBody(D, BodyArg, false);
14709 }
14710 
14711 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14712 /// body.
14713 class ExitFunctionBodyRAII {
14714 public:
14715   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14716   ~ExitFunctionBodyRAII() {
14717     if (!IsLambda)
14718       S.PopExpressionEvaluationContext();
14719   }
14720 
14721 private:
14722   Sema &S;
14723   bool IsLambda = false;
14724 };
14725 
14726 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14727   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14728 
14729   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14730     if (EscapeInfo.count(BD))
14731       return EscapeInfo[BD];
14732 
14733     bool R = false;
14734     const BlockDecl *CurBD = BD;
14735 
14736     do {
14737       R = !CurBD->doesNotEscape();
14738       if (R)
14739         break;
14740       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14741     } while (CurBD);
14742 
14743     return EscapeInfo[BD] = R;
14744   };
14745 
14746   // If the location where 'self' is implicitly retained is inside a escaping
14747   // block, emit a diagnostic.
14748   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14749        S.ImplicitlyRetainedSelfLocs)
14750     if (IsOrNestedInEscapingBlock(P.second))
14751       S.Diag(P.first, diag::warn_implicitly_retains_self)
14752           << FixItHint::CreateInsertion(P.first, "self->");
14753 }
14754 
14755 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14756                                     bool IsInstantiation) {
14757   FunctionScopeInfo *FSI = getCurFunction();
14758   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14759 
14760   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14761     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14762 
14763   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14764   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14765 
14766   if (getLangOpts().Coroutines && FSI->isCoroutine())
14767     CheckCompletedCoroutineBody(FD, Body);
14768 
14769   {
14770     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14771     // one is already popped when finishing the lambda in BuildLambdaExpr().
14772     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14773     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14774 
14775     if (FD) {
14776       FD->setBody(Body);
14777       FD->setWillHaveBody(false);
14778 
14779       if (getLangOpts().CPlusPlus14) {
14780         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14781             FD->getReturnType()->isUndeducedType()) {
14782           // For a function with a deduced result type to return void,
14783           // the result type as written must be 'auto' or 'decltype(auto)',
14784           // possibly cv-qualified or constrained, but not ref-qualified.
14785           if (!FD->getReturnType()->getAs<AutoType>()) {
14786             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14787                 << FD->getReturnType();
14788             FD->setInvalidDecl();
14789           } else {
14790             // Falling off the end of the function is the same as 'return;'.
14791             Expr *Dummy = nullptr;
14792             if (DeduceFunctionTypeFromReturnExpr(
14793                     FD, dcl->getLocation(), Dummy,
14794                     FD->getReturnType()->getAs<AutoType>()))
14795               FD->setInvalidDecl();
14796           }
14797         }
14798       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14799         // In C++11, we don't use 'auto' deduction rules for lambda call
14800         // operators because we don't support return type deduction.
14801         auto *LSI = getCurLambda();
14802         if (LSI->HasImplicitReturnType) {
14803           deduceClosureReturnType(*LSI);
14804 
14805           // C++11 [expr.prim.lambda]p4:
14806           //   [...] if there are no return statements in the compound-statement
14807           //   [the deduced type is] the type void
14808           QualType RetType =
14809               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14810 
14811           // Update the return type to the deduced type.
14812           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14813           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14814                                               Proto->getExtProtoInfo()));
14815         }
14816       }
14817 
14818       // If the function implicitly returns zero (like 'main') or is naked,
14819       // don't complain about missing return statements.
14820       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14821         WP.disableCheckFallThrough();
14822 
14823       // MSVC permits the use of pure specifier (=0) on function definition,
14824       // defined at class scope, warn about this non-standard construct.
14825       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14826         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14827 
14828       if (!FD->isInvalidDecl()) {
14829         // Don't diagnose unused parameters of defaulted, deleted or naked
14830         // functions.
14831         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14832             !FD->hasAttr<NakedAttr>())
14833           DiagnoseUnusedParameters(FD->parameters());
14834         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14835                                                FD->getReturnType(), FD);
14836 
14837         // If this is a structor, we need a vtable.
14838         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14839           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14840         else if (CXXDestructorDecl *Destructor =
14841                      dyn_cast<CXXDestructorDecl>(FD))
14842           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14843 
14844         // Try to apply the named return value optimization. We have to check
14845         // if we can do this here because lambdas keep return statements around
14846         // to deduce an implicit return type.
14847         if (FD->getReturnType()->isRecordType() &&
14848             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14849           computeNRVO(Body, FSI);
14850       }
14851 
14852       // GNU warning -Wmissing-prototypes:
14853       //   Warn if a global function is defined without a previous
14854       //   prototype declaration. This warning is issued even if the
14855       //   definition itself provides a prototype. The aim is to detect
14856       //   global functions that fail to be declared in header files.
14857       const FunctionDecl *PossiblePrototype = nullptr;
14858       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14859         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14860 
14861         if (PossiblePrototype) {
14862           // We found a declaration that is not a prototype,
14863           // but that could be a zero-parameter prototype
14864           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14865             TypeLoc TL = TI->getTypeLoc();
14866             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14867               Diag(PossiblePrototype->getLocation(),
14868                    diag::note_declaration_not_a_prototype)
14869                   << (FD->getNumParams() != 0)
14870                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14871                                                     FTL.getRParenLoc(), "void")
14872                                               : FixItHint{});
14873           }
14874         } else {
14875           // Returns true if the token beginning at this Loc is `const`.
14876           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14877                                   const LangOptions &LangOpts) {
14878             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14879             if (LocInfo.first.isInvalid())
14880               return false;
14881 
14882             bool Invalid = false;
14883             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14884             if (Invalid)
14885               return false;
14886 
14887             if (LocInfo.second > Buffer.size())
14888               return false;
14889 
14890             const char *LexStart = Buffer.data() + LocInfo.second;
14891             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14892 
14893             return StartTok.consume_front("const") &&
14894                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14895                     StartTok.startswith("/*") || StartTok.startswith("//"));
14896           };
14897 
14898           auto findBeginLoc = [&]() {
14899             // If the return type has `const` qualifier, we want to insert
14900             // `static` before `const` (and not before the typename).
14901             if ((FD->getReturnType()->isAnyPointerType() &&
14902                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14903                 FD->getReturnType().isConstQualified()) {
14904               // But only do this if we can determine where the `const` is.
14905 
14906               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14907                                getLangOpts()))
14908 
14909                 return FD->getBeginLoc();
14910             }
14911             return FD->getTypeSpecStartLoc();
14912           };
14913           Diag(FD->getTypeSpecStartLoc(),
14914                diag::note_static_for_internal_linkage)
14915               << /* function */ 1
14916               << (FD->getStorageClass() == SC_None
14917                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14918                       : FixItHint{});
14919         }
14920       }
14921 
14922       // If the function being defined does not have a prototype, then we may
14923       // need to diagnose it as changing behavior in C2x because we now know
14924       // whether the function accepts arguments or not. This only handles the
14925       // case where the definition has no prototype but does have parameters
14926       // and either there is no previous potential prototype, or the previous
14927       // potential prototype also has no actual prototype. This handles cases
14928       // like:
14929       //   void f(); void f(a) int a; {}
14930       //   void g(a) int a; {}
14931       // See MergeFunctionDecl() for other cases of the behavior change
14932       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
14933       // type without a prototype.
14934       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
14935           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
14936                                   !PossiblePrototype->isImplicit()))) {
14937         // The function definition has parameters, so this will change behavior
14938         // in C2x. If there is a possible prototype, it comes before the
14939         // function definition.
14940         // FIXME: The declaration may have already been diagnosed as being
14941         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
14942         // there's no way to test for the "changes behavior" condition in
14943         // SemaType.cpp when forming the declaration's function type. So, we do
14944         // this awkward dance instead.
14945         //
14946         // If we have a possible prototype and it declares a function with a
14947         // prototype, we don't want to diagnose it; if we have a possible
14948         // prototype and it has no prototype, it may have already been
14949         // diagnosed in SemaType.cpp as deprecated depending on whether
14950         // -Wstrict-prototypes is enabled. If we already warned about it being
14951         // deprecated, add a note that it also changes behavior. If we didn't
14952         // warn about it being deprecated (because the diagnostic is not
14953         // enabled), warn now that it is deprecated and changes behavior.
14954         bool AddNote = false;
14955         if (PossiblePrototype) {
14956           if (Diags.isIgnored(diag::warn_strict_prototypes,
14957                               PossiblePrototype->getLocation())) {
14958 
14959             PartialDiagnostic PD =
14960                 PDiag(diag::warn_non_prototype_changes_behavior);
14961             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
14962               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
14963                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
14964             }
14965             Diag(PossiblePrototype->getLocation(), PD);
14966           } else {
14967             AddNote = true;
14968           }
14969         }
14970 
14971         // Because this function definition has no prototype and it has
14972         // parameters, it will definitely change behavior in C2x.
14973         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
14974         if (AddNote)
14975           Diag(PossiblePrototype->getLocation(),
14976                diag::note_func_decl_changes_behavior);
14977       }
14978 
14979       // Warn on CPUDispatch with an actual body.
14980       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14981         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14982           if (!CmpndBody->body_empty())
14983             Diag(CmpndBody->body_front()->getBeginLoc(),
14984                  diag::warn_dispatch_body_ignored);
14985 
14986       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14987         const CXXMethodDecl *KeyFunction;
14988         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14989             MD->isVirtual() &&
14990             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14991             MD == KeyFunction->getCanonicalDecl()) {
14992           // Update the key-function state if necessary for this ABI.
14993           if (FD->isInlined() &&
14994               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14995             Context.setNonKeyFunction(MD);
14996 
14997             // If the newly-chosen key function is already defined, then we
14998             // need to mark the vtable as used retroactively.
14999             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15000             const FunctionDecl *Definition;
15001             if (KeyFunction && KeyFunction->isDefined(Definition))
15002               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15003           } else {
15004             // We just defined they key function; mark the vtable as used.
15005             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15006           }
15007         }
15008       }
15009 
15010       assert(
15011           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15012           "Function parsing confused");
15013     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15014       assert(MD == getCurMethodDecl() && "Method parsing confused");
15015       MD->setBody(Body);
15016       if (!MD->isInvalidDecl()) {
15017         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15018                                                MD->getReturnType(), MD);
15019 
15020         if (Body)
15021           computeNRVO(Body, FSI);
15022       }
15023       if (FSI->ObjCShouldCallSuper) {
15024         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15025             << MD->getSelector().getAsString();
15026         FSI->ObjCShouldCallSuper = false;
15027       }
15028       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15029         const ObjCMethodDecl *InitMethod = nullptr;
15030         bool isDesignated =
15031             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15032         assert(isDesignated && InitMethod);
15033         (void)isDesignated;
15034 
15035         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15036           auto IFace = MD->getClassInterface();
15037           if (!IFace)
15038             return false;
15039           auto SuperD = IFace->getSuperClass();
15040           if (!SuperD)
15041             return false;
15042           return SuperD->getIdentifier() ==
15043                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15044         };
15045         // Don't issue this warning for unavailable inits or direct subclasses
15046         // of NSObject.
15047         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15048           Diag(MD->getLocation(),
15049                diag::warn_objc_designated_init_missing_super_call);
15050           Diag(InitMethod->getLocation(),
15051                diag::note_objc_designated_init_marked_here);
15052         }
15053         FSI->ObjCWarnForNoDesignatedInitChain = false;
15054       }
15055       if (FSI->ObjCWarnForNoInitDelegation) {
15056         // Don't issue this warning for unavaialable inits.
15057         if (!MD->isUnavailable())
15058           Diag(MD->getLocation(),
15059                diag::warn_objc_secondary_init_missing_init_call);
15060         FSI->ObjCWarnForNoInitDelegation = false;
15061       }
15062 
15063       diagnoseImplicitlyRetainedSelf(*this);
15064     } else {
15065       // Parsing the function declaration failed in some way. Pop the fake scope
15066       // we pushed on.
15067       PopFunctionScopeInfo(ActivePolicy, dcl);
15068       return nullptr;
15069     }
15070 
15071     if (Body && FSI->HasPotentialAvailabilityViolations)
15072       DiagnoseUnguardedAvailabilityViolations(dcl);
15073 
15074     assert(!FSI->ObjCShouldCallSuper &&
15075            "This should only be set for ObjC methods, which should have been "
15076            "handled in the block above.");
15077 
15078     // Verify and clean out per-function state.
15079     if (Body && (!FD || !FD->isDefaulted())) {
15080       // C++ constructors that have function-try-blocks can't have return
15081       // statements in the handlers of that block. (C++ [except.handle]p14)
15082       // Verify this.
15083       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15084         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15085 
15086       // Verify that gotos and switch cases don't jump into scopes illegally.
15087       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15088         DiagnoseInvalidJumps(Body);
15089 
15090       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15091         if (!Destructor->getParent()->isDependentType())
15092           CheckDestructor(Destructor);
15093 
15094         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15095                                                Destructor->getParent());
15096       }
15097 
15098       // If any errors have occurred, clear out any temporaries that may have
15099       // been leftover. This ensures that these temporaries won't be picked up
15100       // for deletion in some later function.
15101       if (hasUncompilableErrorOccurred() ||
15102           getDiagnostics().getSuppressAllDiagnostics()) {
15103         DiscardCleanupsInEvaluationContext();
15104       }
15105       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15106         // Since the body is valid, issue any analysis-based warnings that are
15107         // enabled.
15108         ActivePolicy = &WP;
15109       }
15110 
15111       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15112           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15113         FD->setInvalidDecl();
15114 
15115       if (FD && FD->hasAttr<NakedAttr>()) {
15116         for (const Stmt *S : Body->children()) {
15117           // Allow local register variables without initializer as they don't
15118           // require prologue.
15119           bool RegisterVariables = false;
15120           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15121             for (const auto *Decl : DS->decls()) {
15122               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15123                 RegisterVariables =
15124                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15125                 if (!RegisterVariables)
15126                   break;
15127               }
15128             }
15129           }
15130           if (RegisterVariables)
15131             continue;
15132           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15133             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15134             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15135             FD->setInvalidDecl();
15136             break;
15137           }
15138         }
15139       }
15140 
15141       assert(ExprCleanupObjects.size() ==
15142                  ExprEvalContexts.back().NumCleanupObjects &&
15143              "Leftover temporaries in function");
15144       assert(!Cleanup.exprNeedsCleanups() &&
15145              "Unaccounted cleanups in function");
15146       assert(MaybeODRUseExprs.empty() &&
15147              "Leftover expressions for odr-use checking");
15148     }
15149   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15150     // the declaration context below. Otherwise, we're unable to transform
15151     // 'this' expressions when transforming immediate context functions.
15152 
15153   if (!IsInstantiation)
15154     PopDeclContext();
15155 
15156   PopFunctionScopeInfo(ActivePolicy, dcl);
15157   // If any errors have occurred, clear out any temporaries that may have
15158   // been leftover. This ensures that these temporaries won't be picked up for
15159   // deletion in some later function.
15160   if (hasUncompilableErrorOccurred()) {
15161     DiscardCleanupsInEvaluationContext();
15162   }
15163 
15164   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15165                                   !LangOpts.OMPTargetTriples.empty())) ||
15166              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15167     auto ES = getEmissionStatus(FD);
15168     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15169         ES == Sema::FunctionEmissionStatus::Unknown)
15170       DeclsToCheckForDeferredDiags.insert(FD);
15171   }
15172 
15173   if (FD && !FD->isDeleted())
15174     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15175 
15176   return dcl;
15177 }
15178 
15179 /// When we finish delayed parsing of an attribute, we must attach it to the
15180 /// relevant Decl.
15181 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15182                                        ParsedAttributes &Attrs) {
15183   // Always attach attributes to the underlying decl.
15184   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15185     D = TD->getTemplatedDecl();
15186   ProcessDeclAttributeList(S, D, Attrs);
15187 
15188   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15189     if (Method->isStatic())
15190       checkThisInStaticMemberFunctionAttributes(Method);
15191 }
15192 
15193 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15194 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15195 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15196                                           IdentifierInfo &II, Scope *S) {
15197   // Find the scope in which the identifier is injected and the corresponding
15198   // DeclContext.
15199   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15200   // In that case, we inject the declaration into the translation unit scope
15201   // instead.
15202   Scope *BlockScope = S;
15203   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15204     BlockScope = BlockScope->getParent();
15205 
15206   Scope *ContextScope = BlockScope;
15207   while (!ContextScope->getEntity())
15208     ContextScope = ContextScope->getParent();
15209   ContextRAII SavedContext(*this, ContextScope->getEntity());
15210 
15211   // Before we produce a declaration for an implicitly defined
15212   // function, see whether there was a locally-scoped declaration of
15213   // this name as a function or variable. If so, use that
15214   // (non-visible) declaration, and complain about it.
15215   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15216   if (ExternCPrev) {
15217     // We still need to inject the function into the enclosing block scope so
15218     // that later (non-call) uses can see it.
15219     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15220 
15221     // C89 footnote 38:
15222     //   If in fact it is not defined as having type "function returning int",
15223     //   the behavior is undefined.
15224     if (!isa<FunctionDecl>(ExternCPrev) ||
15225         !Context.typesAreCompatible(
15226             cast<FunctionDecl>(ExternCPrev)->getType(),
15227             Context.getFunctionNoProtoType(Context.IntTy))) {
15228       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15229           << ExternCPrev << !getLangOpts().C99;
15230       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15231       return ExternCPrev;
15232     }
15233   }
15234 
15235   // Extension in C99.  Legal in C90, but warn about it.
15236   unsigned diag_id;
15237   if (II.getName().startswith("__builtin_"))
15238     diag_id = diag::warn_builtin_unknown;
15239   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15240   else if (getLangOpts().OpenCL)
15241     diag_id = diag::err_opencl_implicit_function_decl;
15242   else if (getLangOpts().C99)
15243     diag_id = diag::ext_implicit_function_decl;
15244   else
15245     diag_id = diag::warn_implicit_function_decl;
15246 
15247   TypoCorrection Corrected;
15248   // Because typo correction is expensive, only do it if the implicit
15249   // function declaration is going to be treated as an error.
15250   //
15251   // Perform the corection before issuing the main diagnostic, as some consumers
15252   // use typo-correction callbacks to enhance the main diagnostic.
15253   if (S && !ExternCPrev &&
15254       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15255     DeclFilterCCC<FunctionDecl> CCC{};
15256     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15257                             S, nullptr, CCC, CTK_NonError);
15258   }
15259 
15260   Diag(Loc, diag_id) << &II;
15261   if (Corrected)
15262     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15263                  /*ErrorRecovery*/ false);
15264 
15265   // If we found a prior declaration of this function, don't bother building
15266   // another one. We've already pushed that one into scope, so there's nothing
15267   // more to do.
15268   if (ExternCPrev)
15269     return ExternCPrev;
15270 
15271   // Set a Declarator for the implicit definition: int foo();
15272   const char *Dummy;
15273   AttributeFactory attrFactory;
15274   DeclSpec DS(attrFactory);
15275   unsigned DiagID;
15276   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15277                                   Context.getPrintingPolicy());
15278   (void)Error; // Silence warning.
15279   assert(!Error && "Error setting up implicit decl!");
15280   SourceLocation NoLoc;
15281   Declarator D(DS, DeclaratorContext::Block);
15282   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15283                                              /*IsAmbiguous=*/false,
15284                                              /*LParenLoc=*/NoLoc,
15285                                              /*Params=*/nullptr,
15286                                              /*NumParams=*/0,
15287                                              /*EllipsisLoc=*/NoLoc,
15288                                              /*RParenLoc=*/NoLoc,
15289                                              /*RefQualifierIsLvalueRef=*/true,
15290                                              /*RefQualifierLoc=*/NoLoc,
15291                                              /*MutableLoc=*/NoLoc, EST_None,
15292                                              /*ESpecRange=*/SourceRange(),
15293                                              /*Exceptions=*/nullptr,
15294                                              /*ExceptionRanges=*/nullptr,
15295                                              /*NumExceptions=*/0,
15296                                              /*NoexceptExpr=*/nullptr,
15297                                              /*ExceptionSpecTokens=*/nullptr,
15298                                              /*DeclsInPrototype=*/None, Loc,
15299                                              Loc, D),
15300                 std::move(DS.getAttributes()), SourceLocation());
15301   D.SetIdentifier(&II, Loc);
15302 
15303   // Insert this function into the enclosing block scope.
15304   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15305   FD->setImplicit();
15306 
15307   AddKnownFunctionAttributes(FD);
15308 
15309   return FD;
15310 }
15311 
15312 /// If this function is a C++ replaceable global allocation function
15313 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15314 /// adds any function attributes that we know a priori based on the standard.
15315 ///
15316 /// We need to check for duplicate attributes both here and where user-written
15317 /// attributes are applied to declarations.
15318 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15319     FunctionDecl *FD) {
15320   if (FD->isInvalidDecl())
15321     return;
15322 
15323   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15324       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15325     return;
15326 
15327   Optional<unsigned> AlignmentParam;
15328   bool IsNothrow = false;
15329   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15330     return;
15331 
15332   // C++2a [basic.stc.dynamic.allocation]p4:
15333   //   An allocation function that has a non-throwing exception specification
15334   //   indicates failure by returning a null pointer value. Any other allocation
15335   //   function never returns a null pointer value and indicates failure only by
15336   //   throwing an exception [...]
15337   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15338     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15339 
15340   // C++2a [basic.stc.dynamic.allocation]p2:
15341   //   An allocation function attempts to allocate the requested amount of
15342   //   storage. [...] If the request succeeds, the value returned by a
15343   //   replaceable allocation function is a [...] pointer value p0 different
15344   //   from any previously returned value p1 [...]
15345   //
15346   // However, this particular information is being added in codegen,
15347   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15348 
15349   // C++2a [basic.stc.dynamic.allocation]p2:
15350   //   An allocation function attempts to allocate the requested amount of
15351   //   storage. If it is successful, it returns the address of the start of a
15352   //   block of storage whose length in bytes is at least as large as the
15353   //   requested size.
15354   if (!FD->hasAttr<AllocSizeAttr>()) {
15355     FD->addAttr(AllocSizeAttr::CreateImplicit(
15356         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15357         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15358   }
15359 
15360   // C++2a [basic.stc.dynamic.allocation]p3:
15361   //   For an allocation function [...], the pointer returned on a successful
15362   //   call shall represent the address of storage that is aligned as follows:
15363   //   (3.1) If the allocation function takes an argument of type
15364   //         std​::​align_­val_­t, the storage will have the alignment
15365   //         specified by the value of this argument.
15366   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15367     FD->addAttr(AllocAlignAttr::CreateImplicit(
15368         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15369   }
15370 
15371   // FIXME:
15372   // C++2a [basic.stc.dynamic.allocation]p3:
15373   //   For an allocation function [...], the pointer returned on a successful
15374   //   call shall represent the address of storage that is aligned as follows:
15375   //   (3.2) Otherwise, if the allocation function is named operator new[],
15376   //         the storage is aligned for any object that does not have
15377   //         new-extended alignment ([basic.align]) and is no larger than the
15378   //         requested size.
15379   //   (3.3) Otherwise, the storage is aligned for any object that does not
15380   //         have new-extended alignment and is of the requested size.
15381 }
15382 
15383 /// Adds any function attributes that we know a priori based on
15384 /// the declaration of this function.
15385 ///
15386 /// These attributes can apply both to implicitly-declared builtins
15387 /// (like __builtin___printf_chk) or to library-declared functions
15388 /// like NSLog or printf.
15389 ///
15390 /// We need to check for duplicate attributes both here and where user-written
15391 /// attributes are applied to declarations.
15392 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15393   if (FD->isInvalidDecl())
15394     return;
15395 
15396   // If this is a built-in function, map its builtin attributes to
15397   // actual attributes.
15398   if (unsigned BuiltinID = FD->getBuiltinID()) {
15399     // Handle printf-formatting attributes.
15400     unsigned FormatIdx;
15401     bool HasVAListArg;
15402     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15403       if (!FD->hasAttr<FormatAttr>()) {
15404         const char *fmt = "printf";
15405         unsigned int NumParams = FD->getNumParams();
15406         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15407             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15408           fmt = "NSString";
15409         FD->addAttr(FormatAttr::CreateImplicit(Context,
15410                                                &Context.Idents.get(fmt),
15411                                                FormatIdx+1,
15412                                                HasVAListArg ? 0 : FormatIdx+2,
15413                                                FD->getLocation()));
15414       }
15415     }
15416     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15417                                              HasVAListArg)) {
15418      if (!FD->hasAttr<FormatAttr>())
15419        FD->addAttr(FormatAttr::CreateImplicit(Context,
15420                                               &Context.Idents.get("scanf"),
15421                                               FormatIdx+1,
15422                                               HasVAListArg ? 0 : FormatIdx+2,
15423                                               FD->getLocation()));
15424     }
15425 
15426     // Handle automatically recognized callbacks.
15427     SmallVector<int, 4> Encoding;
15428     if (!FD->hasAttr<CallbackAttr>() &&
15429         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15430       FD->addAttr(CallbackAttr::CreateImplicit(
15431           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15432 
15433     // Mark const if we don't care about errno and that is the only thing
15434     // preventing the function from being const. This allows IRgen to use LLVM
15435     // intrinsics for such functions.
15436     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15437         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15438       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15439 
15440     // We make "fma" on GNU or Windows const because we know it does not set
15441     // errno in those environments even though it could set errno based on the
15442     // C standard.
15443     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15444     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15445         !FD->hasAttr<ConstAttr>()) {
15446       switch (BuiltinID) {
15447       case Builtin::BI__builtin_fma:
15448       case Builtin::BI__builtin_fmaf:
15449       case Builtin::BI__builtin_fmal:
15450       case Builtin::BIfma:
15451       case Builtin::BIfmaf:
15452       case Builtin::BIfmal:
15453         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15454         break;
15455       default:
15456         break;
15457       }
15458     }
15459 
15460     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15461         !FD->hasAttr<ReturnsTwiceAttr>())
15462       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15463                                          FD->getLocation()));
15464     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15465       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15466     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15467       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15468     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15469       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15470     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15471         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15472       // Add the appropriate attribute, depending on the CUDA compilation mode
15473       // and which target the builtin belongs to. For example, during host
15474       // compilation, aux builtins are __device__, while the rest are __host__.
15475       if (getLangOpts().CUDAIsDevice !=
15476           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15477         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15478       else
15479         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15480     }
15481 
15482     // Add known guaranteed alignment for allocation functions.
15483     switch (BuiltinID) {
15484     case Builtin::BImemalign:
15485     case Builtin::BIaligned_alloc:
15486       if (!FD->hasAttr<AllocAlignAttr>())
15487         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15488                                                    FD->getLocation()));
15489       break;
15490     default:
15491       break;
15492     }
15493 
15494     // Add allocsize attribute for allocation functions.
15495     switch (BuiltinID) {
15496     case Builtin::BIcalloc:
15497       FD->addAttr(AllocSizeAttr::CreateImplicit(
15498           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15499       break;
15500     case Builtin::BImemalign:
15501     case Builtin::BIaligned_alloc:
15502     case Builtin::BIrealloc:
15503       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15504                                                 ParamIdx(), FD->getLocation()));
15505       break;
15506     case Builtin::BImalloc:
15507       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15508                                                 ParamIdx(), FD->getLocation()));
15509       break;
15510     default:
15511       break;
15512     }
15513   }
15514 
15515   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15516 
15517   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15518   // throw, add an implicit nothrow attribute to any extern "C" function we come
15519   // across.
15520   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15521       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15522     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15523     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15524       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15525   }
15526 
15527   IdentifierInfo *Name = FD->getIdentifier();
15528   if (!Name)
15529     return;
15530   if ((!getLangOpts().CPlusPlus &&
15531        FD->getDeclContext()->isTranslationUnit()) ||
15532       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15533        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15534        LinkageSpecDecl::lang_c)) {
15535     // Okay: this could be a libc/libm/Objective-C function we know
15536     // about.
15537   } else
15538     return;
15539 
15540   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15541     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15542     // target-specific builtins, perhaps?
15543     if (!FD->hasAttr<FormatAttr>())
15544       FD->addAttr(FormatAttr::CreateImplicit(Context,
15545                                              &Context.Idents.get("printf"), 2,
15546                                              Name->isStr("vasprintf") ? 0 : 3,
15547                                              FD->getLocation()));
15548   }
15549 
15550   if (Name->isStr("__CFStringMakeConstantString")) {
15551     // We already have a __builtin___CFStringMakeConstantString,
15552     // but builds that use -fno-constant-cfstrings don't go through that.
15553     if (!FD->hasAttr<FormatArgAttr>())
15554       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15555                                                 FD->getLocation()));
15556   }
15557 }
15558 
15559 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15560                                     TypeSourceInfo *TInfo) {
15561   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15562   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15563 
15564   if (!TInfo) {
15565     assert(D.isInvalidType() && "no declarator info for valid type");
15566     TInfo = Context.getTrivialTypeSourceInfo(T);
15567   }
15568 
15569   // Scope manipulation handled by caller.
15570   TypedefDecl *NewTD =
15571       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15572                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15573 
15574   // Bail out immediately if we have an invalid declaration.
15575   if (D.isInvalidType()) {
15576     NewTD->setInvalidDecl();
15577     return NewTD;
15578   }
15579 
15580   if (D.getDeclSpec().isModulePrivateSpecified()) {
15581     if (CurContext->isFunctionOrMethod())
15582       Diag(NewTD->getLocation(), diag::err_module_private_local)
15583           << 2 << NewTD
15584           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15585           << FixItHint::CreateRemoval(
15586                  D.getDeclSpec().getModulePrivateSpecLoc());
15587     else
15588       NewTD->setModulePrivate();
15589   }
15590 
15591   // C++ [dcl.typedef]p8:
15592   //   If the typedef declaration defines an unnamed class (or
15593   //   enum), the first typedef-name declared by the declaration
15594   //   to be that class type (or enum type) is used to denote the
15595   //   class type (or enum type) for linkage purposes only.
15596   // We need to check whether the type was declared in the declaration.
15597   switch (D.getDeclSpec().getTypeSpecType()) {
15598   case TST_enum:
15599   case TST_struct:
15600   case TST_interface:
15601   case TST_union:
15602   case TST_class: {
15603     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15604     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15605     break;
15606   }
15607 
15608   default:
15609     break;
15610   }
15611 
15612   return NewTD;
15613 }
15614 
15615 /// Check that this is a valid underlying type for an enum declaration.
15616 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15617   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15618   QualType T = TI->getType();
15619 
15620   if (T->isDependentType())
15621     return false;
15622 
15623   // This doesn't use 'isIntegralType' despite the error message mentioning
15624   // integral type because isIntegralType would also allow enum types in C.
15625   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15626     if (BT->isInteger())
15627       return false;
15628 
15629   if (T->isBitIntType())
15630     return false;
15631 
15632   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15633 }
15634 
15635 /// Check whether this is a valid redeclaration of a previous enumeration.
15636 /// \return true if the redeclaration was invalid.
15637 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15638                                   QualType EnumUnderlyingTy, bool IsFixed,
15639                                   const EnumDecl *Prev) {
15640   if (IsScoped != Prev->isScoped()) {
15641     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15642       << Prev->isScoped();
15643     Diag(Prev->getLocation(), diag::note_previous_declaration);
15644     return true;
15645   }
15646 
15647   if (IsFixed && Prev->isFixed()) {
15648     if (!EnumUnderlyingTy->isDependentType() &&
15649         !Prev->getIntegerType()->isDependentType() &&
15650         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15651                                         Prev->getIntegerType())) {
15652       // TODO: Highlight the underlying type of the redeclaration.
15653       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15654         << EnumUnderlyingTy << Prev->getIntegerType();
15655       Diag(Prev->getLocation(), diag::note_previous_declaration)
15656           << Prev->getIntegerTypeRange();
15657       return true;
15658     }
15659   } else if (IsFixed != Prev->isFixed()) {
15660     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15661       << Prev->isFixed();
15662     Diag(Prev->getLocation(), diag::note_previous_declaration);
15663     return true;
15664   }
15665 
15666   return false;
15667 }
15668 
15669 /// Get diagnostic %select index for tag kind for
15670 /// redeclaration diagnostic message.
15671 /// WARNING: Indexes apply to particular diagnostics only!
15672 ///
15673 /// \returns diagnostic %select index.
15674 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15675   switch (Tag) {
15676   case TTK_Struct: return 0;
15677   case TTK_Interface: return 1;
15678   case TTK_Class:  return 2;
15679   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15680   }
15681 }
15682 
15683 /// Determine if tag kind is a class-key compatible with
15684 /// class for redeclaration (class, struct, or __interface).
15685 ///
15686 /// \returns true iff the tag kind is compatible.
15687 static bool isClassCompatTagKind(TagTypeKind Tag)
15688 {
15689   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15690 }
15691 
15692 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15693                                              TagTypeKind TTK) {
15694   if (isa<TypedefDecl>(PrevDecl))
15695     return NTK_Typedef;
15696   else if (isa<TypeAliasDecl>(PrevDecl))
15697     return NTK_TypeAlias;
15698   else if (isa<ClassTemplateDecl>(PrevDecl))
15699     return NTK_Template;
15700   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15701     return NTK_TypeAliasTemplate;
15702   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15703     return NTK_TemplateTemplateArgument;
15704   switch (TTK) {
15705   case TTK_Struct:
15706   case TTK_Interface:
15707   case TTK_Class:
15708     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15709   case TTK_Union:
15710     return NTK_NonUnion;
15711   case TTK_Enum:
15712     return NTK_NonEnum;
15713   }
15714   llvm_unreachable("invalid TTK");
15715 }
15716 
15717 /// Determine whether a tag with a given kind is acceptable
15718 /// as a redeclaration of the given tag declaration.
15719 ///
15720 /// \returns true if the new tag kind is acceptable, false otherwise.
15721 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15722                                         TagTypeKind NewTag, bool isDefinition,
15723                                         SourceLocation NewTagLoc,
15724                                         const IdentifierInfo *Name) {
15725   // C++ [dcl.type.elab]p3:
15726   //   The class-key or enum keyword present in the
15727   //   elaborated-type-specifier shall agree in kind with the
15728   //   declaration to which the name in the elaborated-type-specifier
15729   //   refers. This rule also applies to the form of
15730   //   elaborated-type-specifier that declares a class-name or
15731   //   friend class since it can be construed as referring to the
15732   //   definition of the class. Thus, in any
15733   //   elaborated-type-specifier, the enum keyword shall be used to
15734   //   refer to an enumeration (7.2), the union class-key shall be
15735   //   used to refer to a union (clause 9), and either the class or
15736   //   struct class-key shall be used to refer to a class (clause 9)
15737   //   declared using the class or struct class-key.
15738   TagTypeKind OldTag = Previous->getTagKind();
15739   if (OldTag != NewTag &&
15740       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15741     return false;
15742 
15743   // Tags are compatible, but we might still want to warn on mismatched tags.
15744   // Non-class tags can't be mismatched at this point.
15745   if (!isClassCompatTagKind(NewTag))
15746     return true;
15747 
15748   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15749   // by our warning analysis. We don't want to warn about mismatches with (eg)
15750   // declarations in system headers that are designed to be specialized, but if
15751   // a user asks us to warn, we should warn if their code contains mismatched
15752   // declarations.
15753   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15754     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15755                                       Loc);
15756   };
15757   if (IsIgnoredLoc(NewTagLoc))
15758     return true;
15759 
15760   auto IsIgnored = [&](const TagDecl *Tag) {
15761     return IsIgnoredLoc(Tag->getLocation());
15762   };
15763   while (IsIgnored(Previous)) {
15764     Previous = Previous->getPreviousDecl();
15765     if (!Previous)
15766       return true;
15767     OldTag = Previous->getTagKind();
15768   }
15769 
15770   bool isTemplate = false;
15771   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15772     isTemplate = Record->getDescribedClassTemplate();
15773 
15774   if (inTemplateInstantiation()) {
15775     if (OldTag != NewTag) {
15776       // In a template instantiation, do not offer fix-its for tag mismatches
15777       // since they usually mess up the template instead of fixing the problem.
15778       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15779         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15780         << getRedeclDiagFromTagKind(OldTag);
15781       // FIXME: Note previous location?
15782     }
15783     return true;
15784   }
15785 
15786   if (isDefinition) {
15787     // On definitions, check all previous tags and issue a fix-it for each
15788     // one that doesn't match the current tag.
15789     if (Previous->getDefinition()) {
15790       // Don't suggest fix-its for redefinitions.
15791       return true;
15792     }
15793 
15794     bool previousMismatch = false;
15795     for (const TagDecl *I : Previous->redecls()) {
15796       if (I->getTagKind() != NewTag) {
15797         // Ignore previous declarations for which the warning was disabled.
15798         if (IsIgnored(I))
15799           continue;
15800 
15801         if (!previousMismatch) {
15802           previousMismatch = true;
15803           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15804             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15805             << getRedeclDiagFromTagKind(I->getTagKind());
15806         }
15807         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15808           << getRedeclDiagFromTagKind(NewTag)
15809           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15810                TypeWithKeyword::getTagTypeKindName(NewTag));
15811       }
15812     }
15813     return true;
15814   }
15815 
15816   // Identify the prevailing tag kind: this is the kind of the definition (if
15817   // there is a non-ignored definition), or otherwise the kind of the prior
15818   // (non-ignored) declaration.
15819   const TagDecl *PrevDef = Previous->getDefinition();
15820   if (PrevDef && IsIgnored(PrevDef))
15821     PrevDef = nullptr;
15822   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15823   if (Redecl->getTagKind() != NewTag) {
15824     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15825       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15826       << getRedeclDiagFromTagKind(OldTag);
15827     Diag(Redecl->getLocation(), diag::note_previous_use);
15828 
15829     // If there is a previous definition, suggest a fix-it.
15830     if (PrevDef) {
15831       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15832         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15833         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15834              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15835     }
15836   }
15837 
15838   return true;
15839 }
15840 
15841 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15842 /// from an outer enclosing namespace or file scope inside a friend declaration.
15843 /// This should provide the commented out code in the following snippet:
15844 ///   namespace N {
15845 ///     struct X;
15846 ///     namespace M {
15847 ///       struct Y { friend struct /*N::*/ X; };
15848 ///     }
15849 ///   }
15850 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15851                                          SourceLocation NameLoc) {
15852   // While the decl is in a namespace, do repeated lookup of that name and see
15853   // if we get the same namespace back.  If we do not, continue until
15854   // translation unit scope, at which point we have a fully qualified NNS.
15855   SmallVector<IdentifierInfo *, 4> Namespaces;
15856   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15857   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15858     // This tag should be declared in a namespace, which can only be enclosed by
15859     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15860     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15861     if (!Namespace || Namespace->isAnonymousNamespace())
15862       return FixItHint();
15863     IdentifierInfo *II = Namespace->getIdentifier();
15864     Namespaces.push_back(II);
15865     NamedDecl *Lookup = SemaRef.LookupSingleName(
15866         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15867     if (Lookup == Namespace)
15868       break;
15869   }
15870 
15871   // Once we have all the namespaces, reverse them to go outermost first, and
15872   // build an NNS.
15873   SmallString<64> Insertion;
15874   llvm::raw_svector_ostream OS(Insertion);
15875   if (DC->isTranslationUnit())
15876     OS << "::";
15877   std::reverse(Namespaces.begin(), Namespaces.end());
15878   for (auto *II : Namespaces)
15879     OS << II->getName() << "::";
15880   return FixItHint::CreateInsertion(NameLoc, Insertion);
15881 }
15882 
15883 /// Determine whether a tag originally declared in context \p OldDC can
15884 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15885 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15886 /// using-declaration).
15887 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15888                                          DeclContext *NewDC) {
15889   OldDC = OldDC->getRedeclContext();
15890   NewDC = NewDC->getRedeclContext();
15891 
15892   if (OldDC->Equals(NewDC))
15893     return true;
15894 
15895   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15896   // encloses the other).
15897   if (S.getLangOpts().MSVCCompat &&
15898       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15899     return true;
15900 
15901   return false;
15902 }
15903 
15904 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15905 /// former case, Name will be non-null.  In the later case, Name will be null.
15906 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15907 /// reference/declaration/definition of a tag.
15908 ///
15909 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15910 /// trailing-type-specifier) other than one in an alias-declaration.
15911 ///
15912 /// \param SkipBody If non-null, will be set to indicate if the caller should
15913 /// skip the definition of this tag and treat it as if it were a declaration.
15914 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15915                      SourceLocation KWLoc, CXXScopeSpec &SS,
15916                      IdentifierInfo *Name, SourceLocation NameLoc,
15917                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15918                      SourceLocation ModulePrivateLoc,
15919                      MultiTemplateParamsArg TemplateParameterLists,
15920                      bool &OwnedDecl, bool &IsDependent,
15921                      SourceLocation ScopedEnumKWLoc,
15922                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15923                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15924                      SkipBodyInfo *SkipBody) {
15925   // If this is not a definition, it must have a name.
15926   IdentifierInfo *OrigName = Name;
15927   assert((Name != nullptr || TUK == TUK_Definition) &&
15928          "Nameless record must be a definition!");
15929   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15930 
15931   OwnedDecl = false;
15932   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15933   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15934 
15935   // FIXME: Check member specializations more carefully.
15936   bool isMemberSpecialization = false;
15937   bool Invalid = false;
15938 
15939   // We only need to do this matching if we have template parameters
15940   // or a scope specifier, which also conveniently avoids this work
15941   // for non-C++ cases.
15942   if (TemplateParameterLists.size() > 0 ||
15943       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15944     if (TemplateParameterList *TemplateParams =
15945             MatchTemplateParametersToScopeSpecifier(
15946                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15947                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15948       if (Kind == TTK_Enum) {
15949         Diag(KWLoc, diag::err_enum_template);
15950         return nullptr;
15951       }
15952 
15953       if (TemplateParams->size() > 0) {
15954         // This is a declaration or definition of a class template (which may
15955         // be a member of another template).
15956 
15957         if (Invalid)
15958           return nullptr;
15959 
15960         OwnedDecl = false;
15961         DeclResult Result = CheckClassTemplate(
15962             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15963             AS, ModulePrivateLoc,
15964             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15965             TemplateParameterLists.data(), SkipBody);
15966         return Result.get();
15967       } else {
15968         // The "template<>" header is extraneous.
15969         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15970           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15971         isMemberSpecialization = true;
15972       }
15973     }
15974 
15975     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15976         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15977       return nullptr;
15978   }
15979 
15980   // Figure out the underlying type if this a enum declaration. We need to do
15981   // this early, because it's needed to detect if this is an incompatible
15982   // redeclaration.
15983   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15984   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15985 
15986   if (Kind == TTK_Enum) {
15987     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15988       // No underlying type explicitly specified, or we failed to parse the
15989       // type, default to int.
15990       EnumUnderlying = Context.IntTy.getTypePtr();
15991     } else if (UnderlyingType.get()) {
15992       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15993       // integral type; any cv-qualification is ignored.
15994       TypeSourceInfo *TI = nullptr;
15995       GetTypeFromParser(UnderlyingType.get(), &TI);
15996       EnumUnderlying = TI;
15997 
15998       if (CheckEnumUnderlyingType(TI))
15999         // Recover by falling back to int.
16000         EnumUnderlying = Context.IntTy.getTypePtr();
16001 
16002       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16003                                           UPPC_FixedUnderlyingType))
16004         EnumUnderlying = Context.IntTy.getTypePtr();
16005 
16006     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16007       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16008       // of 'int'. However, if this is an unfixed forward declaration, don't set
16009       // the underlying type unless the user enables -fms-compatibility. This
16010       // makes unfixed forward declared enums incomplete and is more conforming.
16011       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16012         EnumUnderlying = Context.IntTy.getTypePtr();
16013     }
16014   }
16015 
16016   DeclContext *SearchDC = CurContext;
16017   DeclContext *DC = CurContext;
16018   bool isStdBadAlloc = false;
16019   bool isStdAlignValT = false;
16020 
16021   RedeclarationKind Redecl = forRedeclarationInCurContext();
16022   if (TUK == TUK_Friend || TUK == TUK_Reference)
16023     Redecl = NotForRedeclaration;
16024 
16025   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16026   /// implemented asks for structural equivalence checking, the returned decl
16027   /// here is passed back to the parser, allowing the tag body to be parsed.
16028   auto createTagFromNewDecl = [&]() -> TagDecl * {
16029     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16030     // If there is an identifier, use the location of the identifier as the
16031     // location of the decl, otherwise use the location of the struct/union
16032     // keyword.
16033     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16034     TagDecl *New = nullptr;
16035 
16036     if (Kind == TTK_Enum) {
16037       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16038                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16039       // If this is an undefined enum, bail.
16040       if (TUK != TUK_Definition && !Invalid)
16041         return nullptr;
16042       if (EnumUnderlying) {
16043         EnumDecl *ED = cast<EnumDecl>(New);
16044         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16045           ED->setIntegerTypeSourceInfo(TI);
16046         else
16047           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16048         ED->setPromotionType(ED->getIntegerType());
16049       }
16050     } else { // struct/union
16051       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16052                                nullptr);
16053     }
16054 
16055     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16056       // Add alignment attributes if necessary; these attributes are checked
16057       // when the ASTContext lays out the structure.
16058       //
16059       // It is important for implementing the correct semantics that this
16060       // happen here (in ActOnTag). The #pragma pack stack is
16061       // maintained as a result of parser callbacks which can occur at
16062       // many points during the parsing of a struct declaration (because
16063       // the #pragma tokens are effectively skipped over during the
16064       // parsing of the struct).
16065       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16066         AddAlignmentAttributesForRecord(RD);
16067         AddMsStructLayoutForRecord(RD);
16068       }
16069     }
16070     New->setLexicalDeclContext(CurContext);
16071     return New;
16072   };
16073 
16074   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16075   if (Name && SS.isNotEmpty()) {
16076     // We have a nested-name tag ('struct foo::bar').
16077 
16078     // Check for invalid 'foo::'.
16079     if (SS.isInvalid()) {
16080       Name = nullptr;
16081       goto CreateNewDecl;
16082     }
16083 
16084     // If this is a friend or a reference to a class in a dependent
16085     // context, don't try to make a decl for it.
16086     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16087       DC = computeDeclContext(SS, false);
16088       if (!DC) {
16089         IsDependent = true;
16090         return nullptr;
16091       }
16092     } else {
16093       DC = computeDeclContext(SS, true);
16094       if (!DC) {
16095         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16096           << SS.getRange();
16097         return nullptr;
16098       }
16099     }
16100 
16101     if (RequireCompleteDeclContext(SS, DC))
16102       return nullptr;
16103 
16104     SearchDC = DC;
16105     // Look-up name inside 'foo::'.
16106     LookupQualifiedName(Previous, DC);
16107 
16108     if (Previous.isAmbiguous())
16109       return nullptr;
16110 
16111     if (Previous.empty()) {
16112       // Name lookup did not find anything. However, if the
16113       // nested-name-specifier refers to the current instantiation,
16114       // and that current instantiation has any dependent base
16115       // classes, we might find something at instantiation time: treat
16116       // this as a dependent elaborated-type-specifier.
16117       // But this only makes any sense for reference-like lookups.
16118       if (Previous.wasNotFoundInCurrentInstantiation() &&
16119           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16120         IsDependent = true;
16121         return nullptr;
16122       }
16123 
16124       // A tag 'foo::bar' must already exist.
16125       Diag(NameLoc, diag::err_not_tag_in_scope)
16126         << Kind << Name << DC << SS.getRange();
16127       Name = nullptr;
16128       Invalid = true;
16129       goto CreateNewDecl;
16130     }
16131   } else if (Name) {
16132     // C++14 [class.mem]p14:
16133     //   If T is the name of a class, then each of the following shall have a
16134     //   name different from T:
16135     //    -- every member of class T that is itself a type
16136     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16137         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16138       return nullptr;
16139 
16140     // If this is a named struct, check to see if there was a previous forward
16141     // declaration or definition.
16142     // FIXME: We're looking into outer scopes here, even when we
16143     // shouldn't be. Doing so can result in ambiguities that we
16144     // shouldn't be diagnosing.
16145     LookupName(Previous, S);
16146 
16147     // When declaring or defining a tag, ignore ambiguities introduced
16148     // by types using'ed into this scope.
16149     if (Previous.isAmbiguous() &&
16150         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16151       LookupResult::Filter F = Previous.makeFilter();
16152       while (F.hasNext()) {
16153         NamedDecl *ND = F.next();
16154         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16155                 SearchDC->getRedeclContext()))
16156           F.erase();
16157       }
16158       F.done();
16159     }
16160 
16161     // C++11 [namespace.memdef]p3:
16162     //   If the name in a friend declaration is neither qualified nor
16163     //   a template-id and the declaration is a function or an
16164     //   elaborated-type-specifier, the lookup to determine whether
16165     //   the entity has been previously declared shall not consider
16166     //   any scopes outside the innermost enclosing namespace.
16167     //
16168     // MSVC doesn't implement the above rule for types, so a friend tag
16169     // declaration may be a redeclaration of a type declared in an enclosing
16170     // scope.  They do implement this rule for friend functions.
16171     //
16172     // Does it matter that this should be by scope instead of by
16173     // semantic context?
16174     if (!Previous.empty() && TUK == TUK_Friend) {
16175       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16176       LookupResult::Filter F = Previous.makeFilter();
16177       bool FriendSawTagOutsideEnclosingNamespace = false;
16178       while (F.hasNext()) {
16179         NamedDecl *ND = F.next();
16180         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16181         if (DC->isFileContext() &&
16182             !EnclosingNS->Encloses(ND->getDeclContext())) {
16183           if (getLangOpts().MSVCCompat)
16184             FriendSawTagOutsideEnclosingNamespace = true;
16185           else
16186             F.erase();
16187         }
16188       }
16189       F.done();
16190 
16191       // Diagnose this MSVC extension in the easy case where lookup would have
16192       // unambiguously found something outside the enclosing namespace.
16193       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16194         NamedDecl *ND = Previous.getFoundDecl();
16195         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16196             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16197       }
16198     }
16199 
16200     // Note:  there used to be some attempt at recovery here.
16201     if (Previous.isAmbiguous())
16202       return nullptr;
16203 
16204     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16205       // FIXME: This makes sure that we ignore the contexts associated
16206       // with C structs, unions, and enums when looking for a matching
16207       // tag declaration or definition. See the similar lookup tweak
16208       // in Sema::LookupName; is there a better way to deal with this?
16209       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16210         SearchDC = SearchDC->getParent();
16211     } else if (getLangOpts().CPlusPlus) {
16212       // Inside ObjCContainer want to keep it as a lexical decl context but go
16213       // past it (most often to TranslationUnit) to find the semantic decl
16214       // context.
16215       while (isa<ObjCContainerDecl>(SearchDC))
16216         SearchDC = SearchDC->getParent();
16217     }
16218   } else if (getLangOpts().CPlusPlus) {
16219     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16220     // TagDecl the same way as we skip it for named TagDecl.
16221     while (isa<ObjCContainerDecl>(SearchDC))
16222       SearchDC = SearchDC->getParent();
16223   }
16224 
16225   if (Previous.isSingleResult() &&
16226       Previous.getFoundDecl()->isTemplateParameter()) {
16227     // Maybe we will complain about the shadowed template parameter.
16228     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16229     // Just pretend that we didn't see the previous declaration.
16230     Previous.clear();
16231   }
16232 
16233   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16234       DC->Equals(getStdNamespace())) {
16235     if (Name->isStr("bad_alloc")) {
16236       // This is a declaration of or a reference to "std::bad_alloc".
16237       isStdBadAlloc = true;
16238 
16239       // If std::bad_alloc has been implicitly declared (but made invisible to
16240       // name lookup), fill in this implicit declaration as the previous
16241       // declaration, so that the declarations get chained appropriately.
16242       if (Previous.empty() && StdBadAlloc)
16243         Previous.addDecl(getStdBadAlloc());
16244     } else if (Name->isStr("align_val_t")) {
16245       isStdAlignValT = true;
16246       if (Previous.empty() && StdAlignValT)
16247         Previous.addDecl(getStdAlignValT());
16248     }
16249   }
16250 
16251   // If we didn't find a previous declaration, and this is a reference
16252   // (or friend reference), move to the correct scope.  In C++, we
16253   // also need to do a redeclaration lookup there, just in case
16254   // there's a shadow friend decl.
16255   if (Name && Previous.empty() &&
16256       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16257     if (Invalid) goto CreateNewDecl;
16258     assert(SS.isEmpty());
16259 
16260     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16261       // C++ [basic.scope.pdecl]p5:
16262       //   -- for an elaborated-type-specifier of the form
16263       //
16264       //          class-key identifier
16265       //
16266       //      if the elaborated-type-specifier is used in the
16267       //      decl-specifier-seq or parameter-declaration-clause of a
16268       //      function defined in namespace scope, the identifier is
16269       //      declared as a class-name in the namespace that contains
16270       //      the declaration; otherwise, except as a friend
16271       //      declaration, the identifier is declared in the smallest
16272       //      non-class, non-function-prototype scope that contains the
16273       //      declaration.
16274       //
16275       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16276       // C structs and unions.
16277       //
16278       // It is an error in C++ to declare (rather than define) an enum
16279       // type, including via an elaborated type specifier.  We'll
16280       // diagnose that later; for now, declare the enum in the same
16281       // scope as we would have picked for any other tag type.
16282       //
16283       // GNU C also supports this behavior as part of its incomplete
16284       // enum types extension, while GNU C++ does not.
16285       //
16286       // Find the context where we'll be declaring the tag.
16287       // FIXME: We would like to maintain the current DeclContext as the
16288       // lexical context,
16289       SearchDC = getTagInjectionContext(SearchDC);
16290 
16291       // Find the scope where we'll be declaring the tag.
16292       S = getTagInjectionScope(S, getLangOpts());
16293     } else {
16294       assert(TUK == TUK_Friend);
16295       // C++ [namespace.memdef]p3:
16296       //   If a friend declaration in a non-local class first declares a
16297       //   class or function, the friend class or function is a member of
16298       //   the innermost enclosing namespace.
16299       SearchDC = SearchDC->getEnclosingNamespaceContext();
16300     }
16301 
16302     // In C++, we need to do a redeclaration lookup to properly
16303     // diagnose some problems.
16304     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16305     // hidden declaration so that we don't get ambiguity errors when using a
16306     // type declared by an elaborated-type-specifier.  In C that is not correct
16307     // and we should instead merge compatible types found by lookup.
16308     if (getLangOpts().CPlusPlus) {
16309       // FIXME: This can perform qualified lookups into function contexts,
16310       // which are meaningless.
16311       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16312       LookupQualifiedName(Previous, SearchDC);
16313     } else {
16314       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16315       LookupName(Previous, S);
16316     }
16317   }
16318 
16319   // If we have a known previous declaration to use, then use it.
16320   if (Previous.empty() && SkipBody && SkipBody->Previous)
16321     Previous.addDecl(SkipBody->Previous);
16322 
16323   if (!Previous.empty()) {
16324     NamedDecl *PrevDecl = Previous.getFoundDecl();
16325     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16326 
16327     // It's okay to have a tag decl in the same scope as a typedef
16328     // which hides a tag decl in the same scope.  Finding this
16329     // with a redeclaration lookup can only actually happen in C++.
16330     //
16331     // This is also okay for elaborated-type-specifiers, which is
16332     // technically forbidden by the current standard but which is
16333     // okay according to the likely resolution of an open issue;
16334     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16335     if (getLangOpts().CPlusPlus) {
16336       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16337         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16338           TagDecl *Tag = TT->getDecl();
16339           if (Tag->getDeclName() == Name &&
16340               Tag->getDeclContext()->getRedeclContext()
16341                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16342             PrevDecl = Tag;
16343             Previous.clear();
16344             Previous.addDecl(Tag);
16345             Previous.resolveKind();
16346           }
16347         }
16348       }
16349     }
16350 
16351     // If this is a redeclaration of a using shadow declaration, it must
16352     // declare a tag in the same context. In MSVC mode, we allow a
16353     // redefinition if either context is within the other.
16354     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16355       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16356       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16357           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16358           !(OldTag && isAcceptableTagRedeclContext(
16359                           *this, OldTag->getDeclContext(), SearchDC))) {
16360         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16361         Diag(Shadow->getTargetDecl()->getLocation(),
16362              diag::note_using_decl_target);
16363         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16364             << 0;
16365         // Recover by ignoring the old declaration.
16366         Previous.clear();
16367         goto CreateNewDecl;
16368       }
16369     }
16370 
16371     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16372       // If this is a use of a previous tag, or if the tag is already declared
16373       // in the same scope (so that the definition/declaration completes or
16374       // rementions the tag), reuse the decl.
16375       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16376           isDeclInScope(DirectPrevDecl, SearchDC, S,
16377                         SS.isNotEmpty() || isMemberSpecialization)) {
16378         // Make sure that this wasn't declared as an enum and now used as a
16379         // struct or something similar.
16380         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16381                                           TUK == TUK_Definition, KWLoc,
16382                                           Name)) {
16383           bool SafeToContinue
16384             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16385                Kind != TTK_Enum);
16386           if (SafeToContinue)
16387             Diag(KWLoc, diag::err_use_with_wrong_tag)
16388               << Name
16389               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16390                                               PrevTagDecl->getKindName());
16391           else
16392             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16393           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16394 
16395           if (SafeToContinue)
16396             Kind = PrevTagDecl->getTagKind();
16397           else {
16398             // Recover by making this an anonymous redefinition.
16399             Name = nullptr;
16400             Previous.clear();
16401             Invalid = true;
16402           }
16403         }
16404 
16405         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16406           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16407           if (TUK == TUK_Reference || TUK == TUK_Friend)
16408             return PrevTagDecl;
16409 
16410           QualType EnumUnderlyingTy;
16411           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16412             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16413           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16414             EnumUnderlyingTy = QualType(T, 0);
16415 
16416           // All conflicts with previous declarations are recovered by
16417           // returning the previous declaration, unless this is a definition,
16418           // in which case we want the caller to bail out.
16419           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16420                                      ScopedEnum, EnumUnderlyingTy,
16421                                      IsFixed, PrevEnum))
16422             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16423         }
16424 
16425         // C++11 [class.mem]p1:
16426         //   A member shall not be declared twice in the member-specification,
16427         //   except that a nested class or member class template can be declared
16428         //   and then later defined.
16429         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16430             S->isDeclScope(PrevDecl)) {
16431           Diag(NameLoc, diag::ext_member_redeclared);
16432           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16433         }
16434 
16435         if (!Invalid) {
16436           // If this is a use, just return the declaration we found, unless
16437           // we have attributes.
16438           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16439             if (!Attrs.empty()) {
16440               // FIXME: Diagnose these attributes. For now, we create a new
16441               // declaration to hold them.
16442             } else if (TUK == TUK_Reference &&
16443                        (PrevTagDecl->getFriendObjectKind() ==
16444                             Decl::FOK_Undeclared ||
16445                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16446                        SS.isEmpty()) {
16447               // This declaration is a reference to an existing entity, but
16448               // has different visibility from that entity: it either makes
16449               // a friend visible or it makes a type visible in a new module.
16450               // In either case, create a new declaration. We only do this if
16451               // the declaration would have meant the same thing if no prior
16452               // declaration were found, that is, if it was found in the same
16453               // scope where we would have injected a declaration.
16454               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16455                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16456                 return PrevTagDecl;
16457               // This is in the injected scope, create a new declaration in
16458               // that scope.
16459               S = getTagInjectionScope(S, getLangOpts());
16460             } else {
16461               return PrevTagDecl;
16462             }
16463           }
16464 
16465           // Diagnose attempts to redefine a tag.
16466           if (TUK == TUK_Definition) {
16467             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16468               // If we're defining a specialization and the previous definition
16469               // is from an implicit instantiation, don't emit an error
16470               // here; we'll catch this in the general case below.
16471               bool IsExplicitSpecializationAfterInstantiation = false;
16472               if (isMemberSpecialization) {
16473                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16474                   IsExplicitSpecializationAfterInstantiation =
16475                     RD->getTemplateSpecializationKind() !=
16476                     TSK_ExplicitSpecialization;
16477                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16478                   IsExplicitSpecializationAfterInstantiation =
16479                     ED->getTemplateSpecializationKind() !=
16480                     TSK_ExplicitSpecialization;
16481               }
16482 
16483               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16484               // not keep more that one definition around (merge them). However,
16485               // ensure the decl passes the structural compatibility check in
16486               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16487               NamedDecl *Hidden = nullptr;
16488               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16489                 // There is a definition of this tag, but it is not visible. We
16490                 // explicitly make use of C++'s one definition rule here, and
16491                 // assume that this definition is identical to the hidden one
16492                 // we already have. Make the existing definition visible and
16493                 // use it in place of this one.
16494                 if (!getLangOpts().CPlusPlus) {
16495                   // Postpone making the old definition visible until after we
16496                   // complete parsing the new one and do the structural
16497                   // comparison.
16498                   SkipBody->CheckSameAsPrevious = true;
16499                   SkipBody->New = createTagFromNewDecl();
16500                   SkipBody->Previous = Def;
16501                   return Def;
16502                 } else {
16503                   SkipBody->ShouldSkip = true;
16504                   SkipBody->Previous = Def;
16505                   makeMergedDefinitionVisible(Hidden);
16506                   // Carry on and handle it like a normal definition. We'll
16507                   // skip starting the definitiion later.
16508                 }
16509               } else if (!IsExplicitSpecializationAfterInstantiation) {
16510                 // A redeclaration in function prototype scope in C isn't
16511                 // visible elsewhere, so merely issue a warning.
16512                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16513                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16514                 else
16515                   Diag(NameLoc, diag::err_redefinition) << Name;
16516                 notePreviousDefinition(Def,
16517                                        NameLoc.isValid() ? NameLoc : KWLoc);
16518                 // If this is a redefinition, recover by making this
16519                 // struct be anonymous, which will make any later
16520                 // references get the previous definition.
16521                 Name = nullptr;
16522                 Previous.clear();
16523                 Invalid = true;
16524               }
16525             } else {
16526               // If the type is currently being defined, complain
16527               // about a nested redefinition.
16528               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16529               if (TD->isBeingDefined()) {
16530                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16531                 Diag(PrevTagDecl->getLocation(),
16532                      diag::note_previous_definition);
16533                 Name = nullptr;
16534                 Previous.clear();
16535                 Invalid = true;
16536               }
16537             }
16538 
16539             // Okay, this is definition of a previously declared or referenced
16540             // tag. We're going to create a new Decl for it.
16541           }
16542 
16543           // Okay, we're going to make a redeclaration.  If this is some kind
16544           // of reference, make sure we build the redeclaration in the same DC
16545           // as the original, and ignore the current access specifier.
16546           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16547             SearchDC = PrevTagDecl->getDeclContext();
16548             AS = AS_none;
16549           }
16550         }
16551         // If we get here we have (another) forward declaration or we
16552         // have a definition.  Just create a new decl.
16553 
16554       } else {
16555         // If we get here, this is a definition of a new tag type in a nested
16556         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16557         // new decl/type.  We set PrevDecl to NULL so that the entities
16558         // have distinct types.
16559         Previous.clear();
16560       }
16561       // If we get here, we're going to create a new Decl. If PrevDecl
16562       // is non-NULL, it's a definition of the tag declared by
16563       // PrevDecl. If it's NULL, we have a new definition.
16564 
16565     // Otherwise, PrevDecl is not a tag, but was found with tag
16566     // lookup.  This is only actually possible in C++, where a few
16567     // things like templates still live in the tag namespace.
16568     } else {
16569       // Use a better diagnostic if an elaborated-type-specifier
16570       // found the wrong kind of type on the first
16571       // (non-redeclaration) lookup.
16572       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16573           !Previous.isForRedeclaration()) {
16574         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16575         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16576                                                        << Kind;
16577         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16578         Invalid = true;
16579 
16580       // Otherwise, only diagnose if the declaration is in scope.
16581       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16582                                 SS.isNotEmpty() || isMemberSpecialization)) {
16583         // do nothing
16584 
16585       // Diagnose implicit declarations introduced by elaborated types.
16586       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16587         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16588         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16589         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16590         Invalid = true;
16591 
16592       // Otherwise it's a declaration.  Call out a particularly common
16593       // case here.
16594       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16595         unsigned Kind = 0;
16596         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16597         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16598           << Name << Kind << TND->getUnderlyingType();
16599         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16600         Invalid = true;
16601 
16602       // Otherwise, diagnose.
16603       } else {
16604         // The tag name clashes with something else in the target scope,
16605         // issue an error and recover by making this tag be anonymous.
16606         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16607         notePreviousDefinition(PrevDecl, NameLoc);
16608         Name = nullptr;
16609         Invalid = true;
16610       }
16611 
16612       // The existing declaration isn't relevant to us; we're in a
16613       // new scope, so clear out the previous declaration.
16614       Previous.clear();
16615     }
16616   }
16617 
16618 CreateNewDecl:
16619 
16620   TagDecl *PrevDecl = nullptr;
16621   if (Previous.isSingleResult())
16622     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16623 
16624   // If there is an identifier, use the location of the identifier as the
16625   // location of the decl, otherwise use the location of the struct/union
16626   // keyword.
16627   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16628 
16629   // Otherwise, create a new declaration. If there is a previous
16630   // declaration of the same entity, the two will be linked via
16631   // PrevDecl.
16632   TagDecl *New;
16633 
16634   if (Kind == TTK_Enum) {
16635     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16636     // enum X { A, B, C } D;    D should chain to X.
16637     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16638                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16639                            ScopedEnumUsesClassTag, IsFixed);
16640 
16641     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16642       StdAlignValT = cast<EnumDecl>(New);
16643 
16644     // If this is an undefined enum, warn.
16645     if (TUK != TUK_Definition && !Invalid) {
16646       TagDecl *Def;
16647       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16648         // C++0x: 7.2p2: opaque-enum-declaration.
16649         // Conflicts are diagnosed above. Do nothing.
16650       }
16651       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16652         Diag(Loc, diag::ext_forward_ref_enum_def)
16653           << New;
16654         Diag(Def->getLocation(), diag::note_previous_definition);
16655       } else {
16656         unsigned DiagID = diag::ext_forward_ref_enum;
16657         if (getLangOpts().MSVCCompat)
16658           DiagID = diag::ext_ms_forward_ref_enum;
16659         else if (getLangOpts().CPlusPlus)
16660           DiagID = diag::err_forward_ref_enum;
16661         Diag(Loc, DiagID);
16662       }
16663     }
16664 
16665     if (EnumUnderlying) {
16666       EnumDecl *ED = cast<EnumDecl>(New);
16667       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16668         ED->setIntegerTypeSourceInfo(TI);
16669       else
16670         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16671       ED->setPromotionType(ED->getIntegerType());
16672       assert(ED->isComplete() && "enum with type should be complete");
16673     }
16674   } else {
16675     // struct/union/class
16676 
16677     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16678     // struct X { int A; } D;    D should chain to X.
16679     if (getLangOpts().CPlusPlus) {
16680       // FIXME: Look for a way to use RecordDecl for simple structs.
16681       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16682                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16683 
16684       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16685         StdBadAlloc = cast<CXXRecordDecl>(New);
16686     } else
16687       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16688                                cast_or_null<RecordDecl>(PrevDecl));
16689   }
16690 
16691   // C++11 [dcl.type]p3:
16692   //   A type-specifier-seq shall not define a class or enumeration [...].
16693   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16694       TUK == TUK_Definition) {
16695     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16696       << Context.getTagDeclType(New);
16697     Invalid = true;
16698   }
16699 
16700   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16701       DC->getDeclKind() == Decl::Enum) {
16702     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16703       << Context.getTagDeclType(New);
16704     Invalid = true;
16705   }
16706 
16707   // Maybe add qualifier info.
16708   if (SS.isNotEmpty()) {
16709     if (SS.isSet()) {
16710       // If this is either a declaration or a definition, check the
16711       // nested-name-specifier against the current context.
16712       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16713           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16714                                        isMemberSpecialization))
16715         Invalid = true;
16716 
16717       New->setQualifierInfo(SS.getWithLocInContext(Context));
16718       if (TemplateParameterLists.size() > 0) {
16719         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16720       }
16721     }
16722     else
16723       Invalid = true;
16724   }
16725 
16726   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16727     // Add alignment attributes if necessary; these attributes are checked when
16728     // the ASTContext lays out the structure.
16729     //
16730     // It is important for implementing the correct semantics that this
16731     // happen here (in ActOnTag). The #pragma pack stack is
16732     // maintained as a result of parser callbacks which can occur at
16733     // many points during the parsing of a struct declaration (because
16734     // the #pragma tokens are effectively skipped over during the
16735     // parsing of the struct).
16736     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16737       AddAlignmentAttributesForRecord(RD);
16738       AddMsStructLayoutForRecord(RD);
16739     }
16740   }
16741 
16742   if (ModulePrivateLoc.isValid()) {
16743     if (isMemberSpecialization)
16744       Diag(New->getLocation(), diag::err_module_private_specialization)
16745         << 2
16746         << FixItHint::CreateRemoval(ModulePrivateLoc);
16747     // __module_private__ does not apply to local classes. However, we only
16748     // diagnose this as an error when the declaration specifiers are
16749     // freestanding. Here, we just ignore the __module_private__.
16750     else if (!SearchDC->isFunctionOrMethod())
16751       New->setModulePrivate();
16752   }
16753 
16754   // If this is a specialization of a member class (of a class template),
16755   // check the specialization.
16756   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16757     Invalid = true;
16758 
16759   // If we're declaring or defining a tag in function prototype scope in C,
16760   // note that this type can only be used within the function and add it to
16761   // the list of decls to inject into the function definition scope.
16762   if ((Name || Kind == TTK_Enum) &&
16763       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16764     if (getLangOpts().CPlusPlus) {
16765       // C++ [dcl.fct]p6:
16766       //   Types shall not be defined in return or parameter types.
16767       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16768         Diag(Loc, diag::err_type_defined_in_param_type)
16769             << Name;
16770         Invalid = true;
16771       }
16772     } else if (!PrevDecl) {
16773       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16774     }
16775   }
16776 
16777   if (Invalid)
16778     New->setInvalidDecl();
16779 
16780   // Set the lexical context. If the tag has a C++ scope specifier, the
16781   // lexical context will be different from the semantic context.
16782   New->setLexicalDeclContext(CurContext);
16783 
16784   // Mark this as a friend decl if applicable.
16785   // In Microsoft mode, a friend declaration also acts as a forward
16786   // declaration so we always pass true to setObjectOfFriendDecl to make
16787   // the tag name visible.
16788   if (TUK == TUK_Friend)
16789     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16790 
16791   // Set the access specifier.
16792   if (!Invalid && SearchDC->isRecord())
16793     SetMemberAccessSpecifier(New, PrevDecl, AS);
16794 
16795   if (PrevDecl)
16796     CheckRedeclarationInModule(New, PrevDecl);
16797 
16798   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16799     New->startDefinition();
16800 
16801   ProcessDeclAttributeList(S, New, Attrs);
16802   AddPragmaAttributes(S, New);
16803 
16804   // If this has an identifier, add it to the scope stack.
16805   if (TUK == TUK_Friend) {
16806     // We might be replacing an existing declaration in the lookup tables;
16807     // if so, borrow its access specifier.
16808     if (PrevDecl)
16809       New->setAccess(PrevDecl->getAccess());
16810 
16811     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16812     DC->makeDeclVisibleInContext(New);
16813     if (Name) // can be null along some error paths
16814       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16815         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16816   } else if (Name) {
16817     S = getNonFieldDeclScope(S);
16818     PushOnScopeChains(New, S, true);
16819   } else {
16820     CurContext->addDecl(New);
16821   }
16822 
16823   // If this is the C FILE type, notify the AST context.
16824   if (IdentifierInfo *II = New->getIdentifier())
16825     if (!New->isInvalidDecl() &&
16826         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16827         II->isStr("FILE"))
16828       Context.setFILEDecl(New);
16829 
16830   if (PrevDecl)
16831     mergeDeclAttributes(New, PrevDecl);
16832 
16833   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16834     inferGslOwnerPointerAttribute(CXXRD);
16835 
16836   // If there's a #pragma GCC visibility in scope, set the visibility of this
16837   // record.
16838   AddPushedVisibilityAttribute(New);
16839 
16840   if (isMemberSpecialization && !New->isInvalidDecl())
16841     CompleteMemberSpecialization(New, Previous);
16842 
16843   OwnedDecl = true;
16844   // In C++, don't return an invalid declaration. We can't recover well from
16845   // the cases where we make the type anonymous.
16846   if (Invalid && getLangOpts().CPlusPlus) {
16847     if (New->isBeingDefined())
16848       if (auto RD = dyn_cast<RecordDecl>(New))
16849         RD->completeDefinition();
16850     return nullptr;
16851   } else if (SkipBody && SkipBody->ShouldSkip) {
16852     return SkipBody->Previous;
16853   } else {
16854     return New;
16855   }
16856 }
16857 
16858 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16859   AdjustDeclIfTemplate(TagD);
16860   TagDecl *Tag = cast<TagDecl>(TagD);
16861 
16862   // Enter the tag context.
16863   PushDeclContext(S, Tag);
16864 
16865   ActOnDocumentableDecl(TagD);
16866 
16867   // If there's a #pragma GCC visibility in scope, set the visibility of this
16868   // record.
16869   AddPushedVisibilityAttribute(Tag);
16870 }
16871 
16872 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16873   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16874     return false;
16875 
16876   // Make the previous decl visible.
16877   makeMergedDefinitionVisible(SkipBody.Previous);
16878   return true;
16879 }
16880 
16881 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16882   assert(isa<ObjCContainerDecl>(IDecl) &&
16883          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16884   DeclContext *OCD = cast<DeclContext>(IDecl);
16885   assert(OCD->getLexicalParent() == CurContext &&
16886       "The next DeclContext should be lexically contained in the current one.");
16887   CurContext = OCD;
16888   return IDecl;
16889 }
16890 
16891 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16892                                            SourceLocation FinalLoc,
16893                                            bool IsFinalSpelledSealed,
16894                                            bool IsAbstract,
16895                                            SourceLocation LBraceLoc) {
16896   AdjustDeclIfTemplate(TagD);
16897   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16898 
16899   FieldCollector->StartClass();
16900 
16901   if (!Record->getIdentifier())
16902     return;
16903 
16904   if (IsAbstract)
16905     Record->markAbstract();
16906 
16907   if (FinalLoc.isValid()) {
16908     Record->addAttr(FinalAttr::Create(
16909         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16910         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16911   }
16912   // C++ [class]p2:
16913   //   [...] The class-name is also inserted into the scope of the
16914   //   class itself; this is known as the injected-class-name. For
16915   //   purposes of access checking, the injected-class-name is treated
16916   //   as if it were a public member name.
16917   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16918       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16919       Record->getLocation(), Record->getIdentifier(),
16920       /*PrevDecl=*/nullptr,
16921       /*DelayTypeCreation=*/true);
16922   Context.getTypeDeclType(InjectedClassName, Record);
16923   InjectedClassName->setImplicit();
16924   InjectedClassName->setAccess(AS_public);
16925   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16926       InjectedClassName->setDescribedClassTemplate(Template);
16927   PushOnScopeChains(InjectedClassName, S);
16928   assert(InjectedClassName->isInjectedClassName() &&
16929          "Broken injected-class-name");
16930 }
16931 
16932 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16933                                     SourceRange BraceRange) {
16934   AdjustDeclIfTemplate(TagD);
16935   TagDecl *Tag = cast<TagDecl>(TagD);
16936   Tag->setBraceRange(BraceRange);
16937 
16938   // Make sure we "complete" the definition even it is invalid.
16939   if (Tag->isBeingDefined()) {
16940     assert(Tag->isInvalidDecl() && "We should already have completed it");
16941     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16942       RD->completeDefinition();
16943   }
16944 
16945   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16946     FieldCollector->FinishClass();
16947     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16948       auto *Def = RD->getDefinition();
16949       assert(Def && "The record is expected to have a completed definition");
16950       unsigned NumInitMethods = 0;
16951       for (auto *Method : Def->methods()) {
16952         if (!Method->getIdentifier())
16953             continue;
16954         if (Method->getName() == "__init")
16955           NumInitMethods++;
16956       }
16957       if (NumInitMethods > 1 || !Def->hasInitMethod())
16958         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16959     }
16960   }
16961 
16962   // Exit this scope of this tag's definition.
16963   PopDeclContext();
16964 
16965   if (getCurLexicalContext()->isObjCContainer() &&
16966       Tag->getDeclContext()->isFileContext())
16967     Tag->setTopLevelDeclInObjCContainer();
16968 
16969   // Notify the consumer that we've defined a tag.
16970   if (!Tag->isInvalidDecl())
16971     Consumer.HandleTagDeclDefinition(Tag);
16972 
16973   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16974   // from XLs and instead matches the XL #pragma pack(1) behavior.
16975   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16976       AlignPackStack.hasValue()) {
16977     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16978     // Only diagnose #pragma align(packed).
16979     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16980       return;
16981     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16982     if (!RD)
16983       return;
16984     // Only warn if there is at least 1 bitfield member.
16985     if (llvm::any_of(RD->fields(),
16986                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16987       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16988   }
16989 }
16990 
16991 void Sema::ActOnObjCContainerFinishDefinition() {
16992   // Exit this scope of this interface definition.
16993   PopDeclContext();
16994 }
16995 
16996 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16997   assert(DC == CurContext && "Mismatch of container contexts");
16998   OriginalLexicalContext = DC;
16999   ActOnObjCContainerFinishDefinition();
17000 }
17001 
17002 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
17003   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
17004   OriginalLexicalContext = nullptr;
17005 }
17006 
17007 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17008   AdjustDeclIfTemplate(TagD);
17009   TagDecl *Tag = cast<TagDecl>(TagD);
17010   Tag->setInvalidDecl();
17011 
17012   // Make sure we "complete" the definition even it is invalid.
17013   if (Tag->isBeingDefined()) {
17014     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17015       RD->completeDefinition();
17016   }
17017 
17018   // We're undoing ActOnTagStartDefinition here, not
17019   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17020   // the FieldCollector.
17021 
17022   PopDeclContext();
17023 }
17024 
17025 // Note that FieldName may be null for anonymous bitfields.
17026 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17027                                 IdentifierInfo *FieldName,
17028                                 QualType FieldTy, bool IsMsStruct,
17029                                 Expr *BitWidth, bool *ZeroWidth) {
17030   assert(BitWidth);
17031   if (BitWidth->containsErrors())
17032     return ExprError();
17033 
17034   // Default to true; that shouldn't confuse checks for emptiness
17035   if (ZeroWidth)
17036     *ZeroWidth = true;
17037 
17038   // C99 6.7.2.1p4 - verify the field type.
17039   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17040   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17041     // Handle incomplete and sizeless types with a specific error.
17042     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17043                                  diag::err_field_incomplete_or_sizeless))
17044       return ExprError();
17045     if (FieldName)
17046       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17047         << FieldName << FieldTy << BitWidth->getSourceRange();
17048     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17049       << FieldTy << BitWidth->getSourceRange();
17050   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17051                                              UPPC_BitFieldWidth))
17052     return ExprError();
17053 
17054   // If the bit-width is type- or value-dependent, don't try to check
17055   // it now.
17056   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17057     return BitWidth;
17058 
17059   llvm::APSInt Value;
17060   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17061   if (ICE.isInvalid())
17062     return ICE;
17063   BitWidth = ICE.get();
17064 
17065   if (Value != 0 && ZeroWidth)
17066     *ZeroWidth = false;
17067 
17068   // Zero-width bitfield is ok for anonymous field.
17069   if (Value == 0 && FieldName)
17070     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17071 
17072   if (Value.isSigned() && Value.isNegative()) {
17073     if (FieldName)
17074       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17075                << FieldName << toString(Value, 10);
17076     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17077       << toString(Value, 10);
17078   }
17079 
17080   // The size of the bit-field must not exceed our maximum permitted object
17081   // size.
17082   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17083     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17084            << !FieldName << FieldName << toString(Value, 10);
17085   }
17086 
17087   if (!FieldTy->isDependentType()) {
17088     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17089     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17090     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17091 
17092     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17093     // ABI.
17094     bool CStdConstraintViolation =
17095         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17096     bool MSBitfieldViolation =
17097         Value.ugt(TypeStorageSize) &&
17098         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17099     if (CStdConstraintViolation || MSBitfieldViolation) {
17100       unsigned DiagWidth =
17101           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17102       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17103              << (bool)FieldName << FieldName << toString(Value, 10)
17104              << !CStdConstraintViolation << DiagWidth;
17105     }
17106 
17107     // Warn on types where the user might conceivably expect to get all
17108     // specified bits as value bits: that's all integral types other than
17109     // 'bool'.
17110     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17111       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17112           << FieldName << toString(Value, 10)
17113           << (unsigned)TypeWidth;
17114     }
17115   }
17116 
17117   return BitWidth;
17118 }
17119 
17120 /// ActOnField - Each field of a C struct/union is passed into this in order
17121 /// to create a FieldDecl object for it.
17122 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17123                        Declarator &D, Expr *BitfieldWidth) {
17124   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17125                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17126                                /*InitStyle=*/ICIS_NoInit, AS_public);
17127   return Res;
17128 }
17129 
17130 /// HandleField - Analyze a field of a C struct or a C++ data member.
17131 ///
17132 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17133                              SourceLocation DeclStart,
17134                              Declarator &D, Expr *BitWidth,
17135                              InClassInitStyle InitStyle,
17136                              AccessSpecifier AS) {
17137   if (D.isDecompositionDeclarator()) {
17138     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17139     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17140       << Decomp.getSourceRange();
17141     return nullptr;
17142   }
17143 
17144   IdentifierInfo *II = D.getIdentifier();
17145   SourceLocation Loc = DeclStart;
17146   if (II) Loc = D.getIdentifierLoc();
17147 
17148   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17149   QualType T = TInfo->getType();
17150   if (getLangOpts().CPlusPlus) {
17151     CheckExtraCXXDefaultArguments(D);
17152 
17153     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17154                                         UPPC_DataMemberType)) {
17155       D.setInvalidType();
17156       T = Context.IntTy;
17157       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17158     }
17159   }
17160 
17161   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17162 
17163   if (D.getDeclSpec().isInlineSpecified())
17164     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17165         << getLangOpts().CPlusPlus17;
17166   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17167     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17168          diag::err_invalid_thread)
17169       << DeclSpec::getSpecifierName(TSCS);
17170 
17171   // Check to see if this name was declared as a member previously
17172   NamedDecl *PrevDecl = nullptr;
17173   LookupResult Previous(*this, II, Loc, LookupMemberName,
17174                         ForVisibleRedeclaration);
17175   LookupName(Previous, S);
17176   switch (Previous.getResultKind()) {
17177     case LookupResult::Found:
17178     case LookupResult::FoundUnresolvedValue:
17179       PrevDecl = Previous.getAsSingle<NamedDecl>();
17180       break;
17181 
17182     case LookupResult::FoundOverloaded:
17183       PrevDecl = Previous.getRepresentativeDecl();
17184       break;
17185 
17186     case LookupResult::NotFound:
17187     case LookupResult::NotFoundInCurrentInstantiation:
17188     case LookupResult::Ambiguous:
17189       break;
17190   }
17191   Previous.suppressDiagnostics();
17192 
17193   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17194     // Maybe we will complain about the shadowed template parameter.
17195     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17196     // Just pretend that we didn't see the previous declaration.
17197     PrevDecl = nullptr;
17198   }
17199 
17200   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17201     PrevDecl = nullptr;
17202 
17203   bool Mutable
17204     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17205   SourceLocation TSSL = D.getBeginLoc();
17206   FieldDecl *NewFD
17207     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17208                      TSSL, AS, PrevDecl, &D);
17209 
17210   if (NewFD->isInvalidDecl())
17211     Record->setInvalidDecl();
17212 
17213   if (D.getDeclSpec().isModulePrivateSpecified())
17214     NewFD->setModulePrivate();
17215 
17216   if (NewFD->isInvalidDecl() && PrevDecl) {
17217     // Don't introduce NewFD into scope; there's already something
17218     // with the same name in the same scope.
17219   } else if (II) {
17220     PushOnScopeChains(NewFD, S);
17221   } else
17222     Record->addDecl(NewFD);
17223 
17224   return NewFD;
17225 }
17226 
17227 /// Build a new FieldDecl and check its well-formedness.
17228 ///
17229 /// This routine builds a new FieldDecl given the fields name, type,
17230 /// record, etc. \p PrevDecl should refer to any previous declaration
17231 /// with the same name and in the same scope as the field to be
17232 /// created.
17233 ///
17234 /// \returns a new FieldDecl.
17235 ///
17236 /// \todo The Declarator argument is a hack. It will be removed once
17237 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17238                                 TypeSourceInfo *TInfo,
17239                                 RecordDecl *Record, SourceLocation Loc,
17240                                 bool Mutable, Expr *BitWidth,
17241                                 InClassInitStyle InitStyle,
17242                                 SourceLocation TSSL,
17243                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17244                                 Declarator *D) {
17245   IdentifierInfo *II = Name.getAsIdentifierInfo();
17246   bool InvalidDecl = false;
17247   if (D) InvalidDecl = D->isInvalidType();
17248 
17249   // If we receive a broken type, recover by assuming 'int' and
17250   // marking this declaration as invalid.
17251   if (T.isNull() || T->containsErrors()) {
17252     InvalidDecl = true;
17253     T = Context.IntTy;
17254   }
17255 
17256   QualType EltTy = Context.getBaseElementType(T);
17257   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17258     if (RequireCompleteSizedType(Loc, EltTy,
17259                                  diag::err_field_incomplete_or_sizeless)) {
17260       // Fields of incomplete type force their record to be invalid.
17261       Record->setInvalidDecl();
17262       InvalidDecl = true;
17263     } else {
17264       NamedDecl *Def;
17265       EltTy->isIncompleteType(&Def);
17266       if (Def && Def->isInvalidDecl()) {
17267         Record->setInvalidDecl();
17268         InvalidDecl = true;
17269       }
17270     }
17271   }
17272 
17273   // TR 18037 does not allow fields to be declared with address space
17274   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17275       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17276     Diag(Loc, diag::err_field_with_address_space);
17277     Record->setInvalidDecl();
17278     InvalidDecl = true;
17279   }
17280 
17281   if (LangOpts.OpenCL) {
17282     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17283     // used as structure or union field: image, sampler, event or block types.
17284     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17285         T->isBlockPointerType()) {
17286       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17287       Record->setInvalidDecl();
17288       InvalidDecl = true;
17289     }
17290     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17291     // is enabled.
17292     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17293                         "__cl_clang_bitfields", LangOpts)) {
17294       Diag(Loc, diag::err_opencl_bitfields);
17295       InvalidDecl = true;
17296     }
17297   }
17298 
17299   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17300   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17301       T.hasQualifiers()) {
17302     InvalidDecl = true;
17303     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17304   }
17305 
17306   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17307   // than a variably modified type.
17308   if (!InvalidDecl && T->isVariablyModifiedType()) {
17309     if (!tryToFixVariablyModifiedVarType(
17310             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17311       InvalidDecl = true;
17312   }
17313 
17314   // Fields can not have abstract class types
17315   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17316                                              diag::err_abstract_type_in_decl,
17317                                              AbstractFieldType))
17318     InvalidDecl = true;
17319 
17320   bool ZeroWidth = false;
17321   if (InvalidDecl)
17322     BitWidth = nullptr;
17323   // If this is declared as a bit-field, check the bit-field.
17324   if (BitWidth) {
17325     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17326                               &ZeroWidth).get();
17327     if (!BitWidth) {
17328       InvalidDecl = true;
17329       BitWidth = nullptr;
17330       ZeroWidth = false;
17331     }
17332   }
17333 
17334   // Check that 'mutable' is consistent with the type of the declaration.
17335   if (!InvalidDecl && Mutable) {
17336     unsigned DiagID = 0;
17337     if (T->isReferenceType())
17338       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17339                                         : diag::err_mutable_reference;
17340     else if (T.isConstQualified())
17341       DiagID = diag::err_mutable_const;
17342 
17343     if (DiagID) {
17344       SourceLocation ErrLoc = Loc;
17345       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17346         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17347       Diag(ErrLoc, DiagID);
17348       if (DiagID != diag::ext_mutable_reference) {
17349         Mutable = false;
17350         InvalidDecl = true;
17351       }
17352     }
17353   }
17354 
17355   // C++11 [class.union]p8 (DR1460):
17356   //   At most one variant member of a union may have a
17357   //   brace-or-equal-initializer.
17358   if (InitStyle != ICIS_NoInit)
17359     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17360 
17361   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17362                                        BitWidth, Mutable, InitStyle);
17363   if (InvalidDecl)
17364     NewFD->setInvalidDecl();
17365 
17366   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17367     Diag(Loc, diag::err_duplicate_member) << II;
17368     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17369     NewFD->setInvalidDecl();
17370   }
17371 
17372   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17373     if (Record->isUnion()) {
17374       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17375         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17376         if (RDecl->getDefinition()) {
17377           // C++ [class.union]p1: An object of a class with a non-trivial
17378           // constructor, a non-trivial copy constructor, a non-trivial
17379           // destructor, or a non-trivial copy assignment operator
17380           // cannot be a member of a union, nor can an array of such
17381           // objects.
17382           if (CheckNontrivialField(NewFD))
17383             NewFD->setInvalidDecl();
17384         }
17385       }
17386 
17387       // C++ [class.union]p1: If a union contains a member of reference type,
17388       // the program is ill-formed, except when compiling with MSVC extensions
17389       // enabled.
17390       if (EltTy->isReferenceType()) {
17391         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17392                                     diag::ext_union_member_of_reference_type :
17393                                     diag::err_union_member_of_reference_type)
17394           << NewFD->getDeclName() << EltTy;
17395         if (!getLangOpts().MicrosoftExt)
17396           NewFD->setInvalidDecl();
17397       }
17398     }
17399   }
17400 
17401   // FIXME: We need to pass in the attributes given an AST
17402   // representation, not a parser representation.
17403   if (D) {
17404     // FIXME: The current scope is almost... but not entirely... correct here.
17405     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17406 
17407     if (NewFD->hasAttrs())
17408       CheckAlignasUnderalignment(NewFD);
17409   }
17410 
17411   // In auto-retain/release, infer strong retension for fields of
17412   // retainable type.
17413   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17414     NewFD->setInvalidDecl();
17415 
17416   if (T.isObjCGCWeak())
17417     Diag(Loc, diag::warn_attribute_weak_on_field);
17418 
17419   // PPC MMA non-pointer types are not allowed as field types.
17420   if (Context.getTargetInfo().getTriple().isPPC64() &&
17421       CheckPPCMMAType(T, NewFD->getLocation()))
17422     NewFD->setInvalidDecl();
17423 
17424   NewFD->setAccess(AS);
17425   return NewFD;
17426 }
17427 
17428 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17429   assert(FD);
17430   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17431 
17432   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17433     return false;
17434 
17435   QualType EltTy = Context.getBaseElementType(FD->getType());
17436   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17437     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17438     if (RDecl->getDefinition()) {
17439       // We check for copy constructors before constructors
17440       // because otherwise we'll never get complaints about
17441       // copy constructors.
17442 
17443       CXXSpecialMember member = CXXInvalid;
17444       // We're required to check for any non-trivial constructors. Since the
17445       // implicit default constructor is suppressed if there are any
17446       // user-declared constructors, we just need to check that there is a
17447       // trivial default constructor and a trivial copy constructor. (We don't
17448       // worry about move constructors here, since this is a C++98 check.)
17449       if (RDecl->hasNonTrivialCopyConstructor())
17450         member = CXXCopyConstructor;
17451       else if (!RDecl->hasTrivialDefaultConstructor())
17452         member = CXXDefaultConstructor;
17453       else if (RDecl->hasNonTrivialCopyAssignment())
17454         member = CXXCopyAssignment;
17455       else if (RDecl->hasNonTrivialDestructor())
17456         member = CXXDestructor;
17457 
17458       if (member != CXXInvalid) {
17459         if (!getLangOpts().CPlusPlus11 &&
17460             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17461           // Objective-C++ ARC: it is an error to have a non-trivial field of
17462           // a union. However, system headers in Objective-C programs
17463           // occasionally have Objective-C lifetime objects within unions,
17464           // and rather than cause the program to fail, we make those
17465           // members unavailable.
17466           SourceLocation Loc = FD->getLocation();
17467           if (getSourceManager().isInSystemHeader(Loc)) {
17468             if (!FD->hasAttr<UnavailableAttr>())
17469               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17470                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17471             return false;
17472           }
17473         }
17474 
17475         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17476                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17477                diag::err_illegal_union_or_anon_struct_member)
17478           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17479         DiagnoseNontrivial(RDecl, member);
17480         return !getLangOpts().CPlusPlus11;
17481       }
17482     }
17483   }
17484 
17485   return false;
17486 }
17487 
17488 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17489 ///  AST enum value.
17490 static ObjCIvarDecl::AccessControl
17491 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17492   switch (ivarVisibility) {
17493   default: llvm_unreachable("Unknown visitibility kind");
17494   case tok::objc_private: return ObjCIvarDecl::Private;
17495   case tok::objc_public: return ObjCIvarDecl::Public;
17496   case tok::objc_protected: return ObjCIvarDecl::Protected;
17497   case tok::objc_package: return ObjCIvarDecl::Package;
17498   }
17499 }
17500 
17501 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17502 /// in order to create an IvarDecl object for it.
17503 Decl *Sema::ActOnIvar(Scope *S,
17504                                 SourceLocation DeclStart,
17505                                 Declarator &D, Expr *BitfieldWidth,
17506                                 tok::ObjCKeywordKind Visibility) {
17507 
17508   IdentifierInfo *II = D.getIdentifier();
17509   Expr *BitWidth = (Expr*)BitfieldWidth;
17510   SourceLocation Loc = DeclStart;
17511   if (II) Loc = D.getIdentifierLoc();
17512 
17513   // FIXME: Unnamed fields can be handled in various different ways, for
17514   // example, unnamed unions inject all members into the struct namespace!
17515 
17516   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17517   QualType T = TInfo->getType();
17518 
17519   if (BitWidth) {
17520     // 6.7.2.1p3, 6.7.2.1p4
17521     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17522     if (!BitWidth)
17523       D.setInvalidType();
17524   } else {
17525     // Not a bitfield.
17526 
17527     // validate II.
17528 
17529   }
17530   if (T->isReferenceType()) {
17531     Diag(Loc, diag::err_ivar_reference_type);
17532     D.setInvalidType();
17533   }
17534   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17535   // than a variably modified type.
17536   else if (T->isVariablyModifiedType()) {
17537     if (!tryToFixVariablyModifiedVarType(
17538             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17539       D.setInvalidType();
17540   }
17541 
17542   // Get the visibility (access control) for this ivar.
17543   ObjCIvarDecl::AccessControl ac =
17544     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17545                                         : ObjCIvarDecl::None;
17546   // Must set ivar's DeclContext to its enclosing interface.
17547   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17548   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17549     return nullptr;
17550   ObjCContainerDecl *EnclosingContext;
17551   if (ObjCImplementationDecl *IMPDecl =
17552       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17553     if (LangOpts.ObjCRuntime.isFragile()) {
17554     // Case of ivar declared in an implementation. Context is that of its class.
17555       EnclosingContext = IMPDecl->getClassInterface();
17556       assert(EnclosingContext && "Implementation has no class interface!");
17557     }
17558     else
17559       EnclosingContext = EnclosingDecl;
17560   } else {
17561     if (ObjCCategoryDecl *CDecl =
17562         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17563       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17564         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17565         return nullptr;
17566       }
17567     }
17568     EnclosingContext = EnclosingDecl;
17569   }
17570 
17571   // Construct the decl.
17572   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17573                                              DeclStart, Loc, II, T,
17574                                              TInfo, ac, (Expr *)BitfieldWidth);
17575 
17576   if (II) {
17577     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17578                                            ForVisibleRedeclaration);
17579     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17580         && !isa<TagDecl>(PrevDecl)) {
17581       Diag(Loc, diag::err_duplicate_member) << II;
17582       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17583       NewID->setInvalidDecl();
17584     }
17585   }
17586 
17587   // Process attributes attached to the ivar.
17588   ProcessDeclAttributes(S, NewID, D);
17589 
17590   if (D.isInvalidType())
17591     NewID->setInvalidDecl();
17592 
17593   // In ARC, infer 'retaining' for ivars of retainable type.
17594   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17595     NewID->setInvalidDecl();
17596 
17597   if (D.getDeclSpec().isModulePrivateSpecified())
17598     NewID->setModulePrivate();
17599 
17600   if (II) {
17601     // FIXME: When interfaces are DeclContexts, we'll need to add
17602     // these to the interface.
17603     S->AddDecl(NewID);
17604     IdResolver.AddDecl(NewID);
17605   }
17606 
17607   if (LangOpts.ObjCRuntime.isNonFragile() &&
17608       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17609     Diag(Loc, diag::warn_ivars_in_interface);
17610 
17611   return NewID;
17612 }
17613 
17614 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17615 /// class and class extensions. For every class \@interface and class
17616 /// extension \@interface, if the last ivar is a bitfield of any type,
17617 /// then add an implicit `char :0` ivar to the end of that interface.
17618 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17619                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17620   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17621     return;
17622 
17623   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17624   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17625 
17626   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17627     return;
17628   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17629   if (!ID) {
17630     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17631       if (!CD->IsClassExtension())
17632         return;
17633     }
17634     // No need to add this to end of @implementation.
17635     else
17636       return;
17637   }
17638   // All conditions are met. Add a new bitfield to the tail end of ivars.
17639   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17640   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17641 
17642   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17643                               DeclLoc, DeclLoc, nullptr,
17644                               Context.CharTy,
17645                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17646                                                                DeclLoc),
17647                               ObjCIvarDecl::Private, BW,
17648                               true);
17649   AllIvarDecls.push_back(Ivar);
17650 }
17651 
17652 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17653                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17654                        SourceLocation RBrac,
17655                        const ParsedAttributesView &Attrs) {
17656   assert(EnclosingDecl && "missing record or interface decl");
17657 
17658   // If this is an Objective-C @implementation or category and we have
17659   // new fields here we should reset the layout of the interface since
17660   // it will now change.
17661   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17662     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17663     switch (DC->getKind()) {
17664     default: break;
17665     case Decl::ObjCCategory:
17666       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17667       break;
17668     case Decl::ObjCImplementation:
17669       Context.
17670         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17671       break;
17672     }
17673   }
17674 
17675   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17676   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17677 
17678   // Start counting up the number of named members; make sure to include
17679   // members of anonymous structs and unions in the total.
17680   unsigned NumNamedMembers = 0;
17681   if (Record) {
17682     for (const auto *I : Record->decls()) {
17683       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17684         if (IFD->getDeclName())
17685           ++NumNamedMembers;
17686     }
17687   }
17688 
17689   // Verify that all the fields are okay.
17690   SmallVector<FieldDecl*, 32> RecFields;
17691 
17692   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17693        i != end; ++i) {
17694     FieldDecl *FD = cast<FieldDecl>(*i);
17695 
17696     // Get the type for the field.
17697     const Type *FDTy = FD->getType().getTypePtr();
17698 
17699     if (!FD->isAnonymousStructOrUnion()) {
17700       // Remember all fields written by the user.
17701       RecFields.push_back(FD);
17702     }
17703 
17704     // If the field is already invalid for some reason, don't emit more
17705     // diagnostics about it.
17706     if (FD->isInvalidDecl()) {
17707       EnclosingDecl->setInvalidDecl();
17708       continue;
17709     }
17710 
17711     // C99 6.7.2.1p2:
17712     //   A structure or union shall not contain a member with
17713     //   incomplete or function type (hence, a structure shall not
17714     //   contain an instance of itself, but may contain a pointer to
17715     //   an instance of itself), except that the last member of a
17716     //   structure with more than one named member may have incomplete
17717     //   array type; such a structure (and any union containing,
17718     //   possibly recursively, a member that is such a structure)
17719     //   shall not be a member of a structure or an element of an
17720     //   array.
17721     bool IsLastField = (i + 1 == Fields.end());
17722     if (FDTy->isFunctionType()) {
17723       // Field declared as a function.
17724       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17725         << FD->getDeclName();
17726       FD->setInvalidDecl();
17727       EnclosingDecl->setInvalidDecl();
17728       continue;
17729     } else if (FDTy->isIncompleteArrayType() &&
17730                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17731       if (Record) {
17732         // Flexible array member.
17733         // Microsoft and g++ is more permissive regarding flexible array.
17734         // It will accept flexible array in union and also
17735         // as the sole element of a struct/class.
17736         unsigned DiagID = 0;
17737         if (!Record->isUnion() && !IsLastField) {
17738           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17739             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17740           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17741           FD->setInvalidDecl();
17742           EnclosingDecl->setInvalidDecl();
17743           continue;
17744         } else if (Record->isUnion())
17745           DiagID = getLangOpts().MicrosoftExt
17746                        ? diag::ext_flexible_array_union_ms
17747                        : getLangOpts().CPlusPlus
17748                              ? diag::ext_flexible_array_union_gnu
17749                              : diag::err_flexible_array_union;
17750         else if (NumNamedMembers < 1)
17751           DiagID = getLangOpts().MicrosoftExt
17752                        ? diag::ext_flexible_array_empty_aggregate_ms
17753                        : getLangOpts().CPlusPlus
17754                              ? diag::ext_flexible_array_empty_aggregate_gnu
17755                              : diag::err_flexible_array_empty_aggregate;
17756 
17757         if (DiagID)
17758           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17759                                           << Record->getTagKind();
17760         // While the layout of types that contain virtual bases is not specified
17761         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17762         // virtual bases after the derived members.  This would make a flexible
17763         // array member declared at the end of an object not adjacent to the end
17764         // of the type.
17765         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17766           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17767               << FD->getDeclName() << Record->getTagKind();
17768         if (!getLangOpts().C99)
17769           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17770             << FD->getDeclName() << Record->getTagKind();
17771 
17772         // If the element type has a non-trivial destructor, we would not
17773         // implicitly destroy the elements, so disallow it for now.
17774         //
17775         // FIXME: GCC allows this. We should probably either implicitly delete
17776         // the destructor of the containing class, or just allow this.
17777         QualType BaseElem = Context.getBaseElementType(FD->getType());
17778         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17779           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17780             << FD->getDeclName() << FD->getType();
17781           FD->setInvalidDecl();
17782           EnclosingDecl->setInvalidDecl();
17783           continue;
17784         }
17785         // Okay, we have a legal flexible array member at the end of the struct.
17786         Record->setHasFlexibleArrayMember(true);
17787       } else {
17788         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17789         // unless they are followed by another ivar. That check is done
17790         // elsewhere, after synthesized ivars are known.
17791       }
17792     } else if (!FDTy->isDependentType() &&
17793                RequireCompleteSizedType(
17794                    FD->getLocation(), FD->getType(),
17795                    diag::err_field_incomplete_or_sizeless)) {
17796       // Incomplete type
17797       FD->setInvalidDecl();
17798       EnclosingDecl->setInvalidDecl();
17799       continue;
17800     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17801       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17802         // A type which contains a flexible array member is considered to be a
17803         // flexible array member.
17804         Record->setHasFlexibleArrayMember(true);
17805         if (!Record->isUnion()) {
17806           // If this is a struct/class and this is not the last element, reject
17807           // it.  Note that GCC supports variable sized arrays in the middle of
17808           // structures.
17809           if (!IsLastField)
17810             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17811               << FD->getDeclName() << FD->getType();
17812           else {
17813             // We support flexible arrays at the end of structs in
17814             // other structs as an extension.
17815             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17816               << FD->getDeclName();
17817           }
17818         }
17819       }
17820       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17821           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17822                                  diag::err_abstract_type_in_decl,
17823                                  AbstractIvarType)) {
17824         // Ivars can not have abstract class types
17825         FD->setInvalidDecl();
17826       }
17827       if (Record && FDTTy->getDecl()->hasObjectMember())
17828         Record->setHasObjectMember(true);
17829       if (Record && FDTTy->getDecl()->hasVolatileMember())
17830         Record->setHasVolatileMember(true);
17831     } else if (FDTy->isObjCObjectType()) {
17832       /// A field cannot be an Objective-c object
17833       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17834         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17835       QualType T = Context.getObjCObjectPointerType(FD->getType());
17836       FD->setType(T);
17837     } else if (Record && Record->isUnion() &&
17838                FD->getType().hasNonTrivialObjCLifetime() &&
17839                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17840                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17841                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17842                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17843       // For backward compatibility, fields of C unions declared in system
17844       // headers that have non-trivial ObjC ownership qualifications are marked
17845       // as unavailable unless the qualifier is explicit and __strong. This can
17846       // break ABI compatibility between programs compiled with ARC and MRR, but
17847       // is a better option than rejecting programs using those unions under
17848       // ARC.
17849       FD->addAttr(UnavailableAttr::CreateImplicit(
17850           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17851           FD->getLocation()));
17852     } else if (getLangOpts().ObjC &&
17853                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17854                !Record->hasObjectMember()) {
17855       if (FD->getType()->isObjCObjectPointerType() ||
17856           FD->getType().isObjCGCStrong())
17857         Record->setHasObjectMember(true);
17858       else if (Context.getAsArrayType(FD->getType())) {
17859         QualType BaseType = Context.getBaseElementType(FD->getType());
17860         if (BaseType->isRecordType() &&
17861             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17862           Record->setHasObjectMember(true);
17863         else if (BaseType->isObjCObjectPointerType() ||
17864                  BaseType.isObjCGCStrong())
17865                Record->setHasObjectMember(true);
17866       }
17867     }
17868 
17869     if (Record && !getLangOpts().CPlusPlus &&
17870         !shouldIgnoreForRecordTriviality(FD)) {
17871       QualType FT = FD->getType();
17872       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17873         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17874         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17875             Record->isUnion())
17876           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17877       }
17878       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17879       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17880         Record->setNonTrivialToPrimitiveCopy(true);
17881         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17882           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17883       }
17884       if (FT.isDestructedType()) {
17885         Record->setNonTrivialToPrimitiveDestroy(true);
17886         Record->setParamDestroyedInCallee(true);
17887         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17888           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17889       }
17890 
17891       if (const auto *RT = FT->getAs<RecordType>()) {
17892         if (RT->getDecl()->getArgPassingRestrictions() ==
17893             RecordDecl::APK_CanNeverPassInRegs)
17894           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17895       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17896         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17897     }
17898 
17899     if (Record && FD->getType().isVolatileQualified())
17900       Record->setHasVolatileMember(true);
17901     // Keep track of the number of named members.
17902     if (FD->getIdentifier())
17903       ++NumNamedMembers;
17904   }
17905 
17906   // Okay, we successfully defined 'Record'.
17907   if (Record) {
17908     bool Completed = false;
17909     if (CXXRecord) {
17910       if (!CXXRecord->isInvalidDecl()) {
17911         // Set access bits correctly on the directly-declared conversions.
17912         for (CXXRecordDecl::conversion_iterator
17913                I = CXXRecord->conversion_begin(),
17914                E = CXXRecord->conversion_end(); I != E; ++I)
17915           I.setAccess((*I)->getAccess());
17916       }
17917 
17918       // Add any implicitly-declared members to this class.
17919       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17920 
17921       if (!CXXRecord->isDependentType()) {
17922         if (!CXXRecord->isInvalidDecl()) {
17923           // If we have virtual base classes, we may end up finding multiple
17924           // final overriders for a given virtual function. Check for this
17925           // problem now.
17926           if (CXXRecord->getNumVBases()) {
17927             CXXFinalOverriderMap FinalOverriders;
17928             CXXRecord->getFinalOverriders(FinalOverriders);
17929 
17930             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17931                                              MEnd = FinalOverriders.end();
17932                  M != MEnd; ++M) {
17933               for (OverridingMethods::iterator SO = M->second.begin(),
17934                                             SOEnd = M->second.end();
17935                    SO != SOEnd; ++SO) {
17936                 assert(SO->second.size() > 0 &&
17937                        "Virtual function without overriding functions?");
17938                 if (SO->second.size() == 1)
17939                   continue;
17940 
17941                 // C++ [class.virtual]p2:
17942                 //   In a derived class, if a virtual member function of a base
17943                 //   class subobject has more than one final overrider the
17944                 //   program is ill-formed.
17945                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17946                   << (const NamedDecl *)M->first << Record;
17947                 Diag(M->first->getLocation(),
17948                      diag::note_overridden_virtual_function);
17949                 for (OverridingMethods::overriding_iterator
17950                           OM = SO->second.begin(),
17951                        OMEnd = SO->second.end();
17952                      OM != OMEnd; ++OM)
17953                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17954                     << (const NamedDecl *)M->first << OM->Method->getParent();
17955 
17956                 Record->setInvalidDecl();
17957               }
17958             }
17959             CXXRecord->completeDefinition(&FinalOverriders);
17960             Completed = true;
17961           }
17962         }
17963       }
17964     }
17965 
17966     if (!Completed)
17967       Record->completeDefinition();
17968 
17969     // Handle attributes before checking the layout.
17970     ProcessDeclAttributeList(S, Record, Attrs);
17971 
17972     // Maybe randomize the field order.
17973     if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() &&
17974         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
17975         !Record->isRandomized()) {
17976       SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields());
17977       SmallVector<Decl *, 32> NewFieldOrdering;
17978       if (randstruct::randomizeStructureLayout(
17979               Context, Record->getNameAsString(), OrigFieldOrdering,
17980               NewFieldOrdering))
17981         Record->reorderFields(NewFieldOrdering);
17982     }
17983 
17984     // We may have deferred checking for a deleted destructor. Check now.
17985     if (CXXRecord) {
17986       auto *Dtor = CXXRecord->getDestructor();
17987       if (Dtor && Dtor->isImplicit() &&
17988           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17989         CXXRecord->setImplicitDestructorIsDeleted();
17990         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17991       }
17992     }
17993 
17994     if (Record->hasAttrs()) {
17995       CheckAlignasUnderalignment(Record);
17996 
17997       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17998         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17999                                            IA->getRange(), IA->getBestCase(),
18000                                            IA->getInheritanceModel());
18001     }
18002 
18003     // Check if the structure/union declaration is a type that can have zero
18004     // size in C. For C this is a language extension, for C++ it may cause
18005     // compatibility problems.
18006     bool CheckForZeroSize;
18007     if (!getLangOpts().CPlusPlus) {
18008       CheckForZeroSize = true;
18009     } else {
18010       // For C++ filter out types that cannot be referenced in C code.
18011       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18012       CheckForZeroSize =
18013           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18014           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18015           CXXRecord->isCLike();
18016     }
18017     if (CheckForZeroSize) {
18018       bool ZeroSize = true;
18019       bool IsEmpty = true;
18020       unsigned NonBitFields = 0;
18021       for (RecordDecl::field_iterator I = Record->field_begin(),
18022                                       E = Record->field_end();
18023            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18024         IsEmpty = false;
18025         if (I->isUnnamedBitfield()) {
18026           if (!I->isZeroLengthBitField(Context))
18027             ZeroSize = false;
18028         } else {
18029           ++NonBitFields;
18030           QualType FieldType = I->getType();
18031           if (FieldType->isIncompleteType() ||
18032               !Context.getTypeSizeInChars(FieldType).isZero())
18033             ZeroSize = false;
18034         }
18035       }
18036 
18037       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18038       // allowed in C++, but warn if its declaration is inside
18039       // extern "C" block.
18040       if (ZeroSize) {
18041         Diag(RecLoc, getLangOpts().CPlusPlus ?
18042                          diag::warn_zero_size_struct_union_in_extern_c :
18043                          diag::warn_zero_size_struct_union_compat)
18044           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18045       }
18046 
18047       // Structs without named members are extension in C (C99 6.7.2.1p7),
18048       // but are accepted by GCC.
18049       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18050         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18051                                diag::ext_no_named_members_in_struct_union)
18052           << Record->isUnion();
18053       }
18054     }
18055   } else {
18056     ObjCIvarDecl **ClsFields =
18057       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18058     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18059       ID->setEndOfDefinitionLoc(RBrac);
18060       // Add ivar's to class's DeclContext.
18061       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18062         ClsFields[i]->setLexicalDeclContext(ID);
18063         ID->addDecl(ClsFields[i]);
18064       }
18065       // Must enforce the rule that ivars in the base classes may not be
18066       // duplicates.
18067       if (ID->getSuperClass())
18068         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18069     } else if (ObjCImplementationDecl *IMPDecl =
18070                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18071       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18072       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18073         // Ivar declared in @implementation never belongs to the implementation.
18074         // Only it is in implementation's lexical context.
18075         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18076       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18077       IMPDecl->setIvarLBraceLoc(LBrac);
18078       IMPDecl->setIvarRBraceLoc(RBrac);
18079     } else if (ObjCCategoryDecl *CDecl =
18080                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18081       // case of ivars in class extension; all other cases have been
18082       // reported as errors elsewhere.
18083       // FIXME. Class extension does not have a LocEnd field.
18084       // CDecl->setLocEnd(RBrac);
18085       // Add ivar's to class extension's DeclContext.
18086       // Diagnose redeclaration of private ivars.
18087       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18088       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18089         if (IDecl) {
18090           if (const ObjCIvarDecl *ClsIvar =
18091               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18092             Diag(ClsFields[i]->getLocation(),
18093                  diag::err_duplicate_ivar_declaration);
18094             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18095             continue;
18096           }
18097           for (const auto *Ext : IDecl->known_extensions()) {
18098             if (const ObjCIvarDecl *ClsExtIvar
18099                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18100               Diag(ClsFields[i]->getLocation(),
18101                    diag::err_duplicate_ivar_declaration);
18102               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18103               continue;
18104             }
18105           }
18106         }
18107         ClsFields[i]->setLexicalDeclContext(CDecl);
18108         CDecl->addDecl(ClsFields[i]);
18109       }
18110       CDecl->setIvarLBraceLoc(LBrac);
18111       CDecl->setIvarRBraceLoc(RBrac);
18112     }
18113   }
18114 }
18115 
18116 /// Determine whether the given integral value is representable within
18117 /// the given type T.
18118 static bool isRepresentableIntegerValue(ASTContext &Context,
18119                                         llvm::APSInt &Value,
18120                                         QualType T) {
18121   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18122          "Integral type required!");
18123   unsigned BitWidth = Context.getIntWidth(T);
18124 
18125   if (Value.isUnsigned() || Value.isNonNegative()) {
18126     if (T->isSignedIntegerOrEnumerationType())
18127       --BitWidth;
18128     return Value.getActiveBits() <= BitWidth;
18129   }
18130   return Value.getMinSignedBits() <= BitWidth;
18131 }
18132 
18133 // Given an integral type, return the next larger integral type
18134 // (or a NULL type of no such type exists).
18135 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18136   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18137   // enum checking below.
18138   assert((T->isIntegralType(Context) ||
18139          T->isEnumeralType()) && "Integral type required!");
18140   const unsigned NumTypes = 4;
18141   QualType SignedIntegralTypes[NumTypes] = {
18142     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18143   };
18144   QualType UnsignedIntegralTypes[NumTypes] = {
18145     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18146     Context.UnsignedLongLongTy
18147   };
18148 
18149   unsigned BitWidth = Context.getTypeSize(T);
18150   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18151                                                         : UnsignedIntegralTypes;
18152   for (unsigned I = 0; I != NumTypes; ++I)
18153     if (Context.getTypeSize(Types[I]) > BitWidth)
18154       return Types[I];
18155 
18156   return QualType();
18157 }
18158 
18159 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18160                                           EnumConstantDecl *LastEnumConst,
18161                                           SourceLocation IdLoc,
18162                                           IdentifierInfo *Id,
18163                                           Expr *Val) {
18164   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18165   llvm::APSInt EnumVal(IntWidth);
18166   QualType EltTy;
18167 
18168   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18169     Val = nullptr;
18170 
18171   if (Val)
18172     Val = DefaultLvalueConversion(Val).get();
18173 
18174   if (Val) {
18175     if (Enum->isDependentType() || Val->isTypeDependent() ||
18176         Val->containsErrors())
18177       EltTy = Context.DependentTy;
18178     else {
18179       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18180       // underlying type, but do allow it in all other contexts.
18181       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18182         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18183         // constant-expression in the enumerator-definition shall be a converted
18184         // constant expression of the underlying type.
18185         EltTy = Enum->getIntegerType();
18186         ExprResult Converted =
18187           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18188                                            CCEK_Enumerator);
18189         if (Converted.isInvalid())
18190           Val = nullptr;
18191         else
18192           Val = Converted.get();
18193       } else if (!Val->isValueDependent() &&
18194                  !(Val =
18195                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18196                            .get())) {
18197         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18198       } else {
18199         if (Enum->isComplete()) {
18200           EltTy = Enum->getIntegerType();
18201 
18202           // In Obj-C and Microsoft mode, require the enumeration value to be
18203           // representable in the underlying type of the enumeration. In C++11,
18204           // we perform a non-narrowing conversion as part of converted constant
18205           // expression checking.
18206           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18207             if (Context.getTargetInfo()
18208                     .getTriple()
18209                     .isWindowsMSVCEnvironment()) {
18210               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18211             } else {
18212               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18213             }
18214           }
18215 
18216           // Cast to the underlying type.
18217           Val = ImpCastExprToType(Val, EltTy,
18218                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18219                                                          : CK_IntegralCast)
18220                     .get();
18221         } else if (getLangOpts().CPlusPlus) {
18222           // C++11 [dcl.enum]p5:
18223           //   If the underlying type is not fixed, the type of each enumerator
18224           //   is the type of its initializing value:
18225           //     - If an initializer is specified for an enumerator, the
18226           //       initializing value has the same type as the expression.
18227           EltTy = Val->getType();
18228         } else {
18229           // C99 6.7.2.2p2:
18230           //   The expression that defines the value of an enumeration constant
18231           //   shall be an integer constant expression that has a value
18232           //   representable as an int.
18233 
18234           // Complain if the value is not representable in an int.
18235           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18236             Diag(IdLoc, diag::ext_enum_value_not_int)
18237               << toString(EnumVal, 10) << Val->getSourceRange()
18238               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18239           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18240             // Force the type of the expression to 'int'.
18241             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18242           }
18243           EltTy = Val->getType();
18244         }
18245       }
18246     }
18247   }
18248 
18249   if (!Val) {
18250     if (Enum->isDependentType())
18251       EltTy = Context.DependentTy;
18252     else if (!LastEnumConst) {
18253       // C++0x [dcl.enum]p5:
18254       //   If the underlying type is not fixed, the type of each enumerator
18255       //   is the type of its initializing value:
18256       //     - If no initializer is specified for the first enumerator, the
18257       //       initializing value has an unspecified integral type.
18258       //
18259       // GCC uses 'int' for its unspecified integral type, as does
18260       // C99 6.7.2.2p3.
18261       if (Enum->isFixed()) {
18262         EltTy = Enum->getIntegerType();
18263       }
18264       else {
18265         EltTy = Context.IntTy;
18266       }
18267     } else {
18268       // Assign the last value + 1.
18269       EnumVal = LastEnumConst->getInitVal();
18270       ++EnumVal;
18271       EltTy = LastEnumConst->getType();
18272 
18273       // Check for overflow on increment.
18274       if (EnumVal < LastEnumConst->getInitVal()) {
18275         // C++0x [dcl.enum]p5:
18276         //   If the underlying type is not fixed, the type of each enumerator
18277         //   is the type of its initializing value:
18278         //
18279         //     - Otherwise the type of the initializing value is the same as
18280         //       the type of the initializing value of the preceding enumerator
18281         //       unless the incremented value is not representable in that type,
18282         //       in which case the type is an unspecified integral type
18283         //       sufficient to contain the incremented value. If no such type
18284         //       exists, the program is ill-formed.
18285         QualType T = getNextLargerIntegralType(Context, EltTy);
18286         if (T.isNull() || Enum->isFixed()) {
18287           // There is no integral type larger enough to represent this
18288           // value. Complain, then allow the value to wrap around.
18289           EnumVal = LastEnumConst->getInitVal();
18290           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18291           ++EnumVal;
18292           if (Enum->isFixed())
18293             // When the underlying type is fixed, this is ill-formed.
18294             Diag(IdLoc, diag::err_enumerator_wrapped)
18295               << toString(EnumVal, 10)
18296               << EltTy;
18297           else
18298             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18299               << toString(EnumVal, 10);
18300         } else {
18301           EltTy = T;
18302         }
18303 
18304         // Retrieve the last enumerator's value, extent that type to the
18305         // type that is supposed to be large enough to represent the incremented
18306         // value, then increment.
18307         EnumVal = LastEnumConst->getInitVal();
18308         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18309         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18310         ++EnumVal;
18311 
18312         // If we're not in C++, diagnose the overflow of enumerator values,
18313         // which in C99 means that the enumerator value is not representable in
18314         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18315         // permits enumerator values that are representable in some larger
18316         // integral type.
18317         if (!getLangOpts().CPlusPlus && !T.isNull())
18318           Diag(IdLoc, diag::warn_enum_value_overflow);
18319       } else if (!getLangOpts().CPlusPlus &&
18320                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18321         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18322         Diag(IdLoc, diag::ext_enum_value_not_int)
18323           << toString(EnumVal, 10) << 1;
18324       }
18325     }
18326   }
18327 
18328   if (!EltTy->isDependentType()) {
18329     // Make the enumerator value match the signedness and size of the
18330     // enumerator's type.
18331     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18332     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18333   }
18334 
18335   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18336                                   Val, EnumVal);
18337 }
18338 
18339 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18340                                                 SourceLocation IILoc) {
18341   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18342       !getLangOpts().CPlusPlus)
18343     return SkipBodyInfo();
18344 
18345   // We have an anonymous enum definition. Look up the first enumerator to
18346   // determine if we should merge the definition with an existing one and
18347   // skip the body.
18348   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18349                                          forRedeclarationInCurContext());
18350   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18351   if (!PrevECD)
18352     return SkipBodyInfo();
18353 
18354   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18355   NamedDecl *Hidden;
18356   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18357     SkipBodyInfo Skip;
18358     Skip.Previous = Hidden;
18359     return Skip;
18360   }
18361 
18362   return SkipBodyInfo();
18363 }
18364 
18365 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18366                               SourceLocation IdLoc, IdentifierInfo *Id,
18367                               const ParsedAttributesView &Attrs,
18368                               SourceLocation EqualLoc, Expr *Val) {
18369   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18370   EnumConstantDecl *LastEnumConst =
18371     cast_or_null<EnumConstantDecl>(lastEnumConst);
18372 
18373   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18374   // we find one that is.
18375   S = getNonFieldDeclScope(S);
18376 
18377   // Verify that there isn't already something declared with this name in this
18378   // scope.
18379   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18380   LookupName(R, S);
18381   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18382 
18383   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18384     // Maybe we will complain about the shadowed template parameter.
18385     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18386     // Just pretend that we didn't see the previous declaration.
18387     PrevDecl = nullptr;
18388   }
18389 
18390   // C++ [class.mem]p15:
18391   // If T is the name of a class, then each of the following shall have a name
18392   // different from T:
18393   // - every enumerator of every member of class T that is an unscoped
18394   // enumerated type
18395   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18396     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18397                             DeclarationNameInfo(Id, IdLoc));
18398 
18399   EnumConstantDecl *New =
18400     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18401   if (!New)
18402     return nullptr;
18403 
18404   if (PrevDecl) {
18405     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18406       // Check for other kinds of shadowing not already handled.
18407       CheckShadow(New, PrevDecl, R);
18408     }
18409 
18410     // When in C++, we may get a TagDecl with the same name; in this case the
18411     // enum constant will 'hide' the tag.
18412     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18413            "Received TagDecl when not in C++!");
18414     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18415       if (isa<EnumConstantDecl>(PrevDecl))
18416         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18417       else
18418         Diag(IdLoc, diag::err_redefinition) << Id;
18419       notePreviousDefinition(PrevDecl, IdLoc);
18420       return nullptr;
18421     }
18422   }
18423 
18424   // Process attributes.
18425   ProcessDeclAttributeList(S, New, Attrs);
18426   AddPragmaAttributes(S, New);
18427 
18428   // Register this decl in the current scope stack.
18429   New->setAccess(TheEnumDecl->getAccess());
18430   PushOnScopeChains(New, S);
18431 
18432   ActOnDocumentableDecl(New);
18433 
18434   return New;
18435 }
18436 
18437 // Returns true when the enum initial expression does not trigger the
18438 // duplicate enum warning.  A few common cases are exempted as follows:
18439 // Element2 = Element1
18440 // Element2 = Element1 + 1
18441 // Element2 = Element1 - 1
18442 // Where Element2 and Element1 are from the same enum.
18443 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18444   Expr *InitExpr = ECD->getInitExpr();
18445   if (!InitExpr)
18446     return true;
18447   InitExpr = InitExpr->IgnoreImpCasts();
18448 
18449   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18450     if (!BO->isAdditiveOp())
18451       return true;
18452     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18453     if (!IL)
18454       return true;
18455     if (IL->getValue() != 1)
18456       return true;
18457 
18458     InitExpr = BO->getLHS();
18459   }
18460 
18461   // This checks if the elements are from the same enum.
18462   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18463   if (!DRE)
18464     return true;
18465 
18466   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18467   if (!EnumConstant)
18468     return true;
18469 
18470   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18471       Enum)
18472     return true;
18473 
18474   return false;
18475 }
18476 
18477 // Emits a warning when an element is implicitly set a value that
18478 // a previous element has already been set to.
18479 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18480                                         EnumDecl *Enum, QualType EnumType) {
18481   // Avoid anonymous enums
18482   if (!Enum->getIdentifier())
18483     return;
18484 
18485   // Only check for small enums.
18486   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18487     return;
18488 
18489   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18490     return;
18491 
18492   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18493   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18494 
18495   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18496 
18497   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18498   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18499 
18500   // Use int64_t as a key to avoid needing special handling for map keys.
18501   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18502     llvm::APSInt Val = D->getInitVal();
18503     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18504   };
18505 
18506   DuplicatesVector DupVector;
18507   ValueToVectorMap EnumMap;
18508 
18509   // Populate the EnumMap with all values represented by enum constants without
18510   // an initializer.
18511   for (auto *Element : Elements) {
18512     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18513 
18514     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18515     // this constant.  Skip this enum since it may be ill-formed.
18516     if (!ECD) {
18517       return;
18518     }
18519 
18520     // Constants with initalizers are handled in the next loop.
18521     if (ECD->getInitExpr())
18522       continue;
18523 
18524     // Duplicate values are handled in the next loop.
18525     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18526   }
18527 
18528   if (EnumMap.size() == 0)
18529     return;
18530 
18531   // Create vectors for any values that has duplicates.
18532   for (auto *Element : Elements) {
18533     // The last loop returned if any constant was null.
18534     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18535     if (!ValidDuplicateEnum(ECD, Enum))
18536       continue;
18537 
18538     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18539     if (Iter == EnumMap.end())
18540       continue;
18541 
18542     DeclOrVector& Entry = Iter->second;
18543     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18544       // Ensure constants are different.
18545       if (D == ECD)
18546         continue;
18547 
18548       // Create new vector and push values onto it.
18549       auto Vec = std::make_unique<ECDVector>();
18550       Vec->push_back(D);
18551       Vec->push_back(ECD);
18552 
18553       // Update entry to point to the duplicates vector.
18554       Entry = Vec.get();
18555 
18556       // Store the vector somewhere we can consult later for quick emission of
18557       // diagnostics.
18558       DupVector.emplace_back(std::move(Vec));
18559       continue;
18560     }
18561 
18562     ECDVector *Vec = Entry.get<ECDVector*>();
18563     // Make sure constants are not added more than once.
18564     if (*Vec->begin() == ECD)
18565       continue;
18566 
18567     Vec->push_back(ECD);
18568   }
18569 
18570   // Emit diagnostics.
18571   for (const auto &Vec : DupVector) {
18572     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18573 
18574     // Emit warning for one enum constant.
18575     auto *FirstECD = Vec->front();
18576     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18577       << FirstECD << toString(FirstECD->getInitVal(), 10)
18578       << FirstECD->getSourceRange();
18579 
18580     // Emit one note for each of the remaining enum constants with
18581     // the same value.
18582     for (auto *ECD : llvm::drop_begin(*Vec))
18583       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18584         << ECD << toString(ECD->getInitVal(), 10)
18585         << ECD->getSourceRange();
18586   }
18587 }
18588 
18589 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18590                              bool AllowMask) const {
18591   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18592   assert(ED->isCompleteDefinition() && "expected enum definition");
18593 
18594   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18595   llvm::APInt &FlagBits = R.first->second;
18596 
18597   if (R.second) {
18598     for (auto *E : ED->enumerators()) {
18599       const auto &EVal = E->getInitVal();
18600       // Only single-bit enumerators introduce new flag values.
18601       if (EVal.isPowerOf2())
18602         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18603     }
18604   }
18605 
18606   // A value is in a flag enum if either its bits are a subset of the enum's
18607   // flag bits (the first condition) or we are allowing masks and the same is
18608   // true of its complement (the second condition). When masks are allowed, we
18609   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18610   //
18611   // While it's true that any value could be used as a mask, the assumption is
18612   // that a mask will have all of the insignificant bits set. Anything else is
18613   // likely a logic error.
18614   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18615   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18616 }
18617 
18618 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18619                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18620                          const ParsedAttributesView &Attrs) {
18621   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18622   QualType EnumType = Context.getTypeDeclType(Enum);
18623 
18624   ProcessDeclAttributeList(S, Enum, Attrs);
18625 
18626   if (Enum->isDependentType()) {
18627     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18628       EnumConstantDecl *ECD =
18629         cast_or_null<EnumConstantDecl>(Elements[i]);
18630       if (!ECD) continue;
18631 
18632       ECD->setType(EnumType);
18633     }
18634 
18635     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18636     return;
18637   }
18638 
18639   // TODO: If the result value doesn't fit in an int, it must be a long or long
18640   // long value.  ISO C does not support this, but GCC does as an extension,
18641   // emit a warning.
18642   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18643   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18644   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18645 
18646   // Verify that all the values are okay, compute the size of the values, and
18647   // reverse the list.
18648   unsigned NumNegativeBits = 0;
18649   unsigned NumPositiveBits = 0;
18650 
18651   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18652     EnumConstantDecl *ECD =
18653       cast_or_null<EnumConstantDecl>(Elements[i]);
18654     if (!ECD) continue;  // Already issued a diagnostic.
18655 
18656     const llvm::APSInt &InitVal = ECD->getInitVal();
18657 
18658     // Keep track of the size of positive and negative values.
18659     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18660       NumPositiveBits = std::max(NumPositiveBits,
18661                                  (unsigned)InitVal.getActiveBits());
18662     else
18663       NumNegativeBits = std::max(NumNegativeBits,
18664                                  (unsigned)InitVal.getMinSignedBits());
18665   }
18666 
18667   // Figure out the type that should be used for this enum.
18668   QualType BestType;
18669   unsigned BestWidth;
18670 
18671   // C++0x N3000 [conv.prom]p3:
18672   //   An rvalue of an unscoped enumeration type whose underlying
18673   //   type is not fixed can be converted to an rvalue of the first
18674   //   of the following types that can represent all the values of
18675   //   the enumeration: int, unsigned int, long int, unsigned long
18676   //   int, long long int, or unsigned long long int.
18677   // C99 6.4.4.3p2:
18678   //   An identifier declared as an enumeration constant has type int.
18679   // The C99 rule is modified by a gcc extension
18680   QualType BestPromotionType;
18681 
18682   bool Packed = Enum->hasAttr<PackedAttr>();
18683   // -fshort-enums is the equivalent to specifying the packed attribute on all
18684   // enum definitions.
18685   if (LangOpts.ShortEnums)
18686     Packed = true;
18687 
18688   // If the enum already has a type because it is fixed or dictated by the
18689   // target, promote that type instead of analyzing the enumerators.
18690   if (Enum->isComplete()) {
18691     BestType = Enum->getIntegerType();
18692     if (BestType->isPromotableIntegerType())
18693       BestPromotionType = Context.getPromotedIntegerType(BestType);
18694     else
18695       BestPromotionType = BestType;
18696 
18697     BestWidth = Context.getIntWidth(BestType);
18698   }
18699   else if (NumNegativeBits) {
18700     // If there is a negative value, figure out the smallest integer type (of
18701     // int/long/longlong) that fits.
18702     // If it's packed, check also if it fits a char or a short.
18703     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18704       BestType = Context.SignedCharTy;
18705       BestWidth = CharWidth;
18706     } else if (Packed && NumNegativeBits <= ShortWidth &&
18707                NumPositiveBits < ShortWidth) {
18708       BestType = Context.ShortTy;
18709       BestWidth = ShortWidth;
18710     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18711       BestType = Context.IntTy;
18712       BestWidth = IntWidth;
18713     } else {
18714       BestWidth = Context.getTargetInfo().getLongWidth();
18715 
18716       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18717         BestType = Context.LongTy;
18718       } else {
18719         BestWidth = Context.getTargetInfo().getLongLongWidth();
18720 
18721         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18722           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18723         BestType = Context.LongLongTy;
18724       }
18725     }
18726     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18727   } else {
18728     // If there is no negative value, figure out the smallest type that fits
18729     // all of the enumerator values.
18730     // If it's packed, check also if it fits a char or a short.
18731     if (Packed && NumPositiveBits <= CharWidth) {
18732       BestType = Context.UnsignedCharTy;
18733       BestPromotionType = Context.IntTy;
18734       BestWidth = CharWidth;
18735     } else if (Packed && NumPositiveBits <= ShortWidth) {
18736       BestType = Context.UnsignedShortTy;
18737       BestPromotionType = Context.IntTy;
18738       BestWidth = ShortWidth;
18739     } else if (NumPositiveBits <= IntWidth) {
18740       BestType = Context.UnsignedIntTy;
18741       BestWidth = IntWidth;
18742       BestPromotionType
18743         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18744                            ? Context.UnsignedIntTy : Context.IntTy;
18745     } else if (NumPositiveBits <=
18746                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18747       BestType = Context.UnsignedLongTy;
18748       BestPromotionType
18749         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18750                            ? Context.UnsignedLongTy : Context.LongTy;
18751     } else {
18752       BestWidth = Context.getTargetInfo().getLongLongWidth();
18753       assert(NumPositiveBits <= BestWidth &&
18754              "How could an initializer get larger than ULL?");
18755       BestType = Context.UnsignedLongLongTy;
18756       BestPromotionType
18757         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18758                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18759     }
18760   }
18761 
18762   // Loop over all of the enumerator constants, changing their types to match
18763   // the type of the enum if needed.
18764   for (auto *D : Elements) {
18765     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18766     if (!ECD) continue;  // Already issued a diagnostic.
18767 
18768     // Standard C says the enumerators have int type, but we allow, as an
18769     // extension, the enumerators to be larger than int size.  If each
18770     // enumerator value fits in an int, type it as an int, otherwise type it the
18771     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18772     // that X has type 'int', not 'unsigned'.
18773 
18774     // Determine whether the value fits into an int.
18775     llvm::APSInt InitVal = ECD->getInitVal();
18776 
18777     // If it fits into an integer type, force it.  Otherwise force it to match
18778     // the enum decl type.
18779     QualType NewTy;
18780     unsigned NewWidth;
18781     bool NewSign;
18782     if (!getLangOpts().CPlusPlus &&
18783         !Enum->isFixed() &&
18784         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18785       NewTy = Context.IntTy;
18786       NewWidth = IntWidth;
18787       NewSign = true;
18788     } else if (ECD->getType() == BestType) {
18789       // Already the right type!
18790       if (getLangOpts().CPlusPlus)
18791         // C++ [dcl.enum]p4: Following the closing brace of an
18792         // enum-specifier, each enumerator has the type of its
18793         // enumeration.
18794         ECD->setType(EnumType);
18795       continue;
18796     } else {
18797       NewTy = BestType;
18798       NewWidth = BestWidth;
18799       NewSign = BestType->isSignedIntegerOrEnumerationType();
18800     }
18801 
18802     // Adjust the APSInt value.
18803     InitVal = InitVal.extOrTrunc(NewWidth);
18804     InitVal.setIsSigned(NewSign);
18805     ECD->setInitVal(InitVal);
18806 
18807     // Adjust the Expr initializer and type.
18808     if (ECD->getInitExpr() &&
18809         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18810       ECD->setInitExpr(ImplicitCastExpr::Create(
18811           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18812           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18813     if (getLangOpts().CPlusPlus)
18814       // C++ [dcl.enum]p4: Following the closing brace of an
18815       // enum-specifier, each enumerator has the type of its
18816       // enumeration.
18817       ECD->setType(EnumType);
18818     else
18819       ECD->setType(NewTy);
18820   }
18821 
18822   Enum->completeDefinition(BestType, BestPromotionType,
18823                            NumPositiveBits, NumNegativeBits);
18824 
18825   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18826 
18827   if (Enum->isClosedFlag()) {
18828     for (Decl *D : Elements) {
18829       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18830       if (!ECD) continue;  // Already issued a diagnostic.
18831 
18832       llvm::APSInt InitVal = ECD->getInitVal();
18833       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18834           !IsValueInFlagEnum(Enum, InitVal, true))
18835         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18836           << ECD << Enum;
18837     }
18838   }
18839 
18840   // Now that the enum type is defined, ensure it's not been underaligned.
18841   if (Enum->hasAttrs())
18842     CheckAlignasUnderalignment(Enum);
18843 }
18844 
18845 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18846                                   SourceLocation StartLoc,
18847                                   SourceLocation EndLoc) {
18848   StringLiteral *AsmString = cast<StringLiteral>(expr);
18849 
18850   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18851                                                    AsmString, StartLoc,
18852                                                    EndLoc);
18853   CurContext->addDecl(New);
18854   return New;
18855 }
18856 
18857 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18858                                       IdentifierInfo* AliasName,
18859                                       SourceLocation PragmaLoc,
18860                                       SourceLocation NameLoc,
18861                                       SourceLocation AliasNameLoc) {
18862   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18863                                          LookupOrdinaryName);
18864   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18865                            AttributeCommonInfo::AS_Pragma);
18866   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18867       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18868 
18869   // If a declaration that:
18870   // 1) declares a function or a variable
18871   // 2) has external linkage
18872   // already exists, add a label attribute to it.
18873   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18874     if (isDeclExternC(PrevDecl))
18875       PrevDecl->addAttr(Attr);
18876     else
18877       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18878           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18879   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18880   } else
18881     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18882 }
18883 
18884 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18885                              SourceLocation PragmaLoc,
18886                              SourceLocation NameLoc) {
18887   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18888 
18889   if (PrevDecl) {
18890     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18891   } else {
18892     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18893   }
18894 }
18895 
18896 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18897                                 IdentifierInfo* AliasName,
18898                                 SourceLocation PragmaLoc,
18899                                 SourceLocation NameLoc,
18900                                 SourceLocation AliasNameLoc) {
18901   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18902                                     LookupOrdinaryName);
18903   WeakInfo W = WeakInfo(Name, NameLoc);
18904 
18905   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18906     if (!PrevDecl->hasAttr<AliasAttr>())
18907       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18908         DeclApplyPragmaWeak(TUScope, ND, W);
18909   } else {
18910     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18911   }
18912 }
18913 
18914 Decl *Sema::getObjCDeclContext() const {
18915   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18916 }
18917 
18918 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18919                                                      bool Final) {
18920   assert(FD && "Expected non-null FunctionDecl");
18921 
18922   // SYCL functions can be template, so we check if they have appropriate
18923   // attribute prior to checking if it is a template.
18924   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18925     return FunctionEmissionStatus::Emitted;
18926 
18927   // Templates are emitted when they're instantiated.
18928   if (FD->isDependentContext())
18929     return FunctionEmissionStatus::TemplateDiscarded;
18930 
18931   // Check whether this function is an externally visible definition.
18932   auto IsEmittedForExternalSymbol = [this, FD]() {
18933     // We have to check the GVA linkage of the function's *definition* -- if we
18934     // only have a declaration, we don't know whether or not the function will
18935     // be emitted, because (say) the definition could include "inline".
18936     FunctionDecl *Def = FD->getDefinition();
18937 
18938     return Def && !isDiscardableGVALinkage(
18939                       getASTContext().GetGVALinkageForFunction(Def));
18940   };
18941 
18942   if (LangOpts.OpenMPIsDevice) {
18943     // In OpenMP device mode we will not emit host only functions, or functions
18944     // we don't need due to their linkage.
18945     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18946         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18947     // DevTy may be changed later by
18948     //  #pragma omp declare target to(*) device_type(*).
18949     // Therefore DevTy having no value does not imply host. The emission status
18950     // will be checked again at the end of compilation unit with Final = true.
18951     if (DevTy.hasValue())
18952       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18953         return FunctionEmissionStatus::OMPDiscarded;
18954     // If we have an explicit value for the device type, or we are in a target
18955     // declare context, we need to emit all extern and used symbols.
18956     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18957       if (IsEmittedForExternalSymbol())
18958         return FunctionEmissionStatus::Emitted;
18959     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18960     // we'll omit it.
18961     if (Final)
18962       return FunctionEmissionStatus::OMPDiscarded;
18963   } else if (LangOpts.OpenMP > 45) {
18964     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18965     // function. In 5.0, no_host was introduced which might cause a function to
18966     // be ommitted.
18967     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18968         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18969     if (DevTy.hasValue())
18970       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18971         return FunctionEmissionStatus::OMPDiscarded;
18972   }
18973 
18974   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18975     return FunctionEmissionStatus::Emitted;
18976 
18977   if (LangOpts.CUDA) {
18978     // When compiling for device, host functions are never emitted.  Similarly,
18979     // when compiling for host, device and global functions are never emitted.
18980     // (Technically, we do emit a host-side stub for global functions, but this
18981     // doesn't count for our purposes here.)
18982     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18983     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18984       return FunctionEmissionStatus::CUDADiscarded;
18985     if (!LangOpts.CUDAIsDevice &&
18986         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18987       return FunctionEmissionStatus::CUDADiscarded;
18988 
18989     if (IsEmittedForExternalSymbol())
18990       return FunctionEmissionStatus::Emitted;
18991   }
18992 
18993   // Otherwise, the function is known-emitted if it's in our set of
18994   // known-emitted functions.
18995   return FunctionEmissionStatus::Unknown;
18996 }
18997 
18998 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18999   // Host-side references to a __global__ function refer to the stub, so the
19000   // function itself is never emitted and therefore should not be marked.
19001   // If we have host fn calls kernel fn calls host+device, the HD function
19002   // does not get instantiated on the host. We model this by omitting at the
19003   // call to the kernel from the callgraph. This ensures that, when compiling
19004   // for host, only HD functions actually called from the host get marked as
19005   // known-emitted.
19006   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19007          IdentifyCUDATarget(Callee) == CFT_Global;
19008 }
19009