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, Scope *S,
3401                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
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     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3884     // type is specified by a function definition that contains a (possibly
3885     // empty) identifier list, both shall agree in the number of parameters
3886     // and the type of each parameter shall be compatible with the type that
3887     // results from the application of default argument promotions to the
3888     // type of the corresponding identifier. ...
3889     // This cannot be handled by ASTContext::typesAreCompatible() because that
3890     // doesn't know whether the function type is for a definition or not when
3891     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3892     // we need to cover here is that the number of arguments agree as the
3893     // default argument promotion rules were already checked by
3894     // ASTContext::typesAreCompatible().
3895     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3896         Old->getNumParams() != New->getNumParams()) {
3897       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3898       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3899       return true;
3900     }
3901 
3902     // If we are merging two functions where only one of them has a prototype,
3903     // we may have enough information to decide to issue a diagnostic that the
3904     // function without a protoype will change behavior in C2x. This handles
3905     // cases like:
3906     //   void i(); void i(int j);
3907     //   void i(int j); void i();
3908     //   void i(); void i(int j) {}
3909     // See ActOnFinishFunctionBody() for other cases of the behavior change
3910     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3911     // type without a prototype.
3912     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3913         !New->isImplicit() && !Old->isImplicit()) {
3914       const FunctionDecl *WithProto, *WithoutProto;
3915       if (New->hasWrittenPrototype()) {
3916         WithProto = New;
3917         WithoutProto = Old;
3918       } else {
3919         WithProto = Old;
3920         WithoutProto = New;
3921       }
3922 
3923       if (WithProto->getNumParams() != 0) {
3924         // The function definition has parameters, so this will change
3925         // behavior in C2x.
3926         //
3927         // If we already warned about about the function without a prototype
3928         // being deprecated, add a note that it also changes behavior. If we
3929         // didn't warn about it being deprecated (because the diagnostic is
3930         // not enabled), warn now that it is deprecated and changes behavior.
3931         bool AddNote = false;
3932         if (Diags.isIgnored(diag::warn_strict_prototypes,
3933                             WithoutProto->getLocation())) {
3934           if (WithoutProto->getBuiltinID() == 0 &&
3935               !WithoutProto->isImplicit() &&
3936               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3937                                                   WithProto->getLocation())) {
3938             PartialDiagnostic PD =
3939                 PDiag(diag::warn_non_prototype_changes_behavior);
3940             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3941               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3942                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3943             }
3944             Diag(WithoutProto->getLocation(), PD);
3945           }
3946         } else {
3947           AddNote = true;
3948         }
3949 
3950         // Because the function with a prototype has parameters but a previous
3951         // declaration had none, the function with the prototype will also
3952         // change behavior in C2x.
3953         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3954           if (SourceMgr.isBeforeInTranslationUnit(
3955                   WithProto->getLocation(), WithoutProto->getLocation())) {
3956             // If the function with the prototype comes before the function
3957             // without the prototype, we only want to diagnose the one without
3958             // the prototype.
3959             Diag(WithoutProto->getLocation(),
3960                  diag::warn_non_prototype_changes_behavior);
3961           } else {
3962             // Otherwise, diagnose the one with the prototype, and potentially
3963             // attach a note to the one without a prototype if needed.
3964             Diag(WithProto->getLocation(),
3965                  diag::warn_non_prototype_changes_behavior);
3966             if (AddNote && WithoutProto->getBuiltinID() == 0)
3967               Diag(WithoutProto->getLocation(),
3968                    diag::note_func_decl_changes_behavior);
3969           }
3970         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3971                    !WithoutProto->isImplicit()) {
3972           // If we were supposed to add a note but the function with a
3973           // prototype is a builtin or was implicitly declared, which means we
3974           // have nothing to attach the note to, so we issue a warning instead.
3975           Diag(WithoutProto->getLocation(),
3976                diag::warn_non_prototype_changes_behavior);
3977         }
3978       }
3979     }
3980 
3981     if (Context.typesAreCompatible(OldQType, NewQType)) {
3982       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3983       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3984       const FunctionProtoType *OldProto = nullptr;
3985       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3986           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3987         // The old declaration provided a function prototype, but the
3988         // new declaration does not. Merge in the prototype.
3989         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3990         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3991         NewQType =
3992             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3993                                     OldProto->getExtProtoInfo());
3994         New->setType(NewQType);
3995         New->setHasInheritedPrototype();
3996 
3997         // Synthesize parameters with the same types.
3998         SmallVector<ParmVarDecl *, 16> Params;
3999         for (const auto &ParamType : OldProto->param_types()) {
4000           ParmVarDecl *Param = ParmVarDecl::Create(
4001               Context, New, SourceLocation(), SourceLocation(), nullptr,
4002               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4003           Param->setScopeInfo(0, Params.size());
4004           Param->setImplicit();
4005           Params.push_back(Param);
4006         }
4007 
4008         New->setParams(Params);
4009       }
4010 
4011       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4012     }
4013   }
4014 
4015   // Check if the function types are compatible when pointer size address
4016   // spaces are ignored.
4017   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4018     return false;
4019 
4020   // GNU C permits a K&R definition to follow a prototype declaration
4021   // if the declared types of the parameters in the K&R definition
4022   // match the types in the prototype declaration, even when the
4023   // promoted types of the parameters from the K&R definition differ
4024   // from the types in the prototype. GCC then keeps the types from
4025   // the prototype.
4026   //
4027   // If a variadic prototype is followed by a non-variadic K&R definition,
4028   // the K&R definition becomes variadic.  This is sort of an edge case, but
4029   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4030   // C99 6.9.1p8.
4031   if (!getLangOpts().CPlusPlus &&
4032       Old->hasPrototype() && !New->hasPrototype() &&
4033       New->getType()->getAs<FunctionProtoType>() &&
4034       Old->getNumParams() == New->getNumParams()) {
4035     SmallVector<QualType, 16> ArgTypes;
4036     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4037     const FunctionProtoType *OldProto
4038       = Old->getType()->getAs<FunctionProtoType>();
4039     const FunctionProtoType *NewProto
4040       = New->getType()->getAs<FunctionProtoType>();
4041 
4042     // Determine whether this is the GNU C extension.
4043     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4044                                                NewProto->getReturnType());
4045     bool LooseCompatible = !MergedReturn.isNull();
4046     for (unsigned Idx = 0, End = Old->getNumParams();
4047          LooseCompatible && Idx != End; ++Idx) {
4048       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4049       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4050       if (Context.typesAreCompatible(OldParm->getType(),
4051                                      NewProto->getParamType(Idx))) {
4052         ArgTypes.push_back(NewParm->getType());
4053       } else if (Context.typesAreCompatible(OldParm->getType(),
4054                                             NewParm->getType(),
4055                                             /*CompareUnqualified=*/true)) {
4056         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4057                                            NewProto->getParamType(Idx) };
4058         Warnings.push_back(Warn);
4059         ArgTypes.push_back(NewParm->getType());
4060       } else
4061         LooseCompatible = false;
4062     }
4063 
4064     if (LooseCompatible) {
4065       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4066         Diag(Warnings[Warn].NewParm->getLocation(),
4067              diag::ext_param_promoted_not_compatible_with_prototype)
4068           << Warnings[Warn].PromotedType
4069           << Warnings[Warn].OldParm->getType();
4070         if (Warnings[Warn].OldParm->getLocation().isValid())
4071           Diag(Warnings[Warn].OldParm->getLocation(),
4072                diag::note_previous_declaration);
4073       }
4074 
4075       if (MergeTypeWithOld)
4076         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4077                                              OldProto->getExtProtoInfo()));
4078       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4079     }
4080 
4081     // Fall through to diagnose conflicting types.
4082   }
4083 
4084   // A function that has already been declared has been redeclared or
4085   // defined with a different type; show an appropriate diagnostic.
4086 
4087   // If the previous declaration was an implicitly-generated builtin
4088   // declaration, then at the very least we should use a specialized note.
4089   unsigned BuiltinID;
4090   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4091     // If it's actually a library-defined builtin function like 'malloc'
4092     // or 'printf', just warn about the incompatible redeclaration.
4093     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4094       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4095       Diag(OldLocation, diag::note_previous_builtin_declaration)
4096         << Old << Old->getType();
4097       return false;
4098     }
4099 
4100     PrevDiag = diag::note_previous_builtin_declaration;
4101   }
4102 
4103   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4104   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4105   return true;
4106 }
4107 
4108 /// Completes the merge of two function declarations that are
4109 /// known to be compatible.
4110 ///
4111 /// This routine handles the merging of attributes and other
4112 /// properties of function declarations from the old declaration to
4113 /// the new declaration, once we know that New is in fact a
4114 /// redeclaration of Old.
4115 ///
4116 /// \returns false
4117 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4118                                         Scope *S, bool MergeTypeWithOld) {
4119   // Merge the attributes
4120   mergeDeclAttributes(New, Old);
4121 
4122   // Merge "pure" flag.
4123   if (Old->isPure())
4124     New->setPure();
4125 
4126   // Merge "used" flag.
4127   if (Old->getMostRecentDecl()->isUsed(false))
4128     New->setIsUsed();
4129 
4130   // Merge attributes from the parameters.  These can mismatch with K&R
4131   // declarations.
4132   if (New->getNumParams() == Old->getNumParams())
4133       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4134         ParmVarDecl *NewParam = New->getParamDecl(i);
4135         ParmVarDecl *OldParam = Old->getParamDecl(i);
4136         mergeParamDeclAttributes(NewParam, OldParam, *this);
4137         mergeParamDeclTypes(NewParam, OldParam, *this);
4138       }
4139 
4140   if (getLangOpts().CPlusPlus)
4141     return MergeCXXFunctionDecl(New, Old, S);
4142 
4143   // Merge the function types so the we get the composite types for the return
4144   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4145   // was visible.
4146   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4147   if (!Merged.isNull() && MergeTypeWithOld)
4148     New->setType(Merged);
4149 
4150   return false;
4151 }
4152 
4153 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4154                                 ObjCMethodDecl *oldMethod) {
4155   // Merge the attributes, including deprecated/unavailable
4156   AvailabilityMergeKind MergeKind =
4157       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4158           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4159                                      : AMK_ProtocolImplementation)
4160           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4161                                                            : AMK_Override;
4162 
4163   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4164 
4165   // Merge attributes from the parameters.
4166   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4167                                        oe = oldMethod->param_end();
4168   for (ObjCMethodDecl::param_iterator
4169          ni = newMethod->param_begin(), ne = newMethod->param_end();
4170        ni != ne && oi != oe; ++ni, ++oi)
4171     mergeParamDeclAttributes(*ni, *oi, *this);
4172 
4173   CheckObjCMethodOverride(newMethod, oldMethod);
4174 }
4175 
4176 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4177   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4178 
4179   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4180          ? diag::err_redefinition_different_type
4181          : diag::err_redeclaration_different_type)
4182     << New->getDeclName() << New->getType() << Old->getType();
4183 
4184   diag::kind PrevDiag;
4185   SourceLocation OldLocation;
4186   std::tie(PrevDiag, OldLocation)
4187     = getNoteDiagForInvalidRedeclaration(Old, New);
4188   S.Diag(OldLocation, PrevDiag);
4189   New->setInvalidDecl();
4190 }
4191 
4192 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4193 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4194 /// emitting diagnostics as appropriate.
4195 ///
4196 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4197 /// to here in AddInitializerToDecl. We can't check them before the initializer
4198 /// is attached.
4199 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4200                              bool MergeTypeWithOld) {
4201   if (New->isInvalidDecl() || Old->isInvalidDecl())
4202     return;
4203 
4204   QualType MergedT;
4205   if (getLangOpts().CPlusPlus) {
4206     if (New->getType()->isUndeducedType()) {
4207       // We don't know what the new type is until the initializer is attached.
4208       return;
4209     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4210       // These could still be something that needs exception specs checked.
4211       return MergeVarDeclExceptionSpecs(New, Old);
4212     }
4213     // C++ [basic.link]p10:
4214     //   [...] the types specified by all declarations referring to a given
4215     //   object or function shall be identical, except that declarations for an
4216     //   array object can specify array types that differ by the presence or
4217     //   absence of a major array bound (8.3.4).
4218     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4219       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4220       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4221 
4222       // We are merging a variable declaration New into Old. If it has an array
4223       // bound, and that bound differs from Old's bound, we should diagnose the
4224       // mismatch.
4225       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4226         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4227              PrevVD = PrevVD->getPreviousDecl()) {
4228           QualType PrevVDTy = PrevVD->getType();
4229           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4230             continue;
4231 
4232           if (!Context.hasSameType(New->getType(), PrevVDTy))
4233             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4234         }
4235       }
4236 
4237       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4238         if (Context.hasSameType(OldArray->getElementType(),
4239                                 NewArray->getElementType()))
4240           MergedT = New->getType();
4241       }
4242       // FIXME: Check visibility. New is hidden but has a complete type. If New
4243       // has no array bound, it should not inherit one from Old, if Old is not
4244       // visible.
4245       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4246         if (Context.hasSameType(OldArray->getElementType(),
4247                                 NewArray->getElementType()))
4248           MergedT = Old->getType();
4249       }
4250     }
4251     else if (New->getType()->isObjCObjectPointerType() &&
4252                Old->getType()->isObjCObjectPointerType()) {
4253       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4254                                               Old->getType());
4255     }
4256   } else {
4257     // C 6.2.7p2:
4258     //   All declarations that refer to the same object or function shall have
4259     //   compatible type.
4260     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4261   }
4262   if (MergedT.isNull()) {
4263     // It's OK if we couldn't merge types if either type is dependent, for a
4264     // block-scope variable. In other cases (static data members of class
4265     // templates, variable templates, ...), we require the types to be
4266     // equivalent.
4267     // FIXME: The C++ standard doesn't say anything about this.
4268     if ((New->getType()->isDependentType() ||
4269          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4270       // If the old type was dependent, we can't merge with it, so the new type
4271       // becomes dependent for now. We'll reproduce the original type when we
4272       // instantiate the TypeSourceInfo for the variable.
4273       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4274         New->setType(Context.DependentTy);
4275       return;
4276     }
4277     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4278   }
4279 
4280   // Don't actually update the type on the new declaration if the old
4281   // declaration was an extern declaration in a different scope.
4282   if (MergeTypeWithOld)
4283     New->setType(MergedT);
4284 }
4285 
4286 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4287                                   LookupResult &Previous) {
4288   // C11 6.2.7p4:
4289   //   For an identifier with internal or external linkage declared
4290   //   in a scope in which a prior declaration of that identifier is
4291   //   visible, if the prior declaration specifies internal or
4292   //   external linkage, the type of the identifier at the later
4293   //   declaration becomes the composite type.
4294   //
4295   // If the variable isn't visible, we do not merge with its type.
4296   if (Previous.isShadowed())
4297     return false;
4298 
4299   if (S.getLangOpts().CPlusPlus) {
4300     // C++11 [dcl.array]p3:
4301     //   If there is a preceding declaration of the entity in the same
4302     //   scope in which the bound was specified, an omitted array bound
4303     //   is taken to be the same as in that earlier declaration.
4304     return NewVD->isPreviousDeclInSameBlockScope() ||
4305            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4306             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4307   } else {
4308     // If the old declaration was function-local, don't merge with its
4309     // type unless we're in the same function.
4310     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4311            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4312   }
4313 }
4314 
4315 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4316 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4317 /// situation, merging decls or emitting diagnostics as appropriate.
4318 ///
4319 /// Tentative definition rules (C99 6.9.2p2) are checked by
4320 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4321 /// definitions here, since the initializer hasn't been attached.
4322 ///
4323 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4324   // If the new decl is already invalid, don't do any other checking.
4325   if (New->isInvalidDecl())
4326     return;
4327 
4328   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4329     return;
4330 
4331   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4332 
4333   // Verify the old decl was also a variable or variable template.
4334   VarDecl *Old = nullptr;
4335   VarTemplateDecl *OldTemplate = nullptr;
4336   if (Previous.isSingleResult()) {
4337     if (NewTemplate) {
4338       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4339       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4340 
4341       if (auto *Shadow =
4342               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4343         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4344           return New->setInvalidDecl();
4345     } else {
4346       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4347 
4348       if (auto *Shadow =
4349               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4350         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4351           return New->setInvalidDecl();
4352     }
4353   }
4354   if (!Old) {
4355     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4356         << New->getDeclName();
4357     notePreviousDefinition(Previous.getRepresentativeDecl(),
4358                            New->getLocation());
4359     return New->setInvalidDecl();
4360   }
4361 
4362   // If the old declaration was found in an inline namespace and the new
4363   // declaration was qualified, update the DeclContext to match.
4364   adjustDeclContextForDeclaratorDecl(New, Old);
4365 
4366   // Ensure the template parameters are compatible.
4367   if (NewTemplate &&
4368       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4369                                       OldTemplate->getTemplateParameters(),
4370                                       /*Complain=*/true, TPL_TemplateMatch))
4371     return New->setInvalidDecl();
4372 
4373   // C++ [class.mem]p1:
4374   //   A member shall not be declared twice in the member-specification [...]
4375   //
4376   // Here, we need only consider static data members.
4377   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4378     Diag(New->getLocation(), diag::err_duplicate_member)
4379       << New->getIdentifier();
4380     Diag(Old->getLocation(), diag::note_previous_declaration);
4381     New->setInvalidDecl();
4382   }
4383 
4384   mergeDeclAttributes(New, Old);
4385   // Warn if an already-declared variable is made a weak_import in a subsequent
4386   // declaration
4387   if (New->hasAttr<WeakImportAttr>() &&
4388       Old->getStorageClass() == SC_None &&
4389       !Old->hasAttr<WeakImportAttr>()) {
4390     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4391     Diag(Old->getLocation(), diag::note_previous_declaration);
4392     // Remove weak_import attribute on new declaration.
4393     New->dropAttr<WeakImportAttr>();
4394   }
4395 
4396   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4397     if (!Old->hasAttr<InternalLinkageAttr>()) {
4398       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4399           << ILA;
4400       Diag(Old->getLocation(), diag::note_previous_declaration);
4401       New->dropAttr<InternalLinkageAttr>();
4402     }
4403 
4404   // Merge the types.
4405   VarDecl *MostRecent = Old->getMostRecentDecl();
4406   if (MostRecent != Old) {
4407     MergeVarDeclTypes(New, MostRecent,
4408                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4409     if (New->isInvalidDecl())
4410       return;
4411   }
4412 
4413   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4414   if (New->isInvalidDecl())
4415     return;
4416 
4417   diag::kind PrevDiag;
4418   SourceLocation OldLocation;
4419   std::tie(PrevDiag, OldLocation) =
4420       getNoteDiagForInvalidRedeclaration(Old, New);
4421 
4422   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4423   if (New->getStorageClass() == SC_Static &&
4424       !New->isStaticDataMember() &&
4425       Old->hasExternalFormalLinkage()) {
4426     if (getLangOpts().MicrosoftExt) {
4427       Diag(New->getLocation(), diag::ext_static_non_static)
4428           << New->getDeclName();
4429       Diag(OldLocation, PrevDiag);
4430     } else {
4431       Diag(New->getLocation(), diag::err_static_non_static)
4432           << New->getDeclName();
4433       Diag(OldLocation, PrevDiag);
4434       return New->setInvalidDecl();
4435     }
4436   }
4437   // C99 6.2.2p4:
4438   //   For an identifier declared with the storage-class specifier
4439   //   extern in a scope in which a prior declaration of that
4440   //   identifier is visible,23) if the prior declaration specifies
4441   //   internal or external linkage, the linkage of the identifier at
4442   //   the later declaration is the same as the linkage specified at
4443   //   the prior declaration. If no prior declaration is visible, or
4444   //   if the prior declaration specifies no linkage, then the
4445   //   identifier has external linkage.
4446   if (New->hasExternalStorage() && Old->hasLinkage())
4447     /* Okay */;
4448   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4449            !New->isStaticDataMember() &&
4450            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4451     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4452     Diag(OldLocation, PrevDiag);
4453     return New->setInvalidDecl();
4454   }
4455 
4456   // Check if extern is followed by non-extern and vice-versa.
4457   if (New->hasExternalStorage() &&
4458       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4459     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4460     Diag(OldLocation, PrevDiag);
4461     return New->setInvalidDecl();
4462   }
4463   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4464       !New->hasExternalStorage()) {
4465     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4466     Diag(OldLocation, PrevDiag);
4467     return New->setInvalidDecl();
4468   }
4469 
4470   if (CheckRedeclarationInModule(New, Old))
4471     return;
4472 
4473   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4474 
4475   // FIXME: The test for external storage here seems wrong? We still
4476   // need to check for mismatches.
4477   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4478       // Don't complain about out-of-line definitions of static members.
4479       !(Old->getLexicalDeclContext()->isRecord() &&
4480         !New->getLexicalDeclContext()->isRecord())) {
4481     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4482     Diag(OldLocation, PrevDiag);
4483     return New->setInvalidDecl();
4484   }
4485 
4486   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4487     if (VarDecl *Def = Old->getDefinition()) {
4488       // C++1z [dcl.fcn.spec]p4:
4489       //   If the definition of a variable appears in a translation unit before
4490       //   its first declaration as inline, the program is ill-formed.
4491       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4492       Diag(Def->getLocation(), diag::note_previous_definition);
4493     }
4494   }
4495 
4496   // If this redeclaration makes the variable inline, we may need to add it to
4497   // UndefinedButUsed.
4498   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4499       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4500     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4501                                            SourceLocation()));
4502 
4503   if (New->getTLSKind() != Old->getTLSKind()) {
4504     if (!Old->getTLSKind()) {
4505       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4506       Diag(OldLocation, PrevDiag);
4507     } else if (!New->getTLSKind()) {
4508       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4509       Diag(OldLocation, PrevDiag);
4510     } else {
4511       // Do not allow redeclaration to change the variable between requiring
4512       // static and dynamic initialization.
4513       // FIXME: GCC allows this, but uses the TLS keyword on the first
4514       // declaration to determine the kind. Do we need to be compatible here?
4515       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4516         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4517       Diag(OldLocation, PrevDiag);
4518     }
4519   }
4520 
4521   // C++ doesn't have tentative definitions, so go right ahead and check here.
4522   if (getLangOpts().CPlusPlus &&
4523       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4524     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4525         Old->getCanonicalDecl()->isConstexpr()) {
4526       // This definition won't be a definition any more once it's been merged.
4527       Diag(New->getLocation(),
4528            diag::warn_deprecated_redundant_constexpr_static_def);
4529     } else if (VarDecl *Def = Old->getDefinition()) {
4530       if (checkVarDeclRedefinition(Def, New))
4531         return;
4532     }
4533   }
4534 
4535   if (haveIncompatibleLanguageLinkages(Old, New)) {
4536     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4537     Diag(OldLocation, PrevDiag);
4538     New->setInvalidDecl();
4539     return;
4540   }
4541 
4542   // Merge "used" flag.
4543   if (Old->getMostRecentDecl()->isUsed(false))
4544     New->setIsUsed();
4545 
4546   // Keep a chain of previous declarations.
4547   New->setPreviousDecl(Old);
4548   if (NewTemplate)
4549     NewTemplate->setPreviousDecl(OldTemplate);
4550 
4551   // Inherit access appropriately.
4552   New->setAccess(Old->getAccess());
4553   if (NewTemplate)
4554     NewTemplate->setAccess(New->getAccess());
4555 
4556   if (Old->isInline())
4557     New->setImplicitlyInline();
4558 }
4559 
4560 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4561   SourceManager &SrcMgr = getSourceManager();
4562   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4563   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4564   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4565   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4566   auto &HSI = PP.getHeaderSearchInfo();
4567   StringRef HdrFilename =
4568       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4569 
4570   auto noteFromModuleOrInclude = [&](Module *Mod,
4571                                      SourceLocation IncLoc) -> bool {
4572     // Redefinition errors with modules are common with non modular mapped
4573     // headers, example: a non-modular header H in module A that also gets
4574     // included directly in a TU. Pointing twice to the same header/definition
4575     // is confusing, try to get better diagnostics when modules is on.
4576     if (IncLoc.isValid()) {
4577       if (Mod) {
4578         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4579             << HdrFilename.str() << Mod->getFullModuleName();
4580         if (!Mod->DefinitionLoc.isInvalid())
4581           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4582               << Mod->getFullModuleName();
4583       } else {
4584         Diag(IncLoc, diag::note_redefinition_include_same_file)
4585             << HdrFilename.str();
4586       }
4587       return true;
4588     }
4589 
4590     return false;
4591   };
4592 
4593   // Is it the same file and same offset? Provide more information on why
4594   // this leads to a redefinition error.
4595   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4596     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4597     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4598     bool EmittedDiag =
4599         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4600     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4601 
4602     // If the header has no guards, emit a note suggesting one.
4603     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4604       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4605 
4606     if (EmittedDiag)
4607       return;
4608   }
4609 
4610   // Redefinition coming from different files or couldn't do better above.
4611   if (Old->getLocation().isValid())
4612     Diag(Old->getLocation(), diag::note_previous_definition);
4613 }
4614 
4615 /// We've just determined that \p Old and \p New both appear to be definitions
4616 /// of the same variable. Either diagnose or fix the problem.
4617 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4618   if (!hasVisibleDefinition(Old) &&
4619       (New->getFormalLinkage() == InternalLinkage ||
4620        New->isInline() ||
4621        New->getDescribedVarTemplate() ||
4622        New->getNumTemplateParameterLists() ||
4623        New->getDeclContext()->isDependentContext())) {
4624     // The previous definition is hidden, and multiple definitions are
4625     // permitted (in separate TUs). Demote this to a declaration.
4626     New->demoteThisDefinitionToDeclaration();
4627 
4628     // Make the canonical definition visible.
4629     if (auto *OldTD = Old->getDescribedVarTemplate())
4630       makeMergedDefinitionVisible(OldTD);
4631     makeMergedDefinitionVisible(Old);
4632     return false;
4633   } else {
4634     Diag(New->getLocation(), diag::err_redefinition) << New;
4635     notePreviousDefinition(Old, New->getLocation());
4636     New->setInvalidDecl();
4637     return true;
4638   }
4639 }
4640 
4641 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4642 /// no declarator (e.g. "struct foo;") is parsed.
4643 Decl *
4644 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4645                                  RecordDecl *&AnonRecord) {
4646   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4647                                     AnonRecord);
4648 }
4649 
4650 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4651 // disambiguate entities defined in different scopes.
4652 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4653 // compatibility.
4654 // We will pick our mangling number depending on which version of MSVC is being
4655 // targeted.
4656 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4657   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4658              ? S->getMSCurManglingNumber()
4659              : S->getMSLastManglingNumber();
4660 }
4661 
4662 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4663   if (!Context.getLangOpts().CPlusPlus)
4664     return;
4665 
4666   if (isa<CXXRecordDecl>(Tag->getParent())) {
4667     // If this tag is the direct child of a class, number it if
4668     // it is anonymous.
4669     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4670       return;
4671     MangleNumberingContext &MCtx =
4672         Context.getManglingNumberContext(Tag->getParent());
4673     Context.setManglingNumber(
4674         Tag, MCtx.getManglingNumber(
4675                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4676     return;
4677   }
4678 
4679   // If this tag isn't a direct child of a class, number it if it is local.
4680   MangleNumberingContext *MCtx;
4681   Decl *ManglingContextDecl;
4682   std::tie(MCtx, ManglingContextDecl) =
4683       getCurrentMangleNumberContext(Tag->getDeclContext());
4684   if (MCtx) {
4685     Context.setManglingNumber(
4686         Tag, MCtx->getManglingNumber(
4687                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4688   }
4689 }
4690 
4691 namespace {
4692 struct NonCLikeKind {
4693   enum {
4694     None,
4695     BaseClass,
4696     DefaultMemberInit,
4697     Lambda,
4698     Friend,
4699     OtherMember,
4700     Invalid,
4701   } Kind = None;
4702   SourceRange Range;
4703 
4704   explicit operator bool() { return Kind != None; }
4705 };
4706 }
4707 
4708 /// Determine whether a class is C-like, according to the rules of C++
4709 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4710 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4711   if (RD->isInvalidDecl())
4712     return {NonCLikeKind::Invalid, {}};
4713 
4714   // C++ [dcl.typedef]p9: [P1766R1]
4715   //   An unnamed class with a typedef name for linkage purposes shall not
4716   //
4717   //    -- have any base classes
4718   if (RD->getNumBases())
4719     return {NonCLikeKind::BaseClass,
4720             SourceRange(RD->bases_begin()->getBeginLoc(),
4721                         RD->bases_end()[-1].getEndLoc())};
4722   bool Invalid = false;
4723   for (Decl *D : RD->decls()) {
4724     // Don't complain about things we already diagnosed.
4725     if (D->isInvalidDecl()) {
4726       Invalid = true;
4727       continue;
4728     }
4729 
4730     //  -- have any [...] default member initializers
4731     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4732       if (FD->hasInClassInitializer()) {
4733         auto *Init = FD->getInClassInitializer();
4734         return {NonCLikeKind::DefaultMemberInit,
4735                 Init ? Init->getSourceRange() : D->getSourceRange()};
4736       }
4737       continue;
4738     }
4739 
4740     // FIXME: We don't allow friend declarations. This violates the wording of
4741     // P1766, but not the intent.
4742     if (isa<FriendDecl>(D))
4743       return {NonCLikeKind::Friend, D->getSourceRange()};
4744 
4745     //  -- declare any members other than non-static data members, member
4746     //     enumerations, or member classes,
4747     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4748         isa<EnumDecl>(D))
4749       continue;
4750     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4751     if (!MemberRD) {
4752       if (D->isImplicit())
4753         continue;
4754       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4755     }
4756 
4757     //  -- contain a lambda-expression,
4758     if (MemberRD->isLambda())
4759       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4760 
4761     //  and all member classes shall also satisfy these requirements
4762     //  (recursively).
4763     if (MemberRD->isThisDeclarationADefinition()) {
4764       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4765         return Kind;
4766     }
4767   }
4768 
4769   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4770 }
4771 
4772 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4773                                         TypedefNameDecl *NewTD) {
4774   if (TagFromDeclSpec->isInvalidDecl())
4775     return;
4776 
4777   // Do nothing if the tag already has a name for linkage purposes.
4778   if (TagFromDeclSpec->hasNameForLinkage())
4779     return;
4780 
4781   // A well-formed anonymous tag must always be a TUK_Definition.
4782   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4783 
4784   // The type must match the tag exactly;  no qualifiers allowed.
4785   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4786                            Context.getTagDeclType(TagFromDeclSpec))) {
4787     if (getLangOpts().CPlusPlus)
4788       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4789     return;
4790   }
4791 
4792   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4793   //   An unnamed class with a typedef name for linkage purposes shall [be
4794   //   C-like].
4795   //
4796   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4797   // shouldn't happen, but there are constructs that the language rule doesn't
4798   // disallow for which we can't reasonably avoid computing linkage early.
4799   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4800   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4801                              : NonCLikeKind();
4802   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4803   if (NonCLike || ChangesLinkage) {
4804     if (NonCLike.Kind == NonCLikeKind::Invalid)
4805       return;
4806 
4807     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4808     if (ChangesLinkage) {
4809       // If the linkage changes, we can't accept this as an extension.
4810       if (NonCLike.Kind == NonCLikeKind::None)
4811         DiagID = diag::err_typedef_changes_linkage;
4812       else
4813         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4814     }
4815 
4816     SourceLocation FixitLoc =
4817         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4818     llvm::SmallString<40> TextToInsert;
4819     TextToInsert += ' ';
4820     TextToInsert += NewTD->getIdentifier()->getName();
4821 
4822     Diag(FixitLoc, DiagID)
4823       << isa<TypeAliasDecl>(NewTD)
4824       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4825     if (NonCLike.Kind != NonCLikeKind::None) {
4826       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4827         << NonCLike.Kind - 1 << NonCLike.Range;
4828     }
4829     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4830       << NewTD << isa<TypeAliasDecl>(NewTD);
4831 
4832     if (ChangesLinkage)
4833       return;
4834   }
4835 
4836   // Otherwise, set this as the anon-decl typedef for the tag.
4837   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4838 }
4839 
4840 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4841   switch (T) {
4842   case DeclSpec::TST_class:
4843     return 0;
4844   case DeclSpec::TST_struct:
4845     return 1;
4846   case DeclSpec::TST_interface:
4847     return 2;
4848   case DeclSpec::TST_union:
4849     return 3;
4850   case DeclSpec::TST_enum:
4851     return 4;
4852   default:
4853     llvm_unreachable("unexpected type specifier");
4854   }
4855 }
4856 
4857 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4858 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4859 /// parameters to cope with template friend declarations.
4860 Decl *
4861 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4862                                  MultiTemplateParamsArg TemplateParams,
4863                                  bool IsExplicitInstantiation,
4864                                  RecordDecl *&AnonRecord) {
4865   Decl *TagD = nullptr;
4866   TagDecl *Tag = nullptr;
4867   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4868       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4869       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4870       DS.getTypeSpecType() == DeclSpec::TST_union ||
4871       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4872     TagD = DS.getRepAsDecl();
4873 
4874     if (!TagD) // We probably had an error
4875       return nullptr;
4876 
4877     // Note that the above type specs guarantee that the
4878     // type rep is a Decl, whereas in many of the others
4879     // it's a Type.
4880     if (isa<TagDecl>(TagD))
4881       Tag = cast<TagDecl>(TagD);
4882     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4883       Tag = CTD->getTemplatedDecl();
4884   }
4885 
4886   if (Tag) {
4887     handleTagNumbering(Tag, S);
4888     Tag->setFreeStanding();
4889     if (Tag->isInvalidDecl())
4890       return Tag;
4891   }
4892 
4893   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4894     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4895     // or incomplete types shall not be restrict-qualified."
4896     if (TypeQuals & DeclSpec::TQ_restrict)
4897       Diag(DS.getRestrictSpecLoc(),
4898            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4899            << DS.getSourceRange();
4900   }
4901 
4902   if (DS.isInlineSpecified())
4903     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4904         << getLangOpts().CPlusPlus17;
4905 
4906   if (DS.hasConstexprSpecifier()) {
4907     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4908     // and definitions of functions and variables.
4909     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4910     // the declaration of a function or function template
4911     if (Tag)
4912       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4913           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4914           << static_cast<int>(DS.getConstexprSpecifier());
4915     else
4916       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4917           << static_cast<int>(DS.getConstexprSpecifier());
4918     // Don't emit warnings after this error.
4919     return TagD;
4920   }
4921 
4922   DiagnoseFunctionSpecifiers(DS);
4923 
4924   if (DS.isFriendSpecified()) {
4925     // If we're dealing with a decl but not a TagDecl, assume that
4926     // whatever routines created it handled the friendship aspect.
4927     if (TagD && !Tag)
4928       return nullptr;
4929     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4930   }
4931 
4932   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4933   bool IsExplicitSpecialization =
4934     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4935   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4936       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4937       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4938     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4939     // nested-name-specifier unless it is an explicit instantiation
4940     // or an explicit specialization.
4941     //
4942     // FIXME: We allow class template partial specializations here too, per the
4943     // obvious intent of DR1819.
4944     //
4945     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4946     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4947         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4948     return nullptr;
4949   }
4950 
4951   // Track whether this decl-specifier declares anything.
4952   bool DeclaresAnything = true;
4953 
4954   // Handle anonymous struct definitions.
4955   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4956     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4957         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4958       if (getLangOpts().CPlusPlus ||
4959           Record->getDeclContext()->isRecord()) {
4960         // If CurContext is a DeclContext that can contain statements,
4961         // RecursiveASTVisitor won't visit the decls that
4962         // BuildAnonymousStructOrUnion() will put into CurContext.
4963         // Also store them here so that they can be part of the
4964         // DeclStmt that gets created in this case.
4965         // FIXME: Also return the IndirectFieldDecls created by
4966         // BuildAnonymousStructOr union, for the same reason?
4967         if (CurContext->isFunctionOrMethod())
4968           AnonRecord = Record;
4969         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4970                                            Context.getPrintingPolicy());
4971       }
4972 
4973       DeclaresAnything = false;
4974     }
4975   }
4976 
4977   // C11 6.7.2.1p2:
4978   //   A struct-declaration that does not declare an anonymous structure or
4979   //   anonymous union shall contain a struct-declarator-list.
4980   //
4981   // This rule also existed in C89 and C99; the grammar for struct-declaration
4982   // did not permit a struct-declaration without a struct-declarator-list.
4983   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4984       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4985     // Check for Microsoft C extension: anonymous struct/union member.
4986     // Handle 2 kinds of anonymous struct/union:
4987     //   struct STRUCT;
4988     //   union UNION;
4989     // and
4990     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4991     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4992     if ((Tag && Tag->getDeclName()) ||
4993         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4994       RecordDecl *Record = nullptr;
4995       if (Tag)
4996         Record = dyn_cast<RecordDecl>(Tag);
4997       else if (const RecordType *RT =
4998                    DS.getRepAsType().get()->getAsStructureType())
4999         Record = RT->getDecl();
5000       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5001         Record = UT->getDecl();
5002 
5003       if (Record && getLangOpts().MicrosoftExt) {
5004         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5005             << Record->isUnion() << DS.getSourceRange();
5006         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5007       }
5008 
5009       DeclaresAnything = false;
5010     }
5011   }
5012 
5013   // Skip all the checks below if we have a type error.
5014   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5015       (TagD && TagD->isInvalidDecl()))
5016     return TagD;
5017 
5018   if (getLangOpts().CPlusPlus &&
5019       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5020     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5021       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5022           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5023         DeclaresAnything = false;
5024 
5025   if (!DS.isMissingDeclaratorOk()) {
5026     // Customize diagnostic for a typedef missing a name.
5027     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5028       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5029           << DS.getSourceRange();
5030     else
5031       DeclaresAnything = false;
5032   }
5033 
5034   if (DS.isModulePrivateSpecified() &&
5035       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5036     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5037       << Tag->getTagKind()
5038       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5039 
5040   ActOnDocumentableDecl(TagD);
5041 
5042   // C 6.7/2:
5043   //   A declaration [...] shall declare at least a declarator [...], a tag,
5044   //   or the members of an enumeration.
5045   // C++ [dcl.dcl]p3:
5046   //   [If there are no declarators], and except for the declaration of an
5047   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5048   //   names into the program, or shall redeclare a name introduced by a
5049   //   previous declaration.
5050   if (!DeclaresAnything) {
5051     // In C, we allow this as a (popular) extension / bug. Don't bother
5052     // producing further diagnostics for redundant qualifiers after this.
5053     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5054                                ? diag::err_no_declarators
5055                                : diag::ext_no_declarators)
5056         << DS.getSourceRange();
5057     return TagD;
5058   }
5059 
5060   // C++ [dcl.stc]p1:
5061   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5062   //   init-declarator-list of the declaration shall not be empty.
5063   // C++ [dcl.fct.spec]p1:
5064   //   If a cv-qualifier appears in a decl-specifier-seq, the
5065   //   init-declarator-list of the declaration shall not be empty.
5066   //
5067   // Spurious qualifiers here appear to be valid in C.
5068   unsigned DiagID = diag::warn_standalone_specifier;
5069   if (getLangOpts().CPlusPlus)
5070     DiagID = diag::ext_standalone_specifier;
5071 
5072   // Note that a linkage-specification sets a storage class, but
5073   // 'extern "C" struct foo;' is actually valid and not theoretically
5074   // useless.
5075   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5076     if (SCS == DeclSpec::SCS_mutable)
5077       // Since mutable is not a viable storage class specifier in C, there is
5078       // no reason to treat it as an extension. Instead, diagnose as an error.
5079       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5080     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5081       Diag(DS.getStorageClassSpecLoc(), DiagID)
5082         << DeclSpec::getSpecifierName(SCS);
5083   }
5084 
5085   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5086     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5087       << DeclSpec::getSpecifierName(TSCS);
5088   if (DS.getTypeQualifiers()) {
5089     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5090       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5091     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5092       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5093     // Restrict is covered above.
5094     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5095       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5096     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5097       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5098   }
5099 
5100   // Warn about ignored type attributes, for example:
5101   // __attribute__((aligned)) struct A;
5102   // Attributes should be placed after tag to apply to type declaration.
5103   if (!DS.getAttributes().empty()) {
5104     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5105     if (TypeSpecType == DeclSpec::TST_class ||
5106         TypeSpecType == DeclSpec::TST_struct ||
5107         TypeSpecType == DeclSpec::TST_interface ||
5108         TypeSpecType == DeclSpec::TST_union ||
5109         TypeSpecType == DeclSpec::TST_enum) {
5110       for (const ParsedAttr &AL : DS.getAttributes())
5111         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5112             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5113     }
5114   }
5115 
5116   return TagD;
5117 }
5118 
5119 /// We are trying to inject an anonymous member into the given scope;
5120 /// check if there's an existing declaration that can't be overloaded.
5121 ///
5122 /// \return true if this is a forbidden redeclaration
5123 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5124                                          Scope *S,
5125                                          DeclContext *Owner,
5126                                          DeclarationName Name,
5127                                          SourceLocation NameLoc,
5128                                          bool IsUnion) {
5129   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5130                  Sema::ForVisibleRedeclaration);
5131   if (!SemaRef.LookupName(R, S)) return false;
5132 
5133   // Pick a representative declaration.
5134   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5135   assert(PrevDecl && "Expected a non-null Decl");
5136 
5137   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5138     return false;
5139 
5140   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5141     << IsUnion << Name;
5142   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5143 
5144   return true;
5145 }
5146 
5147 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5148 /// anonymous struct or union AnonRecord into the owning context Owner
5149 /// and scope S. This routine will be invoked just after we realize
5150 /// that an unnamed union or struct is actually an anonymous union or
5151 /// struct, e.g.,
5152 ///
5153 /// @code
5154 /// union {
5155 ///   int i;
5156 ///   float f;
5157 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5158 ///    // f into the surrounding scope.x
5159 /// @endcode
5160 ///
5161 /// This routine is recursive, injecting the names of nested anonymous
5162 /// structs/unions into the owning context and scope as well.
5163 static bool
5164 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5165                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5166                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5167   bool Invalid = false;
5168 
5169   // Look every FieldDecl and IndirectFieldDecl with a name.
5170   for (auto *D : AnonRecord->decls()) {
5171     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5172         cast<NamedDecl>(D)->getDeclName()) {
5173       ValueDecl *VD = cast<ValueDecl>(D);
5174       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5175                                        VD->getLocation(),
5176                                        AnonRecord->isUnion())) {
5177         // C++ [class.union]p2:
5178         //   The names of the members of an anonymous union shall be
5179         //   distinct from the names of any other entity in the
5180         //   scope in which the anonymous union is declared.
5181         Invalid = true;
5182       } else {
5183         // C++ [class.union]p2:
5184         //   For the purpose of name lookup, after the anonymous union
5185         //   definition, the members of the anonymous union are
5186         //   considered to have been defined in the scope in which the
5187         //   anonymous union is declared.
5188         unsigned OldChainingSize = Chaining.size();
5189         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5190           Chaining.append(IF->chain_begin(), IF->chain_end());
5191         else
5192           Chaining.push_back(VD);
5193 
5194         assert(Chaining.size() >= 2);
5195         NamedDecl **NamedChain =
5196           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5197         for (unsigned i = 0; i < Chaining.size(); i++)
5198           NamedChain[i] = Chaining[i];
5199 
5200         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5201             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5202             VD->getType(), {NamedChain, Chaining.size()});
5203 
5204         for (const auto *Attr : VD->attrs())
5205           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5206 
5207         IndirectField->setAccess(AS);
5208         IndirectField->setImplicit();
5209         SemaRef.PushOnScopeChains(IndirectField, S);
5210 
5211         // That includes picking up the appropriate access specifier.
5212         if (AS != AS_none) IndirectField->setAccess(AS);
5213 
5214         Chaining.resize(OldChainingSize);
5215       }
5216     }
5217   }
5218 
5219   return Invalid;
5220 }
5221 
5222 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5223 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5224 /// illegal input values are mapped to SC_None.
5225 static StorageClass
5226 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5227   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5228   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5229          "Parser allowed 'typedef' as storage class VarDecl.");
5230   switch (StorageClassSpec) {
5231   case DeclSpec::SCS_unspecified:    return SC_None;
5232   case DeclSpec::SCS_extern:
5233     if (DS.isExternInLinkageSpec())
5234       return SC_None;
5235     return SC_Extern;
5236   case DeclSpec::SCS_static:         return SC_Static;
5237   case DeclSpec::SCS_auto:           return SC_Auto;
5238   case DeclSpec::SCS_register:       return SC_Register;
5239   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5240     // Illegal SCSs map to None: error reporting is up to the caller.
5241   case DeclSpec::SCS_mutable:        // Fall through.
5242   case DeclSpec::SCS_typedef:        return SC_None;
5243   }
5244   llvm_unreachable("unknown storage class specifier");
5245 }
5246 
5247 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5248   assert(Record->hasInClassInitializer());
5249 
5250   for (const auto *I : Record->decls()) {
5251     const auto *FD = dyn_cast<FieldDecl>(I);
5252     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5253       FD = IFD->getAnonField();
5254     if (FD && FD->hasInClassInitializer())
5255       return FD->getLocation();
5256   }
5257 
5258   llvm_unreachable("couldn't find in-class initializer");
5259 }
5260 
5261 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5262                                       SourceLocation DefaultInitLoc) {
5263   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5264     return;
5265 
5266   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5267   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5268 }
5269 
5270 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5271                                       CXXRecordDecl *AnonUnion) {
5272   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5273     return;
5274 
5275   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5276 }
5277 
5278 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5279 /// anonymous structure or union. Anonymous unions are a C++ feature
5280 /// (C++ [class.union]) and a C11 feature; anonymous structures
5281 /// are a C11 feature and GNU C++ extension.
5282 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5283                                         AccessSpecifier AS,
5284                                         RecordDecl *Record,
5285                                         const PrintingPolicy &Policy) {
5286   DeclContext *Owner = Record->getDeclContext();
5287 
5288   // Diagnose whether this anonymous struct/union is an extension.
5289   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5290     Diag(Record->getLocation(), diag::ext_anonymous_union);
5291   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5292     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5293   else if (!Record->isUnion() && !getLangOpts().C11)
5294     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5295 
5296   // C and C++ require different kinds of checks for anonymous
5297   // structs/unions.
5298   bool Invalid = false;
5299   if (getLangOpts().CPlusPlus) {
5300     const char *PrevSpec = nullptr;
5301     if (Record->isUnion()) {
5302       // C++ [class.union]p6:
5303       // C++17 [class.union.anon]p2:
5304       //   Anonymous unions declared in a named namespace or in the
5305       //   global namespace shall be declared static.
5306       unsigned DiagID;
5307       DeclContext *OwnerScope = Owner->getRedeclContext();
5308       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5309           (OwnerScope->isTranslationUnit() ||
5310            (OwnerScope->isNamespace() &&
5311             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5312         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5313           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5314 
5315         // Recover by adding 'static'.
5316         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5317                                PrevSpec, DiagID, Policy);
5318       }
5319       // C++ [class.union]p6:
5320       //   A storage class is not allowed in a declaration of an
5321       //   anonymous union in a class scope.
5322       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5323                isa<RecordDecl>(Owner)) {
5324         Diag(DS.getStorageClassSpecLoc(),
5325              diag::err_anonymous_union_with_storage_spec)
5326           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5327 
5328         // Recover by removing the storage specifier.
5329         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5330                                SourceLocation(),
5331                                PrevSpec, DiagID, Context.getPrintingPolicy());
5332       }
5333     }
5334 
5335     // Ignore const/volatile/restrict qualifiers.
5336     if (DS.getTypeQualifiers()) {
5337       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5338         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5339           << Record->isUnion() << "const"
5340           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5341       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5342         Diag(DS.getVolatileSpecLoc(),
5343              diag::ext_anonymous_struct_union_qualified)
5344           << Record->isUnion() << "volatile"
5345           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5346       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5347         Diag(DS.getRestrictSpecLoc(),
5348              diag::ext_anonymous_struct_union_qualified)
5349           << Record->isUnion() << "restrict"
5350           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5351       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5352         Diag(DS.getAtomicSpecLoc(),
5353              diag::ext_anonymous_struct_union_qualified)
5354           << Record->isUnion() << "_Atomic"
5355           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5356       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5357         Diag(DS.getUnalignedSpecLoc(),
5358              diag::ext_anonymous_struct_union_qualified)
5359           << Record->isUnion() << "__unaligned"
5360           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5361 
5362       DS.ClearTypeQualifiers();
5363     }
5364 
5365     // C++ [class.union]p2:
5366     //   The member-specification of an anonymous union shall only
5367     //   define non-static data members. [Note: nested types and
5368     //   functions cannot be declared within an anonymous union. ]
5369     for (auto *Mem : Record->decls()) {
5370       // Ignore invalid declarations; we already diagnosed them.
5371       if (Mem->isInvalidDecl())
5372         continue;
5373 
5374       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5375         // C++ [class.union]p3:
5376         //   An anonymous union shall not have private or protected
5377         //   members (clause 11).
5378         assert(FD->getAccess() != AS_none);
5379         if (FD->getAccess() != AS_public) {
5380           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5381             << Record->isUnion() << (FD->getAccess() == AS_protected);
5382           Invalid = true;
5383         }
5384 
5385         // C++ [class.union]p1
5386         //   An object of a class with a non-trivial constructor, a non-trivial
5387         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5388         //   assignment operator cannot be a member of a union, nor can an
5389         //   array of such objects.
5390         if (CheckNontrivialField(FD))
5391           Invalid = true;
5392       } else if (Mem->isImplicit()) {
5393         // Any implicit members are fine.
5394       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5395         // This is a type that showed up in an
5396         // elaborated-type-specifier inside the anonymous struct or
5397         // union, but which actually declares a type outside of the
5398         // anonymous struct or union. It's okay.
5399       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5400         if (!MemRecord->isAnonymousStructOrUnion() &&
5401             MemRecord->getDeclName()) {
5402           // Visual C++ allows type definition in anonymous struct or union.
5403           if (getLangOpts().MicrosoftExt)
5404             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5405               << Record->isUnion();
5406           else {
5407             // This is a nested type declaration.
5408             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5409               << Record->isUnion();
5410             Invalid = true;
5411           }
5412         } else {
5413           // This is an anonymous type definition within another anonymous type.
5414           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5415           // not part of standard C++.
5416           Diag(MemRecord->getLocation(),
5417                diag::ext_anonymous_record_with_anonymous_type)
5418             << Record->isUnion();
5419         }
5420       } else if (isa<AccessSpecDecl>(Mem)) {
5421         // Any access specifier is fine.
5422       } else if (isa<StaticAssertDecl>(Mem)) {
5423         // In C++1z, static_assert declarations are also fine.
5424       } else {
5425         // We have something that isn't a non-static data
5426         // member. Complain about it.
5427         unsigned DK = diag::err_anonymous_record_bad_member;
5428         if (isa<TypeDecl>(Mem))
5429           DK = diag::err_anonymous_record_with_type;
5430         else if (isa<FunctionDecl>(Mem))
5431           DK = diag::err_anonymous_record_with_function;
5432         else if (isa<VarDecl>(Mem))
5433           DK = diag::err_anonymous_record_with_static;
5434 
5435         // Visual C++ allows type definition in anonymous struct or union.
5436         if (getLangOpts().MicrosoftExt &&
5437             DK == diag::err_anonymous_record_with_type)
5438           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5439             << Record->isUnion();
5440         else {
5441           Diag(Mem->getLocation(), DK) << Record->isUnion();
5442           Invalid = true;
5443         }
5444       }
5445     }
5446 
5447     // C++11 [class.union]p8 (DR1460):
5448     //   At most one variant member of a union may have a
5449     //   brace-or-equal-initializer.
5450     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5451         Owner->isRecord())
5452       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5453                                 cast<CXXRecordDecl>(Record));
5454   }
5455 
5456   if (!Record->isUnion() && !Owner->isRecord()) {
5457     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5458       << getLangOpts().CPlusPlus;
5459     Invalid = true;
5460   }
5461 
5462   // C++ [dcl.dcl]p3:
5463   //   [If there are no declarators], and except for the declaration of an
5464   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5465   //   names into the program
5466   // C++ [class.mem]p2:
5467   //   each such member-declaration shall either declare at least one member
5468   //   name of the class or declare at least one unnamed bit-field
5469   //
5470   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5471   if (getLangOpts().CPlusPlus && Record->field_empty())
5472     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5473 
5474   // Mock up a declarator.
5475   Declarator Dc(DS, DeclaratorContext::Member);
5476   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5477   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5478 
5479   // Create a declaration for this anonymous struct/union.
5480   NamedDecl *Anon = nullptr;
5481   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5482     Anon = FieldDecl::Create(
5483         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5484         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5485         /*BitWidth=*/nullptr, /*Mutable=*/false,
5486         /*InitStyle=*/ICIS_NoInit);
5487     Anon->setAccess(AS);
5488     ProcessDeclAttributes(S, Anon, Dc);
5489 
5490     if (getLangOpts().CPlusPlus)
5491       FieldCollector->Add(cast<FieldDecl>(Anon));
5492   } else {
5493     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5494     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5495     if (SCSpec == DeclSpec::SCS_mutable) {
5496       // mutable can only appear on non-static class members, so it's always
5497       // an error here
5498       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5499       Invalid = true;
5500       SC = SC_None;
5501     }
5502 
5503     assert(DS.getAttributes().empty() && "No attribute expected");
5504     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5505                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5506                            Context.getTypeDeclType(Record), TInfo, SC);
5507 
5508     // Default-initialize the implicit variable. This initialization will be
5509     // trivial in almost all cases, except if a union member has an in-class
5510     // initializer:
5511     //   union { int n = 0; };
5512     ActOnUninitializedDecl(Anon);
5513   }
5514   Anon->setImplicit();
5515 
5516   // Mark this as an anonymous struct/union type.
5517   Record->setAnonymousStructOrUnion(true);
5518 
5519   // Add the anonymous struct/union object to the current
5520   // context. We'll be referencing this object when we refer to one of
5521   // its members.
5522   Owner->addDecl(Anon);
5523 
5524   // Inject the members of the anonymous struct/union into the owning
5525   // context and into the identifier resolver chain for name lookup
5526   // purposes.
5527   SmallVector<NamedDecl*, 2> Chain;
5528   Chain.push_back(Anon);
5529 
5530   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5531     Invalid = true;
5532 
5533   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5534     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5535       MangleNumberingContext *MCtx;
5536       Decl *ManglingContextDecl;
5537       std::tie(MCtx, ManglingContextDecl) =
5538           getCurrentMangleNumberContext(NewVD->getDeclContext());
5539       if (MCtx) {
5540         Context.setManglingNumber(
5541             NewVD, MCtx->getManglingNumber(
5542                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5543         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5544       }
5545     }
5546   }
5547 
5548   if (Invalid)
5549     Anon->setInvalidDecl();
5550 
5551   return Anon;
5552 }
5553 
5554 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5555 /// Microsoft C anonymous structure.
5556 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5557 /// Example:
5558 ///
5559 /// struct A { int a; };
5560 /// struct B { struct A; int b; };
5561 ///
5562 /// void foo() {
5563 ///   B var;
5564 ///   var.a = 3;
5565 /// }
5566 ///
5567 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5568                                            RecordDecl *Record) {
5569   assert(Record && "expected a record!");
5570 
5571   // Mock up a declarator.
5572   Declarator Dc(DS, DeclaratorContext::TypeName);
5573   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5574   assert(TInfo && "couldn't build declarator info for anonymous struct");
5575 
5576   auto *ParentDecl = cast<RecordDecl>(CurContext);
5577   QualType RecTy = Context.getTypeDeclType(Record);
5578 
5579   // Create a declaration for this anonymous struct.
5580   NamedDecl *Anon =
5581       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5582                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5583                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5584                         /*InitStyle=*/ICIS_NoInit);
5585   Anon->setImplicit();
5586 
5587   // Add the anonymous struct object to the current context.
5588   CurContext->addDecl(Anon);
5589 
5590   // Inject the members of the anonymous struct into the current
5591   // context and into the identifier resolver chain for name lookup
5592   // purposes.
5593   SmallVector<NamedDecl*, 2> Chain;
5594   Chain.push_back(Anon);
5595 
5596   RecordDecl *RecordDef = Record->getDefinition();
5597   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5598                                diag::err_field_incomplete_or_sizeless) ||
5599       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5600                                           AS_none, Chain)) {
5601     Anon->setInvalidDecl();
5602     ParentDecl->setInvalidDecl();
5603   }
5604 
5605   return Anon;
5606 }
5607 
5608 /// GetNameForDeclarator - Determine the full declaration name for the
5609 /// given Declarator.
5610 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5611   return GetNameFromUnqualifiedId(D.getName());
5612 }
5613 
5614 /// Retrieves the declaration name from a parsed unqualified-id.
5615 DeclarationNameInfo
5616 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5617   DeclarationNameInfo NameInfo;
5618   NameInfo.setLoc(Name.StartLocation);
5619 
5620   switch (Name.getKind()) {
5621 
5622   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5623   case UnqualifiedIdKind::IK_Identifier:
5624     NameInfo.setName(Name.Identifier);
5625     return NameInfo;
5626 
5627   case UnqualifiedIdKind::IK_DeductionGuideName: {
5628     // C++ [temp.deduct.guide]p3:
5629     //   The simple-template-id shall name a class template specialization.
5630     //   The template-name shall be the same identifier as the template-name
5631     //   of the simple-template-id.
5632     // These together intend to imply that the template-name shall name a
5633     // class template.
5634     // FIXME: template<typename T> struct X {};
5635     //        template<typename T> using Y = X<T>;
5636     //        Y(int) -> Y<int>;
5637     //   satisfies these rules but does not name a class template.
5638     TemplateName TN = Name.TemplateName.get().get();
5639     auto *Template = TN.getAsTemplateDecl();
5640     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5641       Diag(Name.StartLocation,
5642            diag::err_deduction_guide_name_not_class_template)
5643         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5644       if (Template)
5645         Diag(Template->getLocation(), diag::note_template_decl_here);
5646       return DeclarationNameInfo();
5647     }
5648 
5649     NameInfo.setName(
5650         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5651     return NameInfo;
5652   }
5653 
5654   case UnqualifiedIdKind::IK_OperatorFunctionId:
5655     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5656                                            Name.OperatorFunctionId.Operator));
5657     NameInfo.setCXXOperatorNameRange(SourceRange(
5658         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5659     return NameInfo;
5660 
5661   case UnqualifiedIdKind::IK_LiteralOperatorId:
5662     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5663                                                            Name.Identifier));
5664     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5665     return NameInfo;
5666 
5667   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5668     TypeSourceInfo *TInfo;
5669     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5670     if (Ty.isNull())
5671       return DeclarationNameInfo();
5672     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5673                                                Context.getCanonicalType(Ty)));
5674     NameInfo.setNamedTypeInfo(TInfo);
5675     return NameInfo;
5676   }
5677 
5678   case UnqualifiedIdKind::IK_ConstructorName: {
5679     TypeSourceInfo *TInfo;
5680     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5681     if (Ty.isNull())
5682       return DeclarationNameInfo();
5683     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5684                                               Context.getCanonicalType(Ty)));
5685     NameInfo.setNamedTypeInfo(TInfo);
5686     return NameInfo;
5687   }
5688 
5689   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5690     // In well-formed code, we can only have a constructor
5691     // template-id that refers to the current context, so go there
5692     // to find the actual type being constructed.
5693     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5694     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5695       return DeclarationNameInfo();
5696 
5697     // Determine the type of the class being constructed.
5698     QualType CurClassType = Context.getTypeDeclType(CurClass);
5699 
5700     // FIXME: Check two things: that the template-id names the same type as
5701     // CurClassType, and that the template-id does not occur when the name
5702     // was qualified.
5703 
5704     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5705                                     Context.getCanonicalType(CurClassType)));
5706     // FIXME: should we retrieve TypeSourceInfo?
5707     NameInfo.setNamedTypeInfo(nullptr);
5708     return NameInfo;
5709   }
5710 
5711   case UnqualifiedIdKind::IK_DestructorName: {
5712     TypeSourceInfo *TInfo;
5713     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5714     if (Ty.isNull())
5715       return DeclarationNameInfo();
5716     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5717                                               Context.getCanonicalType(Ty)));
5718     NameInfo.setNamedTypeInfo(TInfo);
5719     return NameInfo;
5720   }
5721 
5722   case UnqualifiedIdKind::IK_TemplateId: {
5723     TemplateName TName = Name.TemplateId->Template.get();
5724     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5725     return Context.getNameForTemplate(TName, TNameLoc);
5726   }
5727 
5728   } // switch (Name.getKind())
5729 
5730   llvm_unreachable("Unknown name kind");
5731 }
5732 
5733 static QualType getCoreType(QualType Ty) {
5734   do {
5735     if (Ty->isPointerType() || Ty->isReferenceType())
5736       Ty = Ty->getPointeeType();
5737     else if (Ty->isArrayType())
5738       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5739     else
5740       return Ty.withoutLocalFastQualifiers();
5741   } while (true);
5742 }
5743 
5744 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5745 /// and Definition have "nearly" matching parameters. This heuristic is
5746 /// used to improve diagnostics in the case where an out-of-line function
5747 /// definition doesn't match any declaration within the class or namespace.
5748 /// Also sets Params to the list of indices to the parameters that differ
5749 /// between the declaration and the definition. If hasSimilarParameters
5750 /// returns true and Params is empty, then all of the parameters match.
5751 static bool hasSimilarParameters(ASTContext &Context,
5752                                      FunctionDecl *Declaration,
5753                                      FunctionDecl *Definition,
5754                                      SmallVectorImpl<unsigned> &Params) {
5755   Params.clear();
5756   if (Declaration->param_size() != Definition->param_size())
5757     return false;
5758   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5759     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5760     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5761 
5762     // The parameter types are identical
5763     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5764       continue;
5765 
5766     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5767     QualType DefParamBaseTy = getCoreType(DefParamTy);
5768     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5769     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5770 
5771     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5772         (DeclTyName && DeclTyName == DefTyName))
5773       Params.push_back(Idx);
5774     else  // The two parameters aren't even close
5775       return false;
5776   }
5777 
5778   return true;
5779 }
5780 
5781 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5782 /// declarator needs to be rebuilt in the current instantiation.
5783 /// Any bits of declarator which appear before the name are valid for
5784 /// consideration here.  That's specifically the type in the decl spec
5785 /// and the base type in any member-pointer chunks.
5786 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5787                                                     DeclarationName Name) {
5788   // The types we specifically need to rebuild are:
5789   //   - typenames, typeofs, and decltypes
5790   //   - types which will become injected class names
5791   // Of course, we also need to rebuild any type referencing such a
5792   // type.  It's safest to just say "dependent", but we call out a
5793   // few cases here.
5794 
5795   DeclSpec &DS = D.getMutableDeclSpec();
5796   switch (DS.getTypeSpecType()) {
5797   case DeclSpec::TST_typename:
5798   case DeclSpec::TST_typeofType:
5799   case DeclSpec::TST_underlyingType:
5800   case DeclSpec::TST_atomic: {
5801     // Grab the type from the parser.
5802     TypeSourceInfo *TSI = nullptr;
5803     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5804     if (T.isNull() || !T->isInstantiationDependentType()) break;
5805 
5806     // Make sure there's a type source info.  This isn't really much
5807     // of a waste; most dependent types should have type source info
5808     // attached already.
5809     if (!TSI)
5810       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5811 
5812     // Rebuild the type in the current instantiation.
5813     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5814     if (!TSI) return true;
5815 
5816     // Store the new type back in the decl spec.
5817     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5818     DS.UpdateTypeRep(LocType);
5819     break;
5820   }
5821 
5822   case DeclSpec::TST_decltype:
5823   case DeclSpec::TST_typeofExpr: {
5824     Expr *E = DS.getRepAsExpr();
5825     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5826     if (Result.isInvalid()) return true;
5827     DS.UpdateExprRep(Result.get());
5828     break;
5829   }
5830 
5831   default:
5832     // Nothing to do for these decl specs.
5833     break;
5834   }
5835 
5836   // It doesn't matter what order we do this in.
5837   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5838     DeclaratorChunk &Chunk = D.getTypeObject(I);
5839 
5840     // The only type information in the declarator which can come
5841     // before the declaration name is the base type of a member
5842     // pointer.
5843     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5844       continue;
5845 
5846     // Rebuild the scope specifier in-place.
5847     CXXScopeSpec &SS = Chunk.Mem.Scope();
5848     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5849       return true;
5850   }
5851 
5852   return false;
5853 }
5854 
5855 /// Returns true if the declaration is declared in a system header or from a
5856 /// system macro.
5857 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5858   return SM.isInSystemHeader(D->getLocation()) ||
5859          SM.isInSystemMacro(D->getLocation());
5860 }
5861 
5862 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5863   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5864   // of system decl.
5865   if (D->getPreviousDecl() || D->isImplicit())
5866     return;
5867   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5868   if (Status != ReservedIdentifierStatus::NotReserved &&
5869       !isFromSystemHeader(Context.getSourceManager(), D)) {
5870     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5871         << D << static_cast<int>(Status);
5872   }
5873 }
5874 
5875 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5876   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5877   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5878 
5879   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5880       Dcl && Dcl->getDeclContext()->isFileContext())
5881     Dcl->setTopLevelDeclInObjCContainer();
5882 
5883   return Dcl;
5884 }
5885 
5886 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5887 ///   If T is the name of a class, then each of the following shall have a
5888 ///   name different from T:
5889 ///     - every static data member of class T;
5890 ///     - every member function of class T
5891 ///     - every member of class T that is itself a type;
5892 /// \returns true if the declaration name violates these rules.
5893 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5894                                    DeclarationNameInfo NameInfo) {
5895   DeclarationName Name = NameInfo.getName();
5896 
5897   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5898   while (Record && Record->isAnonymousStructOrUnion())
5899     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5900   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5901     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5902     return true;
5903   }
5904 
5905   return false;
5906 }
5907 
5908 /// Diagnose a declaration whose declarator-id has the given
5909 /// nested-name-specifier.
5910 ///
5911 /// \param SS The nested-name-specifier of the declarator-id.
5912 ///
5913 /// \param DC The declaration context to which the nested-name-specifier
5914 /// resolves.
5915 ///
5916 /// \param Name The name of the entity being declared.
5917 ///
5918 /// \param Loc The location of the name of the entity being declared.
5919 ///
5920 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5921 /// we're declaring an explicit / partial specialization / instantiation.
5922 ///
5923 /// \returns true if we cannot safely recover from this error, false otherwise.
5924 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5925                                         DeclarationName Name,
5926                                         SourceLocation Loc, bool IsTemplateId) {
5927   DeclContext *Cur = CurContext;
5928   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5929     Cur = Cur->getParent();
5930 
5931   // If the user provided a superfluous scope specifier that refers back to the
5932   // class in which the entity is already declared, diagnose and ignore it.
5933   //
5934   // class X {
5935   //   void X::f();
5936   // };
5937   //
5938   // Note, it was once ill-formed to give redundant qualification in all
5939   // contexts, but that rule was removed by DR482.
5940   if (Cur->Equals(DC)) {
5941     if (Cur->isRecord()) {
5942       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5943                                       : diag::err_member_extra_qualification)
5944         << Name << FixItHint::CreateRemoval(SS.getRange());
5945       SS.clear();
5946     } else {
5947       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5948     }
5949     return false;
5950   }
5951 
5952   // Check whether the qualifying scope encloses the scope of the original
5953   // declaration. For a template-id, we perform the checks in
5954   // CheckTemplateSpecializationScope.
5955   if (!Cur->Encloses(DC) && !IsTemplateId) {
5956     if (Cur->isRecord())
5957       Diag(Loc, diag::err_member_qualification)
5958         << Name << SS.getRange();
5959     else if (isa<TranslationUnitDecl>(DC))
5960       Diag(Loc, diag::err_invalid_declarator_global_scope)
5961         << Name << SS.getRange();
5962     else if (isa<FunctionDecl>(Cur))
5963       Diag(Loc, diag::err_invalid_declarator_in_function)
5964         << Name << SS.getRange();
5965     else if (isa<BlockDecl>(Cur))
5966       Diag(Loc, diag::err_invalid_declarator_in_block)
5967         << Name << SS.getRange();
5968     else if (isa<ExportDecl>(Cur)) {
5969       if (!isa<NamespaceDecl>(DC))
5970         Diag(Loc, diag::err_export_non_namespace_scope_name)
5971             << Name << SS.getRange();
5972       else
5973         // The cases that DC is not NamespaceDecl should be handled in
5974         // CheckRedeclarationExported.
5975         return false;
5976     } else
5977       Diag(Loc, diag::err_invalid_declarator_scope)
5978       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5979 
5980     return true;
5981   }
5982 
5983   if (Cur->isRecord()) {
5984     // Cannot qualify members within a class.
5985     Diag(Loc, diag::err_member_qualification)
5986       << Name << SS.getRange();
5987     SS.clear();
5988 
5989     // C++ constructors and destructors with incorrect scopes can break
5990     // our AST invariants by having the wrong underlying types. If
5991     // that's the case, then drop this declaration entirely.
5992     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5993          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5994         !Context.hasSameType(Name.getCXXNameType(),
5995                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5996       return true;
5997 
5998     return false;
5999   }
6000 
6001   // C++11 [dcl.meaning]p1:
6002   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6003   //   not begin with a decltype-specifer"
6004   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6005   while (SpecLoc.getPrefix())
6006     SpecLoc = SpecLoc.getPrefix();
6007   if (isa_and_nonnull<DecltypeType>(
6008           SpecLoc.getNestedNameSpecifier()->getAsType()))
6009     Diag(Loc, diag::err_decltype_in_declarator)
6010       << SpecLoc.getTypeLoc().getSourceRange();
6011 
6012   return false;
6013 }
6014 
6015 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6016                                   MultiTemplateParamsArg TemplateParamLists) {
6017   // TODO: consider using NameInfo for diagnostic.
6018   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6019   DeclarationName Name = NameInfo.getName();
6020 
6021   // All of these full declarators require an identifier.  If it doesn't have
6022   // one, the ParsedFreeStandingDeclSpec action should be used.
6023   if (D.isDecompositionDeclarator()) {
6024     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6025   } else if (!Name) {
6026     if (!D.isInvalidType())  // Reject this if we think it is valid.
6027       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6028           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6029     return nullptr;
6030   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6031     return nullptr;
6032 
6033   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6034   // we find one that is.
6035   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6036          (S->getFlags() & Scope::TemplateParamScope) != 0)
6037     S = S->getParent();
6038 
6039   DeclContext *DC = CurContext;
6040   if (D.getCXXScopeSpec().isInvalid())
6041     D.setInvalidType();
6042   else if (D.getCXXScopeSpec().isSet()) {
6043     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6044                                         UPPC_DeclarationQualifier))
6045       return nullptr;
6046 
6047     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6048     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6049     if (!DC || isa<EnumDecl>(DC)) {
6050       // If we could not compute the declaration context, it's because the
6051       // declaration context is dependent but does not refer to a class,
6052       // class template, or class template partial specialization. Complain
6053       // and return early, to avoid the coming semantic disaster.
6054       Diag(D.getIdentifierLoc(),
6055            diag::err_template_qualified_declarator_no_match)
6056         << D.getCXXScopeSpec().getScopeRep()
6057         << D.getCXXScopeSpec().getRange();
6058       return nullptr;
6059     }
6060     bool IsDependentContext = DC->isDependentContext();
6061 
6062     if (!IsDependentContext &&
6063         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6064       return nullptr;
6065 
6066     // If a class is incomplete, do not parse entities inside it.
6067     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6068       Diag(D.getIdentifierLoc(),
6069            diag::err_member_def_undefined_record)
6070         << Name << DC << D.getCXXScopeSpec().getRange();
6071       return nullptr;
6072     }
6073     if (!D.getDeclSpec().isFriendSpecified()) {
6074       if (diagnoseQualifiedDeclaration(
6075               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6076               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6077         if (DC->isRecord())
6078           return nullptr;
6079 
6080         D.setInvalidType();
6081       }
6082     }
6083 
6084     // Check whether we need to rebuild the type of the given
6085     // declaration in the current instantiation.
6086     if (EnteringContext && IsDependentContext &&
6087         TemplateParamLists.size() != 0) {
6088       ContextRAII SavedContext(*this, DC);
6089       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6090         D.setInvalidType();
6091     }
6092   }
6093 
6094   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6095   QualType R = TInfo->getType();
6096 
6097   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6098                                       UPPC_DeclarationType))
6099     D.setInvalidType();
6100 
6101   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6102                         forRedeclarationInCurContext());
6103 
6104   // See if this is a redefinition of a variable in the same scope.
6105   if (!D.getCXXScopeSpec().isSet()) {
6106     bool IsLinkageLookup = false;
6107     bool CreateBuiltins = false;
6108 
6109     // If the declaration we're planning to build will be a function
6110     // or object with linkage, then look for another declaration with
6111     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6112     //
6113     // If the declaration we're planning to build will be declared with
6114     // external linkage in the translation unit, create any builtin with
6115     // the same name.
6116     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6117       /* Do nothing*/;
6118     else if (CurContext->isFunctionOrMethod() &&
6119              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6120               R->isFunctionType())) {
6121       IsLinkageLookup = true;
6122       CreateBuiltins =
6123           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6124     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6125                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6126       CreateBuiltins = true;
6127 
6128     if (IsLinkageLookup) {
6129       Previous.clear(LookupRedeclarationWithLinkage);
6130       Previous.setRedeclarationKind(ForExternalRedeclaration);
6131     }
6132 
6133     LookupName(Previous, S, CreateBuiltins);
6134   } else { // Something like "int foo::x;"
6135     LookupQualifiedName(Previous, DC);
6136 
6137     // C++ [dcl.meaning]p1:
6138     //   When the declarator-id is qualified, the declaration shall refer to a
6139     //  previously declared member of the class or namespace to which the
6140     //  qualifier refers (or, in the case of a namespace, of an element of the
6141     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6142     //  thereof; [...]
6143     //
6144     // Note that we already checked the context above, and that we do not have
6145     // enough information to make sure that Previous contains the declaration
6146     // we want to match. For example, given:
6147     //
6148     //   class X {
6149     //     void f();
6150     //     void f(float);
6151     //   };
6152     //
6153     //   void X::f(int) { } // ill-formed
6154     //
6155     // In this case, Previous will point to the overload set
6156     // containing the two f's declared in X, but neither of them
6157     // matches.
6158 
6159     // C++ [dcl.meaning]p1:
6160     //   [...] the member shall not merely have been introduced by a
6161     //   using-declaration in the scope of the class or namespace nominated by
6162     //   the nested-name-specifier of the declarator-id.
6163     RemoveUsingDecls(Previous);
6164   }
6165 
6166   if (Previous.isSingleResult() &&
6167       Previous.getFoundDecl()->isTemplateParameter()) {
6168     // Maybe we will complain about the shadowed template parameter.
6169     if (!D.isInvalidType())
6170       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6171                                       Previous.getFoundDecl());
6172 
6173     // Just pretend that we didn't see the previous declaration.
6174     Previous.clear();
6175   }
6176 
6177   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6178     // Forget that the previous declaration is the injected-class-name.
6179     Previous.clear();
6180 
6181   // In C++, the previous declaration we find might be a tag type
6182   // (class or enum). In this case, the new declaration will hide the
6183   // tag type. Note that this applies to functions, function templates, and
6184   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6185   if (Previous.isSingleTagDecl() &&
6186       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6187       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6188     Previous.clear();
6189 
6190   // Check that there are no default arguments other than in the parameters
6191   // of a function declaration (C++ only).
6192   if (getLangOpts().CPlusPlus)
6193     CheckExtraCXXDefaultArguments(D);
6194 
6195   NamedDecl *New;
6196 
6197   bool AddToScope = true;
6198   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6199     if (TemplateParamLists.size()) {
6200       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6201       return nullptr;
6202     }
6203 
6204     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6205   } else if (R->isFunctionType()) {
6206     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6207                                   TemplateParamLists,
6208                                   AddToScope);
6209   } else {
6210     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6211                                   AddToScope);
6212   }
6213 
6214   if (!New)
6215     return nullptr;
6216 
6217   // If this has an identifier and is not a function template specialization,
6218   // add it to the scope stack.
6219   if (New->getDeclName() && AddToScope)
6220     PushOnScopeChains(New, S);
6221 
6222   if (isInOpenMPDeclareTargetContext())
6223     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6224 
6225   return New;
6226 }
6227 
6228 /// Helper method to turn variable array types into constant array
6229 /// types in certain situations which would otherwise be errors (for
6230 /// GCC compatibility).
6231 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6232                                                     ASTContext &Context,
6233                                                     bool &SizeIsNegative,
6234                                                     llvm::APSInt &Oversized) {
6235   // This method tries to turn a variable array into a constant
6236   // array even when the size isn't an ICE.  This is necessary
6237   // for compatibility with code that depends on gcc's buggy
6238   // constant expression folding, like struct {char x[(int)(char*)2];}
6239   SizeIsNegative = false;
6240   Oversized = 0;
6241 
6242   if (T->isDependentType())
6243     return QualType();
6244 
6245   QualifierCollector Qs;
6246   const Type *Ty = Qs.strip(T);
6247 
6248   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6249     QualType Pointee = PTy->getPointeeType();
6250     QualType FixedType =
6251         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6252                                             Oversized);
6253     if (FixedType.isNull()) return FixedType;
6254     FixedType = Context.getPointerType(FixedType);
6255     return Qs.apply(Context, FixedType);
6256   }
6257   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6258     QualType Inner = PTy->getInnerType();
6259     QualType FixedType =
6260         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6261                                             Oversized);
6262     if (FixedType.isNull()) return FixedType;
6263     FixedType = Context.getParenType(FixedType);
6264     return Qs.apply(Context, FixedType);
6265   }
6266 
6267   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6268   if (!VLATy)
6269     return QualType();
6270 
6271   QualType ElemTy = VLATy->getElementType();
6272   if (ElemTy->isVariablyModifiedType()) {
6273     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6274                                                  SizeIsNegative, Oversized);
6275     if (ElemTy.isNull())
6276       return QualType();
6277   }
6278 
6279   Expr::EvalResult Result;
6280   if (!VLATy->getSizeExpr() ||
6281       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6282     return QualType();
6283 
6284   llvm::APSInt Res = Result.Val.getInt();
6285 
6286   // Check whether the array size is negative.
6287   if (Res.isSigned() && Res.isNegative()) {
6288     SizeIsNegative = true;
6289     return QualType();
6290   }
6291 
6292   // Check whether the array is too large to be addressed.
6293   unsigned ActiveSizeBits =
6294       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6295        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6296           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6297           : Res.getActiveBits();
6298   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6299     Oversized = Res;
6300     return QualType();
6301   }
6302 
6303   QualType FoldedArrayType = Context.getConstantArrayType(
6304       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6305   return Qs.apply(Context, FoldedArrayType);
6306 }
6307 
6308 static void
6309 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6310   SrcTL = SrcTL.getUnqualifiedLoc();
6311   DstTL = DstTL.getUnqualifiedLoc();
6312   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6313     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6314     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6315                                       DstPTL.getPointeeLoc());
6316     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6317     return;
6318   }
6319   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6320     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6321     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6322                                       DstPTL.getInnerLoc());
6323     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6324     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6325     return;
6326   }
6327   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6328   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6329   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6330   TypeLoc DstElemTL = DstATL.getElementLoc();
6331   if (VariableArrayTypeLoc SrcElemATL =
6332           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6333     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6334     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6335   } else {
6336     DstElemTL.initializeFullCopy(SrcElemTL);
6337   }
6338   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6339   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6340   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6341 }
6342 
6343 /// Helper method to turn variable array types into constant array
6344 /// types in certain situations which would otherwise be errors (for
6345 /// GCC compatibility).
6346 static TypeSourceInfo*
6347 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6348                                               ASTContext &Context,
6349                                               bool &SizeIsNegative,
6350                                               llvm::APSInt &Oversized) {
6351   QualType FixedTy
6352     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6353                                           SizeIsNegative, Oversized);
6354   if (FixedTy.isNull())
6355     return nullptr;
6356   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6357   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6358                                     FixedTInfo->getTypeLoc());
6359   return FixedTInfo;
6360 }
6361 
6362 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6363 /// true if we were successful.
6364 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6365                                            QualType &T, SourceLocation Loc,
6366                                            unsigned FailedFoldDiagID) {
6367   bool SizeIsNegative;
6368   llvm::APSInt Oversized;
6369   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6370       TInfo, Context, SizeIsNegative, Oversized);
6371   if (FixedTInfo) {
6372     Diag(Loc, diag::ext_vla_folded_to_constant);
6373     TInfo = FixedTInfo;
6374     T = FixedTInfo->getType();
6375     return true;
6376   }
6377 
6378   if (SizeIsNegative)
6379     Diag(Loc, diag::err_typecheck_negative_array_size);
6380   else if (Oversized.getBoolValue())
6381     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6382   else if (FailedFoldDiagID)
6383     Diag(Loc, FailedFoldDiagID);
6384   return false;
6385 }
6386 
6387 /// Register the given locally-scoped extern "C" declaration so
6388 /// that it can be found later for redeclarations. We include any extern "C"
6389 /// declaration that is not visible in the translation unit here, not just
6390 /// function-scope declarations.
6391 void
6392 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6393   if (!getLangOpts().CPlusPlus &&
6394       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6395     // Don't need to track declarations in the TU in C.
6396     return;
6397 
6398   // Note that we have a locally-scoped external with this name.
6399   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6400 }
6401 
6402 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6403   // FIXME: We can have multiple results via __attribute__((overloadable)).
6404   auto Result = Context.getExternCContextDecl()->lookup(Name);
6405   return Result.empty() ? nullptr : *Result.begin();
6406 }
6407 
6408 /// Diagnose function specifiers on a declaration of an identifier that
6409 /// does not identify a function.
6410 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6411   // FIXME: We should probably indicate the identifier in question to avoid
6412   // confusion for constructs like "virtual int a(), b;"
6413   if (DS.isVirtualSpecified())
6414     Diag(DS.getVirtualSpecLoc(),
6415          diag::err_virtual_non_function);
6416 
6417   if (DS.hasExplicitSpecifier())
6418     Diag(DS.getExplicitSpecLoc(),
6419          diag::err_explicit_non_function);
6420 
6421   if (DS.isNoreturnSpecified())
6422     Diag(DS.getNoreturnSpecLoc(),
6423          diag::err_noreturn_non_function);
6424 }
6425 
6426 NamedDecl*
6427 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6428                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6429   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6430   if (D.getCXXScopeSpec().isSet()) {
6431     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6432       << D.getCXXScopeSpec().getRange();
6433     D.setInvalidType();
6434     // Pretend we didn't see the scope specifier.
6435     DC = CurContext;
6436     Previous.clear();
6437   }
6438 
6439   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6440 
6441   if (D.getDeclSpec().isInlineSpecified())
6442     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6443         << getLangOpts().CPlusPlus17;
6444   if (D.getDeclSpec().hasConstexprSpecifier())
6445     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6446         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6447 
6448   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6449     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6450       Diag(D.getName().StartLocation,
6451            diag::err_deduction_guide_invalid_specifier)
6452           << "typedef";
6453     else
6454       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6455           << D.getName().getSourceRange();
6456     return nullptr;
6457   }
6458 
6459   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6460   if (!NewTD) return nullptr;
6461 
6462   // Handle attributes prior to checking for duplicates in MergeVarDecl
6463   ProcessDeclAttributes(S, NewTD, D);
6464 
6465   CheckTypedefForVariablyModifiedType(S, NewTD);
6466 
6467   bool Redeclaration = D.isRedeclaration();
6468   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6469   D.setRedeclaration(Redeclaration);
6470   return ND;
6471 }
6472 
6473 void
6474 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6475   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6476   // then it shall have block scope.
6477   // Note that variably modified types must be fixed before merging the decl so
6478   // that redeclarations will match.
6479   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6480   QualType T = TInfo->getType();
6481   if (T->isVariablyModifiedType()) {
6482     setFunctionHasBranchProtectedScope();
6483 
6484     if (S->getFnParent() == nullptr) {
6485       bool SizeIsNegative;
6486       llvm::APSInt Oversized;
6487       TypeSourceInfo *FixedTInfo =
6488         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6489                                                       SizeIsNegative,
6490                                                       Oversized);
6491       if (FixedTInfo) {
6492         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6493         NewTD->setTypeSourceInfo(FixedTInfo);
6494       } else {
6495         if (SizeIsNegative)
6496           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6497         else if (T->isVariableArrayType())
6498           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6499         else if (Oversized.getBoolValue())
6500           Diag(NewTD->getLocation(), diag::err_array_too_large)
6501             << toString(Oversized, 10);
6502         else
6503           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6504         NewTD->setInvalidDecl();
6505       }
6506     }
6507   }
6508 }
6509 
6510 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6511 /// declares a typedef-name, either using the 'typedef' type specifier or via
6512 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6513 NamedDecl*
6514 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6515                            LookupResult &Previous, bool &Redeclaration) {
6516 
6517   // Find the shadowed declaration before filtering for scope.
6518   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6519 
6520   // Merge the decl with the existing one if appropriate. If the decl is
6521   // in an outer scope, it isn't the same thing.
6522   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6523                        /*AllowInlineNamespace*/false);
6524   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6525   if (!Previous.empty()) {
6526     Redeclaration = true;
6527     MergeTypedefNameDecl(S, NewTD, Previous);
6528   } else {
6529     inferGslPointerAttribute(NewTD);
6530   }
6531 
6532   if (ShadowedDecl && !Redeclaration)
6533     CheckShadow(NewTD, ShadowedDecl, Previous);
6534 
6535   // If this is the C FILE type, notify the AST context.
6536   if (IdentifierInfo *II = NewTD->getIdentifier())
6537     if (!NewTD->isInvalidDecl() &&
6538         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6539       if (II->isStr("FILE"))
6540         Context.setFILEDecl(NewTD);
6541       else if (II->isStr("jmp_buf"))
6542         Context.setjmp_bufDecl(NewTD);
6543       else if (II->isStr("sigjmp_buf"))
6544         Context.setsigjmp_bufDecl(NewTD);
6545       else if (II->isStr("ucontext_t"))
6546         Context.setucontext_tDecl(NewTD);
6547     }
6548 
6549   return NewTD;
6550 }
6551 
6552 /// Determines whether the given declaration is an out-of-scope
6553 /// previous declaration.
6554 ///
6555 /// This routine should be invoked when name lookup has found a
6556 /// previous declaration (PrevDecl) that is not in the scope where a
6557 /// new declaration by the same name is being introduced. If the new
6558 /// declaration occurs in a local scope, previous declarations with
6559 /// linkage may still be considered previous declarations (C99
6560 /// 6.2.2p4-5, C++ [basic.link]p6).
6561 ///
6562 /// \param PrevDecl the previous declaration found by name
6563 /// lookup
6564 ///
6565 /// \param DC the context in which the new declaration is being
6566 /// declared.
6567 ///
6568 /// \returns true if PrevDecl is an out-of-scope previous declaration
6569 /// for a new delcaration with the same name.
6570 static bool
6571 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6572                                 ASTContext &Context) {
6573   if (!PrevDecl)
6574     return false;
6575 
6576   if (!PrevDecl->hasLinkage())
6577     return false;
6578 
6579   if (Context.getLangOpts().CPlusPlus) {
6580     // C++ [basic.link]p6:
6581     //   If there is a visible declaration of an entity with linkage
6582     //   having the same name and type, ignoring entities declared
6583     //   outside the innermost enclosing namespace scope, the block
6584     //   scope declaration declares that same entity and receives the
6585     //   linkage of the previous declaration.
6586     DeclContext *OuterContext = DC->getRedeclContext();
6587     if (!OuterContext->isFunctionOrMethod())
6588       // This rule only applies to block-scope declarations.
6589       return false;
6590 
6591     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6592     if (PrevOuterContext->isRecord())
6593       // We found a member function: ignore it.
6594       return false;
6595 
6596     // Find the innermost enclosing namespace for the new and
6597     // previous declarations.
6598     OuterContext = OuterContext->getEnclosingNamespaceContext();
6599     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6600 
6601     // The previous declaration is in a different namespace, so it
6602     // isn't the same function.
6603     if (!OuterContext->Equals(PrevOuterContext))
6604       return false;
6605   }
6606 
6607   return true;
6608 }
6609 
6610 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6611   CXXScopeSpec &SS = D.getCXXScopeSpec();
6612   if (!SS.isSet()) return;
6613   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6614 }
6615 
6616 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6617   QualType type = decl->getType();
6618   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6619   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6620     // Various kinds of declaration aren't allowed to be __autoreleasing.
6621     unsigned kind = -1U;
6622     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6623       if (var->hasAttr<BlocksAttr>())
6624         kind = 0; // __block
6625       else if (!var->hasLocalStorage())
6626         kind = 1; // global
6627     } else if (isa<ObjCIvarDecl>(decl)) {
6628       kind = 3; // ivar
6629     } else if (isa<FieldDecl>(decl)) {
6630       kind = 2; // field
6631     }
6632 
6633     if (kind != -1U) {
6634       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6635         << kind;
6636     }
6637   } else if (lifetime == Qualifiers::OCL_None) {
6638     // Try to infer lifetime.
6639     if (!type->isObjCLifetimeType())
6640       return false;
6641 
6642     lifetime = type->getObjCARCImplicitLifetime();
6643     type = Context.getLifetimeQualifiedType(type, lifetime);
6644     decl->setType(type);
6645   }
6646 
6647   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6648     // Thread-local variables cannot have lifetime.
6649     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6650         var->getTLSKind()) {
6651       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6652         << var->getType();
6653       return true;
6654     }
6655   }
6656 
6657   return false;
6658 }
6659 
6660 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6661   if (Decl->getType().hasAddressSpace())
6662     return;
6663   if (Decl->getType()->isDependentType())
6664     return;
6665   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6666     QualType Type = Var->getType();
6667     if (Type->isSamplerT() || Type->isVoidType())
6668       return;
6669     LangAS ImplAS = LangAS::opencl_private;
6670     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6671     // __opencl_c_program_scope_global_variables feature, the address space
6672     // for a variable at program scope or a static or extern variable inside
6673     // a function are inferred to be __global.
6674     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6675         Var->hasGlobalStorage())
6676       ImplAS = LangAS::opencl_global;
6677     // If the original type from a decayed type is an array type and that array
6678     // type has no address space yet, deduce it now.
6679     if (auto DT = dyn_cast<DecayedType>(Type)) {
6680       auto OrigTy = DT->getOriginalType();
6681       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6682         // Add the address space to the original array type and then propagate
6683         // that to the element type through `getAsArrayType`.
6684         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6685         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6686         // Re-generate the decayed type.
6687         Type = Context.getDecayedType(OrigTy);
6688       }
6689     }
6690     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6691     // Apply any qualifiers (including address space) from the array type to
6692     // the element type. This implements C99 6.7.3p8: "If the specification of
6693     // an array type includes any type qualifiers, the element type is so
6694     // qualified, not the array type."
6695     if (Type->isArrayType())
6696       Type = QualType(Context.getAsArrayType(Type), 0);
6697     Decl->setType(Type);
6698   }
6699 }
6700 
6701 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6702   // Ensure that an auto decl is deduced otherwise the checks below might cache
6703   // the wrong linkage.
6704   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6705 
6706   // 'weak' only applies to declarations with external linkage.
6707   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6708     if (!ND.isExternallyVisible()) {
6709       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6710       ND.dropAttr<WeakAttr>();
6711     }
6712   }
6713   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6714     if (ND.isExternallyVisible()) {
6715       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6716       ND.dropAttr<WeakRefAttr>();
6717       ND.dropAttr<AliasAttr>();
6718     }
6719   }
6720 
6721   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6722     if (VD->hasInit()) {
6723       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6724         assert(VD->isThisDeclarationADefinition() &&
6725                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6726         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6727         VD->dropAttr<AliasAttr>();
6728       }
6729     }
6730   }
6731 
6732   // 'selectany' only applies to externally visible variable declarations.
6733   // It does not apply to functions.
6734   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6735     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6736       S.Diag(Attr->getLocation(),
6737              diag::err_attribute_selectany_non_extern_data);
6738       ND.dropAttr<SelectAnyAttr>();
6739     }
6740   }
6741 
6742   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6743     auto *VD = dyn_cast<VarDecl>(&ND);
6744     bool IsAnonymousNS = false;
6745     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6746     if (VD) {
6747       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6748       while (NS && !IsAnonymousNS) {
6749         IsAnonymousNS = NS->isAnonymousNamespace();
6750         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6751       }
6752     }
6753     // dll attributes require external linkage. Static locals may have external
6754     // linkage but still cannot be explicitly imported or exported.
6755     // In Microsoft mode, a variable defined in anonymous namespace must have
6756     // external linkage in order to be exported.
6757     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6758     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6759         (!AnonNSInMicrosoftMode &&
6760          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6761       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6762         << &ND << Attr;
6763       ND.setInvalidDecl();
6764     }
6765   }
6766 
6767   // Check the attributes on the function type, if any.
6768   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6769     // Don't declare this variable in the second operand of the for-statement;
6770     // GCC miscompiles that by ending its lifetime before evaluating the
6771     // third operand. See gcc.gnu.org/PR86769.
6772     AttributedTypeLoc ATL;
6773     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6774          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6775          TL = ATL.getModifiedLoc()) {
6776       // The [[lifetimebound]] attribute can be applied to the implicit object
6777       // parameter of a non-static member function (other than a ctor or dtor)
6778       // by applying it to the function type.
6779       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6780         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6781         if (!MD || MD->isStatic()) {
6782           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6783               << !MD << A->getRange();
6784         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6785           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6786               << isa<CXXDestructorDecl>(MD) << A->getRange();
6787         }
6788       }
6789     }
6790   }
6791 }
6792 
6793 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6794                                            NamedDecl *NewDecl,
6795                                            bool IsSpecialization,
6796                                            bool IsDefinition) {
6797   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6798     return;
6799 
6800   bool IsTemplate = false;
6801   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6802     OldDecl = OldTD->getTemplatedDecl();
6803     IsTemplate = true;
6804     if (!IsSpecialization)
6805       IsDefinition = false;
6806   }
6807   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6808     NewDecl = NewTD->getTemplatedDecl();
6809     IsTemplate = true;
6810   }
6811 
6812   if (!OldDecl || !NewDecl)
6813     return;
6814 
6815   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6816   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6817   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6818   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6819 
6820   // dllimport and dllexport are inheritable attributes so we have to exclude
6821   // inherited attribute instances.
6822   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6823                     (NewExportAttr && !NewExportAttr->isInherited());
6824 
6825   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6826   // the only exception being explicit specializations.
6827   // Implicitly generated declarations are also excluded for now because there
6828   // is no other way to switch these to use dllimport or dllexport.
6829   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6830 
6831   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6832     // Allow with a warning for free functions and global variables.
6833     bool JustWarn = false;
6834     if (!OldDecl->isCXXClassMember()) {
6835       auto *VD = dyn_cast<VarDecl>(OldDecl);
6836       if (VD && !VD->getDescribedVarTemplate())
6837         JustWarn = true;
6838       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6839       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6840         JustWarn = true;
6841     }
6842 
6843     // We cannot change a declaration that's been used because IR has already
6844     // been emitted. Dllimported functions will still work though (modulo
6845     // address equality) as they can use the thunk.
6846     if (OldDecl->isUsed())
6847       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6848         JustWarn = false;
6849 
6850     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6851                                : diag::err_attribute_dll_redeclaration;
6852     S.Diag(NewDecl->getLocation(), DiagID)
6853         << NewDecl
6854         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6855     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6856     if (!JustWarn) {
6857       NewDecl->setInvalidDecl();
6858       return;
6859     }
6860   }
6861 
6862   // A redeclaration is not allowed to drop a dllimport attribute, the only
6863   // exceptions being inline function definitions (except for function
6864   // templates), local extern declarations, qualified friend declarations or
6865   // special MSVC extension: in the last case, the declaration is treated as if
6866   // it were marked dllexport.
6867   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6868   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6869   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6870     // Ignore static data because out-of-line definitions are diagnosed
6871     // separately.
6872     IsStaticDataMember = VD->isStaticDataMember();
6873     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6874                    VarDecl::DeclarationOnly;
6875   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6876     IsInline = FD->isInlined();
6877     IsQualifiedFriend = FD->getQualifier() &&
6878                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6879   }
6880 
6881   if (OldImportAttr && !HasNewAttr &&
6882       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6883       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6884     if (IsMicrosoftABI && IsDefinition) {
6885       S.Diag(NewDecl->getLocation(),
6886              diag::warn_redeclaration_without_import_attribute)
6887           << NewDecl;
6888       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6889       NewDecl->dropAttr<DLLImportAttr>();
6890       NewDecl->addAttr(
6891           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6892     } else {
6893       S.Diag(NewDecl->getLocation(),
6894              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6895           << NewDecl << OldImportAttr;
6896       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6897       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6898       OldDecl->dropAttr<DLLImportAttr>();
6899       NewDecl->dropAttr<DLLImportAttr>();
6900     }
6901   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6902     // In MinGW, seeing a function declared inline drops the dllimport
6903     // attribute.
6904     OldDecl->dropAttr<DLLImportAttr>();
6905     NewDecl->dropAttr<DLLImportAttr>();
6906     S.Diag(NewDecl->getLocation(),
6907            diag::warn_dllimport_dropped_from_inline_function)
6908         << NewDecl << OldImportAttr;
6909   }
6910 
6911   // A specialization of a class template member function is processed here
6912   // since it's a redeclaration. If the parent class is dllexport, the
6913   // specialization inherits that attribute. This doesn't happen automatically
6914   // since the parent class isn't instantiated until later.
6915   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6916     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6917         !NewImportAttr && !NewExportAttr) {
6918       if (const DLLExportAttr *ParentExportAttr =
6919               MD->getParent()->getAttr<DLLExportAttr>()) {
6920         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6921         NewAttr->setInherited(true);
6922         NewDecl->addAttr(NewAttr);
6923       }
6924     }
6925   }
6926 }
6927 
6928 /// Given that we are within the definition of the given function,
6929 /// will that definition behave like C99's 'inline', where the
6930 /// definition is discarded except for optimization purposes?
6931 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6932   // Try to avoid calling GetGVALinkageForFunction.
6933 
6934   // All cases of this require the 'inline' keyword.
6935   if (!FD->isInlined()) return false;
6936 
6937   // This is only possible in C++ with the gnu_inline attribute.
6938   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6939     return false;
6940 
6941   // Okay, go ahead and call the relatively-more-expensive function.
6942   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6943 }
6944 
6945 /// Determine whether a variable is extern "C" prior to attaching
6946 /// an initializer. We can't just call isExternC() here, because that
6947 /// will also compute and cache whether the declaration is externally
6948 /// visible, which might change when we attach the initializer.
6949 ///
6950 /// This can only be used if the declaration is known to not be a
6951 /// redeclaration of an internal linkage declaration.
6952 ///
6953 /// For instance:
6954 ///
6955 ///   auto x = []{};
6956 ///
6957 /// Attaching the initializer here makes this declaration not externally
6958 /// visible, because its type has internal linkage.
6959 ///
6960 /// FIXME: This is a hack.
6961 template<typename T>
6962 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6963   if (S.getLangOpts().CPlusPlus) {
6964     // In C++, the overloadable attribute negates the effects of extern "C".
6965     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6966       return false;
6967 
6968     // So do CUDA's host/device attributes.
6969     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6970                                  D->template hasAttr<CUDAHostAttr>()))
6971       return false;
6972   }
6973   return D->isExternC();
6974 }
6975 
6976 static bool shouldConsiderLinkage(const VarDecl *VD) {
6977   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6978   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6979       isa<OMPDeclareMapperDecl>(DC))
6980     return VD->hasExternalStorage();
6981   if (DC->isFileContext())
6982     return true;
6983   if (DC->isRecord())
6984     return false;
6985   if (isa<RequiresExprBodyDecl>(DC))
6986     return false;
6987   llvm_unreachable("Unexpected context");
6988 }
6989 
6990 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6991   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6992   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6993       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6994     return true;
6995   if (DC->isRecord())
6996     return false;
6997   llvm_unreachable("Unexpected context");
6998 }
6999 
7000 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7001                           ParsedAttr::Kind Kind) {
7002   // Check decl attributes on the DeclSpec.
7003   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7004     return true;
7005 
7006   // Walk the declarator structure, checking decl attributes that were in a type
7007   // position to the decl itself.
7008   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7009     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7010       return true;
7011   }
7012 
7013   // Finally, check attributes on the decl itself.
7014   return PD.getAttributes().hasAttribute(Kind);
7015 }
7016 
7017 /// Adjust the \c DeclContext for a function or variable that might be a
7018 /// function-local external declaration.
7019 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7020   if (!DC->isFunctionOrMethod())
7021     return false;
7022 
7023   // If this is a local extern function or variable declared within a function
7024   // template, don't add it into the enclosing namespace scope until it is
7025   // instantiated; it might have a dependent type right now.
7026   if (DC->isDependentContext())
7027     return true;
7028 
7029   // C++11 [basic.link]p7:
7030   //   When a block scope declaration of an entity with linkage is not found to
7031   //   refer to some other declaration, then that entity is a member of the
7032   //   innermost enclosing namespace.
7033   //
7034   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7035   // semantically-enclosing namespace, not a lexically-enclosing one.
7036   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7037     DC = DC->getParent();
7038   return true;
7039 }
7040 
7041 /// Returns true if given declaration has external C language linkage.
7042 static bool isDeclExternC(const Decl *D) {
7043   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7044     return FD->isExternC();
7045   if (const auto *VD = dyn_cast<VarDecl>(D))
7046     return VD->isExternC();
7047 
7048   llvm_unreachable("Unknown type of decl!");
7049 }
7050 
7051 /// Returns true if there hasn't been any invalid type diagnosed.
7052 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7053   DeclContext *DC = NewVD->getDeclContext();
7054   QualType R = NewVD->getType();
7055 
7056   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7057   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7058   // argument.
7059   if (R->isImageType() || R->isPipeType()) {
7060     Se.Diag(NewVD->getLocation(),
7061             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7062         << R;
7063     NewVD->setInvalidDecl();
7064     return false;
7065   }
7066 
7067   // OpenCL v1.2 s6.9.r:
7068   // The event type cannot be used to declare a program scope variable.
7069   // OpenCL v2.0 s6.9.q:
7070   // The clk_event_t and reserve_id_t types cannot be declared in program
7071   // scope.
7072   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7073     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7074       Se.Diag(NewVD->getLocation(),
7075               diag::err_invalid_type_for_program_scope_var)
7076           << R;
7077       NewVD->setInvalidDecl();
7078       return false;
7079     }
7080   }
7081 
7082   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7083   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7084                                                Se.getLangOpts())) {
7085     QualType NR = R.getCanonicalType();
7086     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7087            NR->isReferenceType()) {
7088       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7089           NR->isFunctionReferenceType()) {
7090         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7091             << NR->isReferenceType();
7092         NewVD->setInvalidDecl();
7093         return false;
7094       }
7095       NR = NR->getPointeeType();
7096     }
7097   }
7098 
7099   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7100                                                Se.getLangOpts())) {
7101     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7102     // half array type (unless the cl_khr_fp16 extension is enabled).
7103     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7104       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7105       NewVD->setInvalidDecl();
7106       return false;
7107     }
7108   }
7109 
7110   // OpenCL v1.2 s6.9.r:
7111   // The event type cannot be used with the __local, __constant and __global
7112   // address space qualifiers.
7113   if (R->isEventT()) {
7114     if (R.getAddressSpace() != LangAS::opencl_private) {
7115       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7116       NewVD->setInvalidDecl();
7117       return false;
7118     }
7119   }
7120 
7121   if (R->isSamplerT()) {
7122     // OpenCL v1.2 s6.9.b p4:
7123     // The sampler type cannot be used with the __local and __global address
7124     // space qualifiers.
7125     if (R.getAddressSpace() == LangAS::opencl_local ||
7126         R.getAddressSpace() == LangAS::opencl_global) {
7127       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7128       NewVD->setInvalidDecl();
7129     }
7130 
7131     // OpenCL v1.2 s6.12.14.1:
7132     // A global sampler must be declared with either the constant address
7133     // space qualifier or with the const qualifier.
7134     if (DC->isTranslationUnit() &&
7135         !(R.getAddressSpace() == LangAS::opencl_constant ||
7136           R.isConstQualified())) {
7137       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7138       NewVD->setInvalidDecl();
7139     }
7140     if (NewVD->isInvalidDecl())
7141       return false;
7142   }
7143 
7144   return true;
7145 }
7146 
7147 template <typename AttrTy>
7148 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7149   const TypedefNameDecl *TND = TT->getDecl();
7150   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7151     AttrTy *Clone = Attribute->clone(S.Context);
7152     Clone->setInherited(true);
7153     D->addAttr(Clone);
7154   }
7155 }
7156 
7157 NamedDecl *Sema::ActOnVariableDeclarator(
7158     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7159     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7160     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7161   QualType R = TInfo->getType();
7162   DeclarationName Name = GetNameForDeclarator(D).getName();
7163 
7164   IdentifierInfo *II = Name.getAsIdentifierInfo();
7165 
7166   if (D.isDecompositionDeclarator()) {
7167     // Take the name of the first declarator as our name for diagnostic
7168     // purposes.
7169     auto &Decomp = D.getDecompositionDeclarator();
7170     if (!Decomp.bindings().empty()) {
7171       II = Decomp.bindings()[0].Name;
7172       Name = II;
7173     }
7174   } else if (!II) {
7175     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7176     return nullptr;
7177   }
7178 
7179 
7180   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7181   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7182 
7183   // dllimport globals without explicit storage class are treated as extern. We
7184   // have to change the storage class this early to get the right DeclContext.
7185   if (SC == SC_None && !DC->isRecord() &&
7186       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7187       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7188     SC = SC_Extern;
7189 
7190   DeclContext *OriginalDC = DC;
7191   bool IsLocalExternDecl = SC == SC_Extern &&
7192                            adjustContextForLocalExternDecl(DC);
7193 
7194   if (SCSpec == DeclSpec::SCS_mutable) {
7195     // mutable can only appear on non-static class members, so it's always
7196     // an error here
7197     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7198     D.setInvalidType();
7199     SC = SC_None;
7200   }
7201 
7202   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7203       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7204                               D.getDeclSpec().getStorageClassSpecLoc())) {
7205     // In C++11, the 'register' storage class specifier is deprecated.
7206     // Suppress the warning in system macros, it's used in macros in some
7207     // popular C system headers, such as in glibc's htonl() macro.
7208     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7209          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7210                                    : diag::warn_deprecated_register)
7211       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7212   }
7213 
7214   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7215 
7216   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7217     // C99 6.9p2: The storage-class specifiers auto and register shall not
7218     // appear in the declaration specifiers in an external declaration.
7219     // Global Register+Asm is a GNU extension we support.
7220     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7221       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7222       D.setInvalidType();
7223     }
7224   }
7225 
7226   // If this variable has a VLA type and an initializer, try to
7227   // fold to a constant-sized type. This is otherwise invalid.
7228   if (D.hasInitializer() && R->isVariableArrayType())
7229     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7230                                     /*DiagID=*/0);
7231 
7232   bool IsMemberSpecialization = false;
7233   bool IsVariableTemplateSpecialization = false;
7234   bool IsPartialSpecialization = false;
7235   bool IsVariableTemplate = false;
7236   VarDecl *NewVD = nullptr;
7237   VarTemplateDecl *NewTemplate = nullptr;
7238   TemplateParameterList *TemplateParams = nullptr;
7239   if (!getLangOpts().CPlusPlus) {
7240     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7241                             II, R, TInfo, SC);
7242 
7243     if (R->getContainedDeducedType())
7244       ParsingInitForAutoVars.insert(NewVD);
7245 
7246     if (D.isInvalidType())
7247       NewVD->setInvalidDecl();
7248 
7249     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7250         NewVD->hasLocalStorage())
7251       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7252                             NTCUC_AutoVar, NTCUK_Destruct);
7253   } else {
7254     bool Invalid = false;
7255 
7256     if (DC->isRecord() && !CurContext->isRecord()) {
7257       // This is an out-of-line definition of a static data member.
7258       switch (SC) {
7259       case SC_None:
7260         break;
7261       case SC_Static:
7262         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7263              diag::err_static_out_of_line)
7264           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7265         break;
7266       case SC_Auto:
7267       case SC_Register:
7268       case SC_Extern:
7269         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7270         // to names of variables declared in a block or to function parameters.
7271         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7272         // of class members
7273 
7274         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7275              diag::err_storage_class_for_static_member)
7276           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7277         break;
7278       case SC_PrivateExtern:
7279         llvm_unreachable("C storage class in c++!");
7280       }
7281     }
7282 
7283     if (SC == SC_Static && CurContext->isRecord()) {
7284       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7285         // Walk up the enclosing DeclContexts to check for any that are
7286         // incompatible with static data members.
7287         const DeclContext *FunctionOrMethod = nullptr;
7288         const CXXRecordDecl *AnonStruct = nullptr;
7289         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7290           if (Ctxt->isFunctionOrMethod()) {
7291             FunctionOrMethod = Ctxt;
7292             break;
7293           }
7294           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7295           if (ParentDecl && !ParentDecl->getDeclName()) {
7296             AnonStruct = ParentDecl;
7297             break;
7298           }
7299         }
7300         if (FunctionOrMethod) {
7301           // C++ [class.static.data]p5: A local class shall not have static data
7302           // members.
7303           Diag(D.getIdentifierLoc(),
7304                diag::err_static_data_member_not_allowed_in_local_class)
7305             << Name << RD->getDeclName() << RD->getTagKind();
7306         } else if (AnonStruct) {
7307           // C++ [class.static.data]p4: Unnamed classes and classes contained
7308           // directly or indirectly within unnamed classes shall not contain
7309           // static data members.
7310           Diag(D.getIdentifierLoc(),
7311                diag::err_static_data_member_not_allowed_in_anon_struct)
7312             << Name << AnonStruct->getTagKind();
7313           Invalid = true;
7314         } else if (RD->isUnion()) {
7315           // C++98 [class.union]p1: If a union contains a static data member,
7316           // the program is ill-formed. C++11 drops this restriction.
7317           Diag(D.getIdentifierLoc(),
7318                getLangOpts().CPlusPlus11
7319                  ? diag::warn_cxx98_compat_static_data_member_in_union
7320                  : diag::ext_static_data_member_in_union) << Name;
7321         }
7322       }
7323     }
7324 
7325     // Match up the template parameter lists with the scope specifier, then
7326     // determine whether we have a template or a template specialization.
7327     bool InvalidScope = false;
7328     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7329         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7330         D.getCXXScopeSpec(),
7331         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7332             ? D.getName().TemplateId
7333             : nullptr,
7334         TemplateParamLists,
7335         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7336     Invalid |= InvalidScope;
7337 
7338     if (TemplateParams) {
7339       if (!TemplateParams->size() &&
7340           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7341         // There is an extraneous 'template<>' for this variable. Complain
7342         // about it, but allow the declaration of the variable.
7343         Diag(TemplateParams->getTemplateLoc(),
7344              diag::err_template_variable_noparams)
7345           << II
7346           << SourceRange(TemplateParams->getTemplateLoc(),
7347                          TemplateParams->getRAngleLoc());
7348         TemplateParams = nullptr;
7349       } else {
7350         // Check that we can declare a template here.
7351         if (CheckTemplateDeclScope(S, TemplateParams))
7352           return nullptr;
7353 
7354         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7355           // This is an explicit specialization or a partial specialization.
7356           IsVariableTemplateSpecialization = true;
7357           IsPartialSpecialization = TemplateParams->size() > 0;
7358         } else { // if (TemplateParams->size() > 0)
7359           // This is a template declaration.
7360           IsVariableTemplate = true;
7361 
7362           // Only C++1y supports variable templates (N3651).
7363           Diag(D.getIdentifierLoc(),
7364                getLangOpts().CPlusPlus14
7365                    ? diag::warn_cxx11_compat_variable_template
7366                    : diag::ext_variable_template);
7367         }
7368       }
7369     } else {
7370       // Check that we can declare a member specialization here.
7371       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7372           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7373         return nullptr;
7374       assert((Invalid ||
7375               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7376              "should have a 'template<>' for this decl");
7377     }
7378 
7379     if (IsVariableTemplateSpecialization) {
7380       SourceLocation TemplateKWLoc =
7381           TemplateParamLists.size() > 0
7382               ? TemplateParamLists[0]->getTemplateLoc()
7383               : SourceLocation();
7384       DeclResult Res = ActOnVarTemplateSpecialization(
7385           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7386           IsPartialSpecialization);
7387       if (Res.isInvalid())
7388         return nullptr;
7389       NewVD = cast<VarDecl>(Res.get());
7390       AddToScope = false;
7391     } else if (D.isDecompositionDeclarator()) {
7392       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7393                                         D.getIdentifierLoc(), R, TInfo, SC,
7394                                         Bindings);
7395     } else
7396       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7397                               D.getIdentifierLoc(), II, R, TInfo, SC);
7398 
7399     // If this is supposed to be a variable template, create it as such.
7400     if (IsVariableTemplate) {
7401       NewTemplate =
7402           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7403                                   TemplateParams, NewVD);
7404       NewVD->setDescribedVarTemplate(NewTemplate);
7405     }
7406 
7407     // If this decl has an auto type in need of deduction, make a note of the
7408     // Decl so we can diagnose uses of it in its own initializer.
7409     if (R->getContainedDeducedType())
7410       ParsingInitForAutoVars.insert(NewVD);
7411 
7412     if (D.isInvalidType() || Invalid) {
7413       NewVD->setInvalidDecl();
7414       if (NewTemplate)
7415         NewTemplate->setInvalidDecl();
7416     }
7417 
7418     SetNestedNameSpecifier(*this, NewVD, D);
7419 
7420     // If we have any template parameter lists that don't directly belong to
7421     // the variable (matching the scope specifier), store them.
7422     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7423     if (TemplateParamLists.size() > VDTemplateParamLists)
7424       NewVD->setTemplateParameterListsInfo(
7425           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7426   }
7427 
7428   if (D.getDeclSpec().isInlineSpecified()) {
7429     if (!getLangOpts().CPlusPlus) {
7430       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7431           << 0;
7432     } else if (CurContext->isFunctionOrMethod()) {
7433       // 'inline' is not allowed on block scope variable declaration.
7434       Diag(D.getDeclSpec().getInlineSpecLoc(),
7435            diag::err_inline_declaration_block_scope) << Name
7436         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7437     } else {
7438       Diag(D.getDeclSpec().getInlineSpecLoc(),
7439            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7440                                      : diag::ext_inline_variable);
7441       NewVD->setInlineSpecified();
7442     }
7443   }
7444 
7445   // Set the lexical context. If the declarator has a C++ scope specifier, the
7446   // lexical context will be different from the semantic context.
7447   NewVD->setLexicalDeclContext(CurContext);
7448   if (NewTemplate)
7449     NewTemplate->setLexicalDeclContext(CurContext);
7450 
7451   if (IsLocalExternDecl) {
7452     if (D.isDecompositionDeclarator())
7453       for (auto *B : Bindings)
7454         B->setLocalExternDecl();
7455     else
7456       NewVD->setLocalExternDecl();
7457   }
7458 
7459   bool EmitTLSUnsupportedError = false;
7460   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7461     // C++11 [dcl.stc]p4:
7462     //   When thread_local is applied to a variable of block scope the
7463     //   storage-class-specifier static is implied if it does not appear
7464     //   explicitly.
7465     // Core issue: 'static' is not implied if the variable is declared
7466     //   'extern'.
7467     if (NewVD->hasLocalStorage() &&
7468         (SCSpec != DeclSpec::SCS_unspecified ||
7469          TSCS != DeclSpec::TSCS_thread_local ||
7470          !DC->isFunctionOrMethod()))
7471       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7472            diag::err_thread_non_global)
7473         << DeclSpec::getSpecifierName(TSCS);
7474     else if (!Context.getTargetInfo().isTLSSupported()) {
7475       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7476           getLangOpts().SYCLIsDevice) {
7477         // Postpone error emission until we've collected attributes required to
7478         // figure out whether it's a host or device variable and whether the
7479         // error should be ignored.
7480         EmitTLSUnsupportedError = true;
7481         // We still need to mark the variable as TLS so it shows up in AST with
7482         // proper storage class for other tools to use even if we're not going
7483         // to emit any code for it.
7484         NewVD->setTSCSpec(TSCS);
7485       } else
7486         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7487              diag::err_thread_unsupported);
7488     } else
7489       NewVD->setTSCSpec(TSCS);
7490   }
7491 
7492   switch (D.getDeclSpec().getConstexprSpecifier()) {
7493   case ConstexprSpecKind::Unspecified:
7494     break;
7495 
7496   case ConstexprSpecKind::Consteval:
7497     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7498          diag::err_constexpr_wrong_decl_kind)
7499         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7500     LLVM_FALLTHROUGH;
7501 
7502   case ConstexprSpecKind::Constexpr:
7503     NewVD->setConstexpr(true);
7504     // C++1z [dcl.spec.constexpr]p1:
7505     //   A static data member declared with the constexpr specifier is
7506     //   implicitly an inline variable.
7507     if (NewVD->isStaticDataMember() &&
7508         (getLangOpts().CPlusPlus17 ||
7509          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7510       NewVD->setImplicitlyInline();
7511     break;
7512 
7513   case ConstexprSpecKind::Constinit:
7514     if (!NewVD->hasGlobalStorage())
7515       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7516            diag::err_constinit_local_variable);
7517     else
7518       NewVD->addAttr(ConstInitAttr::Create(
7519           Context, D.getDeclSpec().getConstexprSpecLoc(),
7520           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7521     break;
7522   }
7523 
7524   // C99 6.7.4p3
7525   //   An inline definition of a function with external linkage shall
7526   //   not contain a definition of a modifiable object with static or
7527   //   thread storage duration...
7528   // We only apply this when the function is required to be defined
7529   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7530   // that a local variable with thread storage duration still has to
7531   // be marked 'static'.  Also note that it's possible to get these
7532   // semantics in C++ using __attribute__((gnu_inline)).
7533   if (SC == SC_Static && S->getFnParent() != nullptr &&
7534       !NewVD->getType().isConstQualified()) {
7535     FunctionDecl *CurFD = getCurFunctionDecl();
7536     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7537       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7538            diag::warn_static_local_in_extern_inline);
7539       MaybeSuggestAddingStaticToDecl(CurFD);
7540     }
7541   }
7542 
7543   if (D.getDeclSpec().isModulePrivateSpecified()) {
7544     if (IsVariableTemplateSpecialization)
7545       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7546           << (IsPartialSpecialization ? 1 : 0)
7547           << FixItHint::CreateRemoval(
7548                  D.getDeclSpec().getModulePrivateSpecLoc());
7549     else if (IsMemberSpecialization)
7550       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7551         << 2
7552         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7553     else if (NewVD->hasLocalStorage())
7554       Diag(NewVD->getLocation(), diag::err_module_private_local)
7555           << 0 << NewVD
7556           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7557           << FixItHint::CreateRemoval(
7558                  D.getDeclSpec().getModulePrivateSpecLoc());
7559     else {
7560       NewVD->setModulePrivate();
7561       if (NewTemplate)
7562         NewTemplate->setModulePrivate();
7563       for (auto *B : Bindings)
7564         B->setModulePrivate();
7565     }
7566   }
7567 
7568   if (getLangOpts().OpenCL) {
7569     deduceOpenCLAddressSpace(NewVD);
7570 
7571     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7572     if (TSC != TSCS_unspecified) {
7573       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7574            diag::err_opencl_unknown_type_specifier)
7575           << getLangOpts().getOpenCLVersionString()
7576           << DeclSpec::getSpecifierName(TSC) << 1;
7577       NewVD->setInvalidDecl();
7578     }
7579   }
7580 
7581   // Handle attributes prior to checking for duplicates in MergeVarDecl
7582   ProcessDeclAttributes(S, NewVD, D);
7583 
7584   // FIXME: This is probably the wrong location to be doing this and we should
7585   // probably be doing this for more attributes (especially for function
7586   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7587   // the code to copy attributes would be generated by TableGen.
7588   if (R->isFunctionPointerType())
7589     if (const auto *TT = R->getAs<TypedefType>())
7590       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7591 
7592   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7593       getLangOpts().SYCLIsDevice) {
7594     if (EmitTLSUnsupportedError &&
7595         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7596          (getLangOpts().OpenMPIsDevice &&
7597           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7598       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7599            diag::err_thread_unsupported);
7600 
7601     if (EmitTLSUnsupportedError &&
7602         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7603       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7604     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7605     // storage [duration]."
7606     if (SC == SC_None && S->getFnParent() != nullptr &&
7607         (NewVD->hasAttr<CUDASharedAttr>() ||
7608          NewVD->hasAttr<CUDAConstantAttr>())) {
7609       NewVD->setStorageClass(SC_Static);
7610     }
7611   }
7612 
7613   // Ensure that dllimport globals without explicit storage class are treated as
7614   // extern. The storage class is set above using parsed attributes. Now we can
7615   // check the VarDecl itself.
7616   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7617          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7618          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7619 
7620   // In auto-retain/release, infer strong retension for variables of
7621   // retainable type.
7622   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7623     NewVD->setInvalidDecl();
7624 
7625   // Handle GNU asm-label extension (encoded as an attribute).
7626   if (Expr *E = (Expr*)D.getAsmLabel()) {
7627     // The parser guarantees this is a string.
7628     StringLiteral *SE = cast<StringLiteral>(E);
7629     StringRef Label = SE->getString();
7630     if (S->getFnParent() != nullptr) {
7631       switch (SC) {
7632       case SC_None:
7633       case SC_Auto:
7634         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7635         break;
7636       case SC_Register:
7637         // Local Named register
7638         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7639             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7640           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7641         break;
7642       case SC_Static:
7643       case SC_Extern:
7644       case SC_PrivateExtern:
7645         break;
7646       }
7647     } else if (SC == SC_Register) {
7648       // Global Named register
7649       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7650         const auto &TI = Context.getTargetInfo();
7651         bool HasSizeMismatch;
7652 
7653         if (!TI.isValidGCCRegisterName(Label))
7654           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7655         else if (!TI.validateGlobalRegisterVariable(Label,
7656                                                     Context.getTypeSize(R),
7657                                                     HasSizeMismatch))
7658           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7659         else if (HasSizeMismatch)
7660           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7661       }
7662 
7663       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7664         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7665         NewVD->setInvalidDecl(true);
7666       }
7667     }
7668 
7669     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7670                                         /*IsLiteralLabel=*/true,
7671                                         SE->getStrTokenLoc(0)));
7672   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7673     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7674       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7675     if (I != ExtnameUndeclaredIdentifiers.end()) {
7676       if (isDeclExternC(NewVD)) {
7677         NewVD->addAttr(I->second);
7678         ExtnameUndeclaredIdentifiers.erase(I);
7679       } else
7680         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7681             << /*Variable*/1 << NewVD;
7682     }
7683   }
7684 
7685   // Find the shadowed declaration before filtering for scope.
7686   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7687                                 ? getShadowedDeclaration(NewVD, Previous)
7688                                 : nullptr;
7689 
7690   // Don't consider existing declarations that are in a different
7691   // scope and are out-of-semantic-context declarations (if the new
7692   // declaration has linkage).
7693   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7694                        D.getCXXScopeSpec().isNotEmpty() ||
7695                        IsMemberSpecialization ||
7696                        IsVariableTemplateSpecialization);
7697 
7698   // Check whether the previous declaration is in the same block scope. This
7699   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7700   if (getLangOpts().CPlusPlus &&
7701       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7702     NewVD->setPreviousDeclInSameBlockScope(
7703         Previous.isSingleResult() && !Previous.isShadowed() &&
7704         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7705 
7706   if (!getLangOpts().CPlusPlus) {
7707     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7708   } else {
7709     // If this is an explicit specialization of a static data member, check it.
7710     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7711         CheckMemberSpecialization(NewVD, Previous))
7712       NewVD->setInvalidDecl();
7713 
7714     // Merge the decl with the existing one if appropriate.
7715     if (!Previous.empty()) {
7716       if (Previous.isSingleResult() &&
7717           isa<FieldDecl>(Previous.getFoundDecl()) &&
7718           D.getCXXScopeSpec().isSet()) {
7719         // The user tried to define a non-static data member
7720         // out-of-line (C++ [dcl.meaning]p1).
7721         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7722           << D.getCXXScopeSpec().getRange();
7723         Previous.clear();
7724         NewVD->setInvalidDecl();
7725       }
7726     } else if (D.getCXXScopeSpec().isSet()) {
7727       // No previous declaration in the qualifying scope.
7728       Diag(D.getIdentifierLoc(), diag::err_no_member)
7729         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7730         << D.getCXXScopeSpec().getRange();
7731       NewVD->setInvalidDecl();
7732     }
7733 
7734     if (!IsVariableTemplateSpecialization)
7735       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7736 
7737     if (NewTemplate) {
7738       VarTemplateDecl *PrevVarTemplate =
7739           NewVD->getPreviousDecl()
7740               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7741               : nullptr;
7742 
7743       // Check the template parameter list of this declaration, possibly
7744       // merging in the template parameter list from the previous variable
7745       // template declaration.
7746       if (CheckTemplateParameterList(
7747               TemplateParams,
7748               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7749                               : nullptr,
7750               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7751                DC->isDependentContext())
7752                   ? TPC_ClassTemplateMember
7753                   : TPC_VarTemplate))
7754         NewVD->setInvalidDecl();
7755 
7756       // If we are providing an explicit specialization of a static variable
7757       // template, make a note of that.
7758       if (PrevVarTemplate &&
7759           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7760         PrevVarTemplate->setMemberSpecialization();
7761     }
7762   }
7763 
7764   // Diagnose shadowed variables iff this isn't a redeclaration.
7765   if (ShadowedDecl && !D.isRedeclaration())
7766     CheckShadow(NewVD, ShadowedDecl, Previous);
7767 
7768   ProcessPragmaWeak(S, NewVD);
7769 
7770   // If this is the first declaration of an extern C variable, update
7771   // the map of such variables.
7772   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7773       isIncompleteDeclExternC(*this, NewVD))
7774     RegisterLocallyScopedExternCDecl(NewVD, S);
7775 
7776   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7777     MangleNumberingContext *MCtx;
7778     Decl *ManglingContextDecl;
7779     std::tie(MCtx, ManglingContextDecl) =
7780         getCurrentMangleNumberContext(NewVD->getDeclContext());
7781     if (MCtx) {
7782       Context.setManglingNumber(
7783           NewVD, MCtx->getManglingNumber(
7784                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7785       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7786     }
7787   }
7788 
7789   // Special handling of variable named 'main'.
7790   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7791       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7792       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7793 
7794     // C++ [basic.start.main]p3
7795     // A program that declares a variable main at global scope is ill-formed.
7796     if (getLangOpts().CPlusPlus)
7797       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7798 
7799     // In C, and external-linkage variable named main results in undefined
7800     // behavior.
7801     else if (NewVD->hasExternalFormalLinkage())
7802       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7803   }
7804 
7805   if (D.isRedeclaration() && !Previous.empty()) {
7806     NamedDecl *Prev = Previous.getRepresentativeDecl();
7807     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7808                                    D.isFunctionDefinition());
7809   }
7810 
7811   if (NewTemplate) {
7812     if (NewVD->isInvalidDecl())
7813       NewTemplate->setInvalidDecl();
7814     ActOnDocumentableDecl(NewTemplate);
7815     return NewTemplate;
7816   }
7817 
7818   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7819     CompleteMemberSpecialization(NewVD, Previous);
7820 
7821   return NewVD;
7822 }
7823 
7824 /// Enum describing the %select options in diag::warn_decl_shadow.
7825 enum ShadowedDeclKind {
7826   SDK_Local,
7827   SDK_Global,
7828   SDK_StaticMember,
7829   SDK_Field,
7830   SDK_Typedef,
7831   SDK_Using,
7832   SDK_StructuredBinding
7833 };
7834 
7835 /// Determine what kind of declaration we're shadowing.
7836 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7837                                                 const DeclContext *OldDC) {
7838   if (isa<TypeAliasDecl>(ShadowedDecl))
7839     return SDK_Using;
7840   else if (isa<TypedefDecl>(ShadowedDecl))
7841     return SDK_Typedef;
7842   else if (isa<BindingDecl>(ShadowedDecl))
7843     return SDK_StructuredBinding;
7844   else if (isa<RecordDecl>(OldDC))
7845     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7846 
7847   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7848 }
7849 
7850 /// Return the location of the capture if the given lambda captures the given
7851 /// variable \p VD, or an invalid source location otherwise.
7852 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7853                                          const VarDecl *VD) {
7854   for (const Capture &Capture : LSI->Captures) {
7855     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7856       return Capture.getLocation();
7857   }
7858   return SourceLocation();
7859 }
7860 
7861 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7862                                      const LookupResult &R) {
7863   // Only diagnose if we're shadowing an unambiguous field or variable.
7864   if (R.getResultKind() != LookupResult::Found)
7865     return false;
7866 
7867   // Return false if warning is ignored.
7868   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7869 }
7870 
7871 /// Return the declaration shadowed by the given variable \p D, or null
7872 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7873 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7874                                         const LookupResult &R) {
7875   if (!shouldWarnIfShadowedDecl(Diags, R))
7876     return nullptr;
7877 
7878   // Don't diagnose declarations at file scope.
7879   if (D->hasGlobalStorage())
7880     return nullptr;
7881 
7882   NamedDecl *ShadowedDecl = R.getFoundDecl();
7883   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7884                                                             : nullptr;
7885 }
7886 
7887 /// Return the declaration shadowed by the given typedef \p D, or null
7888 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7889 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7890                                         const LookupResult &R) {
7891   // Don't warn if typedef declaration is part of a class
7892   if (D->getDeclContext()->isRecord())
7893     return nullptr;
7894 
7895   if (!shouldWarnIfShadowedDecl(Diags, R))
7896     return nullptr;
7897 
7898   NamedDecl *ShadowedDecl = R.getFoundDecl();
7899   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7900 }
7901 
7902 /// Return the declaration shadowed by the given variable \p D, or null
7903 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7904 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7905                                         const LookupResult &R) {
7906   if (!shouldWarnIfShadowedDecl(Diags, R))
7907     return nullptr;
7908 
7909   NamedDecl *ShadowedDecl = R.getFoundDecl();
7910   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7911                                                             : nullptr;
7912 }
7913 
7914 /// Diagnose variable or built-in function shadowing.  Implements
7915 /// -Wshadow.
7916 ///
7917 /// This method is called whenever a VarDecl is added to a "useful"
7918 /// scope.
7919 ///
7920 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7921 /// \param R the lookup of the name
7922 ///
7923 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7924                        const LookupResult &R) {
7925   DeclContext *NewDC = D->getDeclContext();
7926 
7927   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7928     // Fields are not shadowed by variables in C++ static methods.
7929     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7930       if (MD->isStatic())
7931         return;
7932 
7933     // Fields shadowed by constructor parameters are a special case. Usually
7934     // the constructor initializes the field with the parameter.
7935     if (isa<CXXConstructorDecl>(NewDC))
7936       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7937         // Remember that this was shadowed so we can either warn about its
7938         // modification or its existence depending on warning settings.
7939         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7940         return;
7941       }
7942   }
7943 
7944   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7945     if (shadowedVar->isExternC()) {
7946       // For shadowing external vars, make sure that we point to the global
7947       // declaration, not a locally scoped extern declaration.
7948       for (auto I : shadowedVar->redecls())
7949         if (I->isFileVarDecl()) {
7950           ShadowedDecl = I;
7951           break;
7952         }
7953     }
7954 
7955   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7956 
7957   unsigned WarningDiag = diag::warn_decl_shadow;
7958   SourceLocation CaptureLoc;
7959   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7960       isa<CXXMethodDecl>(NewDC)) {
7961     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7962       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7963         if (RD->getLambdaCaptureDefault() == LCD_None) {
7964           // Try to avoid warnings for lambdas with an explicit capture list.
7965           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7966           // Warn only when the lambda captures the shadowed decl explicitly.
7967           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7968           if (CaptureLoc.isInvalid())
7969             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7970         } else {
7971           // Remember that this was shadowed so we can avoid the warning if the
7972           // shadowed decl isn't captured and the warning settings allow it.
7973           cast<LambdaScopeInfo>(getCurFunction())
7974               ->ShadowingDecls.push_back(
7975                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7976           return;
7977         }
7978       }
7979 
7980       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7981         // A variable can't shadow a local variable in an enclosing scope, if
7982         // they are separated by a non-capturing declaration context.
7983         for (DeclContext *ParentDC = NewDC;
7984              ParentDC && !ParentDC->Equals(OldDC);
7985              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7986           // Only block literals, captured statements, and lambda expressions
7987           // can capture; other scopes don't.
7988           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7989               !isLambdaCallOperator(ParentDC)) {
7990             return;
7991           }
7992         }
7993       }
7994     }
7995   }
7996 
7997   // Only warn about certain kinds of shadowing for class members.
7998   if (NewDC && NewDC->isRecord()) {
7999     // In particular, don't warn about shadowing non-class members.
8000     if (!OldDC->isRecord())
8001       return;
8002 
8003     // TODO: should we warn about static data members shadowing
8004     // static data members from base classes?
8005 
8006     // TODO: don't diagnose for inaccessible shadowed members.
8007     // This is hard to do perfectly because we might friend the
8008     // shadowing context, but that's just a false negative.
8009   }
8010 
8011 
8012   DeclarationName Name = R.getLookupName();
8013 
8014   // Emit warning and note.
8015   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8016   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8017   if (!CaptureLoc.isInvalid())
8018     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8019         << Name << /*explicitly*/ 1;
8020   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8021 }
8022 
8023 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8024 /// when these variables are captured by the lambda.
8025 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8026   for (const auto &Shadow : LSI->ShadowingDecls) {
8027     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8028     // Try to avoid the warning when the shadowed decl isn't captured.
8029     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8030     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8031     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8032                                        ? diag::warn_decl_shadow_uncaptured_local
8033                                        : diag::warn_decl_shadow)
8034         << Shadow.VD->getDeclName()
8035         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8036     if (!CaptureLoc.isInvalid())
8037       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8038           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8039     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8040   }
8041 }
8042 
8043 /// Check -Wshadow without the advantage of a previous lookup.
8044 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8045   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8046     return;
8047 
8048   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8049                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8050   LookupName(R, S);
8051   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8052     CheckShadow(D, ShadowedDecl, R);
8053 }
8054 
8055 /// Check if 'E', which is an expression that is about to be modified, refers
8056 /// to a constructor parameter that shadows a field.
8057 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8058   // Quickly ignore expressions that can't be shadowing ctor parameters.
8059   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8060     return;
8061   E = E->IgnoreParenImpCasts();
8062   auto *DRE = dyn_cast<DeclRefExpr>(E);
8063   if (!DRE)
8064     return;
8065   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8066   auto I = ShadowingDecls.find(D);
8067   if (I == ShadowingDecls.end())
8068     return;
8069   const NamedDecl *ShadowedDecl = I->second;
8070   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8071   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8072   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8073   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8074 
8075   // Avoid issuing multiple warnings about the same decl.
8076   ShadowingDecls.erase(I);
8077 }
8078 
8079 /// Check for conflict between this global or extern "C" declaration and
8080 /// previous global or extern "C" declarations. This is only used in C++.
8081 template<typename T>
8082 static bool checkGlobalOrExternCConflict(
8083     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8084   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8085   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8086 
8087   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8088     // The common case: this global doesn't conflict with any extern "C"
8089     // declaration.
8090     return false;
8091   }
8092 
8093   if (Prev) {
8094     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8095       // Both the old and new declarations have C language linkage. This is a
8096       // redeclaration.
8097       Previous.clear();
8098       Previous.addDecl(Prev);
8099       return true;
8100     }
8101 
8102     // This is a global, non-extern "C" declaration, and there is a previous
8103     // non-global extern "C" declaration. Diagnose if this is a variable
8104     // declaration.
8105     if (!isa<VarDecl>(ND))
8106       return false;
8107   } else {
8108     // The declaration is extern "C". Check for any declaration in the
8109     // translation unit which might conflict.
8110     if (IsGlobal) {
8111       // We have already performed the lookup into the translation unit.
8112       IsGlobal = false;
8113       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8114            I != E; ++I) {
8115         if (isa<VarDecl>(*I)) {
8116           Prev = *I;
8117           break;
8118         }
8119       }
8120     } else {
8121       DeclContext::lookup_result R =
8122           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8123       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8124            I != E; ++I) {
8125         if (isa<VarDecl>(*I)) {
8126           Prev = *I;
8127           break;
8128         }
8129         // FIXME: If we have any other entity with this name in global scope,
8130         // the declaration is ill-formed, but that is a defect: it breaks the
8131         // 'stat' hack, for instance. Only variables can have mangled name
8132         // clashes with extern "C" declarations, so only they deserve a
8133         // diagnostic.
8134       }
8135     }
8136 
8137     if (!Prev)
8138       return false;
8139   }
8140 
8141   // Use the first declaration's location to ensure we point at something which
8142   // is lexically inside an extern "C" linkage-spec.
8143   assert(Prev && "should have found a previous declaration to diagnose");
8144   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8145     Prev = FD->getFirstDecl();
8146   else
8147     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8148 
8149   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8150     << IsGlobal << ND;
8151   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8152     << IsGlobal;
8153   return false;
8154 }
8155 
8156 /// Apply special rules for handling extern "C" declarations. Returns \c true
8157 /// if we have found that this is a redeclaration of some prior entity.
8158 ///
8159 /// Per C++ [dcl.link]p6:
8160 ///   Two declarations [for a function or variable] with C language linkage
8161 ///   with the same name that appear in different scopes refer to the same
8162 ///   [entity]. An entity with C language linkage shall not be declared with
8163 ///   the same name as an entity in global scope.
8164 template<typename T>
8165 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8166                                                   LookupResult &Previous) {
8167   if (!S.getLangOpts().CPlusPlus) {
8168     // In C, when declaring a global variable, look for a corresponding 'extern'
8169     // variable declared in function scope. We don't need this in C++, because
8170     // we find local extern decls in the surrounding file-scope DeclContext.
8171     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8172       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8173         Previous.clear();
8174         Previous.addDecl(Prev);
8175         return true;
8176       }
8177     }
8178     return false;
8179   }
8180 
8181   // A declaration in the translation unit can conflict with an extern "C"
8182   // declaration.
8183   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8184     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8185 
8186   // An extern "C" declaration can conflict with a declaration in the
8187   // translation unit or can be a redeclaration of an extern "C" declaration
8188   // in another scope.
8189   if (isIncompleteDeclExternC(S,ND))
8190     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8191 
8192   // Neither global nor extern "C": nothing to do.
8193   return false;
8194 }
8195 
8196 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8197   // If the decl is already known invalid, don't check it.
8198   if (NewVD->isInvalidDecl())
8199     return;
8200 
8201   QualType T = NewVD->getType();
8202 
8203   // Defer checking an 'auto' type until its initializer is attached.
8204   if (T->isUndeducedType())
8205     return;
8206 
8207   if (NewVD->hasAttrs())
8208     CheckAlignasUnderalignment(NewVD);
8209 
8210   if (T->isObjCObjectType()) {
8211     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8212       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8213     T = Context.getObjCObjectPointerType(T);
8214     NewVD->setType(T);
8215   }
8216 
8217   // Emit an error if an address space was applied to decl with local storage.
8218   // This includes arrays of objects with address space qualifiers, but not
8219   // automatic variables that point to other address spaces.
8220   // ISO/IEC TR 18037 S5.1.2
8221   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8222       T.getAddressSpace() != LangAS::Default) {
8223     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8224     NewVD->setInvalidDecl();
8225     return;
8226   }
8227 
8228   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8229   // scope.
8230   if (getLangOpts().OpenCLVersion == 120 &&
8231       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8232                                             getLangOpts()) &&
8233       NewVD->isStaticLocal()) {
8234     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8235     NewVD->setInvalidDecl();
8236     return;
8237   }
8238 
8239   if (getLangOpts().OpenCL) {
8240     if (!diagnoseOpenCLTypes(*this, NewVD))
8241       return;
8242 
8243     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8244     if (NewVD->hasAttr<BlocksAttr>()) {
8245       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8246       return;
8247     }
8248 
8249     if (T->isBlockPointerType()) {
8250       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8251       // can't use 'extern' storage class.
8252       if (!T.isConstQualified()) {
8253         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8254             << 0 /*const*/;
8255         NewVD->setInvalidDecl();
8256         return;
8257       }
8258       if (NewVD->hasExternalStorage()) {
8259         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8260         NewVD->setInvalidDecl();
8261         return;
8262       }
8263     }
8264 
8265     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8266     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8267         NewVD->hasExternalStorage()) {
8268       if (!T->isSamplerT() && !T->isDependentType() &&
8269           !(T.getAddressSpace() == LangAS::opencl_constant ||
8270             (T.getAddressSpace() == LangAS::opencl_global &&
8271              getOpenCLOptions().areProgramScopeVariablesSupported(
8272                  getLangOpts())))) {
8273         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8274         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8275           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8276               << Scope << "global or constant";
8277         else
8278           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8279               << Scope << "constant";
8280         NewVD->setInvalidDecl();
8281         return;
8282       }
8283     } else {
8284       if (T.getAddressSpace() == LangAS::opencl_global) {
8285         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8286             << 1 /*is any function*/ << "global";
8287         NewVD->setInvalidDecl();
8288         return;
8289       }
8290       if (T.getAddressSpace() == LangAS::opencl_constant ||
8291           T.getAddressSpace() == LangAS::opencl_local) {
8292         FunctionDecl *FD = getCurFunctionDecl();
8293         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8294         // in functions.
8295         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8296           if (T.getAddressSpace() == LangAS::opencl_constant)
8297             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8298                 << 0 /*non-kernel only*/ << "constant";
8299           else
8300             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8301                 << 0 /*non-kernel only*/ << "local";
8302           NewVD->setInvalidDecl();
8303           return;
8304         }
8305         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8306         // in the outermost scope of a kernel function.
8307         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8308           if (!getCurScope()->isFunctionScope()) {
8309             if (T.getAddressSpace() == LangAS::opencl_constant)
8310               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8311                   << "constant";
8312             else
8313               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8314                   << "local";
8315             NewVD->setInvalidDecl();
8316             return;
8317           }
8318         }
8319       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8320                  // If we are parsing a template we didn't deduce an addr
8321                  // space yet.
8322                  T.getAddressSpace() != LangAS::Default) {
8323         // Do not allow other address spaces on automatic variable.
8324         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8325         NewVD->setInvalidDecl();
8326         return;
8327       }
8328     }
8329   }
8330 
8331   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8332       && !NewVD->hasAttr<BlocksAttr>()) {
8333     if (getLangOpts().getGC() != LangOptions::NonGC)
8334       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8335     else {
8336       assert(!getLangOpts().ObjCAutoRefCount);
8337       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8338     }
8339   }
8340 
8341   bool isVM = T->isVariablyModifiedType();
8342   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8343       NewVD->hasAttr<BlocksAttr>())
8344     setFunctionHasBranchProtectedScope();
8345 
8346   if ((isVM && NewVD->hasLinkage()) ||
8347       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8348     bool SizeIsNegative;
8349     llvm::APSInt Oversized;
8350     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8351         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8352     QualType FixedT;
8353     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8354       FixedT = FixedTInfo->getType();
8355     else if (FixedTInfo) {
8356       // Type and type-as-written are canonically different. We need to fix up
8357       // both types separately.
8358       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8359                                                    Oversized);
8360     }
8361     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8362       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8363       // FIXME: This won't give the correct result for
8364       // int a[10][n];
8365       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8366 
8367       if (NewVD->isFileVarDecl())
8368         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8369         << SizeRange;
8370       else if (NewVD->isStaticLocal())
8371         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8372         << SizeRange;
8373       else
8374         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8375         << SizeRange;
8376       NewVD->setInvalidDecl();
8377       return;
8378     }
8379 
8380     if (!FixedTInfo) {
8381       if (NewVD->isFileVarDecl())
8382         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8383       else
8384         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8385       NewVD->setInvalidDecl();
8386       return;
8387     }
8388 
8389     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8390     NewVD->setType(FixedT);
8391     NewVD->setTypeSourceInfo(FixedTInfo);
8392   }
8393 
8394   if (T->isVoidType()) {
8395     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8396     //                    of objects and functions.
8397     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8398       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8399         << T;
8400       NewVD->setInvalidDecl();
8401       return;
8402     }
8403   }
8404 
8405   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8406     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8407     NewVD->setInvalidDecl();
8408     return;
8409   }
8410 
8411   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8412     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8413     NewVD->setInvalidDecl();
8414     return;
8415   }
8416 
8417   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8418     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8419     NewVD->setInvalidDecl();
8420     return;
8421   }
8422 
8423   if (NewVD->isConstexpr() && !T->isDependentType() &&
8424       RequireLiteralType(NewVD->getLocation(), T,
8425                          diag::err_constexpr_var_non_literal)) {
8426     NewVD->setInvalidDecl();
8427     return;
8428   }
8429 
8430   // PPC MMA non-pointer types are not allowed as non-local variable types.
8431   if (Context.getTargetInfo().getTriple().isPPC64() &&
8432       !NewVD->isLocalVarDecl() &&
8433       CheckPPCMMAType(T, NewVD->getLocation())) {
8434     NewVD->setInvalidDecl();
8435     return;
8436   }
8437 }
8438 
8439 /// Perform semantic checking on a newly-created variable
8440 /// declaration.
8441 ///
8442 /// This routine performs all of the type-checking required for a
8443 /// variable declaration once it has been built. It is used both to
8444 /// check variables after they have been parsed and their declarators
8445 /// have been translated into a declaration, and to check variables
8446 /// that have been instantiated from a template.
8447 ///
8448 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8449 ///
8450 /// Returns true if the variable declaration is a redeclaration.
8451 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8452   CheckVariableDeclarationType(NewVD);
8453 
8454   // If the decl is already known invalid, don't check it.
8455   if (NewVD->isInvalidDecl())
8456     return false;
8457 
8458   // If we did not find anything by this name, look for a non-visible
8459   // extern "C" declaration with the same name.
8460   if (Previous.empty() &&
8461       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8462     Previous.setShadowed();
8463 
8464   if (!Previous.empty()) {
8465     MergeVarDecl(NewVD, Previous);
8466     return true;
8467   }
8468   return false;
8469 }
8470 
8471 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8472 /// and if so, check that it's a valid override and remember it.
8473 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8474   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8475 
8476   // Look for methods in base classes that this method might override.
8477   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8478                      /*DetectVirtual=*/false);
8479   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8480     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8481     DeclarationName Name = MD->getDeclName();
8482 
8483     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8484       // We really want to find the base class destructor here.
8485       QualType T = Context.getTypeDeclType(BaseRecord);
8486       CanQualType CT = Context.getCanonicalType(T);
8487       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8488     }
8489 
8490     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8491       CXXMethodDecl *BaseMD =
8492           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8493       if (!BaseMD || !BaseMD->isVirtual() ||
8494           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8495                      /*ConsiderCudaAttrs=*/true,
8496                      // C++2a [class.virtual]p2 does not consider requires
8497                      // clauses when overriding.
8498                      /*ConsiderRequiresClauses=*/false))
8499         continue;
8500 
8501       if (Overridden.insert(BaseMD).second) {
8502         MD->addOverriddenMethod(BaseMD);
8503         CheckOverridingFunctionReturnType(MD, BaseMD);
8504         CheckOverridingFunctionAttributes(MD, BaseMD);
8505         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8506         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8507       }
8508 
8509       // A method can only override one function from each base class. We
8510       // don't track indirectly overridden methods from bases of bases.
8511       return true;
8512     }
8513 
8514     return false;
8515   };
8516 
8517   DC->lookupInBases(VisitBase, Paths);
8518   return !Overridden.empty();
8519 }
8520 
8521 namespace {
8522   // Struct for holding all of the extra arguments needed by
8523   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8524   struct ActOnFDArgs {
8525     Scope *S;
8526     Declarator &D;
8527     MultiTemplateParamsArg TemplateParamLists;
8528     bool AddToScope;
8529   };
8530 } // end anonymous namespace
8531 
8532 namespace {
8533 
8534 // Callback to only accept typo corrections that have a non-zero edit distance.
8535 // Also only accept corrections that have the same parent decl.
8536 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8537  public:
8538   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8539                             CXXRecordDecl *Parent)
8540       : Context(Context), OriginalFD(TypoFD),
8541         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8542 
8543   bool ValidateCandidate(const TypoCorrection &candidate) override {
8544     if (candidate.getEditDistance() == 0)
8545       return false;
8546 
8547     SmallVector<unsigned, 1> MismatchedParams;
8548     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8549                                           CDeclEnd = candidate.end();
8550          CDecl != CDeclEnd; ++CDecl) {
8551       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8552 
8553       if (FD && !FD->hasBody() &&
8554           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8555         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8556           CXXRecordDecl *Parent = MD->getParent();
8557           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8558             return true;
8559         } else if (!ExpectedParent) {
8560           return true;
8561         }
8562       }
8563     }
8564 
8565     return false;
8566   }
8567 
8568   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8569     return std::make_unique<DifferentNameValidatorCCC>(*this);
8570   }
8571 
8572  private:
8573   ASTContext &Context;
8574   FunctionDecl *OriginalFD;
8575   CXXRecordDecl *ExpectedParent;
8576 };
8577 
8578 } // end anonymous namespace
8579 
8580 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8581   TypoCorrectedFunctionDefinitions.insert(F);
8582 }
8583 
8584 /// Generate diagnostics for an invalid function redeclaration.
8585 ///
8586 /// This routine handles generating the diagnostic messages for an invalid
8587 /// function redeclaration, including finding possible similar declarations
8588 /// or performing typo correction if there are no previous declarations with
8589 /// the same name.
8590 ///
8591 /// Returns a NamedDecl iff typo correction was performed and substituting in
8592 /// the new declaration name does not cause new errors.
8593 static NamedDecl *DiagnoseInvalidRedeclaration(
8594     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8595     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8596   DeclarationName Name = NewFD->getDeclName();
8597   DeclContext *NewDC = NewFD->getDeclContext();
8598   SmallVector<unsigned, 1> MismatchedParams;
8599   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8600   TypoCorrection Correction;
8601   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8602   unsigned DiagMsg =
8603     IsLocalFriend ? diag::err_no_matching_local_friend :
8604     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8605     diag::err_member_decl_does_not_match;
8606   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8607                     IsLocalFriend ? Sema::LookupLocalFriendName
8608                                   : Sema::LookupOrdinaryName,
8609                     Sema::ForVisibleRedeclaration);
8610 
8611   NewFD->setInvalidDecl();
8612   if (IsLocalFriend)
8613     SemaRef.LookupName(Prev, S);
8614   else
8615     SemaRef.LookupQualifiedName(Prev, NewDC);
8616   assert(!Prev.isAmbiguous() &&
8617          "Cannot have an ambiguity in previous-declaration lookup");
8618   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8619   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8620                                 MD ? MD->getParent() : nullptr);
8621   if (!Prev.empty()) {
8622     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8623          Func != FuncEnd; ++Func) {
8624       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8625       if (FD &&
8626           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8627         // Add 1 to the index so that 0 can mean the mismatch didn't
8628         // involve a parameter
8629         unsigned ParamNum =
8630             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8631         NearMatches.push_back(std::make_pair(FD, ParamNum));
8632       }
8633     }
8634   // If the qualified name lookup yielded nothing, try typo correction
8635   } else if ((Correction = SemaRef.CorrectTypo(
8636                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8637                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8638                   IsLocalFriend ? nullptr : NewDC))) {
8639     // Set up everything for the call to ActOnFunctionDeclarator
8640     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8641                               ExtraArgs.D.getIdentifierLoc());
8642     Previous.clear();
8643     Previous.setLookupName(Correction.getCorrection());
8644     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8645                                     CDeclEnd = Correction.end();
8646          CDecl != CDeclEnd; ++CDecl) {
8647       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8648       if (FD && !FD->hasBody() &&
8649           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8650         Previous.addDecl(FD);
8651       }
8652     }
8653     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8654 
8655     NamedDecl *Result;
8656     // Retry building the function declaration with the new previous
8657     // declarations, and with errors suppressed.
8658     {
8659       // Trap errors.
8660       Sema::SFINAETrap Trap(SemaRef);
8661 
8662       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8663       // pieces need to verify the typo-corrected C++ declaration and hopefully
8664       // eliminate the need for the parameter pack ExtraArgs.
8665       Result = SemaRef.ActOnFunctionDeclarator(
8666           ExtraArgs.S, ExtraArgs.D,
8667           Correction.getCorrectionDecl()->getDeclContext(),
8668           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8669           ExtraArgs.AddToScope);
8670 
8671       if (Trap.hasErrorOccurred())
8672         Result = nullptr;
8673     }
8674 
8675     if (Result) {
8676       // Determine which correction we picked.
8677       Decl *Canonical = Result->getCanonicalDecl();
8678       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8679            I != E; ++I)
8680         if ((*I)->getCanonicalDecl() == Canonical)
8681           Correction.setCorrectionDecl(*I);
8682 
8683       // Let Sema know about the correction.
8684       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8685       SemaRef.diagnoseTypo(
8686           Correction,
8687           SemaRef.PDiag(IsLocalFriend
8688                           ? diag::err_no_matching_local_friend_suggest
8689                           : diag::err_member_decl_does_not_match_suggest)
8690             << Name << NewDC << IsDefinition);
8691       return Result;
8692     }
8693 
8694     // Pretend the typo correction never occurred
8695     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8696                               ExtraArgs.D.getIdentifierLoc());
8697     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8698     Previous.clear();
8699     Previous.setLookupName(Name);
8700   }
8701 
8702   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8703       << Name << NewDC << IsDefinition << NewFD->getLocation();
8704 
8705   bool NewFDisConst = false;
8706   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8707     NewFDisConst = NewMD->isConst();
8708 
8709   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8710        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8711        NearMatch != NearMatchEnd; ++NearMatch) {
8712     FunctionDecl *FD = NearMatch->first;
8713     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8714     bool FDisConst = MD && MD->isConst();
8715     bool IsMember = MD || !IsLocalFriend;
8716 
8717     // FIXME: These notes are poorly worded for the local friend case.
8718     if (unsigned Idx = NearMatch->second) {
8719       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8720       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8721       if (Loc.isInvalid()) Loc = FD->getLocation();
8722       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8723                                  : diag::note_local_decl_close_param_match)
8724         << Idx << FDParam->getType()
8725         << NewFD->getParamDecl(Idx - 1)->getType();
8726     } else if (FDisConst != NewFDisConst) {
8727       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8728           << NewFDisConst << FD->getSourceRange().getEnd()
8729           << (NewFDisConst
8730                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8731                                                  .getConstQualifierLoc())
8732                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8733                                                    .getRParenLoc()
8734                                                    .getLocWithOffset(1),
8735                                                " const"));
8736     } else
8737       SemaRef.Diag(FD->getLocation(),
8738                    IsMember ? diag::note_member_def_close_match
8739                             : diag::note_local_decl_close_match);
8740   }
8741   return nullptr;
8742 }
8743 
8744 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8745   switch (D.getDeclSpec().getStorageClassSpec()) {
8746   default: llvm_unreachable("Unknown storage class!");
8747   case DeclSpec::SCS_auto:
8748   case DeclSpec::SCS_register:
8749   case DeclSpec::SCS_mutable:
8750     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8751                  diag::err_typecheck_sclass_func);
8752     D.getMutableDeclSpec().ClearStorageClassSpecs();
8753     D.setInvalidType();
8754     break;
8755   case DeclSpec::SCS_unspecified: break;
8756   case DeclSpec::SCS_extern:
8757     if (D.getDeclSpec().isExternInLinkageSpec())
8758       return SC_None;
8759     return SC_Extern;
8760   case DeclSpec::SCS_static: {
8761     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8762       // C99 6.7.1p5:
8763       //   The declaration of an identifier for a function that has
8764       //   block scope shall have no explicit storage-class specifier
8765       //   other than extern
8766       // See also (C++ [dcl.stc]p4).
8767       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8768                    diag::err_static_block_func);
8769       break;
8770     } else
8771       return SC_Static;
8772   }
8773   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8774   }
8775 
8776   // No explicit storage class has already been returned
8777   return SC_None;
8778 }
8779 
8780 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8781                                            DeclContext *DC, QualType &R,
8782                                            TypeSourceInfo *TInfo,
8783                                            StorageClass SC,
8784                                            bool &IsVirtualOkay) {
8785   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8786   DeclarationName Name = NameInfo.getName();
8787 
8788   FunctionDecl *NewFD = nullptr;
8789   bool isInline = D.getDeclSpec().isInlineSpecified();
8790 
8791   if (!SemaRef.getLangOpts().CPlusPlus) {
8792     // Determine whether the function was written with a
8793     // prototype. This true when:
8794     //   - there is a prototype in the declarator, or
8795     //   - the type R of the function is some kind of typedef or other non-
8796     //     attributed reference to a type name (which eventually refers to a
8797     //     function type).
8798     bool HasPrototype =
8799       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8800       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8801 
8802     NewFD = FunctionDecl::Create(
8803         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8804         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8805         ConstexprSpecKind::Unspecified,
8806         /*TrailingRequiresClause=*/nullptr);
8807     if (D.isInvalidType())
8808       NewFD->setInvalidDecl();
8809 
8810     return NewFD;
8811   }
8812 
8813   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8814 
8815   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8816   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8817     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8818                  diag::err_constexpr_wrong_decl_kind)
8819         << static_cast<int>(ConstexprKind);
8820     ConstexprKind = ConstexprSpecKind::Unspecified;
8821     D.getMutableDeclSpec().ClearConstexprSpec();
8822   }
8823   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8824 
8825   // Check that the return type is not an abstract class type.
8826   // For record types, this is done by the AbstractClassUsageDiagnoser once
8827   // the class has been completely parsed.
8828   if (!DC->isRecord() &&
8829       SemaRef.RequireNonAbstractType(
8830           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8831           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8832     D.setInvalidType();
8833 
8834   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8835     // This is a C++ constructor declaration.
8836     assert(DC->isRecord() &&
8837            "Constructors can only be declared in a member context");
8838 
8839     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8840     return CXXConstructorDecl::Create(
8841         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8842         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8843         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8844         InheritedConstructor(), TrailingRequiresClause);
8845 
8846   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8847     // This is a C++ destructor declaration.
8848     if (DC->isRecord()) {
8849       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8850       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8851       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8852           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8853           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8854           /*isImplicitlyDeclared=*/false, ConstexprKind,
8855           TrailingRequiresClause);
8856 
8857       // If the destructor needs an implicit exception specification, set it
8858       // now. FIXME: It'd be nice to be able to create the right type to start
8859       // with, but the type needs to reference the destructor declaration.
8860       if (SemaRef.getLangOpts().CPlusPlus11)
8861         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8862 
8863       IsVirtualOkay = true;
8864       return NewDD;
8865 
8866     } else {
8867       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8868       D.setInvalidType();
8869 
8870       // Create a FunctionDecl to satisfy the function definition parsing
8871       // code path.
8872       return FunctionDecl::Create(
8873           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8874           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8875           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8876     }
8877 
8878   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8879     if (!DC->isRecord()) {
8880       SemaRef.Diag(D.getIdentifierLoc(),
8881            diag::err_conv_function_not_member);
8882       return nullptr;
8883     }
8884 
8885     SemaRef.CheckConversionDeclarator(D, R, SC);
8886     if (D.isInvalidType())
8887       return nullptr;
8888 
8889     IsVirtualOkay = true;
8890     return CXXConversionDecl::Create(
8891         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8892         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8893         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8894         TrailingRequiresClause);
8895 
8896   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8897     if (TrailingRequiresClause)
8898       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8899                    diag::err_trailing_requires_clause_on_deduction_guide)
8900           << TrailingRequiresClause->getSourceRange();
8901     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8902 
8903     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8904                                          ExplicitSpecifier, NameInfo, R, TInfo,
8905                                          D.getEndLoc());
8906   } else if (DC->isRecord()) {
8907     // If the name of the function is the same as the name of the record,
8908     // then this must be an invalid constructor that has a return type.
8909     // (The parser checks for a return type and makes the declarator a
8910     // constructor if it has no return type).
8911     if (Name.getAsIdentifierInfo() &&
8912         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8913       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8914         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8915         << SourceRange(D.getIdentifierLoc());
8916       return nullptr;
8917     }
8918 
8919     // This is a C++ method declaration.
8920     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8921         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8922         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8923         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8924     IsVirtualOkay = !Ret->isStatic();
8925     return Ret;
8926   } else {
8927     bool isFriend =
8928         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8929     if (!isFriend && SemaRef.CurContext->isRecord())
8930       return nullptr;
8931 
8932     // Determine whether the function was written with a
8933     // prototype. This true when:
8934     //   - we're in C++ (where every function has a prototype),
8935     return FunctionDecl::Create(
8936         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8937         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8938         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8939   }
8940 }
8941 
8942 enum OpenCLParamType {
8943   ValidKernelParam,
8944   PtrPtrKernelParam,
8945   PtrKernelParam,
8946   InvalidAddrSpacePtrKernelParam,
8947   InvalidKernelParam,
8948   RecordKernelParam
8949 };
8950 
8951 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8952   // Size dependent types are just typedefs to normal integer types
8953   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8954   // integers other than by their names.
8955   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8956 
8957   // Remove typedefs one by one until we reach a typedef
8958   // for a size dependent type.
8959   QualType DesugaredTy = Ty;
8960   do {
8961     ArrayRef<StringRef> Names(SizeTypeNames);
8962     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8963     if (Names.end() != Match)
8964       return true;
8965 
8966     Ty = DesugaredTy;
8967     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8968   } while (DesugaredTy != Ty);
8969 
8970   return false;
8971 }
8972 
8973 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8974   if (PT->isDependentType())
8975     return InvalidKernelParam;
8976 
8977   if (PT->isPointerType() || PT->isReferenceType()) {
8978     QualType PointeeType = PT->getPointeeType();
8979     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8980         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8981         PointeeType.getAddressSpace() == LangAS::Default)
8982       return InvalidAddrSpacePtrKernelParam;
8983 
8984     if (PointeeType->isPointerType()) {
8985       // This is a pointer to pointer parameter.
8986       // Recursively check inner type.
8987       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8988       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8989           ParamKind == InvalidKernelParam)
8990         return ParamKind;
8991 
8992       return PtrPtrKernelParam;
8993     }
8994 
8995     // C++ for OpenCL v1.0 s2.4:
8996     // Moreover the types used in parameters of the kernel functions must be:
8997     // Standard layout types for pointer parameters. The same applies to
8998     // reference if an implementation supports them in kernel parameters.
8999     if (S.getLangOpts().OpenCLCPlusPlus &&
9000         !S.getOpenCLOptions().isAvailableOption(
9001             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9002         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9003         !PointeeType->isStandardLayoutType())
9004       return InvalidKernelParam;
9005 
9006     return PtrKernelParam;
9007   }
9008 
9009   // OpenCL v1.2 s6.9.k:
9010   // Arguments to kernel functions in a program cannot be declared with the
9011   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9012   // uintptr_t or a struct and/or union that contain fields declared to be one
9013   // of these built-in scalar types.
9014   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9015     return InvalidKernelParam;
9016 
9017   if (PT->isImageType())
9018     return PtrKernelParam;
9019 
9020   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9021     return InvalidKernelParam;
9022 
9023   // OpenCL extension spec v1.2 s9.5:
9024   // This extension adds support for half scalar and vector types as built-in
9025   // types that can be used for arithmetic operations, conversions etc.
9026   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9027       PT->isHalfType())
9028     return InvalidKernelParam;
9029 
9030   // Look into an array argument to check if it has a forbidden type.
9031   if (PT->isArrayType()) {
9032     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9033     // Call ourself to check an underlying type of an array. Since the
9034     // getPointeeOrArrayElementType returns an innermost type which is not an
9035     // array, this recursive call only happens once.
9036     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9037   }
9038 
9039   // C++ for OpenCL v1.0 s2.4:
9040   // Moreover the types used in parameters of the kernel functions must be:
9041   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9042   // types) for parameters passed by value;
9043   if (S.getLangOpts().OpenCLCPlusPlus &&
9044       !S.getOpenCLOptions().isAvailableOption(
9045           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9046       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9047     return InvalidKernelParam;
9048 
9049   if (PT->isRecordType())
9050     return RecordKernelParam;
9051 
9052   return ValidKernelParam;
9053 }
9054 
9055 static void checkIsValidOpenCLKernelParameter(
9056   Sema &S,
9057   Declarator &D,
9058   ParmVarDecl *Param,
9059   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9060   QualType PT = Param->getType();
9061 
9062   // Cache the valid types we encounter to avoid rechecking structs that are
9063   // used again
9064   if (ValidTypes.count(PT.getTypePtr()))
9065     return;
9066 
9067   switch (getOpenCLKernelParameterType(S, PT)) {
9068   case PtrPtrKernelParam:
9069     // OpenCL v3.0 s6.11.a:
9070     // A kernel function argument cannot be declared as a pointer to a pointer
9071     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9072     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9073       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9074       D.setInvalidType();
9075       return;
9076     }
9077 
9078     ValidTypes.insert(PT.getTypePtr());
9079     return;
9080 
9081   case InvalidAddrSpacePtrKernelParam:
9082     // OpenCL v1.0 s6.5:
9083     // __kernel function arguments declared to be a pointer of a type can point
9084     // to one of the following address spaces only : __global, __local or
9085     // __constant.
9086     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9087     D.setInvalidType();
9088     return;
9089 
9090     // OpenCL v1.2 s6.9.k:
9091     // Arguments to kernel functions in a program cannot be declared with the
9092     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9093     // uintptr_t or a struct and/or union that contain fields declared to be
9094     // one of these built-in scalar types.
9095 
9096   case InvalidKernelParam:
9097     // OpenCL v1.2 s6.8 n:
9098     // A kernel function argument cannot be declared
9099     // of event_t type.
9100     // Do not diagnose half type since it is diagnosed as invalid argument
9101     // type for any function elsewhere.
9102     if (!PT->isHalfType()) {
9103       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9104 
9105       // Explain what typedefs are involved.
9106       const TypedefType *Typedef = nullptr;
9107       while ((Typedef = PT->getAs<TypedefType>())) {
9108         SourceLocation Loc = Typedef->getDecl()->getLocation();
9109         // SourceLocation may be invalid for a built-in type.
9110         if (Loc.isValid())
9111           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9112         PT = Typedef->desugar();
9113       }
9114     }
9115 
9116     D.setInvalidType();
9117     return;
9118 
9119   case PtrKernelParam:
9120   case ValidKernelParam:
9121     ValidTypes.insert(PT.getTypePtr());
9122     return;
9123 
9124   case RecordKernelParam:
9125     break;
9126   }
9127 
9128   // Track nested structs we will inspect
9129   SmallVector<const Decl *, 4> VisitStack;
9130 
9131   // Track where we are in the nested structs. Items will migrate from
9132   // VisitStack to HistoryStack as we do the DFS for bad field.
9133   SmallVector<const FieldDecl *, 4> HistoryStack;
9134   HistoryStack.push_back(nullptr);
9135 
9136   // At this point we already handled everything except of a RecordType or
9137   // an ArrayType of a RecordType.
9138   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9139   const RecordType *RecTy =
9140       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9141   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9142 
9143   VisitStack.push_back(RecTy->getDecl());
9144   assert(VisitStack.back() && "First decl null?");
9145 
9146   do {
9147     const Decl *Next = VisitStack.pop_back_val();
9148     if (!Next) {
9149       assert(!HistoryStack.empty());
9150       // Found a marker, we have gone up a level
9151       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9152         ValidTypes.insert(Hist->getType().getTypePtr());
9153 
9154       continue;
9155     }
9156 
9157     // Adds everything except the original parameter declaration (which is not a
9158     // field itself) to the history stack.
9159     const RecordDecl *RD;
9160     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9161       HistoryStack.push_back(Field);
9162 
9163       QualType FieldTy = Field->getType();
9164       // Other field types (known to be valid or invalid) are handled while we
9165       // walk around RecordDecl::fields().
9166       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9167              "Unexpected type.");
9168       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9169 
9170       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9171     } else {
9172       RD = cast<RecordDecl>(Next);
9173     }
9174 
9175     // Add a null marker so we know when we've gone back up a level
9176     VisitStack.push_back(nullptr);
9177 
9178     for (const auto *FD : RD->fields()) {
9179       QualType QT = FD->getType();
9180 
9181       if (ValidTypes.count(QT.getTypePtr()))
9182         continue;
9183 
9184       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9185       if (ParamType == ValidKernelParam)
9186         continue;
9187 
9188       if (ParamType == RecordKernelParam) {
9189         VisitStack.push_back(FD);
9190         continue;
9191       }
9192 
9193       // OpenCL v1.2 s6.9.p:
9194       // Arguments to kernel functions that are declared to be a struct or union
9195       // do not allow OpenCL objects to be passed as elements of the struct or
9196       // union.
9197       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9198           ParamType == InvalidAddrSpacePtrKernelParam) {
9199         S.Diag(Param->getLocation(),
9200                diag::err_record_with_pointers_kernel_param)
9201           << PT->isUnionType()
9202           << PT;
9203       } else {
9204         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9205       }
9206 
9207       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9208           << OrigRecDecl->getDeclName();
9209 
9210       // We have an error, now let's go back up through history and show where
9211       // the offending field came from
9212       for (ArrayRef<const FieldDecl *>::const_iterator
9213                I = HistoryStack.begin() + 1,
9214                E = HistoryStack.end();
9215            I != E; ++I) {
9216         const FieldDecl *OuterField = *I;
9217         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9218           << OuterField->getType();
9219       }
9220 
9221       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9222         << QT->isPointerType()
9223         << QT;
9224       D.setInvalidType();
9225       return;
9226     }
9227   } while (!VisitStack.empty());
9228 }
9229 
9230 /// Find the DeclContext in which a tag is implicitly declared if we see an
9231 /// elaborated type specifier in the specified context, and lookup finds
9232 /// nothing.
9233 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9234   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9235     DC = DC->getParent();
9236   return DC;
9237 }
9238 
9239 /// Find the Scope in which a tag is implicitly declared if we see an
9240 /// elaborated type specifier in the specified context, and lookup finds
9241 /// nothing.
9242 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9243   while (S->isClassScope() ||
9244          (LangOpts.CPlusPlus &&
9245           S->isFunctionPrototypeScope()) ||
9246          ((S->getFlags() & Scope::DeclScope) == 0) ||
9247          (S->getEntity() && S->getEntity()->isTransparentContext()))
9248     S = S->getParent();
9249   return S;
9250 }
9251 
9252 NamedDecl*
9253 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9254                               TypeSourceInfo *TInfo, LookupResult &Previous,
9255                               MultiTemplateParamsArg TemplateParamListsRef,
9256                               bool &AddToScope) {
9257   QualType R = TInfo->getType();
9258 
9259   assert(R->isFunctionType());
9260   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9261     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9262 
9263   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9264   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9265   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9266     if (!TemplateParamLists.empty() &&
9267         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9268       TemplateParamLists.back() = Invented;
9269     else
9270       TemplateParamLists.push_back(Invented);
9271   }
9272 
9273   // TODO: consider using NameInfo for diagnostic.
9274   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9275   DeclarationName Name = NameInfo.getName();
9276   StorageClass SC = getFunctionStorageClass(*this, D);
9277 
9278   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9279     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9280          diag::err_invalid_thread)
9281       << DeclSpec::getSpecifierName(TSCS);
9282 
9283   if (D.isFirstDeclarationOfMember())
9284     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9285                            D.getIdentifierLoc());
9286 
9287   bool isFriend = false;
9288   FunctionTemplateDecl *FunctionTemplate = nullptr;
9289   bool isMemberSpecialization = false;
9290   bool isFunctionTemplateSpecialization = false;
9291 
9292   bool isDependentClassScopeExplicitSpecialization = false;
9293   bool HasExplicitTemplateArgs = false;
9294   TemplateArgumentListInfo TemplateArgs;
9295 
9296   bool isVirtualOkay = false;
9297 
9298   DeclContext *OriginalDC = DC;
9299   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9300 
9301   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9302                                               isVirtualOkay);
9303   if (!NewFD) return nullptr;
9304 
9305   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9306     NewFD->setTopLevelDeclInObjCContainer();
9307 
9308   // Set the lexical context. If this is a function-scope declaration, or has a
9309   // C++ scope specifier, or is the object of a friend declaration, the lexical
9310   // context will be different from the semantic context.
9311   NewFD->setLexicalDeclContext(CurContext);
9312 
9313   if (IsLocalExternDecl)
9314     NewFD->setLocalExternDecl();
9315 
9316   if (getLangOpts().CPlusPlus) {
9317     bool isInline = D.getDeclSpec().isInlineSpecified();
9318     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9319     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9320     isFriend = D.getDeclSpec().isFriendSpecified();
9321     if (isFriend && !isInline && D.isFunctionDefinition()) {
9322       // C++ [class.friend]p5
9323       //   A function can be defined in a friend declaration of a
9324       //   class . . . . Such a function is implicitly inline.
9325       NewFD->setImplicitlyInline();
9326     }
9327 
9328     // If this is a method defined in an __interface, and is not a constructor
9329     // or an overloaded operator, then set the pure flag (isVirtual will already
9330     // return true).
9331     if (const CXXRecordDecl *Parent =
9332           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9333       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9334         NewFD->setPure(true);
9335 
9336       // C++ [class.union]p2
9337       //   A union can have member functions, but not virtual functions.
9338       if (isVirtual && Parent->isUnion()) {
9339         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9340         NewFD->setInvalidDecl();
9341       }
9342       if ((Parent->isClass() || Parent->isStruct()) &&
9343           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9344           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9345           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9346         if (auto *Def = Parent->getDefinition())
9347           Def->setInitMethod(true);
9348       }
9349     }
9350 
9351     SetNestedNameSpecifier(*this, NewFD, D);
9352     isMemberSpecialization = false;
9353     isFunctionTemplateSpecialization = false;
9354     if (D.isInvalidType())
9355       NewFD->setInvalidDecl();
9356 
9357     // Match up the template parameter lists with the scope specifier, then
9358     // determine whether we have a template or a template specialization.
9359     bool Invalid = false;
9360     TemplateParameterList *TemplateParams =
9361         MatchTemplateParametersToScopeSpecifier(
9362             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9363             D.getCXXScopeSpec(),
9364             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9365                 ? D.getName().TemplateId
9366                 : nullptr,
9367             TemplateParamLists, isFriend, isMemberSpecialization,
9368             Invalid);
9369     if (TemplateParams) {
9370       // Check that we can declare a template here.
9371       if (CheckTemplateDeclScope(S, TemplateParams))
9372         NewFD->setInvalidDecl();
9373 
9374       if (TemplateParams->size() > 0) {
9375         // This is a function template
9376 
9377         // A destructor cannot be a template.
9378         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9379           Diag(NewFD->getLocation(), diag::err_destructor_template);
9380           NewFD->setInvalidDecl();
9381         }
9382 
9383         // If we're adding a template to a dependent context, we may need to
9384         // rebuilding some of the types used within the template parameter list,
9385         // now that we know what the current instantiation is.
9386         if (DC->isDependentContext()) {
9387           ContextRAII SavedContext(*this, DC);
9388           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9389             Invalid = true;
9390         }
9391 
9392         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9393                                                         NewFD->getLocation(),
9394                                                         Name, TemplateParams,
9395                                                         NewFD);
9396         FunctionTemplate->setLexicalDeclContext(CurContext);
9397         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9398 
9399         // For source fidelity, store the other template param lists.
9400         if (TemplateParamLists.size() > 1) {
9401           NewFD->setTemplateParameterListsInfo(Context,
9402               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9403                   .drop_back(1));
9404         }
9405       } else {
9406         // This is a function template specialization.
9407         isFunctionTemplateSpecialization = true;
9408         // For source fidelity, store all the template param lists.
9409         if (TemplateParamLists.size() > 0)
9410           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9411 
9412         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9413         if (isFriend) {
9414           // We want to remove the "template<>", found here.
9415           SourceRange RemoveRange = TemplateParams->getSourceRange();
9416 
9417           // If we remove the template<> and the name is not a
9418           // template-id, we're actually silently creating a problem:
9419           // the friend declaration will refer to an untemplated decl,
9420           // and clearly the user wants a template specialization.  So
9421           // we need to insert '<>' after the name.
9422           SourceLocation InsertLoc;
9423           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9424             InsertLoc = D.getName().getSourceRange().getEnd();
9425             InsertLoc = getLocForEndOfToken(InsertLoc);
9426           }
9427 
9428           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9429             << Name << RemoveRange
9430             << FixItHint::CreateRemoval(RemoveRange)
9431             << FixItHint::CreateInsertion(InsertLoc, "<>");
9432           Invalid = true;
9433         }
9434       }
9435     } else {
9436       // Check that we can declare a template here.
9437       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9438           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9439         NewFD->setInvalidDecl();
9440 
9441       // All template param lists were matched against the scope specifier:
9442       // this is NOT (an explicit specialization of) a template.
9443       if (TemplateParamLists.size() > 0)
9444         // For source fidelity, store all the template param lists.
9445         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9446     }
9447 
9448     if (Invalid) {
9449       NewFD->setInvalidDecl();
9450       if (FunctionTemplate)
9451         FunctionTemplate->setInvalidDecl();
9452     }
9453 
9454     // C++ [dcl.fct.spec]p5:
9455     //   The virtual specifier shall only be used in declarations of
9456     //   nonstatic class member functions that appear within a
9457     //   member-specification of a class declaration; see 10.3.
9458     //
9459     if (isVirtual && !NewFD->isInvalidDecl()) {
9460       if (!isVirtualOkay) {
9461         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9462              diag::err_virtual_non_function);
9463       } else if (!CurContext->isRecord()) {
9464         // 'virtual' was specified outside of the class.
9465         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9466              diag::err_virtual_out_of_class)
9467           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9468       } else if (NewFD->getDescribedFunctionTemplate()) {
9469         // C++ [temp.mem]p3:
9470         //  A member function template shall not be virtual.
9471         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9472              diag::err_virtual_member_function_template)
9473           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9474       } else {
9475         // Okay: Add virtual to the method.
9476         NewFD->setVirtualAsWritten(true);
9477       }
9478 
9479       if (getLangOpts().CPlusPlus14 &&
9480           NewFD->getReturnType()->isUndeducedType())
9481         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9482     }
9483 
9484     if (getLangOpts().CPlusPlus14 &&
9485         (NewFD->isDependentContext() ||
9486          (isFriend && CurContext->isDependentContext())) &&
9487         NewFD->getReturnType()->isUndeducedType()) {
9488       // If the function template is referenced directly (for instance, as a
9489       // member of the current instantiation), pretend it has a dependent type.
9490       // This is not really justified by the standard, but is the only sane
9491       // thing to do.
9492       // FIXME: For a friend function, we have not marked the function as being
9493       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9494       const FunctionProtoType *FPT =
9495           NewFD->getType()->castAs<FunctionProtoType>();
9496       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9497       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9498                                              FPT->getExtProtoInfo()));
9499     }
9500 
9501     // C++ [dcl.fct.spec]p3:
9502     //  The inline specifier shall not appear on a block scope function
9503     //  declaration.
9504     if (isInline && !NewFD->isInvalidDecl()) {
9505       if (CurContext->isFunctionOrMethod()) {
9506         // 'inline' is not allowed on block scope function declaration.
9507         Diag(D.getDeclSpec().getInlineSpecLoc(),
9508              diag::err_inline_declaration_block_scope) << Name
9509           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9510       }
9511     }
9512 
9513     // C++ [dcl.fct.spec]p6:
9514     //  The explicit specifier shall be used only in the declaration of a
9515     //  constructor or conversion function within its class definition;
9516     //  see 12.3.1 and 12.3.2.
9517     if (hasExplicit && !NewFD->isInvalidDecl() &&
9518         !isa<CXXDeductionGuideDecl>(NewFD)) {
9519       if (!CurContext->isRecord()) {
9520         // 'explicit' was specified outside of the class.
9521         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9522              diag::err_explicit_out_of_class)
9523             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9524       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9525                  !isa<CXXConversionDecl>(NewFD)) {
9526         // 'explicit' was specified on a function that wasn't a constructor
9527         // or conversion function.
9528         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9529              diag::err_explicit_non_ctor_or_conv_function)
9530             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9531       }
9532     }
9533 
9534     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9535     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9536       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9537       // are implicitly inline.
9538       NewFD->setImplicitlyInline();
9539 
9540       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9541       // be either constructors or to return a literal type. Therefore,
9542       // destructors cannot be declared constexpr.
9543       if (isa<CXXDestructorDecl>(NewFD) &&
9544           (!getLangOpts().CPlusPlus20 ||
9545            ConstexprKind == ConstexprSpecKind::Consteval)) {
9546         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9547             << static_cast<int>(ConstexprKind);
9548         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9549                                     ? ConstexprSpecKind::Unspecified
9550                                     : ConstexprSpecKind::Constexpr);
9551       }
9552       // C++20 [dcl.constexpr]p2: An allocation function, or a
9553       // deallocation function shall not be declared with the consteval
9554       // specifier.
9555       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9556           (NewFD->getOverloadedOperator() == OO_New ||
9557            NewFD->getOverloadedOperator() == OO_Array_New ||
9558            NewFD->getOverloadedOperator() == OO_Delete ||
9559            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9560         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9561              diag::err_invalid_consteval_decl_kind)
9562             << NewFD;
9563         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9564       }
9565     }
9566 
9567     // If __module_private__ was specified, mark the function accordingly.
9568     if (D.getDeclSpec().isModulePrivateSpecified()) {
9569       if (isFunctionTemplateSpecialization) {
9570         SourceLocation ModulePrivateLoc
9571           = D.getDeclSpec().getModulePrivateSpecLoc();
9572         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9573           << 0
9574           << FixItHint::CreateRemoval(ModulePrivateLoc);
9575       } else {
9576         NewFD->setModulePrivate();
9577         if (FunctionTemplate)
9578           FunctionTemplate->setModulePrivate();
9579       }
9580     }
9581 
9582     if (isFriend) {
9583       if (FunctionTemplate) {
9584         FunctionTemplate->setObjectOfFriendDecl();
9585         FunctionTemplate->setAccess(AS_public);
9586       }
9587       NewFD->setObjectOfFriendDecl();
9588       NewFD->setAccess(AS_public);
9589     }
9590 
9591     // If a function is defined as defaulted or deleted, mark it as such now.
9592     // We'll do the relevant checks on defaulted / deleted functions later.
9593     switch (D.getFunctionDefinitionKind()) {
9594     case FunctionDefinitionKind::Declaration:
9595     case FunctionDefinitionKind::Definition:
9596       break;
9597 
9598     case FunctionDefinitionKind::Defaulted:
9599       NewFD->setDefaulted();
9600       break;
9601 
9602     case FunctionDefinitionKind::Deleted:
9603       NewFD->setDeletedAsWritten();
9604       break;
9605     }
9606 
9607     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9608         D.isFunctionDefinition()) {
9609       // C++ [class.mfct]p2:
9610       //   A member function may be defined (8.4) in its class definition, in
9611       //   which case it is an inline member function (7.1.2)
9612       NewFD->setImplicitlyInline();
9613     }
9614 
9615     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9616         !CurContext->isRecord()) {
9617       // C++ [class.static]p1:
9618       //   A data or function member of a class may be declared static
9619       //   in a class definition, in which case it is a static member of
9620       //   the class.
9621 
9622       // Complain about the 'static' specifier if it's on an out-of-line
9623       // member function definition.
9624 
9625       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9626       // member function template declaration and class member template
9627       // declaration (MSVC versions before 2015), warn about this.
9628       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9629            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9630              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9631            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9632            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9633         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9634     }
9635 
9636     // C++11 [except.spec]p15:
9637     //   A deallocation function with no exception-specification is treated
9638     //   as if it were specified with noexcept(true).
9639     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9640     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9641          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9642         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9643       NewFD->setType(Context.getFunctionType(
9644           FPT->getReturnType(), FPT->getParamTypes(),
9645           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9646   }
9647 
9648   // Filter out previous declarations that don't match the scope.
9649   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9650                        D.getCXXScopeSpec().isNotEmpty() ||
9651                        isMemberSpecialization ||
9652                        isFunctionTemplateSpecialization);
9653 
9654   // Handle GNU asm-label extension (encoded as an attribute).
9655   if (Expr *E = (Expr*) D.getAsmLabel()) {
9656     // The parser guarantees this is a string.
9657     StringLiteral *SE = cast<StringLiteral>(E);
9658     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9659                                         /*IsLiteralLabel=*/true,
9660                                         SE->getStrTokenLoc(0)));
9661   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9662     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9663       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9664     if (I != ExtnameUndeclaredIdentifiers.end()) {
9665       if (isDeclExternC(NewFD)) {
9666         NewFD->addAttr(I->second);
9667         ExtnameUndeclaredIdentifiers.erase(I);
9668       } else
9669         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9670             << /*Variable*/0 << NewFD;
9671     }
9672   }
9673 
9674   // Copy the parameter declarations from the declarator D to the function
9675   // declaration NewFD, if they are available.  First scavenge them into Params.
9676   SmallVector<ParmVarDecl*, 16> Params;
9677   unsigned FTIIdx;
9678   if (D.isFunctionDeclarator(FTIIdx)) {
9679     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9680 
9681     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9682     // function that takes no arguments, not a function that takes a
9683     // single void argument.
9684     // We let through "const void" here because Sema::GetTypeForDeclarator
9685     // already checks for that case.
9686     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9687       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9688         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9689         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9690         Param->setDeclContext(NewFD);
9691         Params.push_back(Param);
9692 
9693         if (Param->isInvalidDecl())
9694           NewFD->setInvalidDecl();
9695       }
9696     }
9697 
9698     if (!getLangOpts().CPlusPlus) {
9699       // In C, find all the tag declarations from the prototype and move them
9700       // into the function DeclContext. Remove them from the surrounding tag
9701       // injection context of the function, which is typically but not always
9702       // the TU.
9703       DeclContext *PrototypeTagContext =
9704           getTagInjectionContext(NewFD->getLexicalDeclContext());
9705       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9706         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9707 
9708         // We don't want to reparent enumerators. Look at their parent enum
9709         // instead.
9710         if (!TD) {
9711           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9712             TD = cast<EnumDecl>(ECD->getDeclContext());
9713         }
9714         if (!TD)
9715           continue;
9716         DeclContext *TagDC = TD->getLexicalDeclContext();
9717         if (!TagDC->containsDecl(TD))
9718           continue;
9719         TagDC->removeDecl(TD);
9720         TD->setDeclContext(NewFD);
9721         NewFD->addDecl(TD);
9722 
9723         // Preserve the lexical DeclContext if it is not the surrounding tag
9724         // injection context of the FD. In this example, the semantic context of
9725         // E will be f and the lexical context will be S, while both the
9726         // semantic and lexical contexts of S will be f:
9727         //   void f(struct S { enum E { a } f; } s);
9728         if (TagDC != PrototypeTagContext)
9729           TD->setLexicalDeclContext(TagDC);
9730       }
9731     }
9732   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9733     // When we're declaring a function with a typedef, typeof, etc as in the
9734     // following example, we'll need to synthesize (unnamed)
9735     // parameters for use in the declaration.
9736     //
9737     // @code
9738     // typedef void fn(int);
9739     // fn f;
9740     // @endcode
9741 
9742     // Synthesize a parameter for each argument type.
9743     for (const auto &AI : FT->param_types()) {
9744       ParmVarDecl *Param =
9745           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9746       Param->setScopeInfo(0, Params.size());
9747       Params.push_back(Param);
9748     }
9749   } else {
9750     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9751            "Should not need args for typedef of non-prototype fn");
9752   }
9753 
9754   // Finally, we know we have the right number of parameters, install them.
9755   NewFD->setParams(Params);
9756 
9757   if (D.getDeclSpec().isNoreturnSpecified())
9758     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9759                                            D.getDeclSpec().getNoreturnSpecLoc(),
9760                                            AttributeCommonInfo::AS_Keyword));
9761 
9762   // Functions returning a variably modified type violate C99 6.7.5.2p2
9763   // because all functions have linkage.
9764   if (!NewFD->isInvalidDecl() &&
9765       NewFD->getReturnType()->isVariablyModifiedType()) {
9766     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9767     NewFD->setInvalidDecl();
9768   }
9769 
9770   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9771   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9772       !NewFD->hasAttr<SectionAttr>())
9773     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9774         Context, PragmaClangTextSection.SectionName,
9775         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9776 
9777   // Apply an implicit SectionAttr if #pragma code_seg is active.
9778   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9779       !NewFD->hasAttr<SectionAttr>()) {
9780     NewFD->addAttr(SectionAttr::CreateImplicit(
9781         Context, CodeSegStack.CurrentValue->getString(),
9782         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9783         SectionAttr::Declspec_allocate));
9784     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9785                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9786                          ASTContext::PSF_Read,
9787                      NewFD))
9788       NewFD->dropAttr<SectionAttr>();
9789   }
9790 
9791   // Apply an implicit CodeSegAttr from class declspec or
9792   // apply an implicit SectionAttr from #pragma code_seg if active.
9793   if (!NewFD->hasAttr<CodeSegAttr>()) {
9794     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9795                                                                  D.isFunctionDefinition())) {
9796       NewFD->addAttr(SAttr);
9797     }
9798   }
9799 
9800   // Handle attributes.
9801   ProcessDeclAttributes(S, NewFD, D);
9802 
9803   if (getLangOpts().OpenCL) {
9804     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9805     // type declaration will generate a compilation error.
9806     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9807     if (AddressSpace != LangAS::Default) {
9808       Diag(NewFD->getLocation(),
9809            diag::err_opencl_return_value_with_address_space);
9810       NewFD->setInvalidDecl();
9811     }
9812   }
9813 
9814   if (!getLangOpts().CPlusPlus) {
9815     // Perform semantic checking on the function declaration.
9816     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9817       CheckMain(NewFD, D.getDeclSpec());
9818 
9819     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9820       CheckMSVCRTEntryPoint(NewFD);
9821 
9822     if (!NewFD->isInvalidDecl())
9823       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9824                                                   isMemberSpecialization,
9825                                                   D.isFunctionDefinition()));
9826     else if (!Previous.empty())
9827       // Recover gracefully from an invalid redeclaration.
9828       D.setRedeclaration(true);
9829     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9830             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9831            "previous declaration set still overloaded");
9832 
9833     // Diagnose no-prototype function declarations with calling conventions that
9834     // don't support variadic calls. Only do this in C and do it after merging
9835     // possibly prototyped redeclarations.
9836     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9837     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9838       CallingConv CC = FT->getExtInfo().getCC();
9839       if (!supportsVariadicCall(CC)) {
9840         // Windows system headers sometimes accidentally use stdcall without
9841         // (void) parameters, so we relax this to a warning.
9842         int DiagID =
9843             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9844         Diag(NewFD->getLocation(), DiagID)
9845             << FunctionType::getNameForCallConv(CC);
9846       }
9847     }
9848 
9849    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9850        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9851      checkNonTrivialCUnion(NewFD->getReturnType(),
9852                            NewFD->getReturnTypeSourceRange().getBegin(),
9853                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9854   } else {
9855     // C++11 [replacement.functions]p3:
9856     //  The program's definitions shall not be specified as inline.
9857     //
9858     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9859     //
9860     // Suppress the diagnostic if the function is __attribute__((used)), since
9861     // that forces an external definition to be emitted.
9862     if (D.getDeclSpec().isInlineSpecified() &&
9863         NewFD->isReplaceableGlobalAllocationFunction() &&
9864         !NewFD->hasAttr<UsedAttr>())
9865       Diag(D.getDeclSpec().getInlineSpecLoc(),
9866            diag::ext_operator_new_delete_declared_inline)
9867         << NewFD->getDeclName();
9868 
9869     // If the declarator is a template-id, translate the parser's template
9870     // argument list into our AST format.
9871     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9872       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9873       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9874       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9875       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9876                                          TemplateId->NumArgs);
9877       translateTemplateArguments(TemplateArgsPtr,
9878                                  TemplateArgs);
9879 
9880       HasExplicitTemplateArgs = true;
9881 
9882       if (NewFD->isInvalidDecl()) {
9883         HasExplicitTemplateArgs = false;
9884       } else if (FunctionTemplate) {
9885         // Function template with explicit template arguments.
9886         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9887           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9888 
9889         HasExplicitTemplateArgs = false;
9890       } else {
9891         assert((isFunctionTemplateSpecialization ||
9892                 D.getDeclSpec().isFriendSpecified()) &&
9893                "should have a 'template<>' for this decl");
9894         // "friend void foo<>(int);" is an implicit specialization decl.
9895         isFunctionTemplateSpecialization = true;
9896       }
9897     } else if (isFriend && isFunctionTemplateSpecialization) {
9898       // This combination is only possible in a recovery case;  the user
9899       // wrote something like:
9900       //   template <> friend void foo(int);
9901       // which we're recovering from as if the user had written:
9902       //   friend void foo<>(int);
9903       // Go ahead and fake up a template id.
9904       HasExplicitTemplateArgs = true;
9905       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9906       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9907     }
9908 
9909     // We do not add HD attributes to specializations here because
9910     // they may have different constexpr-ness compared to their
9911     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9912     // may end up with different effective targets. Instead, a
9913     // specialization inherits its target attributes from its template
9914     // in the CheckFunctionTemplateSpecialization() call below.
9915     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9916       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9917 
9918     // If it's a friend (and only if it's a friend), it's possible
9919     // that either the specialized function type or the specialized
9920     // template is dependent, and therefore matching will fail.  In
9921     // this case, don't check the specialization yet.
9922     if (isFunctionTemplateSpecialization && isFriend &&
9923         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9924          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9925              TemplateArgs.arguments()))) {
9926       assert(HasExplicitTemplateArgs &&
9927              "friend function specialization without template args");
9928       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9929                                                        Previous))
9930         NewFD->setInvalidDecl();
9931     } else if (isFunctionTemplateSpecialization) {
9932       if (CurContext->isDependentContext() && CurContext->isRecord()
9933           && !isFriend) {
9934         isDependentClassScopeExplicitSpecialization = true;
9935       } else if (!NewFD->isInvalidDecl() &&
9936                  CheckFunctionTemplateSpecialization(
9937                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9938                      Previous))
9939         NewFD->setInvalidDecl();
9940 
9941       // C++ [dcl.stc]p1:
9942       //   A storage-class-specifier shall not be specified in an explicit
9943       //   specialization (14.7.3)
9944       FunctionTemplateSpecializationInfo *Info =
9945           NewFD->getTemplateSpecializationInfo();
9946       if (Info && SC != SC_None) {
9947         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9948           Diag(NewFD->getLocation(),
9949                diag::err_explicit_specialization_inconsistent_storage_class)
9950             << SC
9951             << FixItHint::CreateRemoval(
9952                                       D.getDeclSpec().getStorageClassSpecLoc());
9953 
9954         else
9955           Diag(NewFD->getLocation(),
9956                diag::ext_explicit_specialization_storage_class)
9957             << FixItHint::CreateRemoval(
9958                                       D.getDeclSpec().getStorageClassSpecLoc());
9959       }
9960     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9961       if (CheckMemberSpecialization(NewFD, Previous))
9962           NewFD->setInvalidDecl();
9963     }
9964 
9965     // Perform semantic checking on the function declaration.
9966     if (!isDependentClassScopeExplicitSpecialization) {
9967       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9968         CheckMain(NewFD, D.getDeclSpec());
9969 
9970       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9971         CheckMSVCRTEntryPoint(NewFD);
9972 
9973       if (!NewFD->isInvalidDecl())
9974         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9975                                                     isMemberSpecialization,
9976                                                     D.isFunctionDefinition()));
9977       else if (!Previous.empty())
9978         // Recover gracefully from an invalid redeclaration.
9979         D.setRedeclaration(true);
9980     }
9981 
9982     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9983             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9984            "previous declaration set still overloaded");
9985 
9986     NamedDecl *PrincipalDecl = (FunctionTemplate
9987                                 ? cast<NamedDecl>(FunctionTemplate)
9988                                 : NewFD);
9989 
9990     if (isFriend && NewFD->getPreviousDecl()) {
9991       AccessSpecifier Access = AS_public;
9992       if (!NewFD->isInvalidDecl())
9993         Access = NewFD->getPreviousDecl()->getAccess();
9994 
9995       NewFD->setAccess(Access);
9996       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9997     }
9998 
9999     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10000         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10001       PrincipalDecl->setNonMemberOperator();
10002 
10003     // If we have a function template, check the template parameter
10004     // list. This will check and merge default template arguments.
10005     if (FunctionTemplate) {
10006       FunctionTemplateDecl *PrevTemplate =
10007                                      FunctionTemplate->getPreviousDecl();
10008       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10009                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10010                                     : nullptr,
10011                             D.getDeclSpec().isFriendSpecified()
10012                               ? (D.isFunctionDefinition()
10013                                    ? TPC_FriendFunctionTemplateDefinition
10014                                    : TPC_FriendFunctionTemplate)
10015                               : (D.getCXXScopeSpec().isSet() &&
10016                                  DC && DC->isRecord() &&
10017                                  DC->isDependentContext())
10018                                   ? TPC_ClassTemplateMember
10019                                   : TPC_FunctionTemplate);
10020     }
10021 
10022     if (NewFD->isInvalidDecl()) {
10023       // Ignore all the rest of this.
10024     } else if (!D.isRedeclaration()) {
10025       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10026                                        AddToScope };
10027       // Fake up an access specifier if it's supposed to be a class member.
10028       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10029         NewFD->setAccess(AS_public);
10030 
10031       // Qualified decls generally require a previous declaration.
10032       if (D.getCXXScopeSpec().isSet()) {
10033         // ...with the major exception of templated-scope or
10034         // dependent-scope friend declarations.
10035 
10036         // TODO: we currently also suppress this check in dependent
10037         // contexts because (1) the parameter depth will be off when
10038         // matching friend templates and (2) we might actually be
10039         // selecting a friend based on a dependent factor.  But there
10040         // are situations where these conditions don't apply and we
10041         // can actually do this check immediately.
10042         //
10043         // Unless the scope is dependent, it's always an error if qualified
10044         // redeclaration lookup found nothing at all. Diagnose that now;
10045         // nothing will diagnose that error later.
10046         if (isFriend &&
10047             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10048              (!Previous.empty() && CurContext->isDependentContext()))) {
10049           // ignore these
10050         } else if (NewFD->isCPUDispatchMultiVersion() ||
10051                    NewFD->isCPUSpecificMultiVersion()) {
10052           // ignore this, we allow the redeclaration behavior here to create new
10053           // versions of the function.
10054         } else {
10055           // The user tried to provide an out-of-line definition for a
10056           // function that is a member of a class or namespace, but there
10057           // was no such member function declared (C++ [class.mfct]p2,
10058           // C++ [namespace.memdef]p2). For example:
10059           //
10060           // class X {
10061           //   void f() const;
10062           // };
10063           //
10064           // void X::f() { } // ill-formed
10065           //
10066           // Complain about this problem, and attempt to suggest close
10067           // matches (e.g., those that differ only in cv-qualifiers and
10068           // whether the parameter types are references).
10069 
10070           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10071                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10072             AddToScope = ExtraArgs.AddToScope;
10073             return Result;
10074           }
10075         }
10076 
10077         // Unqualified local friend declarations are required to resolve
10078         // to something.
10079       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10080         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10081                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10082           AddToScope = ExtraArgs.AddToScope;
10083           return Result;
10084         }
10085       }
10086     } else if (!D.isFunctionDefinition() &&
10087                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10088                !isFriend && !isFunctionTemplateSpecialization &&
10089                !isMemberSpecialization) {
10090       // An out-of-line member function declaration must also be a
10091       // definition (C++ [class.mfct]p2).
10092       // Note that this is not the case for explicit specializations of
10093       // function templates or member functions of class templates, per
10094       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10095       // extension for compatibility with old SWIG code which likes to
10096       // generate them.
10097       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10098         << D.getCXXScopeSpec().getRange();
10099     }
10100   }
10101 
10102   // If this is the first declaration of a library builtin function, add
10103   // attributes as appropriate.
10104   if (!D.isRedeclaration() &&
10105       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10106     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10107       if (unsigned BuiltinID = II->getBuiltinID()) {
10108         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10109           // Validate the type matches unless this builtin is specified as
10110           // matching regardless of its declared type.
10111           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10112             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10113           } else {
10114             ASTContext::GetBuiltinTypeError Error;
10115             LookupNecessaryTypesForBuiltin(S, BuiltinID);
10116             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10117 
10118             if (!Error && !BuiltinType.isNull() &&
10119                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10120                     NewFD->getType(), BuiltinType))
10121               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10122           }
10123         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10124                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10125           // FIXME: We should consider this a builtin only in the std namespace.
10126           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10127         }
10128       }
10129     }
10130   }
10131 
10132   ProcessPragmaWeak(S, NewFD);
10133   checkAttributesAfterMerging(*this, *NewFD);
10134 
10135   AddKnownFunctionAttributes(NewFD);
10136 
10137   if (NewFD->hasAttr<OverloadableAttr>() &&
10138       !NewFD->getType()->getAs<FunctionProtoType>()) {
10139     Diag(NewFD->getLocation(),
10140          diag::err_attribute_overloadable_no_prototype)
10141       << NewFD;
10142 
10143     // Turn this into a variadic function with no parameters.
10144     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10145     FunctionProtoType::ExtProtoInfo EPI(
10146         Context.getDefaultCallingConvention(true, false));
10147     EPI.Variadic = true;
10148     EPI.ExtInfo = FT->getExtInfo();
10149 
10150     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10151     NewFD->setType(R);
10152   }
10153 
10154   // If there's a #pragma GCC visibility in scope, and this isn't a class
10155   // member, set the visibility of this function.
10156   if (!DC->isRecord() && NewFD->isExternallyVisible())
10157     AddPushedVisibilityAttribute(NewFD);
10158 
10159   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10160   // marking the function.
10161   AddCFAuditedAttribute(NewFD);
10162 
10163   // If this is a function definition, check if we have to apply optnone due to
10164   // a pragma.
10165   if(D.isFunctionDefinition())
10166     AddRangeBasedOptnone(NewFD);
10167 
10168   // If this is the first declaration of an extern C variable, update
10169   // the map of such variables.
10170   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10171       isIncompleteDeclExternC(*this, NewFD))
10172     RegisterLocallyScopedExternCDecl(NewFD, S);
10173 
10174   // Set this FunctionDecl's range up to the right paren.
10175   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10176 
10177   if (D.isRedeclaration() && !Previous.empty()) {
10178     NamedDecl *Prev = Previous.getRepresentativeDecl();
10179     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10180                                    isMemberSpecialization ||
10181                                        isFunctionTemplateSpecialization,
10182                                    D.isFunctionDefinition());
10183   }
10184 
10185   if (getLangOpts().CUDA) {
10186     IdentifierInfo *II = NewFD->getIdentifier();
10187     if (II && II->isStr(getCudaConfigureFuncName()) &&
10188         !NewFD->isInvalidDecl() &&
10189         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10190       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10191         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10192             << getCudaConfigureFuncName();
10193       Context.setcudaConfigureCallDecl(NewFD);
10194     }
10195 
10196     // Variadic functions, other than a *declaration* of printf, are not allowed
10197     // in device-side CUDA code, unless someone passed
10198     // -fcuda-allow-variadic-functions.
10199     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10200         (NewFD->hasAttr<CUDADeviceAttr>() ||
10201          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10202         !(II && II->isStr("printf") && NewFD->isExternC() &&
10203           !D.isFunctionDefinition())) {
10204       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10205     }
10206   }
10207 
10208   MarkUnusedFileScopedDecl(NewFD);
10209 
10210 
10211 
10212   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10213     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10214     if (SC == SC_Static) {
10215       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10216       D.setInvalidType();
10217     }
10218 
10219     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10220     if (!NewFD->getReturnType()->isVoidType()) {
10221       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10222       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10223           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10224                                 : FixItHint());
10225       D.setInvalidType();
10226     }
10227 
10228     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10229     for (auto Param : NewFD->parameters())
10230       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10231 
10232     if (getLangOpts().OpenCLCPlusPlus) {
10233       if (DC->isRecord()) {
10234         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10235         D.setInvalidType();
10236       }
10237       if (FunctionTemplate) {
10238         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10239         D.setInvalidType();
10240       }
10241     }
10242   }
10243 
10244   if (getLangOpts().CPlusPlus) {
10245     if (FunctionTemplate) {
10246       if (NewFD->isInvalidDecl())
10247         FunctionTemplate->setInvalidDecl();
10248       return FunctionTemplate;
10249     }
10250 
10251     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10252       CompleteMemberSpecialization(NewFD, Previous);
10253   }
10254 
10255   for (const ParmVarDecl *Param : NewFD->parameters()) {
10256     QualType PT = Param->getType();
10257 
10258     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10259     // types.
10260     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10261       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10262         QualType ElemTy = PipeTy->getElementType();
10263           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10264             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10265             D.setInvalidType();
10266           }
10267       }
10268     }
10269   }
10270 
10271   // Here we have an function template explicit specialization at class scope.
10272   // The actual specialization will be postponed to template instatiation
10273   // time via the ClassScopeFunctionSpecializationDecl node.
10274   if (isDependentClassScopeExplicitSpecialization) {
10275     ClassScopeFunctionSpecializationDecl *NewSpec =
10276                          ClassScopeFunctionSpecializationDecl::Create(
10277                                 Context, CurContext, NewFD->getLocation(),
10278                                 cast<CXXMethodDecl>(NewFD),
10279                                 HasExplicitTemplateArgs, TemplateArgs);
10280     CurContext->addDecl(NewSpec);
10281     AddToScope = false;
10282   }
10283 
10284   // Diagnose availability attributes. Availability cannot be used on functions
10285   // that are run during load/unload.
10286   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10287     if (NewFD->hasAttr<ConstructorAttr>()) {
10288       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10289           << 1;
10290       NewFD->dropAttr<AvailabilityAttr>();
10291     }
10292     if (NewFD->hasAttr<DestructorAttr>()) {
10293       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10294           << 2;
10295       NewFD->dropAttr<AvailabilityAttr>();
10296     }
10297   }
10298 
10299   // Diagnose no_builtin attribute on function declaration that are not a
10300   // definition.
10301   // FIXME: We should really be doing this in
10302   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10303   // the FunctionDecl and at this point of the code
10304   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10305   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10306   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10307     switch (D.getFunctionDefinitionKind()) {
10308     case FunctionDefinitionKind::Defaulted:
10309     case FunctionDefinitionKind::Deleted:
10310       Diag(NBA->getLocation(),
10311            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10312           << NBA->getSpelling();
10313       break;
10314     case FunctionDefinitionKind::Declaration:
10315       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10316           << NBA->getSpelling();
10317       break;
10318     case FunctionDefinitionKind::Definition:
10319       break;
10320     }
10321 
10322   return NewFD;
10323 }
10324 
10325 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10326 /// when __declspec(code_seg) "is applied to a class, all member functions of
10327 /// the class and nested classes -- this includes compiler-generated special
10328 /// member functions -- are put in the specified segment."
10329 /// The actual behavior is a little more complicated. The Microsoft compiler
10330 /// won't check outer classes if there is an active value from #pragma code_seg.
10331 /// The CodeSeg is always applied from the direct parent but only from outer
10332 /// classes when the #pragma code_seg stack is empty. See:
10333 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10334 /// available since MS has removed the page.
10335 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10336   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10337   if (!Method)
10338     return nullptr;
10339   const CXXRecordDecl *Parent = Method->getParent();
10340   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10341     Attr *NewAttr = SAttr->clone(S.getASTContext());
10342     NewAttr->setImplicit(true);
10343     return NewAttr;
10344   }
10345 
10346   // The Microsoft compiler won't check outer classes for the CodeSeg
10347   // when the #pragma code_seg stack is active.
10348   if (S.CodeSegStack.CurrentValue)
10349    return nullptr;
10350 
10351   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10352     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10353       Attr *NewAttr = SAttr->clone(S.getASTContext());
10354       NewAttr->setImplicit(true);
10355       return NewAttr;
10356     }
10357   }
10358   return nullptr;
10359 }
10360 
10361 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10362 /// containing class. Otherwise it will return implicit SectionAttr if the
10363 /// function is a definition and there is an active value on CodeSegStack
10364 /// (from the current #pragma code-seg value).
10365 ///
10366 /// \param FD Function being declared.
10367 /// \param IsDefinition Whether it is a definition or just a declarartion.
10368 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10369 ///          nullptr if no attribute should be added.
10370 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10371                                                        bool IsDefinition) {
10372   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10373     return A;
10374   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10375       CodeSegStack.CurrentValue)
10376     return SectionAttr::CreateImplicit(
10377         getASTContext(), CodeSegStack.CurrentValue->getString(),
10378         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10379         SectionAttr::Declspec_allocate);
10380   return nullptr;
10381 }
10382 
10383 /// Determines if we can perform a correct type check for \p D as a
10384 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10385 /// best-effort check.
10386 ///
10387 /// \param NewD The new declaration.
10388 /// \param OldD The old declaration.
10389 /// \param NewT The portion of the type of the new declaration to check.
10390 /// \param OldT The portion of the type of the old declaration to check.
10391 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10392                                           QualType NewT, QualType OldT) {
10393   if (!NewD->getLexicalDeclContext()->isDependentContext())
10394     return true;
10395 
10396   // For dependently-typed local extern declarations and friends, we can't
10397   // perform a correct type check in general until instantiation:
10398   //
10399   //   int f();
10400   //   template<typename T> void g() { T f(); }
10401   //
10402   // (valid if g() is only instantiated with T = int).
10403   if (NewT->isDependentType() &&
10404       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10405     return false;
10406 
10407   // Similarly, if the previous declaration was a dependent local extern
10408   // declaration, we don't really know its type yet.
10409   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10410     return false;
10411 
10412   return true;
10413 }
10414 
10415 /// Checks if the new declaration declared in dependent context must be
10416 /// put in the same redeclaration chain as the specified declaration.
10417 ///
10418 /// \param D Declaration that is checked.
10419 /// \param PrevDecl Previous declaration found with proper lookup method for the
10420 ///                 same declaration name.
10421 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10422 ///          belongs to.
10423 ///
10424 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10425   if (!D->getLexicalDeclContext()->isDependentContext())
10426     return true;
10427 
10428   // Don't chain dependent friend function definitions until instantiation, to
10429   // permit cases like
10430   //
10431   //   void func();
10432   //   template<typename T> class C1 { friend void func() {} };
10433   //   template<typename T> class C2 { friend void func() {} };
10434   //
10435   // ... which is valid if only one of C1 and C2 is ever instantiated.
10436   //
10437   // FIXME: This need only apply to function definitions. For now, we proxy
10438   // this by checking for a file-scope function. We do not want this to apply
10439   // to friend declarations nominating member functions, because that gets in
10440   // the way of access checks.
10441   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10442     return false;
10443 
10444   auto *VD = dyn_cast<ValueDecl>(D);
10445   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10446   return !VD || !PrevVD ||
10447          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10448                                         PrevVD->getType());
10449 }
10450 
10451 /// Check the target attribute of the function for MultiVersion
10452 /// validity.
10453 ///
10454 /// Returns true if there was an error, false otherwise.
10455 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10456   const auto *TA = FD->getAttr<TargetAttr>();
10457   assert(TA && "MultiVersion Candidate requires a target attribute");
10458   ParsedTargetAttr ParseInfo = TA->parse();
10459   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10460   enum ErrType { Feature = 0, Architecture = 1 };
10461 
10462   if (!ParseInfo.Architecture.empty() &&
10463       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10464     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10465         << Architecture << ParseInfo.Architecture;
10466     return true;
10467   }
10468 
10469   for (const auto &Feat : ParseInfo.Features) {
10470     auto BareFeat = StringRef{Feat}.substr(1);
10471     if (Feat[0] == '-') {
10472       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10473           << Feature << ("no-" + BareFeat).str();
10474       return true;
10475     }
10476 
10477     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10478         !TargetInfo.isValidFeatureName(BareFeat)) {
10479       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10480           << Feature << BareFeat;
10481       return true;
10482     }
10483   }
10484   return false;
10485 }
10486 
10487 // Provide a white-list of attributes that are allowed to be combined with
10488 // multiversion functions.
10489 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10490                                            MultiVersionKind MVKind) {
10491   // Note: this list/diagnosis must match the list in
10492   // checkMultiversionAttributesAllSame.
10493   switch (Kind) {
10494   default:
10495     return false;
10496   case attr::Used:
10497     return MVKind == MultiVersionKind::Target;
10498   case attr::NonNull:
10499   case attr::NoThrow:
10500     return true;
10501   }
10502 }
10503 
10504 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10505                                                  const FunctionDecl *FD,
10506                                                  const FunctionDecl *CausedFD,
10507                                                  MultiVersionKind MVKind) {
10508   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10509     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10510         << static_cast<unsigned>(MVKind) << A;
10511     if (CausedFD)
10512       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10513     return true;
10514   };
10515 
10516   for (const Attr *A : FD->attrs()) {
10517     switch (A->getKind()) {
10518     case attr::CPUDispatch:
10519     case attr::CPUSpecific:
10520       if (MVKind != MultiVersionKind::CPUDispatch &&
10521           MVKind != MultiVersionKind::CPUSpecific)
10522         return Diagnose(S, A);
10523       break;
10524     case attr::Target:
10525       if (MVKind != MultiVersionKind::Target)
10526         return Diagnose(S, A);
10527       break;
10528     case attr::TargetClones:
10529       if (MVKind != MultiVersionKind::TargetClones)
10530         return Diagnose(S, A);
10531       break;
10532     default:
10533       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10534         return Diagnose(S, A);
10535       break;
10536     }
10537   }
10538   return false;
10539 }
10540 
10541 bool Sema::areMultiversionVariantFunctionsCompatible(
10542     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10543     const PartialDiagnostic &NoProtoDiagID,
10544     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10545     const PartialDiagnosticAt &NoSupportDiagIDAt,
10546     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10547     bool ConstexprSupported, bool CLinkageMayDiffer) {
10548   enum DoesntSupport {
10549     FuncTemplates = 0,
10550     VirtFuncs = 1,
10551     DeducedReturn = 2,
10552     Constructors = 3,
10553     Destructors = 4,
10554     DeletedFuncs = 5,
10555     DefaultedFuncs = 6,
10556     ConstexprFuncs = 7,
10557     ConstevalFuncs = 8,
10558     Lambda = 9,
10559   };
10560   enum Different {
10561     CallingConv = 0,
10562     ReturnType = 1,
10563     ConstexprSpec = 2,
10564     InlineSpec = 3,
10565     Linkage = 4,
10566     LanguageLinkage = 5,
10567   };
10568 
10569   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10570       !OldFD->getType()->getAs<FunctionProtoType>()) {
10571     Diag(OldFD->getLocation(), NoProtoDiagID);
10572     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10573     return true;
10574   }
10575 
10576   if (NoProtoDiagID.getDiagID() != 0 &&
10577       !NewFD->getType()->getAs<FunctionProtoType>())
10578     return Diag(NewFD->getLocation(), NoProtoDiagID);
10579 
10580   if (!TemplatesSupported &&
10581       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10582     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10583            << FuncTemplates;
10584 
10585   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10586     if (NewCXXFD->isVirtual())
10587       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10588              << VirtFuncs;
10589 
10590     if (isa<CXXConstructorDecl>(NewCXXFD))
10591       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10592              << Constructors;
10593 
10594     if (isa<CXXDestructorDecl>(NewCXXFD))
10595       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10596              << Destructors;
10597   }
10598 
10599   if (NewFD->isDeleted())
10600     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10601            << DeletedFuncs;
10602 
10603   if (NewFD->isDefaulted())
10604     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10605            << DefaultedFuncs;
10606 
10607   if (!ConstexprSupported && NewFD->isConstexpr())
10608     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10609            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10610 
10611   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10612   const auto *NewType = cast<FunctionType>(NewQType);
10613   QualType NewReturnType = NewType->getReturnType();
10614 
10615   if (NewReturnType->isUndeducedType())
10616     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10617            << DeducedReturn;
10618 
10619   // Ensure the return type is identical.
10620   if (OldFD) {
10621     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10622     const auto *OldType = cast<FunctionType>(OldQType);
10623     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10624     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10625 
10626     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10627       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10628 
10629     QualType OldReturnType = OldType->getReturnType();
10630 
10631     if (OldReturnType != NewReturnType)
10632       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10633 
10634     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10635       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10636 
10637     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10638       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10639 
10640     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10641       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10642 
10643     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10644       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10645 
10646     if (CheckEquivalentExceptionSpec(
10647             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10648             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10649       return true;
10650   }
10651   return false;
10652 }
10653 
10654 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10655                                              const FunctionDecl *NewFD,
10656                                              bool CausesMV,
10657                                              MultiVersionKind MVKind) {
10658   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10659     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10660     if (OldFD)
10661       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10662     return true;
10663   }
10664 
10665   bool IsCPUSpecificCPUDispatchMVKind =
10666       MVKind == MultiVersionKind::CPUDispatch ||
10667       MVKind == MultiVersionKind::CPUSpecific;
10668 
10669   if (CausesMV && OldFD &&
10670       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10671     return true;
10672 
10673   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10674     return true;
10675 
10676   // Only allow transition to MultiVersion if it hasn't been used.
10677   if (OldFD && CausesMV && OldFD->isUsed(false))
10678     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10679 
10680   return S.areMultiversionVariantFunctionsCompatible(
10681       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10682       PartialDiagnosticAt(NewFD->getLocation(),
10683                           S.PDiag(diag::note_multiversioning_caused_here)),
10684       PartialDiagnosticAt(NewFD->getLocation(),
10685                           S.PDiag(diag::err_multiversion_doesnt_support)
10686                               << static_cast<unsigned>(MVKind)),
10687       PartialDiagnosticAt(NewFD->getLocation(),
10688                           S.PDiag(diag::err_multiversion_diff)),
10689       /*TemplatesSupported=*/false,
10690       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10691       /*CLinkageMayDiffer=*/false);
10692 }
10693 
10694 /// Check the validity of a multiversion function declaration that is the
10695 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10696 ///
10697 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10698 ///
10699 /// Returns true if there was an error, false otherwise.
10700 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10701                                            MultiVersionKind MVKind,
10702                                            const TargetAttr *TA) {
10703   assert(MVKind != MultiVersionKind::None &&
10704          "Function lacks multiversion attribute");
10705 
10706   // Target only causes MV if it is default, otherwise this is a normal
10707   // function.
10708   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10709     return false;
10710 
10711   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10712     FD->setInvalidDecl();
10713     return true;
10714   }
10715 
10716   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10717     FD->setInvalidDecl();
10718     return true;
10719   }
10720 
10721   FD->setIsMultiVersion();
10722   return false;
10723 }
10724 
10725 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10726   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10727     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10728       return true;
10729   }
10730 
10731   return false;
10732 }
10733 
10734 static bool CheckTargetCausesMultiVersioning(
10735     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10736     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10737   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10738   ParsedTargetAttr NewParsed = NewTA->parse();
10739   // Sort order doesn't matter, it just needs to be consistent.
10740   llvm::sort(NewParsed.Features);
10741 
10742   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10743   // to change, this is a simple redeclaration.
10744   if (!NewTA->isDefaultVersion() &&
10745       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10746     return false;
10747 
10748   // Otherwise, this decl causes MultiVersioning.
10749   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10750                                        MultiVersionKind::Target)) {
10751     NewFD->setInvalidDecl();
10752     return true;
10753   }
10754 
10755   if (CheckMultiVersionValue(S, NewFD)) {
10756     NewFD->setInvalidDecl();
10757     return true;
10758   }
10759 
10760   // If this is 'default', permit the forward declaration.
10761   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10762     Redeclaration = true;
10763     OldDecl = OldFD;
10764     OldFD->setIsMultiVersion();
10765     NewFD->setIsMultiVersion();
10766     return false;
10767   }
10768 
10769   if (CheckMultiVersionValue(S, OldFD)) {
10770     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10771     NewFD->setInvalidDecl();
10772     return true;
10773   }
10774 
10775   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10776 
10777   if (OldParsed == NewParsed) {
10778     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10779     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10780     NewFD->setInvalidDecl();
10781     return true;
10782   }
10783 
10784   for (const auto *FD : OldFD->redecls()) {
10785     const auto *CurTA = FD->getAttr<TargetAttr>();
10786     // We allow forward declarations before ANY multiversioning attributes, but
10787     // nothing after the fact.
10788     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10789         (!CurTA || CurTA->isInherited())) {
10790       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10791           << 0;
10792       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10793       NewFD->setInvalidDecl();
10794       return true;
10795     }
10796   }
10797 
10798   OldFD->setIsMultiVersion();
10799   NewFD->setIsMultiVersion();
10800   Redeclaration = false;
10801   OldDecl = nullptr;
10802   Previous.clear();
10803   return false;
10804 }
10805 
10806 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10807                                         MultiVersionKind New) {
10808   if (Old == New || Old == MultiVersionKind::None ||
10809       New == MultiVersionKind::None)
10810     return true;
10811 
10812   return (Old == MultiVersionKind::CPUDispatch &&
10813           New == MultiVersionKind::CPUSpecific) ||
10814          (Old == MultiVersionKind::CPUSpecific &&
10815           New == MultiVersionKind::CPUDispatch);
10816 }
10817 
10818 /// Check the validity of a new function declaration being added to an existing
10819 /// multiversioned declaration collection.
10820 static bool CheckMultiVersionAdditionalDecl(
10821     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10822     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10823     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10824     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10825     LookupResult &Previous) {
10826 
10827   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10828   // Disallow mixing of multiversioning types.
10829   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10830     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10831     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10832     NewFD->setInvalidDecl();
10833     return true;
10834   }
10835 
10836   ParsedTargetAttr NewParsed;
10837   if (NewTA) {
10838     NewParsed = NewTA->parse();
10839     llvm::sort(NewParsed.Features);
10840   }
10841 
10842   bool UseMemberUsingDeclRules =
10843       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10844 
10845   bool MayNeedOverloadableChecks =
10846       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10847 
10848   // Next, check ALL non-overloads to see if this is a redeclaration of a
10849   // previous member of the MultiVersion set.
10850   for (NamedDecl *ND : Previous) {
10851     FunctionDecl *CurFD = ND->getAsFunction();
10852     if (!CurFD)
10853       continue;
10854     if (MayNeedOverloadableChecks &&
10855         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10856       continue;
10857 
10858     switch (NewMVKind) {
10859     case MultiVersionKind::None:
10860       assert(OldMVKind == MultiVersionKind::TargetClones &&
10861              "Only target_clones can be omitted in subsequent declarations");
10862       break;
10863     case MultiVersionKind::Target: {
10864       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10865       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10866         NewFD->setIsMultiVersion();
10867         Redeclaration = true;
10868         OldDecl = ND;
10869         return false;
10870       }
10871 
10872       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10873       if (CurParsed == NewParsed) {
10874         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10875         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10876         NewFD->setInvalidDecl();
10877         return true;
10878       }
10879       break;
10880     }
10881     case MultiVersionKind::TargetClones: {
10882       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10883       Redeclaration = true;
10884       OldDecl = CurFD;
10885       NewFD->setIsMultiVersion();
10886 
10887       if (CurClones && NewClones &&
10888           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10889            !std::equal(CurClones->featuresStrs_begin(),
10890                        CurClones->featuresStrs_end(),
10891                        NewClones->featuresStrs_begin()))) {
10892         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10893         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10894         NewFD->setInvalidDecl();
10895         return true;
10896       }
10897 
10898       return false;
10899     }
10900     case MultiVersionKind::CPUSpecific:
10901     case MultiVersionKind::CPUDispatch: {
10902       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10903       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10904       // Handle CPUDispatch/CPUSpecific versions.
10905       // Only 1 CPUDispatch function is allowed, this will make it go through
10906       // the redeclaration errors.
10907       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10908           CurFD->hasAttr<CPUDispatchAttr>()) {
10909         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10910             std::equal(
10911                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10912                 NewCPUDisp->cpus_begin(),
10913                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10914                   return Cur->getName() == New->getName();
10915                 })) {
10916           NewFD->setIsMultiVersion();
10917           Redeclaration = true;
10918           OldDecl = ND;
10919           return false;
10920         }
10921 
10922         // If the declarations don't match, this is an error condition.
10923         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10924         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10925         NewFD->setInvalidDecl();
10926         return true;
10927       }
10928       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10929         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10930             std::equal(
10931                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10932                 NewCPUSpec->cpus_begin(),
10933                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10934                   return Cur->getName() == New->getName();
10935                 })) {
10936           NewFD->setIsMultiVersion();
10937           Redeclaration = true;
10938           OldDecl = ND;
10939           return false;
10940         }
10941 
10942         // Only 1 version of CPUSpecific is allowed for each CPU.
10943         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10944           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10945             if (CurII == NewII) {
10946               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10947                   << NewII;
10948               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10949               NewFD->setInvalidDecl();
10950               return true;
10951             }
10952           }
10953         }
10954       }
10955       break;
10956     }
10957     }
10958   }
10959 
10960   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10961   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10962   // handled in the attribute adding step.
10963   if (NewMVKind == MultiVersionKind::Target &&
10964       CheckMultiVersionValue(S, NewFD)) {
10965     NewFD->setInvalidDecl();
10966     return true;
10967   }
10968 
10969   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10970                                        !OldFD->isMultiVersion(), NewMVKind)) {
10971     NewFD->setInvalidDecl();
10972     return true;
10973   }
10974 
10975   // Permit forward declarations in the case where these two are compatible.
10976   if (!OldFD->isMultiVersion()) {
10977     OldFD->setIsMultiVersion();
10978     NewFD->setIsMultiVersion();
10979     Redeclaration = true;
10980     OldDecl = OldFD;
10981     return false;
10982   }
10983 
10984   NewFD->setIsMultiVersion();
10985   Redeclaration = false;
10986   OldDecl = nullptr;
10987   Previous.clear();
10988   return false;
10989 }
10990 
10991 /// Check the validity of a mulitversion function declaration.
10992 /// Also sets the multiversion'ness' of the function itself.
10993 ///
10994 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10995 ///
10996 /// Returns true if there was an error, false otherwise.
10997 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10998                                       bool &Redeclaration, NamedDecl *&OldDecl,
10999                                       LookupResult &Previous) {
11000   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11001   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11002   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11003   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11004   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11005 
11006   // Main isn't allowed to become a multiversion function, however it IS
11007   // permitted to have 'main' be marked with the 'target' optimization hint.
11008   if (NewFD->isMain()) {
11009     if (MVKind != MultiVersionKind::None &&
11010         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11011       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11012       NewFD->setInvalidDecl();
11013       return true;
11014     }
11015     return false;
11016   }
11017 
11018   if (!OldDecl || !OldDecl->getAsFunction() ||
11019       OldDecl->getDeclContext()->getRedeclContext() !=
11020           NewFD->getDeclContext()->getRedeclContext()) {
11021     // If there's no previous declaration, AND this isn't attempting to cause
11022     // multiversioning, this isn't an error condition.
11023     if (MVKind == MultiVersionKind::None)
11024       return false;
11025     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11026   }
11027 
11028   FunctionDecl *OldFD = OldDecl->getAsFunction();
11029 
11030   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11031     return false;
11032 
11033   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11034   // for target_clones.
11035   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11036       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11037     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11038         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11039     NewFD->setInvalidDecl();
11040     return true;
11041   }
11042 
11043   if (!OldFD->isMultiVersion()) {
11044     switch (MVKind) {
11045     case MultiVersionKind::Target:
11046       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11047                                               Redeclaration, OldDecl, Previous);
11048     case MultiVersionKind::TargetClones:
11049       if (OldFD->isUsed(false)) {
11050         NewFD->setInvalidDecl();
11051         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11052       }
11053       OldFD->setIsMultiVersion();
11054       break;
11055     case MultiVersionKind::CPUDispatch:
11056     case MultiVersionKind::CPUSpecific:
11057     case MultiVersionKind::None:
11058       break;
11059     }
11060   }
11061 
11062   // At this point, we have a multiversion function decl (in OldFD) AND an
11063   // appropriate attribute in the current function decl.  Resolve that these are
11064   // still compatible with previous declarations.
11065   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11066                                          NewCPUDisp, NewCPUSpec, NewClones,
11067                                          Redeclaration, OldDecl, Previous);
11068 }
11069 
11070 /// Perform semantic checking of a new function declaration.
11071 ///
11072 /// Performs semantic analysis of the new function declaration
11073 /// NewFD. This routine performs all semantic checking that does not
11074 /// require the actual declarator involved in the declaration, and is
11075 /// used both for the declaration of functions as they are parsed
11076 /// (called via ActOnDeclarator) and for the declaration of functions
11077 /// that have been instantiated via C++ template instantiation (called
11078 /// via InstantiateDecl).
11079 ///
11080 /// \param IsMemberSpecialization whether this new function declaration is
11081 /// a member specialization (that replaces any definition provided by the
11082 /// previous declaration).
11083 ///
11084 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11085 ///
11086 /// \returns true if the function declaration is a redeclaration.
11087 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11088                                     LookupResult &Previous,
11089                                     bool IsMemberSpecialization,
11090                                     bool DeclIsDefn) {
11091   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11092          "Variably modified return types are not handled here");
11093 
11094   // Determine whether the type of this function should be merged with
11095   // a previous visible declaration. This never happens for functions in C++,
11096   // and always happens in C if the previous declaration was visible.
11097   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11098                                !Previous.isShadowed();
11099 
11100   bool Redeclaration = false;
11101   NamedDecl *OldDecl = nullptr;
11102   bool MayNeedOverloadableChecks = false;
11103 
11104   // Merge or overload the declaration with an existing declaration of
11105   // the same name, if appropriate.
11106   if (!Previous.empty()) {
11107     // Determine whether NewFD is an overload of PrevDecl or
11108     // a declaration that requires merging. If it's an overload,
11109     // there's no more work to do here; we'll just add the new
11110     // function to the scope.
11111     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11112       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11113       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11114         Redeclaration = true;
11115         OldDecl = Candidate;
11116       }
11117     } else {
11118       MayNeedOverloadableChecks = true;
11119       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11120                             /*NewIsUsingDecl*/ false)) {
11121       case Ovl_Match:
11122         Redeclaration = true;
11123         break;
11124 
11125       case Ovl_NonFunction:
11126         Redeclaration = true;
11127         break;
11128 
11129       case Ovl_Overload:
11130         Redeclaration = false;
11131         break;
11132       }
11133     }
11134   }
11135 
11136   // Check for a previous extern "C" declaration with this name.
11137   if (!Redeclaration &&
11138       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11139     if (!Previous.empty()) {
11140       // This is an extern "C" declaration with the same name as a previous
11141       // declaration, and thus redeclares that entity...
11142       Redeclaration = true;
11143       OldDecl = Previous.getFoundDecl();
11144       MergeTypeWithPrevious = false;
11145 
11146       // ... except in the presence of __attribute__((overloadable)).
11147       if (OldDecl->hasAttr<OverloadableAttr>() ||
11148           NewFD->hasAttr<OverloadableAttr>()) {
11149         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11150           MayNeedOverloadableChecks = true;
11151           Redeclaration = false;
11152           OldDecl = nullptr;
11153         }
11154       }
11155     }
11156   }
11157 
11158   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11159     return Redeclaration;
11160 
11161   // PPC MMA non-pointer types are not allowed as function return types.
11162   if (Context.getTargetInfo().getTriple().isPPC64() &&
11163       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11164     NewFD->setInvalidDecl();
11165   }
11166 
11167   // C++11 [dcl.constexpr]p8:
11168   //   A constexpr specifier for a non-static member function that is not
11169   //   a constructor declares that member function to be const.
11170   //
11171   // This needs to be delayed until we know whether this is an out-of-line
11172   // definition of a static member function.
11173   //
11174   // This rule is not present in C++1y, so we produce a backwards
11175   // compatibility warning whenever it happens in C++11.
11176   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11177   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11178       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11179       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11180     CXXMethodDecl *OldMD = nullptr;
11181     if (OldDecl)
11182       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11183     if (!OldMD || !OldMD->isStatic()) {
11184       const FunctionProtoType *FPT =
11185         MD->getType()->castAs<FunctionProtoType>();
11186       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11187       EPI.TypeQuals.addConst();
11188       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11189                                           FPT->getParamTypes(), EPI));
11190 
11191       // Warn that we did this, if we're not performing template instantiation.
11192       // In that case, we'll have warned already when the template was defined.
11193       if (!inTemplateInstantiation()) {
11194         SourceLocation AddConstLoc;
11195         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11196                 .IgnoreParens().getAs<FunctionTypeLoc>())
11197           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11198 
11199         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11200           << FixItHint::CreateInsertion(AddConstLoc, " const");
11201       }
11202     }
11203   }
11204 
11205   if (Redeclaration) {
11206     // NewFD and OldDecl represent declarations that need to be
11207     // merged.
11208     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11209                           DeclIsDefn)) {
11210       NewFD->setInvalidDecl();
11211       return Redeclaration;
11212     }
11213 
11214     Previous.clear();
11215     Previous.addDecl(OldDecl);
11216 
11217     if (FunctionTemplateDecl *OldTemplateDecl =
11218             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11219       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11220       FunctionTemplateDecl *NewTemplateDecl
11221         = NewFD->getDescribedFunctionTemplate();
11222       assert(NewTemplateDecl && "Template/non-template mismatch");
11223 
11224       // The call to MergeFunctionDecl above may have created some state in
11225       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11226       // can add it as a redeclaration.
11227       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11228 
11229       NewFD->setPreviousDeclaration(OldFD);
11230       if (NewFD->isCXXClassMember()) {
11231         NewFD->setAccess(OldTemplateDecl->getAccess());
11232         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11233       }
11234 
11235       // If this is an explicit specialization of a member that is a function
11236       // template, mark it as a member specialization.
11237       if (IsMemberSpecialization &&
11238           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11239         NewTemplateDecl->setMemberSpecialization();
11240         assert(OldTemplateDecl->isMemberSpecialization());
11241         // Explicit specializations of a member template do not inherit deleted
11242         // status from the parent member template that they are specializing.
11243         if (OldFD->isDeleted()) {
11244           // FIXME: This assert will not hold in the presence of modules.
11245           assert(OldFD->getCanonicalDecl() == OldFD);
11246           // FIXME: We need an update record for this AST mutation.
11247           OldFD->setDeletedAsWritten(false);
11248         }
11249       }
11250 
11251     } else {
11252       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11253         auto *OldFD = cast<FunctionDecl>(OldDecl);
11254         // This needs to happen first so that 'inline' propagates.
11255         NewFD->setPreviousDeclaration(OldFD);
11256         if (NewFD->isCXXClassMember())
11257           NewFD->setAccess(OldFD->getAccess());
11258       }
11259     }
11260   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11261              !NewFD->getAttr<OverloadableAttr>()) {
11262     assert((Previous.empty() ||
11263             llvm::any_of(Previous,
11264                          [](const NamedDecl *ND) {
11265                            return ND->hasAttr<OverloadableAttr>();
11266                          })) &&
11267            "Non-redecls shouldn't happen without overloadable present");
11268 
11269     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11270       const auto *FD = dyn_cast<FunctionDecl>(ND);
11271       return FD && !FD->hasAttr<OverloadableAttr>();
11272     });
11273 
11274     if (OtherUnmarkedIter != Previous.end()) {
11275       Diag(NewFD->getLocation(),
11276            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11277       Diag((*OtherUnmarkedIter)->getLocation(),
11278            diag::note_attribute_overloadable_prev_overload)
11279           << false;
11280 
11281       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11282     }
11283   }
11284 
11285   if (LangOpts.OpenMP)
11286     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11287 
11288   // Semantic checking for this function declaration (in isolation).
11289 
11290   if (getLangOpts().CPlusPlus) {
11291     // C++-specific checks.
11292     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11293       CheckConstructor(Constructor);
11294     } else if (CXXDestructorDecl *Destructor =
11295                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11296       CXXRecordDecl *Record = Destructor->getParent();
11297       QualType ClassType = Context.getTypeDeclType(Record);
11298 
11299       // FIXME: Shouldn't we be able to perform this check even when the class
11300       // type is dependent? Both gcc and edg can handle that.
11301       if (!ClassType->isDependentType()) {
11302         DeclarationName Name
11303           = Context.DeclarationNames.getCXXDestructorName(
11304                                         Context.getCanonicalType(ClassType));
11305         if (NewFD->getDeclName() != Name) {
11306           Diag(NewFD->getLocation(), diag::err_destructor_name);
11307           NewFD->setInvalidDecl();
11308           return Redeclaration;
11309         }
11310       }
11311     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11312       if (auto *TD = Guide->getDescribedFunctionTemplate())
11313         CheckDeductionGuideTemplate(TD);
11314 
11315       // A deduction guide is not on the list of entities that can be
11316       // explicitly specialized.
11317       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11318         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11319             << /*explicit specialization*/ 1;
11320     }
11321 
11322     // Find any virtual functions that this function overrides.
11323     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11324       if (!Method->isFunctionTemplateSpecialization() &&
11325           !Method->getDescribedFunctionTemplate() &&
11326           Method->isCanonicalDecl()) {
11327         AddOverriddenMethods(Method->getParent(), Method);
11328       }
11329       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11330         // C++2a [class.virtual]p6
11331         // A virtual method shall not have a requires-clause.
11332         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11333              diag::err_constrained_virtual_method);
11334 
11335       if (Method->isStatic())
11336         checkThisInStaticMemberFunctionType(Method);
11337     }
11338 
11339     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11340       ActOnConversionDeclarator(Conversion);
11341 
11342     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11343     if (NewFD->isOverloadedOperator() &&
11344         CheckOverloadedOperatorDeclaration(NewFD)) {
11345       NewFD->setInvalidDecl();
11346       return Redeclaration;
11347     }
11348 
11349     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11350     if (NewFD->getLiteralIdentifier() &&
11351         CheckLiteralOperatorDeclaration(NewFD)) {
11352       NewFD->setInvalidDecl();
11353       return Redeclaration;
11354     }
11355 
11356     // In C++, check default arguments now that we have merged decls. Unless
11357     // the lexical context is the class, because in this case this is done
11358     // during delayed parsing anyway.
11359     if (!CurContext->isRecord())
11360       CheckCXXDefaultArguments(NewFD);
11361 
11362     // If this function is declared as being extern "C", then check to see if
11363     // the function returns a UDT (class, struct, or union type) that is not C
11364     // compatible, and if it does, warn the user.
11365     // But, issue any diagnostic on the first declaration only.
11366     if (Previous.empty() && NewFD->isExternC()) {
11367       QualType R = NewFD->getReturnType();
11368       if (R->isIncompleteType() && !R->isVoidType())
11369         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11370             << NewFD << R;
11371       else if (!R.isPODType(Context) && !R->isVoidType() &&
11372                !R->isObjCObjectPointerType())
11373         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11374     }
11375 
11376     // C++1z [dcl.fct]p6:
11377     //   [...] whether the function has a non-throwing exception-specification
11378     //   [is] part of the function type
11379     //
11380     // This results in an ABI break between C++14 and C++17 for functions whose
11381     // declared type includes an exception-specification in a parameter or
11382     // return type. (Exception specifications on the function itself are OK in
11383     // most cases, and exception specifications are not permitted in most other
11384     // contexts where they could make it into a mangling.)
11385     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11386       auto HasNoexcept = [&](QualType T) -> bool {
11387         // Strip off declarator chunks that could be between us and a function
11388         // type. We don't need to look far, exception specifications are very
11389         // restricted prior to C++17.
11390         if (auto *RT = T->getAs<ReferenceType>())
11391           T = RT->getPointeeType();
11392         else if (T->isAnyPointerType())
11393           T = T->getPointeeType();
11394         else if (auto *MPT = T->getAs<MemberPointerType>())
11395           T = MPT->getPointeeType();
11396         if (auto *FPT = T->getAs<FunctionProtoType>())
11397           if (FPT->isNothrow())
11398             return true;
11399         return false;
11400       };
11401 
11402       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11403       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11404       for (QualType T : FPT->param_types())
11405         AnyNoexcept |= HasNoexcept(T);
11406       if (AnyNoexcept)
11407         Diag(NewFD->getLocation(),
11408              diag::warn_cxx17_compat_exception_spec_in_signature)
11409             << NewFD;
11410     }
11411 
11412     if (!Redeclaration && LangOpts.CUDA)
11413       checkCUDATargetOverload(NewFD, Previous);
11414   }
11415   return Redeclaration;
11416 }
11417 
11418 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11419   // C++11 [basic.start.main]p3:
11420   //   A program that [...] declares main to be inline, static or
11421   //   constexpr is ill-formed.
11422   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11423   //   appear in a declaration of main.
11424   // static main is not an error under C99, but we should warn about it.
11425   // We accept _Noreturn main as an extension.
11426   if (FD->getStorageClass() == SC_Static)
11427     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11428          ? diag::err_static_main : diag::warn_static_main)
11429       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11430   if (FD->isInlineSpecified())
11431     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11432       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11433   if (DS.isNoreturnSpecified()) {
11434     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11435     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11436     Diag(NoreturnLoc, diag::ext_noreturn_main);
11437     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11438       << FixItHint::CreateRemoval(NoreturnRange);
11439   }
11440   if (FD->isConstexpr()) {
11441     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11442         << FD->isConsteval()
11443         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11444     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11445   }
11446 
11447   if (getLangOpts().OpenCL) {
11448     Diag(FD->getLocation(), diag::err_opencl_no_main)
11449         << FD->hasAttr<OpenCLKernelAttr>();
11450     FD->setInvalidDecl();
11451     return;
11452   }
11453 
11454   // Functions named main in hlsl are default entries, but don't have specific
11455   // signatures they are required to conform to.
11456   if (getLangOpts().HLSL)
11457     return;
11458 
11459   QualType T = FD->getType();
11460   assert(T->isFunctionType() && "function decl is not of function type");
11461   const FunctionType* FT = T->castAs<FunctionType>();
11462 
11463   // Set default calling convention for main()
11464   if (FT->getCallConv() != CC_C) {
11465     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11466     FD->setType(QualType(FT, 0));
11467     T = Context.getCanonicalType(FD->getType());
11468   }
11469 
11470   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11471     // In C with GNU extensions we allow main() to have non-integer return
11472     // type, but we should warn about the extension, and we disable the
11473     // implicit-return-zero rule.
11474 
11475     // GCC in C mode accepts qualified 'int'.
11476     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11477       FD->setHasImplicitReturnZero(true);
11478     else {
11479       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11480       SourceRange RTRange = FD->getReturnTypeSourceRange();
11481       if (RTRange.isValid())
11482         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11483             << FixItHint::CreateReplacement(RTRange, "int");
11484     }
11485   } else {
11486     // In C and C++, main magically returns 0 if you fall off the end;
11487     // set the flag which tells us that.
11488     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11489 
11490     // All the standards say that main() should return 'int'.
11491     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11492       FD->setHasImplicitReturnZero(true);
11493     else {
11494       // Otherwise, this is just a flat-out error.
11495       SourceRange RTRange = FD->getReturnTypeSourceRange();
11496       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11497           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11498                                 : FixItHint());
11499       FD->setInvalidDecl(true);
11500     }
11501   }
11502 
11503   // Treat protoless main() as nullary.
11504   if (isa<FunctionNoProtoType>(FT)) return;
11505 
11506   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11507   unsigned nparams = FTP->getNumParams();
11508   assert(FD->getNumParams() == nparams);
11509 
11510   bool HasExtraParameters = (nparams > 3);
11511 
11512   if (FTP->isVariadic()) {
11513     Diag(FD->getLocation(), diag::ext_variadic_main);
11514     // FIXME: if we had information about the location of the ellipsis, we
11515     // could add a FixIt hint to remove it as a parameter.
11516   }
11517 
11518   // Darwin passes an undocumented fourth argument of type char**.  If
11519   // other platforms start sprouting these, the logic below will start
11520   // getting shifty.
11521   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11522     HasExtraParameters = false;
11523 
11524   if (HasExtraParameters) {
11525     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11526     FD->setInvalidDecl(true);
11527     nparams = 3;
11528   }
11529 
11530   // FIXME: a lot of the following diagnostics would be improved
11531   // if we had some location information about types.
11532 
11533   QualType CharPP =
11534     Context.getPointerType(Context.getPointerType(Context.CharTy));
11535   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11536 
11537   for (unsigned i = 0; i < nparams; ++i) {
11538     QualType AT = FTP->getParamType(i);
11539 
11540     bool mismatch = true;
11541 
11542     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11543       mismatch = false;
11544     else if (Expected[i] == CharPP) {
11545       // As an extension, the following forms are okay:
11546       //   char const **
11547       //   char const * const *
11548       //   char * const *
11549 
11550       QualifierCollector qs;
11551       const PointerType* PT;
11552       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11553           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11554           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11555                               Context.CharTy)) {
11556         qs.removeConst();
11557         mismatch = !qs.empty();
11558       }
11559     }
11560 
11561     if (mismatch) {
11562       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11563       // TODO: suggest replacing given type with expected type
11564       FD->setInvalidDecl(true);
11565     }
11566   }
11567 
11568   if (nparams == 1 && !FD->isInvalidDecl()) {
11569     Diag(FD->getLocation(), diag::warn_main_one_arg);
11570   }
11571 
11572   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11573     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11574     FD->setInvalidDecl();
11575   }
11576 }
11577 
11578 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11579 
11580   // Default calling convention for main and wmain is __cdecl
11581   if (FD->getName() == "main" || FD->getName() == "wmain")
11582     return false;
11583 
11584   // Default calling convention for MinGW is __cdecl
11585   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11586   if (T.isWindowsGNUEnvironment())
11587     return false;
11588 
11589   // Default calling convention for WinMain, wWinMain and DllMain
11590   // is __stdcall on 32 bit Windows
11591   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11592     return true;
11593 
11594   return false;
11595 }
11596 
11597 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11598   QualType T = FD->getType();
11599   assert(T->isFunctionType() && "function decl is not of function type");
11600   const FunctionType *FT = T->castAs<FunctionType>();
11601 
11602   // Set an implicit return of 'zero' if the function can return some integral,
11603   // enumeration, pointer or nullptr type.
11604   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11605       FT->getReturnType()->isAnyPointerType() ||
11606       FT->getReturnType()->isNullPtrType())
11607     // DllMain is exempt because a return value of zero means it failed.
11608     if (FD->getName() != "DllMain")
11609       FD->setHasImplicitReturnZero(true);
11610 
11611   // Explicity specified calling conventions are applied to MSVC entry points
11612   if (!hasExplicitCallingConv(T)) {
11613     if (isDefaultStdCall(FD, *this)) {
11614       if (FT->getCallConv() != CC_X86StdCall) {
11615         FT = Context.adjustFunctionType(
11616             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11617         FD->setType(QualType(FT, 0));
11618       }
11619     } else if (FT->getCallConv() != CC_C) {
11620       FT = Context.adjustFunctionType(FT,
11621                                       FT->getExtInfo().withCallingConv(CC_C));
11622       FD->setType(QualType(FT, 0));
11623     }
11624   }
11625 
11626   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11627     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11628     FD->setInvalidDecl();
11629   }
11630 }
11631 
11632 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11633   // FIXME: Need strict checking.  In C89, we need to check for
11634   // any assignment, increment, decrement, function-calls, or
11635   // commas outside of a sizeof.  In C99, it's the same list,
11636   // except that the aforementioned are allowed in unevaluated
11637   // expressions.  Everything else falls under the
11638   // "may accept other forms of constant expressions" exception.
11639   //
11640   // Regular C++ code will not end up here (exceptions: language extensions,
11641   // OpenCL C++ etc), so the constant expression rules there don't matter.
11642   if (Init->isValueDependent()) {
11643     assert(Init->containsErrors() &&
11644            "Dependent code should only occur in error-recovery path.");
11645     return true;
11646   }
11647   const Expr *Culprit;
11648   if (Init->isConstantInitializer(Context, false, &Culprit))
11649     return false;
11650   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11651     << Culprit->getSourceRange();
11652   return true;
11653 }
11654 
11655 namespace {
11656   // Visits an initialization expression to see if OrigDecl is evaluated in
11657   // its own initialization and throws a warning if it does.
11658   class SelfReferenceChecker
11659       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11660     Sema &S;
11661     Decl *OrigDecl;
11662     bool isRecordType;
11663     bool isPODType;
11664     bool isReferenceType;
11665 
11666     bool isInitList;
11667     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11668 
11669   public:
11670     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11671 
11672     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11673                                                     S(S), OrigDecl(OrigDecl) {
11674       isPODType = false;
11675       isRecordType = false;
11676       isReferenceType = false;
11677       isInitList = false;
11678       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11679         isPODType = VD->getType().isPODType(S.Context);
11680         isRecordType = VD->getType()->isRecordType();
11681         isReferenceType = VD->getType()->isReferenceType();
11682       }
11683     }
11684 
11685     // For most expressions, just call the visitor.  For initializer lists,
11686     // track the index of the field being initialized since fields are
11687     // initialized in order allowing use of previously initialized fields.
11688     void CheckExpr(Expr *E) {
11689       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11690       if (!InitList) {
11691         Visit(E);
11692         return;
11693       }
11694 
11695       // Track and increment the index here.
11696       isInitList = true;
11697       InitFieldIndex.push_back(0);
11698       for (auto Child : InitList->children()) {
11699         CheckExpr(cast<Expr>(Child));
11700         ++InitFieldIndex.back();
11701       }
11702       InitFieldIndex.pop_back();
11703     }
11704 
11705     // Returns true if MemberExpr is checked and no further checking is needed.
11706     // Returns false if additional checking is required.
11707     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11708       llvm::SmallVector<FieldDecl*, 4> Fields;
11709       Expr *Base = E;
11710       bool ReferenceField = false;
11711 
11712       // Get the field members used.
11713       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11714         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11715         if (!FD)
11716           return false;
11717         Fields.push_back(FD);
11718         if (FD->getType()->isReferenceType())
11719           ReferenceField = true;
11720         Base = ME->getBase()->IgnoreParenImpCasts();
11721       }
11722 
11723       // Keep checking only if the base Decl is the same.
11724       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11725       if (!DRE || DRE->getDecl() != OrigDecl)
11726         return false;
11727 
11728       // A reference field can be bound to an unininitialized field.
11729       if (CheckReference && !ReferenceField)
11730         return true;
11731 
11732       // Convert FieldDecls to their index number.
11733       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11734       for (const FieldDecl *I : llvm::reverse(Fields))
11735         UsedFieldIndex.push_back(I->getFieldIndex());
11736 
11737       // See if a warning is needed by checking the first difference in index
11738       // numbers.  If field being used has index less than the field being
11739       // initialized, then the use is safe.
11740       for (auto UsedIter = UsedFieldIndex.begin(),
11741                 UsedEnd = UsedFieldIndex.end(),
11742                 OrigIter = InitFieldIndex.begin(),
11743                 OrigEnd = InitFieldIndex.end();
11744            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11745         if (*UsedIter < *OrigIter)
11746           return true;
11747         if (*UsedIter > *OrigIter)
11748           break;
11749       }
11750 
11751       // TODO: Add a different warning which will print the field names.
11752       HandleDeclRefExpr(DRE);
11753       return true;
11754     }
11755 
11756     // For most expressions, the cast is directly above the DeclRefExpr.
11757     // For conditional operators, the cast can be outside the conditional
11758     // operator if both expressions are DeclRefExpr's.
11759     void HandleValue(Expr *E) {
11760       E = E->IgnoreParens();
11761       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11762         HandleDeclRefExpr(DRE);
11763         return;
11764       }
11765 
11766       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11767         Visit(CO->getCond());
11768         HandleValue(CO->getTrueExpr());
11769         HandleValue(CO->getFalseExpr());
11770         return;
11771       }
11772 
11773       if (BinaryConditionalOperator *BCO =
11774               dyn_cast<BinaryConditionalOperator>(E)) {
11775         Visit(BCO->getCond());
11776         HandleValue(BCO->getFalseExpr());
11777         return;
11778       }
11779 
11780       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11781         HandleValue(OVE->getSourceExpr());
11782         return;
11783       }
11784 
11785       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11786         if (BO->getOpcode() == BO_Comma) {
11787           Visit(BO->getLHS());
11788           HandleValue(BO->getRHS());
11789           return;
11790         }
11791       }
11792 
11793       if (isa<MemberExpr>(E)) {
11794         if (isInitList) {
11795           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11796                                       false /*CheckReference*/))
11797             return;
11798         }
11799 
11800         Expr *Base = E->IgnoreParenImpCasts();
11801         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11802           // Check for static member variables and don't warn on them.
11803           if (!isa<FieldDecl>(ME->getMemberDecl()))
11804             return;
11805           Base = ME->getBase()->IgnoreParenImpCasts();
11806         }
11807         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11808           HandleDeclRefExpr(DRE);
11809         return;
11810       }
11811 
11812       Visit(E);
11813     }
11814 
11815     // Reference types not handled in HandleValue are handled here since all
11816     // uses of references are bad, not just r-value uses.
11817     void VisitDeclRefExpr(DeclRefExpr *E) {
11818       if (isReferenceType)
11819         HandleDeclRefExpr(E);
11820     }
11821 
11822     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11823       if (E->getCastKind() == CK_LValueToRValue) {
11824         HandleValue(E->getSubExpr());
11825         return;
11826       }
11827 
11828       Inherited::VisitImplicitCastExpr(E);
11829     }
11830 
11831     void VisitMemberExpr(MemberExpr *E) {
11832       if (isInitList) {
11833         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11834           return;
11835       }
11836 
11837       // Don't warn on arrays since they can be treated as pointers.
11838       if (E->getType()->canDecayToPointerType()) return;
11839 
11840       // Warn when a non-static method call is followed by non-static member
11841       // field accesses, which is followed by a DeclRefExpr.
11842       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11843       bool Warn = (MD && !MD->isStatic());
11844       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11845       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11846         if (!isa<FieldDecl>(ME->getMemberDecl()))
11847           Warn = false;
11848         Base = ME->getBase()->IgnoreParenImpCasts();
11849       }
11850 
11851       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11852         if (Warn)
11853           HandleDeclRefExpr(DRE);
11854         return;
11855       }
11856 
11857       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11858       // Visit that expression.
11859       Visit(Base);
11860     }
11861 
11862     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11863       Expr *Callee = E->getCallee();
11864 
11865       if (isa<UnresolvedLookupExpr>(Callee))
11866         return Inherited::VisitCXXOperatorCallExpr(E);
11867 
11868       Visit(Callee);
11869       for (auto Arg: E->arguments())
11870         HandleValue(Arg->IgnoreParenImpCasts());
11871     }
11872 
11873     void VisitUnaryOperator(UnaryOperator *E) {
11874       // For POD record types, addresses of its own members are well-defined.
11875       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11876           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11877         if (!isPODType)
11878           HandleValue(E->getSubExpr());
11879         return;
11880       }
11881 
11882       if (E->isIncrementDecrementOp()) {
11883         HandleValue(E->getSubExpr());
11884         return;
11885       }
11886 
11887       Inherited::VisitUnaryOperator(E);
11888     }
11889 
11890     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11891 
11892     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11893       if (E->getConstructor()->isCopyConstructor()) {
11894         Expr *ArgExpr = E->getArg(0);
11895         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11896           if (ILE->getNumInits() == 1)
11897             ArgExpr = ILE->getInit(0);
11898         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11899           if (ICE->getCastKind() == CK_NoOp)
11900             ArgExpr = ICE->getSubExpr();
11901         HandleValue(ArgExpr);
11902         return;
11903       }
11904       Inherited::VisitCXXConstructExpr(E);
11905     }
11906 
11907     void VisitCallExpr(CallExpr *E) {
11908       // Treat std::move as a use.
11909       if (E->isCallToStdMove()) {
11910         HandleValue(E->getArg(0));
11911         return;
11912       }
11913 
11914       Inherited::VisitCallExpr(E);
11915     }
11916 
11917     void VisitBinaryOperator(BinaryOperator *E) {
11918       if (E->isCompoundAssignmentOp()) {
11919         HandleValue(E->getLHS());
11920         Visit(E->getRHS());
11921         return;
11922       }
11923 
11924       Inherited::VisitBinaryOperator(E);
11925     }
11926 
11927     // A custom visitor for BinaryConditionalOperator is needed because the
11928     // regular visitor would check the condition and true expression separately
11929     // but both point to the same place giving duplicate diagnostics.
11930     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11931       Visit(E->getCond());
11932       Visit(E->getFalseExpr());
11933     }
11934 
11935     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11936       Decl* ReferenceDecl = DRE->getDecl();
11937       if (OrigDecl != ReferenceDecl) return;
11938       unsigned diag;
11939       if (isReferenceType) {
11940         diag = diag::warn_uninit_self_reference_in_reference_init;
11941       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11942         diag = diag::warn_static_self_reference_in_init;
11943       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11944                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11945                  DRE->getDecl()->getType()->isRecordType()) {
11946         diag = diag::warn_uninit_self_reference_in_init;
11947       } else {
11948         // Local variables will be handled by the CFG analysis.
11949         return;
11950       }
11951 
11952       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11953                             S.PDiag(diag)
11954                                 << DRE->getDecl() << OrigDecl->getLocation()
11955                                 << DRE->getSourceRange());
11956     }
11957   };
11958 
11959   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11960   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11961                                  bool DirectInit) {
11962     // Parameters arguments are occassionially constructed with itself,
11963     // for instance, in recursive functions.  Skip them.
11964     if (isa<ParmVarDecl>(OrigDecl))
11965       return;
11966 
11967     E = E->IgnoreParens();
11968 
11969     // Skip checking T a = a where T is not a record or reference type.
11970     // Doing so is a way to silence uninitialized warnings.
11971     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11972       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11973         if (ICE->getCastKind() == CK_LValueToRValue)
11974           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11975             if (DRE->getDecl() == OrigDecl)
11976               return;
11977 
11978     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11979   }
11980 } // end anonymous namespace
11981 
11982 namespace {
11983   // Simple wrapper to add the name of a variable or (if no variable is
11984   // available) a DeclarationName into a diagnostic.
11985   struct VarDeclOrName {
11986     VarDecl *VDecl;
11987     DeclarationName Name;
11988 
11989     friend const Sema::SemaDiagnosticBuilder &
11990     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11991       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11992     }
11993   };
11994 } // end anonymous namespace
11995 
11996 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11997                                             DeclarationName Name, QualType Type,
11998                                             TypeSourceInfo *TSI,
11999                                             SourceRange Range, bool DirectInit,
12000                                             Expr *Init) {
12001   bool IsInitCapture = !VDecl;
12002   assert((!VDecl || !VDecl->isInitCapture()) &&
12003          "init captures are expected to be deduced prior to initialization");
12004 
12005   VarDeclOrName VN{VDecl, Name};
12006 
12007   DeducedType *Deduced = Type->getContainedDeducedType();
12008   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12009 
12010   // C++11 [dcl.spec.auto]p3
12011   if (!Init) {
12012     assert(VDecl && "no init for init capture deduction?");
12013 
12014     // Except for class argument deduction, and then for an initializing
12015     // declaration only, i.e. no static at class scope or extern.
12016     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12017         VDecl->hasExternalStorage() ||
12018         VDecl->isStaticDataMember()) {
12019       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12020         << VDecl->getDeclName() << Type;
12021       return QualType();
12022     }
12023   }
12024 
12025   ArrayRef<Expr*> DeduceInits;
12026   if (Init)
12027     DeduceInits = Init;
12028 
12029   if (DirectInit) {
12030     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12031       DeduceInits = PL->exprs();
12032   }
12033 
12034   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12035     assert(VDecl && "non-auto type for init capture deduction?");
12036     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12037     InitializationKind Kind = InitializationKind::CreateForInit(
12038         VDecl->getLocation(), DirectInit, Init);
12039     // FIXME: Initialization should not be taking a mutable list of inits.
12040     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12041     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12042                                                        InitsCopy);
12043   }
12044 
12045   if (DirectInit) {
12046     if (auto *IL = dyn_cast<InitListExpr>(Init))
12047       DeduceInits = IL->inits();
12048   }
12049 
12050   // Deduction only works if we have exactly one source expression.
12051   if (DeduceInits.empty()) {
12052     // It isn't possible to write this directly, but it is possible to
12053     // end up in this situation with "auto x(some_pack...);"
12054     Diag(Init->getBeginLoc(), IsInitCapture
12055                                   ? diag::err_init_capture_no_expression
12056                                   : diag::err_auto_var_init_no_expression)
12057         << VN << Type << Range;
12058     return QualType();
12059   }
12060 
12061   if (DeduceInits.size() > 1) {
12062     Diag(DeduceInits[1]->getBeginLoc(),
12063          IsInitCapture ? diag::err_init_capture_multiple_expressions
12064                        : diag::err_auto_var_init_multiple_expressions)
12065         << VN << Type << Range;
12066     return QualType();
12067   }
12068 
12069   Expr *DeduceInit = DeduceInits[0];
12070   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12071     Diag(Init->getBeginLoc(), IsInitCapture
12072                                   ? diag::err_init_capture_paren_braces
12073                                   : diag::err_auto_var_init_paren_braces)
12074         << isa<InitListExpr>(Init) << VN << Type << Range;
12075     return QualType();
12076   }
12077 
12078   // Expressions default to 'id' when we're in a debugger.
12079   bool DefaultedAnyToId = false;
12080   if (getLangOpts().DebuggerCastResultToId &&
12081       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12082     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12083     if (Result.isInvalid()) {
12084       return QualType();
12085     }
12086     Init = Result.get();
12087     DefaultedAnyToId = true;
12088   }
12089 
12090   // C++ [dcl.decomp]p1:
12091   //   If the assignment-expression [...] has array type A and no ref-qualifier
12092   //   is present, e has type cv A
12093   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12094       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12095       DeduceInit->getType()->isConstantArrayType())
12096     return Context.getQualifiedType(DeduceInit->getType(),
12097                                     Type.getQualifiers());
12098 
12099   QualType DeducedType;
12100   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12101     if (!IsInitCapture)
12102       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12103     else if (isa<InitListExpr>(Init))
12104       Diag(Range.getBegin(),
12105            diag::err_init_capture_deduction_failure_from_init_list)
12106           << VN
12107           << (DeduceInit->getType().isNull() ? TSI->getType()
12108                                              : DeduceInit->getType())
12109           << DeduceInit->getSourceRange();
12110     else
12111       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12112           << VN << TSI->getType()
12113           << (DeduceInit->getType().isNull() ? TSI->getType()
12114                                              : DeduceInit->getType())
12115           << DeduceInit->getSourceRange();
12116   }
12117 
12118   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12119   // 'id' instead of a specific object type prevents most of our usual
12120   // checks.
12121   // We only want to warn outside of template instantiations, though:
12122   // inside a template, the 'id' could have come from a parameter.
12123   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12124       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12125     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12126     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12127   }
12128 
12129   return DeducedType;
12130 }
12131 
12132 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12133                                          Expr *Init) {
12134   assert(!Init || !Init->containsErrors());
12135   QualType DeducedType = deduceVarTypeFromInitializer(
12136       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12137       VDecl->getSourceRange(), DirectInit, Init);
12138   if (DeducedType.isNull()) {
12139     VDecl->setInvalidDecl();
12140     return true;
12141   }
12142 
12143   VDecl->setType(DeducedType);
12144   assert(VDecl->isLinkageValid());
12145 
12146   // In ARC, infer lifetime.
12147   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12148     VDecl->setInvalidDecl();
12149 
12150   if (getLangOpts().OpenCL)
12151     deduceOpenCLAddressSpace(VDecl);
12152 
12153   // If this is a redeclaration, check that the type we just deduced matches
12154   // the previously declared type.
12155   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12156     // We never need to merge the type, because we cannot form an incomplete
12157     // array of auto, nor deduce such a type.
12158     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12159   }
12160 
12161   // Check the deduced type is valid for a variable declaration.
12162   CheckVariableDeclarationType(VDecl);
12163   return VDecl->isInvalidDecl();
12164 }
12165 
12166 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12167                                               SourceLocation Loc) {
12168   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12169     Init = EWC->getSubExpr();
12170 
12171   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12172     Init = CE->getSubExpr();
12173 
12174   QualType InitType = Init->getType();
12175   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12176           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12177          "shouldn't be called if type doesn't have a non-trivial C struct");
12178   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12179     for (auto I : ILE->inits()) {
12180       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12181           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12182         continue;
12183       SourceLocation SL = I->getExprLoc();
12184       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12185     }
12186     return;
12187   }
12188 
12189   if (isa<ImplicitValueInitExpr>(Init)) {
12190     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12191       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12192                             NTCUK_Init);
12193   } else {
12194     // Assume all other explicit initializers involving copying some existing
12195     // object.
12196     // TODO: ignore any explicit initializers where we can guarantee
12197     // copy-elision.
12198     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12199       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12200   }
12201 }
12202 
12203 namespace {
12204 
12205 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12206   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12207   // in the source code or implicitly by the compiler if it is in a union
12208   // defined in a system header and has non-trivial ObjC ownership
12209   // qualifications. We don't want those fields to participate in determining
12210   // whether the containing union is non-trivial.
12211   return FD->hasAttr<UnavailableAttr>();
12212 }
12213 
12214 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12215     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12216                                     void> {
12217   using Super =
12218       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12219                                     void>;
12220 
12221   DiagNonTrivalCUnionDefaultInitializeVisitor(
12222       QualType OrigTy, SourceLocation OrigLoc,
12223       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12224       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12225 
12226   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12227                      const FieldDecl *FD, bool InNonTrivialUnion) {
12228     if (const auto *AT = S.Context.getAsArrayType(QT))
12229       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12230                                      InNonTrivialUnion);
12231     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12232   }
12233 
12234   void visitARCStrong(QualType QT, const FieldDecl *FD,
12235                       bool InNonTrivialUnion) {
12236     if (InNonTrivialUnion)
12237       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12238           << 1 << 0 << QT << FD->getName();
12239   }
12240 
12241   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12242     if (InNonTrivialUnion)
12243       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12244           << 1 << 0 << QT << FD->getName();
12245   }
12246 
12247   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12248     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12249     if (RD->isUnion()) {
12250       if (OrigLoc.isValid()) {
12251         bool IsUnion = false;
12252         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12253           IsUnion = OrigRD->isUnion();
12254         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12255             << 0 << OrigTy << IsUnion << UseContext;
12256         // Reset OrigLoc so that this diagnostic is emitted only once.
12257         OrigLoc = SourceLocation();
12258       }
12259       InNonTrivialUnion = true;
12260     }
12261 
12262     if (InNonTrivialUnion)
12263       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12264           << 0 << 0 << QT.getUnqualifiedType() << "";
12265 
12266     for (const FieldDecl *FD : RD->fields())
12267       if (!shouldIgnoreForRecordTriviality(FD))
12268         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12269   }
12270 
12271   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12272 
12273   // The non-trivial C union type or the struct/union type that contains a
12274   // non-trivial C union.
12275   QualType OrigTy;
12276   SourceLocation OrigLoc;
12277   Sema::NonTrivialCUnionContext UseContext;
12278   Sema &S;
12279 };
12280 
12281 struct DiagNonTrivalCUnionDestructedTypeVisitor
12282     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12283   using Super =
12284       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12285 
12286   DiagNonTrivalCUnionDestructedTypeVisitor(
12287       QualType OrigTy, SourceLocation OrigLoc,
12288       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12289       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12290 
12291   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12292                      const FieldDecl *FD, bool InNonTrivialUnion) {
12293     if (const auto *AT = S.Context.getAsArrayType(QT))
12294       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12295                                      InNonTrivialUnion);
12296     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12297   }
12298 
12299   void visitARCStrong(QualType QT, const FieldDecl *FD,
12300                       bool InNonTrivialUnion) {
12301     if (InNonTrivialUnion)
12302       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12303           << 1 << 1 << QT << FD->getName();
12304   }
12305 
12306   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12307     if (InNonTrivialUnion)
12308       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12309           << 1 << 1 << QT << FD->getName();
12310   }
12311 
12312   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12313     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12314     if (RD->isUnion()) {
12315       if (OrigLoc.isValid()) {
12316         bool IsUnion = false;
12317         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12318           IsUnion = OrigRD->isUnion();
12319         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12320             << 1 << OrigTy << IsUnion << UseContext;
12321         // Reset OrigLoc so that this diagnostic is emitted only once.
12322         OrigLoc = SourceLocation();
12323       }
12324       InNonTrivialUnion = true;
12325     }
12326 
12327     if (InNonTrivialUnion)
12328       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12329           << 0 << 1 << QT.getUnqualifiedType() << "";
12330 
12331     for (const FieldDecl *FD : RD->fields())
12332       if (!shouldIgnoreForRecordTriviality(FD))
12333         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12334   }
12335 
12336   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12337   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12338                           bool InNonTrivialUnion) {}
12339 
12340   // The non-trivial C union type or the struct/union type that contains a
12341   // non-trivial C union.
12342   QualType OrigTy;
12343   SourceLocation OrigLoc;
12344   Sema::NonTrivialCUnionContext UseContext;
12345   Sema &S;
12346 };
12347 
12348 struct DiagNonTrivalCUnionCopyVisitor
12349     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12350   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12351 
12352   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12353                                  Sema::NonTrivialCUnionContext UseContext,
12354                                  Sema &S)
12355       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12356 
12357   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12358                      const FieldDecl *FD, bool InNonTrivialUnion) {
12359     if (const auto *AT = S.Context.getAsArrayType(QT))
12360       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12361                                      InNonTrivialUnion);
12362     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12363   }
12364 
12365   void visitARCStrong(QualType QT, const FieldDecl *FD,
12366                       bool InNonTrivialUnion) {
12367     if (InNonTrivialUnion)
12368       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12369           << 1 << 2 << QT << FD->getName();
12370   }
12371 
12372   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12373     if (InNonTrivialUnion)
12374       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12375           << 1 << 2 << QT << FD->getName();
12376   }
12377 
12378   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12379     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12380     if (RD->isUnion()) {
12381       if (OrigLoc.isValid()) {
12382         bool IsUnion = false;
12383         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12384           IsUnion = OrigRD->isUnion();
12385         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12386             << 2 << OrigTy << IsUnion << UseContext;
12387         // Reset OrigLoc so that this diagnostic is emitted only once.
12388         OrigLoc = SourceLocation();
12389       }
12390       InNonTrivialUnion = true;
12391     }
12392 
12393     if (InNonTrivialUnion)
12394       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12395           << 0 << 2 << QT.getUnqualifiedType() << "";
12396 
12397     for (const FieldDecl *FD : RD->fields())
12398       if (!shouldIgnoreForRecordTriviality(FD))
12399         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12400   }
12401 
12402   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12403                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12404   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12405   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12406                             bool InNonTrivialUnion) {}
12407 
12408   // The non-trivial C union type or the struct/union type that contains a
12409   // non-trivial C union.
12410   QualType OrigTy;
12411   SourceLocation OrigLoc;
12412   Sema::NonTrivialCUnionContext UseContext;
12413   Sema &S;
12414 };
12415 
12416 } // namespace
12417 
12418 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12419                                  NonTrivialCUnionContext UseContext,
12420                                  unsigned NonTrivialKind) {
12421   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12422           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12423           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12424          "shouldn't be called if type doesn't have a non-trivial C union");
12425 
12426   if ((NonTrivialKind & NTCUK_Init) &&
12427       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12428     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12429         .visit(QT, nullptr, false);
12430   if ((NonTrivialKind & NTCUK_Destruct) &&
12431       QT.hasNonTrivialToPrimitiveDestructCUnion())
12432     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12433         .visit(QT, nullptr, false);
12434   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12435     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12436         .visit(QT, nullptr, false);
12437 }
12438 
12439 /// AddInitializerToDecl - Adds the initializer Init to the
12440 /// declaration dcl. If DirectInit is true, this is C++ direct
12441 /// initialization rather than copy initialization.
12442 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12443   // If there is no declaration, there was an error parsing it.  Just ignore
12444   // the initializer.
12445   if (!RealDecl || RealDecl->isInvalidDecl()) {
12446     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12447     return;
12448   }
12449 
12450   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12451     // Pure-specifiers are handled in ActOnPureSpecifier.
12452     Diag(Method->getLocation(), diag::err_member_function_initialization)
12453       << Method->getDeclName() << Init->getSourceRange();
12454     Method->setInvalidDecl();
12455     return;
12456   }
12457 
12458   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12459   if (!VDecl) {
12460     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12461     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12462     RealDecl->setInvalidDecl();
12463     return;
12464   }
12465 
12466   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12467   if (VDecl->getType()->isUndeducedType()) {
12468     // Attempt typo correction early so that the type of the init expression can
12469     // be deduced based on the chosen correction if the original init contains a
12470     // TypoExpr.
12471     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12472     if (!Res.isUsable()) {
12473       // There are unresolved typos in Init, just drop them.
12474       // FIXME: improve the recovery strategy to preserve the Init.
12475       RealDecl->setInvalidDecl();
12476       return;
12477     }
12478     if (Res.get()->containsErrors()) {
12479       // Invalidate the decl as we don't know the type for recovery-expr yet.
12480       RealDecl->setInvalidDecl();
12481       VDecl->setInit(Res.get());
12482       return;
12483     }
12484     Init = Res.get();
12485 
12486     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12487       return;
12488   }
12489 
12490   // dllimport cannot be used on variable definitions.
12491   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12492     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12493     VDecl->setInvalidDecl();
12494     return;
12495   }
12496 
12497   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12498     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12499     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12500     VDecl->setInvalidDecl();
12501     return;
12502   }
12503 
12504   if (!VDecl->getType()->isDependentType()) {
12505     // A definition must end up with a complete type, which means it must be
12506     // complete with the restriction that an array type might be completed by
12507     // the initializer; note that later code assumes this restriction.
12508     QualType BaseDeclType = VDecl->getType();
12509     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12510       BaseDeclType = Array->getElementType();
12511     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12512                             diag::err_typecheck_decl_incomplete_type)) {
12513       RealDecl->setInvalidDecl();
12514       return;
12515     }
12516 
12517     // The variable can not have an abstract class type.
12518     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12519                                diag::err_abstract_type_in_decl,
12520                                AbstractVariableType))
12521       VDecl->setInvalidDecl();
12522   }
12523 
12524   // If adding the initializer will turn this declaration into a definition,
12525   // and we already have a definition for this variable, diagnose or otherwise
12526   // handle the situation.
12527   if (VarDecl *Def = VDecl->getDefinition())
12528     if (Def != VDecl &&
12529         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12530         !VDecl->isThisDeclarationADemotedDefinition() &&
12531         checkVarDeclRedefinition(Def, VDecl))
12532       return;
12533 
12534   if (getLangOpts().CPlusPlus) {
12535     // C++ [class.static.data]p4
12536     //   If a static data member is of const integral or const
12537     //   enumeration type, its declaration in the class definition can
12538     //   specify a constant-initializer which shall be an integral
12539     //   constant expression (5.19). In that case, the member can appear
12540     //   in integral constant expressions. The member shall still be
12541     //   defined in a namespace scope if it is used in the program and the
12542     //   namespace scope definition shall not contain an initializer.
12543     //
12544     // We already performed a redefinition check above, but for static
12545     // data members we also need to check whether there was an in-class
12546     // declaration with an initializer.
12547     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12548       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12549           << VDecl->getDeclName();
12550       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12551            diag::note_previous_initializer)
12552           << 0;
12553       return;
12554     }
12555 
12556     if (VDecl->hasLocalStorage())
12557       setFunctionHasBranchProtectedScope();
12558 
12559     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12560       VDecl->setInvalidDecl();
12561       return;
12562     }
12563   }
12564 
12565   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12566   // a kernel function cannot be initialized."
12567   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12568     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12569     VDecl->setInvalidDecl();
12570     return;
12571   }
12572 
12573   // The LoaderUninitialized attribute acts as a definition (of undef).
12574   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12575     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12576     VDecl->setInvalidDecl();
12577     return;
12578   }
12579 
12580   // Get the decls type and save a reference for later, since
12581   // CheckInitializerTypes may change it.
12582   QualType DclT = VDecl->getType(), SavT = DclT;
12583 
12584   // Expressions default to 'id' when we're in a debugger
12585   // and we are assigning it to a variable of Objective-C pointer type.
12586   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12587       Init->getType() == Context.UnknownAnyTy) {
12588     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12589     if (Result.isInvalid()) {
12590       VDecl->setInvalidDecl();
12591       return;
12592     }
12593     Init = Result.get();
12594   }
12595 
12596   // Perform the initialization.
12597   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12598   if (!VDecl->isInvalidDecl()) {
12599     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12600     InitializationKind Kind = InitializationKind::CreateForInit(
12601         VDecl->getLocation(), DirectInit, Init);
12602 
12603     MultiExprArg Args = Init;
12604     if (CXXDirectInit)
12605       Args = MultiExprArg(CXXDirectInit->getExprs(),
12606                           CXXDirectInit->getNumExprs());
12607 
12608     // Try to correct any TypoExprs in the initialization arguments.
12609     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12610       ExprResult Res = CorrectDelayedTyposInExpr(
12611           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12612           [this, Entity, Kind](Expr *E) {
12613             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12614             return Init.Failed() ? ExprError() : E;
12615           });
12616       if (Res.isInvalid()) {
12617         VDecl->setInvalidDecl();
12618       } else if (Res.get() != Args[Idx]) {
12619         Args[Idx] = Res.get();
12620       }
12621     }
12622     if (VDecl->isInvalidDecl())
12623       return;
12624 
12625     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12626                                    /*TopLevelOfInitList=*/false,
12627                                    /*TreatUnavailableAsInvalid=*/false);
12628     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12629     if (Result.isInvalid()) {
12630       // If the provided initializer fails to initialize the var decl,
12631       // we attach a recovery expr for better recovery.
12632       auto RecoveryExpr =
12633           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12634       if (RecoveryExpr.get())
12635         VDecl->setInit(RecoveryExpr.get());
12636       return;
12637     }
12638 
12639     Init = Result.getAs<Expr>();
12640   }
12641 
12642   // Check for self-references within variable initializers.
12643   // Variables declared within a function/method body (except for references)
12644   // are handled by a dataflow analysis.
12645   // This is undefined behavior in C++, but valid in C.
12646   if (getLangOpts().CPlusPlus)
12647     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12648         VDecl->getType()->isReferenceType())
12649       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12650 
12651   // If the type changed, it means we had an incomplete type that was
12652   // completed by the initializer. For example:
12653   //   int ary[] = { 1, 3, 5 };
12654   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12655   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12656     VDecl->setType(DclT);
12657 
12658   if (!VDecl->isInvalidDecl()) {
12659     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12660 
12661     if (VDecl->hasAttr<BlocksAttr>())
12662       checkRetainCycles(VDecl, Init);
12663 
12664     // It is safe to assign a weak reference into a strong variable.
12665     // Although this code can still have problems:
12666     //   id x = self.weakProp;
12667     //   id y = self.weakProp;
12668     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12669     // paths through the function. This should be revisited if
12670     // -Wrepeated-use-of-weak is made flow-sensitive.
12671     if (FunctionScopeInfo *FSI = getCurFunction())
12672       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12673            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12674           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12675                            Init->getBeginLoc()))
12676         FSI->markSafeWeakUse(Init);
12677   }
12678 
12679   // The initialization is usually a full-expression.
12680   //
12681   // FIXME: If this is a braced initialization of an aggregate, it is not
12682   // an expression, and each individual field initializer is a separate
12683   // full-expression. For instance, in:
12684   //
12685   //   struct Temp { ~Temp(); };
12686   //   struct S { S(Temp); };
12687   //   struct T { S a, b; } t = { Temp(), Temp() }
12688   //
12689   // we should destroy the first Temp before constructing the second.
12690   ExprResult Result =
12691       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12692                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12693   if (Result.isInvalid()) {
12694     VDecl->setInvalidDecl();
12695     return;
12696   }
12697   Init = Result.get();
12698 
12699   // Attach the initializer to the decl.
12700   VDecl->setInit(Init);
12701 
12702   if (VDecl->isLocalVarDecl()) {
12703     // Don't check the initializer if the declaration is malformed.
12704     if (VDecl->isInvalidDecl()) {
12705       // do nothing
12706 
12707     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12708     // This is true even in C++ for OpenCL.
12709     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12710       CheckForConstantInitializer(Init, DclT);
12711 
12712     // Otherwise, C++ does not restrict the initializer.
12713     } else if (getLangOpts().CPlusPlus) {
12714       // do nothing
12715 
12716     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12717     // static storage duration shall be constant expressions or string literals.
12718     } else if (VDecl->getStorageClass() == SC_Static) {
12719       CheckForConstantInitializer(Init, DclT);
12720 
12721     // C89 is stricter than C99 for aggregate initializers.
12722     // C89 6.5.7p3: All the expressions [...] in an initializer list
12723     // for an object that has aggregate or union type shall be
12724     // constant expressions.
12725     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12726                isa<InitListExpr>(Init)) {
12727       const Expr *Culprit;
12728       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12729         Diag(Culprit->getExprLoc(),
12730              diag::ext_aggregate_init_not_constant)
12731           << Culprit->getSourceRange();
12732       }
12733     }
12734 
12735     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12736       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12737         if (VDecl->hasLocalStorage())
12738           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12739   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12740              VDecl->getLexicalDeclContext()->isRecord()) {
12741     // This is an in-class initialization for a static data member, e.g.,
12742     //
12743     // struct S {
12744     //   static const int value = 17;
12745     // };
12746 
12747     // C++ [class.mem]p4:
12748     //   A member-declarator can contain a constant-initializer only
12749     //   if it declares a static member (9.4) of const integral or
12750     //   const enumeration type, see 9.4.2.
12751     //
12752     // C++11 [class.static.data]p3:
12753     //   If a non-volatile non-inline const static data member is of integral
12754     //   or enumeration type, its declaration in the class definition can
12755     //   specify a brace-or-equal-initializer in which every initializer-clause
12756     //   that is an assignment-expression is a constant expression. A static
12757     //   data member of literal type can be declared in the class definition
12758     //   with the constexpr specifier; if so, its declaration shall specify a
12759     //   brace-or-equal-initializer in which every initializer-clause that is
12760     //   an assignment-expression is a constant expression.
12761 
12762     // Do nothing on dependent types.
12763     if (DclT->isDependentType()) {
12764 
12765     // Allow any 'static constexpr' members, whether or not they are of literal
12766     // type. We separately check that every constexpr variable is of literal
12767     // type.
12768     } else if (VDecl->isConstexpr()) {
12769 
12770     // Require constness.
12771     } else if (!DclT.isConstQualified()) {
12772       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12773         << Init->getSourceRange();
12774       VDecl->setInvalidDecl();
12775 
12776     // We allow integer constant expressions in all cases.
12777     } else if (DclT->isIntegralOrEnumerationType()) {
12778       // Check whether the expression is a constant expression.
12779       SourceLocation Loc;
12780       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12781         // In C++11, a non-constexpr const static data member with an
12782         // in-class initializer cannot be volatile.
12783         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12784       else if (Init->isValueDependent())
12785         ; // Nothing to check.
12786       else if (Init->isIntegerConstantExpr(Context, &Loc))
12787         ; // Ok, it's an ICE!
12788       else if (Init->getType()->isScopedEnumeralType() &&
12789                Init->isCXX11ConstantExpr(Context))
12790         ; // Ok, it is a scoped-enum constant expression.
12791       else if (Init->isEvaluatable(Context)) {
12792         // If we can constant fold the initializer through heroics, accept it,
12793         // but report this as a use of an extension for -pedantic.
12794         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12795           << Init->getSourceRange();
12796       } else {
12797         // Otherwise, this is some crazy unknown case.  Report the issue at the
12798         // location provided by the isIntegerConstantExpr failed check.
12799         Diag(Loc, diag::err_in_class_initializer_non_constant)
12800           << Init->getSourceRange();
12801         VDecl->setInvalidDecl();
12802       }
12803 
12804     // We allow foldable floating-point constants as an extension.
12805     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12806       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12807       // it anyway and provide a fixit to add the 'constexpr'.
12808       if (getLangOpts().CPlusPlus11) {
12809         Diag(VDecl->getLocation(),
12810              diag::ext_in_class_initializer_float_type_cxx11)
12811             << DclT << Init->getSourceRange();
12812         Diag(VDecl->getBeginLoc(),
12813              diag::note_in_class_initializer_float_type_cxx11)
12814             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12815       } else {
12816         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12817           << DclT << Init->getSourceRange();
12818 
12819         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12820           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12821             << Init->getSourceRange();
12822           VDecl->setInvalidDecl();
12823         }
12824       }
12825 
12826     // Suggest adding 'constexpr' in C++11 for literal types.
12827     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12828       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12829           << DclT << Init->getSourceRange()
12830           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12831       VDecl->setConstexpr(true);
12832 
12833     } else {
12834       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12835         << DclT << Init->getSourceRange();
12836       VDecl->setInvalidDecl();
12837     }
12838   } else if (VDecl->isFileVarDecl()) {
12839     // In C, extern is typically used to avoid tentative definitions when
12840     // declaring variables in headers, but adding an intializer makes it a
12841     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12842     // In C++, extern is often used to give implictly static const variables
12843     // external linkage, so don't warn in that case. If selectany is present,
12844     // this might be header code intended for C and C++ inclusion, so apply the
12845     // C++ rules.
12846     if (VDecl->getStorageClass() == SC_Extern &&
12847         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12848          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12849         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12850         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12851       Diag(VDecl->getLocation(), diag::warn_extern_init);
12852 
12853     // In Microsoft C++ mode, a const variable defined in namespace scope has
12854     // external linkage by default if the variable is declared with
12855     // __declspec(dllexport).
12856     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12857         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12858         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12859       VDecl->setStorageClass(SC_Extern);
12860 
12861     // C99 6.7.8p4. All file scoped initializers need to be constant.
12862     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12863       CheckForConstantInitializer(Init, DclT);
12864   }
12865 
12866   QualType InitType = Init->getType();
12867   if (!InitType.isNull() &&
12868       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12869        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12870     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12871 
12872   // We will represent direct-initialization similarly to copy-initialization:
12873   //    int x(1);  -as-> int x = 1;
12874   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12875   //
12876   // Clients that want to distinguish between the two forms, can check for
12877   // direct initializer using VarDecl::getInitStyle().
12878   // A major benefit is that clients that don't particularly care about which
12879   // exactly form was it (like the CodeGen) can handle both cases without
12880   // special case code.
12881 
12882   // C++ 8.5p11:
12883   // The form of initialization (using parentheses or '=') is generally
12884   // insignificant, but does matter when the entity being initialized has a
12885   // class type.
12886   if (CXXDirectInit) {
12887     assert(DirectInit && "Call-style initializer must be direct init.");
12888     VDecl->setInitStyle(VarDecl::CallInit);
12889   } else if (DirectInit) {
12890     // This must be list-initialization. No other way is direct-initialization.
12891     VDecl->setInitStyle(VarDecl::ListInit);
12892   }
12893 
12894   if (LangOpts.OpenMP &&
12895       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12896       VDecl->isFileVarDecl())
12897     DeclsToCheckForDeferredDiags.insert(VDecl);
12898   CheckCompleteVariableDeclaration(VDecl);
12899 }
12900 
12901 /// ActOnInitializerError - Given that there was an error parsing an
12902 /// initializer for the given declaration, try to at least re-establish
12903 /// invariants such as whether a variable's type is either dependent or
12904 /// complete.
12905 void Sema::ActOnInitializerError(Decl *D) {
12906   // Our main concern here is re-establishing invariants like "a
12907   // variable's type is either dependent or complete".
12908   if (!D || D->isInvalidDecl()) return;
12909 
12910   VarDecl *VD = dyn_cast<VarDecl>(D);
12911   if (!VD) return;
12912 
12913   // Bindings are not usable if we can't make sense of the initializer.
12914   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12915     for (auto *BD : DD->bindings())
12916       BD->setInvalidDecl();
12917 
12918   // Auto types are meaningless if we can't make sense of the initializer.
12919   if (VD->getType()->isUndeducedType()) {
12920     D->setInvalidDecl();
12921     return;
12922   }
12923 
12924   QualType Ty = VD->getType();
12925   if (Ty->isDependentType()) return;
12926 
12927   // Require a complete type.
12928   if (RequireCompleteType(VD->getLocation(),
12929                           Context.getBaseElementType(Ty),
12930                           diag::err_typecheck_decl_incomplete_type)) {
12931     VD->setInvalidDecl();
12932     return;
12933   }
12934 
12935   // Require a non-abstract type.
12936   if (RequireNonAbstractType(VD->getLocation(), Ty,
12937                              diag::err_abstract_type_in_decl,
12938                              AbstractVariableType)) {
12939     VD->setInvalidDecl();
12940     return;
12941   }
12942 
12943   // Don't bother complaining about constructors or destructors,
12944   // though.
12945 }
12946 
12947 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12948   // If there is no declaration, there was an error parsing it. Just ignore it.
12949   if (!RealDecl)
12950     return;
12951 
12952   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12953     QualType Type = Var->getType();
12954 
12955     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12956     if (isa<DecompositionDecl>(RealDecl)) {
12957       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12958       Var->setInvalidDecl();
12959       return;
12960     }
12961 
12962     if (Type->isUndeducedType() &&
12963         DeduceVariableDeclarationType(Var, false, nullptr))
12964       return;
12965 
12966     // C++11 [class.static.data]p3: A static data member can be declared with
12967     // the constexpr specifier; if so, its declaration shall specify
12968     // a brace-or-equal-initializer.
12969     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12970     // the definition of a variable [...] or the declaration of a static data
12971     // member.
12972     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12973         !Var->isThisDeclarationADemotedDefinition()) {
12974       if (Var->isStaticDataMember()) {
12975         // C++1z removes the relevant rule; the in-class declaration is always
12976         // a definition there.
12977         if (!getLangOpts().CPlusPlus17 &&
12978             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12979           Diag(Var->getLocation(),
12980                diag::err_constexpr_static_mem_var_requires_init)
12981               << Var;
12982           Var->setInvalidDecl();
12983           return;
12984         }
12985       } else {
12986         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12987         Var->setInvalidDecl();
12988         return;
12989       }
12990     }
12991 
12992     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12993     // be initialized.
12994     if (!Var->isInvalidDecl() &&
12995         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12996         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12997       bool HasConstExprDefaultConstructor = false;
12998       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12999         for (auto *Ctor : RD->ctors()) {
13000           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13001               Ctor->getMethodQualifiers().getAddressSpace() ==
13002                   LangAS::opencl_constant) {
13003             HasConstExprDefaultConstructor = true;
13004           }
13005         }
13006       }
13007       if (!HasConstExprDefaultConstructor) {
13008         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13009         Var->setInvalidDecl();
13010         return;
13011       }
13012     }
13013 
13014     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13015       if (Var->getStorageClass() == SC_Extern) {
13016         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13017             << Var;
13018         Var->setInvalidDecl();
13019         return;
13020       }
13021       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13022                               diag::err_typecheck_decl_incomplete_type)) {
13023         Var->setInvalidDecl();
13024         return;
13025       }
13026       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13027         if (!RD->hasTrivialDefaultConstructor()) {
13028           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13029           Var->setInvalidDecl();
13030           return;
13031         }
13032       }
13033       // The declaration is unitialized, no need for further checks.
13034       return;
13035     }
13036 
13037     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13038     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13039         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13040       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13041                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13042 
13043 
13044     switch (DefKind) {
13045     case VarDecl::Definition:
13046       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13047         break;
13048 
13049       // We have an out-of-line definition of a static data member
13050       // that has an in-class initializer, so we type-check this like
13051       // a declaration.
13052       //
13053       LLVM_FALLTHROUGH;
13054 
13055     case VarDecl::DeclarationOnly:
13056       // It's only a declaration.
13057 
13058       // Block scope. C99 6.7p7: If an identifier for an object is
13059       // declared with no linkage (C99 6.2.2p6), the type for the
13060       // object shall be complete.
13061       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13062           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13063           RequireCompleteType(Var->getLocation(), Type,
13064                               diag::err_typecheck_decl_incomplete_type))
13065         Var->setInvalidDecl();
13066 
13067       // Make sure that the type is not abstract.
13068       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13069           RequireNonAbstractType(Var->getLocation(), Type,
13070                                  diag::err_abstract_type_in_decl,
13071                                  AbstractVariableType))
13072         Var->setInvalidDecl();
13073       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13074           Var->getStorageClass() == SC_PrivateExtern) {
13075         Diag(Var->getLocation(), diag::warn_private_extern);
13076         Diag(Var->getLocation(), diag::note_private_extern);
13077       }
13078 
13079       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13080           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13081         ExternalDeclarations.push_back(Var);
13082 
13083       return;
13084 
13085     case VarDecl::TentativeDefinition:
13086       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13087       // object that has file scope without an initializer, and without a
13088       // storage-class specifier or with the storage-class specifier "static",
13089       // constitutes a tentative definition. Note: A tentative definition with
13090       // external linkage is valid (C99 6.2.2p5).
13091       if (!Var->isInvalidDecl()) {
13092         if (const IncompleteArrayType *ArrayT
13093                                     = Context.getAsIncompleteArrayType(Type)) {
13094           if (RequireCompleteSizedType(
13095                   Var->getLocation(), ArrayT->getElementType(),
13096                   diag::err_array_incomplete_or_sizeless_type))
13097             Var->setInvalidDecl();
13098         } else if (Var->getStorageClass() == SC_Static) {
13099           // C99 6.9.2p3: If the declaration of an identifier for an object is
13100           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13101           // declared type shall not be an incomplete type.
13102           // NOTE: code such as the following
13103           //     static struct s;
13104           //     struct s { int a; };
13105           // is accepted by gcc. Hence here we issue a warning instead of
13106           // an error and we do not invalidate the static declaration.
13107           // NOTE: to avoid multiple warnings, only check the first declaration.
13108           if (Var->isFirstDecl())
13109             RequireCompleteType(Var->getLocation(), Type,
13110                                 diag::ext_typecheck_decl_incomplete_type);
13111         }
13112       }
13113 
13114       // Record the tentative definition; we're done.
13115       if (!Var->isInvalidDecl())
13116         TentativeDefinitions.push_back(Var);
13117       return;
13118     }
13119 
13120     // Provide a specific diagnostic for uninitialized variable
13121     // definitions with incomplete array type.
13122     if (Type->isIncompleteArrayType()) {
13123       Diag(Var->getLocation(),
13124            diag::err_typecheck_incomplete_array_needs_initializer);
13125       Var->setInvalidDecl();
13126       return;
13127     }
13128 
13129     // Provide a specific diagnostic for uninitialized variable
13130     // definitions with reference type.
13131     if (Type->isReferenceType()) {
13132       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13133           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13134       Var->setInvalidDecl();
13135       return;
13136     }
13137 
13138     // Do not attempt to type-check the default initializer for a
13139     // variable with dependent type.
13140     if (Type->isDependentType())
13141       return;
13142 
13143     if (Var->isInvalidDecl())
13144       return;
13145 
13146     if (!Var->hasAttr<AliasAttr>()) {
13147       if (RequireCompleteType(Var->getLocation(),
13148                               Context.getBaseElementType(Type),
13149                               diag::err_typecheck_decl_incomplete_type)) {
13150         Var->setInvalidDecl();
13151         return;
13152       }
13153     } else {
13154       return;
13155     }
13156 
13157     // The variable can not have an abstract class type.
13158     if (RequireNonAbstractType(Var->getLocation(), Type,
13159                                diag::err_abstract_type_in_decl,
13160                                AbstractVariableType)) {
13161       Var->setInvalidDecl();
13162       return;
13163     }
13164 
13165     // Check for jumps past the implicit initializer.  C++0x
13166     // clarifies that this applies to a "variable with automatic
13167     // storage duration", not a "local variable".
13168     // C++11 [stmt.dcl]p3
13169     //   A program that jumps from a point where a variable with automatic
13170     //   storage duration is not in scope to a point where it is in scope is
13171     //   ill-formed unless the variable has scalar type, class type with a
13172     //   trivial default constructor and a trivial destructor, a cv-qualified
13173     //   version of one of these types, or an array of one of the preceding
13174     //   types and is declared without an initializer.
13175     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13176       if (const RecordType *Record
13177             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13178         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13179         // Mark the function (if we're in one) for further checking even if the
13180         // looser rules of C++11 do not require such checks, so that we can
13181         // diagnose incompatibilities with C++98.
13182         if (!CXXRecord->isPOD())
13183           setFunctionHasBranchProtectedScope();
13184       }
13185     }
13186     // In OpenCL, we can't initialize objects in the __local address space,
13187     // even implicitly, so don't synthesize an implicit initializer.
13188     if (getLangOpts().OpenCL &&
13189         Var->getType().getAddressSpace() == LangAS::opencl_local)
13190       return;
13191     // C++03 [dcl.init]p9:
13192     //   If no initializer is specified for an object, and the
13193     //   object is of (possibly cv-qualified) non-POD class type (or
13194     //   array thereof), the object shall be default-initialized; if
13195     //   the object is of const-qualified type, the underlying class
13196     //   type shall have a user-declared default
13197     //   constructor. Otherwise, if no initializer is specified for
13198     //   a non- static object, the object and its subobjects, if
13199     //   any, have an indeterminate initial value); if the object
13200     //   or any of its subobjects are of const-qualified type, the
13201     //   program is ill-formed.
13202     // C++0x [dcl.init]p11:
13203     //   If no initializer is specified for an object, the object is
13204     //   default-initialized; [...].
13205     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13206     InitializationKind Kind
13207       = InitializationKind::CreateDefault(Var->getLocation());
13208 
13209     InitializationSequence InitSeq(*this, Entity, Kind, None);
13210     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13211 
13212     if (Init.get()) {
13213       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13214       // This is important for template substitution.
13215       Var->setInitStyle(VarDecl::CallInit);
13216     } else if (Init.isInvalid()) {
13217       // If default-init fails, attach a recovery-expr initializer to track
13218       // that initialization was attempted and failed.
13219       auto RecoveryExpr =
13220           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13221       if (RecoveryExpr.get())
13222         Var->setInit(RecoveryExpr.get());
13223     }
13224 
13225     CheckCompleteVariableDeclaration(Var);
13226   }
13227 }
13228 
13229 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13230   // If there is no declaration, there was an error parsing it. Ignore it.
13231   if (!D)
13232     return;
13233 
13234   VarDecl *VD = dyn_cast<VarDecl>(D);
13235   if (!VD) {
13236     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13237     D->setInvalidDecl();
13238     return;
13239   }
13240 
13241   VD->setCXXForRangeDecl(true);
13242 
13243   // for-range-declaration cannot be given a storage class specifier.
13244   int Error = -1;
13245   switch (VD->getStorageClass()) {
13246   case SC_None:
13247     break;
13248   case SC_Extern:
13249     Error = 0;
13250     break;
13251   case SC_Static:
13252     Error = 1;
13253     break;
13254   case SC_PrivateExtern:
13255     Error = 2;
13256     break;
13257   case SC_Auto:
13258     Error = 3;
13259     break;
13260   case SC_Register:
13261     Error = 4;
13262     break;
13263   }
13264 
13265   // for-range-declaration cannot be given a storage class specifier con't.
13266   switch (VD->getTSCSpec()) {
13267   case TSCS_thread_local:
13268     Error = 6;
13269     break;
13270   case TSCS___thread:
13271   case TSCS__Thread_local:
13272   case TSCS_unspecified:
13273     break;
13274   }
13275 
13276   if (Error != -1) {
13277     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13278         << VD << Error;
13279     D->setInvalidDecl();
13280   }
13281 }
13282 
13283 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13284                                             IdentifierInfo *Ident,
13285                                             ParsedAttributes &Attrs) {
13286   // C++1y [stmt.iter]p1:
13287   //   A range-based for statement of the form
13288   //      for ( for-range-identifier : for-range-initializer ) statement
13289   //   is equivalent to
13290   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13291   DeclSpec DS(Attrs.getPool().getFactory());
13292 
13293   const char *PrevSpec;
13294   unsigned DiagID;
13295   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13296                      getPrintingPolicy());
13297 
13298   Declarator D(DS, DeclaratorContext::ForInit);
13299   D.SetIdentifier(Ident, IdentLoc);
13300   D.takeAttributes(Attrs);
13301 
13302   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13303                 IdentLoc);
13304   Decl *Var = ActOnDeclarator(S, D);
13305   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13306   FinalizeDeclaration(Var);
13307   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13308                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13309                                                       : IdentLoc);
13310 }
13311 
13312 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13313   if (var->isInvalidDecl()) return;
13314 
13315   MaybeAddCUDAConstantAttr(var);
13316 
13317   if (getLangOpts().OpenCL) {
13318     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13319     // initialiser
13320     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13321         !var->hasInit()) {
13322       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13323           << 1 /*Init*/;
13324       var->setInvalidDecl();
13325       return;
13326     }
13327   }
13328 
13329   // In Objective-C, don't allow jumps past the implicit initialization of a
13330   // local retaining variable.
13331   if (getLangOpts().ObjC &&
13332       var->hasLocalStorage()) {
13333     switch (var->getType().getObjCLifetime()) {
13334     case Qualifiers::OCL_None:
13335     case Qualifiers::OCL_ExplicitNone:
13336     case Qualifiers::OCL_Autoreleasing:
13337       break;
13338 
13339     case Qualifiers::OCL_Weak:
13340     case Qualifiers::OCL_Strong:
13341       setFunctionHasBranchProtectedScope();
13342       break;
13343     }
13344   }
13345 
13346   if (var->hasLocalStorage() &&
13347       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13348     setFunctionHasBranchProtectedScope();
13349 
13350   // Warn about externally-visible variables being defined without a
13351   // prior declaration.  We only want to do this for global
13352   // declarations, but we also specifically need to avoid doing it for
13353   // class members because the linkage of an anonymous class can
13354   // change if it's later given a typedef name.
13355   if (var->isThisDeclarationADefinition() &&
13356       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13357       var->isExternallyVisible() && var->hasLinkage() &&
13358       !var->isInline() && !var->getDescribedVarTemplate() &&
13359       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13360       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13361       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13362                                   var->getLocation())) {
13363     // Find a previous declaration that's not a definition.
13364     VarDecl *prev = var->getPreviousDecl();
13365     while (prev && prev->isThisDeclarationADefinition())
13366       prev = prev->getPreviousDecl();
13367 
13368     if (!prev) {
13369       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13370       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13371           << /* variable */ 0;
13372     }
13373   }
13374 
13375   // Cache the result of checking for constant initialization.
13376   Optional<bool> CacheHasConstInit;
13377   const Expr *CacheCulprit = nullptr;
13378   auto checkConstInit = [&]() mutable {
13379     if (!CacheHasConstInit)
13380       CacheHasConstInit = var->getInit()->isConstantInitializer(
13381             Context, var->getType()->isReferenceType(), &CacheCulprit);
13382     return *CacheHasConstInit;
13383   };
13384 
13385   if (var->getTLSKind() == VarDecl::TLS_Static) {
13386     if (var->getType().isDestructedType()) {
13387       // GNU C++98 edits for __thread, [basic.start.term]p3:
13388       //   The type of an object with thread storage duration shall not
13389       //   have a non-trivial destructor.
13390       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13391       if (getLangOpts().CPlusPlus11)
13392         Diag(var->getLocation(), diag::note_use_thread_local);
13393     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13394       if (!checkConstInit()) {
13395         // GNU C++98 edits for __thread, [basic.start.init]p4:
13396         //   An object of thread storage duration shall not require dynamic
13397         //   initialization.
13398         // FIXME: Need strict checking here.
13399         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13400           << CacheCulprit->getSourceRange();
13401         if (getLangOpts().CPlusPlus11)
13402           Diag(var->getLocation(), diag::note_use_thread_local);
13403       }
13404     }
13405   }
13406 
13407 
13408   if (!var->getType()->isStructureType() && var->hasInit() &&
13409       isa<InitListExpr>(var->getInit())) {
13410     const auto *ILE = cast<InitListExpr>(var->getInit());
13411     unsigned NumInits = ILE->getNumInits();
13412     if (NumInits > 2)
13413       for (unsigned I = 0; I < NumInits; ++I) {
13414         const auto *Init = ILE->getInit(I);
13415         if (!Init)
13416           break;
13417         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13418         if (!SL)
13419           break;
13420 
13421         unsigned NumConcat = SL->getNumConcatenated();
13422         // Diagnose missing comma in string array initialization.
13423         // Do not warn when all the elements in the initializer are concatenated
13424         // together. Do not warn for macros too.
13425         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13426           bool OnlyOneMissingComma = true;
13427           for (unsigned J = I + 1; J < NumInits; ++J) {
13428             const auto *Init = ILE->getInit(J);
13429             if (!Init)
13430               break;
13431             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13432             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13433               OnlyOneMissingComma = false;
13434               break;
13435             }
13436           }
13437 
13438           if (OnlyOneMissingComma) {
13439             SmallVector<FixItHint, 1> Hints;
13440             for (unsigned i = 0; i < NumConcat - 1; ++i)
13441               Hints.push_back(FixItHint::CreateInsertion(
13442                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13443 
13444             Diag(SL->getStrTokenLoc(1),
13445                  diag::warn_concatenated_literal_array_init)
13446                 << Hints;
13447             Diag(SL->getBeginLoc(),
13448                  diag::note_concatenated_string_literal_silence);
13449           }
13450           // In any case, stop now.
13451           break;
13452         }
13453       }
13454   }
13455 
13456 
13457   QualType type = var->getType();
13458 
13459   if (var->hasAttr<BlocksAttr>())
13460     getCurFunction()->addByrefBlockVar(var);
13461 
13462   Expr *Init = var->getInit();
13463   bool GlobalStorage = var->hasGlobalStorage();
13464   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13465   QualType baseType = Context.getBaseElementType(type);
13466   bool HasConstInit = true;
13467 
13468   // Check whether the initializer is sufficiently constant.
13469   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13470       !Init->isValueDependent() &&
13471       (GlobalStorage || var->isConstexpr() ||
13472        var->mightBeUsableInConstantExpressions(Context))) {
13473     // If this variable might have a constant initializer or might be usable in
13474     // constant expressions, check whether or not it actually is now.  We can't
13475     // do this lazily, because the result might depend on things that change
13476     // later, such as which constexpr functions happen to be defined.
13477     SmallVector<PartialDiagnosticAt, 8> Notes;
13478     if (!getLangOpts().CPlusPlus11) {
13479       // Prior to C++11, in contexts where a constant initializer is required,
13480       // the set of valid constant initializers is described by syntactic rules
13481       // in [expr.const]p2-6.
13482       // FIXME: Stricter checking for these rules would be useful for constinit /
13483       // -Wglobal-constructors.
13484       HasConstInit = checkConstInit();
13485 
13486       // Compute and cache the constant value, and remember that we have a
13487       // constant initializer.
13488       if (HasConstInit) {
13489         (void)var->checkForConstantInitialization(Notes);
13490         Notes.clear();
13491       } else if (CacheCulprit) {
13492         Notes.emplace_back(CacheCulprit->getExprLoc(),
13493                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13494         Notes.back().second << CacheCulprit->getSourceRange();
13495       }
13496     } else {
13497       // Evaluate the initializer to see if it's a constant initializer.
13498       HasConstInit = var->checkForConstantInitialization(Notes);
13499     }
13500 
13501     if (HasConstInit) {
13502       // FIXME: Consider replacing the initializer with a ConstantExpr.
13503     } else if (var->isConstexpr()) {
13504       SourceLocation DiagLoc = var->getLocation();
13505       // If the note doesn't add any useful information other than a source
13506       // location, fold it into the primary diagnostic.
13507       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13508                                    diag::note_invalid_subexpr_in_const_expr) {
13509         DiagLoc = Notes[0].first;
13510         Notes.clear();
13511       }
13512       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13513           << var << Init->getSourceRange();
13514       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13515         Diag(Notes[I].first, Notes[I].second);
13516     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13517       auto *Attr = var->getAttr<ConstInitAttr>();
13518       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13519           << Init->getSourceRange();
13520       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13521           << Attr->getRange() << Attr->isConstinit();
13522       for (auto &it : Notes)
13523         Diag(it.first, it.second);
13524     } else if (IsGlobal &&
13525                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13526                                            var->getLocation())) {
13527       // Warn about globals which don't have a constant initializer.  Don't
13528       // warn about globals with a non-trivial destructor because we already
13529       // warned about them.
13530       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13531       if (!(RD && !RD->hasTrivialDestructor())) {
13532         // checkConstInit() here permits trivial default initialization even in
13533         // C++11 onwards, where such an initializer is not a constant initializer
13534         // but nonetheless doesn't require a global constructor.
13535         if (!checkConstInit())
13536           Diag(var->getLocation(), diag::warn_global_constructor)
13537               << Init->getSourceRange();
13538       }
13539     }
13540   }
13541 
13542   // Apply section attributes and pragmas to global variables.
13543   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13544       !inTemplateInstantiation()) {
13545     PragmaStack<StringLiteral *> *Stack = nullptr;
13546     int SectionFlags = ASTContext::PSF_Read;
13547     if (var->getType().isConstQualified()) {
13548       if (HasConstInit)
13549         Stack = &ConstSegStack;
13550       else {
13551         Stack = &BSSSegStack;
13552         SectionFlags |= ASTContext::PSF_Write;
13553       }
13554     } else if (var->hasInit() && HasConstInit) {
13555       Stack = &DataSegStack;
13556       SectionFlags |= ASTContext::PSF_Write;
13557     } else {
13558       Stack = &BSSSegStack;
13559       SectionFlags |= ASTContext::PSF_Write;
13560     }
13561     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13562       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13563         SectionFlags |= ASTContext::PSF_Implicit;
13564       UnifySection(SA->getName(), SectionFlags, var);
13565     } else if (Stack->CurrentValue) {
13566       SectionFlags |= ASTContext::PSF_Implicit;
13567       auto SectionName = Stack->CurrentValue->getString();
13568       var->addAttr(SectionAttr::CreateImplicit(
13569           Context, SectionName, Stack->CurrentPragmaLocation,
13570           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13571       if (UnifySection(SectionName, SectionFlags, var))
13572         var->dropAttr<SectionAttr>();
13573     }
13574 
13575     // Apply the init_seg attribute if this has an initializer.  If the
13576     // initializer turns out to not be dynamic, we'll end up ignoring this
13577     // attribute.
13578     if (CurInitSeg && var->getInit())
13579       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13580                                                CurInitSegLoc,
13581                                                AttributeCommonInfo::AS_Pragma));
13582   }
13583 
13584   // All the following checks are C++ only.
13585   if (!getLangOpts().CPlusPlus) {
13586     // If this variable must be emitted, add it as an initializer for the
13587     // current module.
13588     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13589       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13590     return;
13591   }
13592 
13593   // Require the destructor.
13594   if (!type->isDependentType())
13595     if (const RecordType *recordType = baseType->getAs<RecordType>())
13596       FinalizeVarWithDestructor(var, recordType);
13597 
13598   // If this variable must be emitted, add it as an initializer for the current
13599   // module.
13600   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13601     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13602 
13603   // Build the bindings if this is a structured binding declaration.
13604   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13605     CheckCompleteDecompositionDeclaration(DD);
13606 }
13607 
13608 /// Check if VD needs to be dllexport/dllimport due to being in a
13609 /// dllexport/import function.
13610 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13611   assert(VD->isStaticLocal());
13612 
13613   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13614 
13615   // Find outermost function when VD is in lambda function.
13616   while (FD && !getDLLAttr(FD) &&
13617          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13618          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13619     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13620   }
13621 
13622   if (!FD)
13623     return;
13624 
13625   // Static locals inherit dll attributes from their function.
13626   if (Attr *A = getDLLAttr(FD)) {
13627     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13628     NewAttr->setInherited(true);
13629     VD->addAttr(NewAttr);
13630   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13631     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13632     NewAttr->setInherited(true);
13633     VD->addAttr(NewAttr);
13634 
13635     // Export this function to enforce exporting this static variable even
13636     // if it is not used in this compilation unit.
13637     if (!FD->hasAttr<DLLExportAttr>())
13638       FD->addAttr(NewAttr);
13639 
13640   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13641     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13642     NewAttr->setInherited(true);
13643     VD->addAttr(NewAttr);
13644   }
13645 }
13646 
13647 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13648 /// any semantic actions necessary after any initializer has been attached.
13649 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13650   // Note that we are no longer parsing the initializer for this declaration.
13651   ParsingInitForAutoVars.erase(ThisDecl);
13652 
13653   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13654   if (!VD)
13655     return;
13656 
13657   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13658   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13659       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13660     if (PragmaClangBSSSection.Valid)
13661       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13662           Context, PragmaClangBSSSection.SectionName,
13663           PragmaClangBSSSection.PragmaLocation,
13664           AttributeCommonInfo::AS_Pragma));
13665     if (PragmaClangDataSection.Valid)
13666       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13667           Context, PragmaClangDataSection.SectionName,
13668           PragmaClangDataSection.PragmaLocation,
13669           AttributeCommonInfo::AS_Pragma));
13670     if (PragmaClangRodataSection.Valid)
13671       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13672           Context, PragmaClangRodataSection.SectionName,
13673           PragmaClangRodataSection.PragmaLocation,
13674           AttributeCommonInfo::AS_Pragma));
13675     if (PragmaClangRelroSection.Valid)
13676       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13677           Context, PragmaClangRelroSection.SectionName,
13678           PragmaClangRelroSection.PragmaLocation,
13679           AttributeCommonInfo::AS_Pragma));
13680   }
13681 
13682   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13683     for (auto *BD : DD->bindings()) {
13684       FinalizeDeclaration(BD);
13685     }
13686   }
13687 
13688   checkAttributesAfterMerging(*this, *VD);
13689 
13690   // Perform TLS alignment check here after attributes attached to the variable
13691   // which may affect the alignment have been processed. Only perform the check
13692   // if the target has a maximum TLS alignment (zero means no constraints).
13693   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13694     // Protect the check so that it's not performed on dependent types and
13695     // dependent alignments (we can't determine the alignment in that case).
13696     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13697       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13698       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13699         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13700           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13701           << (unsigned)MaxAlignChars.getQuantity();
13702       }
13703     }
13704   }
13705 
13706   if (VD->isStaticLocal())
13707     CheckStaticLocalForDllExport(VD);
13708 
13709   // Perform check for initializers of device-side global variables.
13710   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13711   // 7.5). We must also apply the same checks to all __shared__
13712   // variables whether they are local or not. CUDA also allows
13713   // constant initializers for __constant__ and __device__ variables.
13714   if (getLangOpts().CUDA)
13715     checkAllowedCUDAInitializer(VD);
13716 
13717   // Grab the dllimport or dllexport attribute off of the VarDecl.
13718   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13719 
13720   // Imported static data members cannot be defined out-of-line.
13721   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13722     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13723         VD->isThisDeclarationADefinition()) {
13724       // We allow definitions of dllimport class template static data members
13725       // with a warning.
13726       CXXRecordDecl *Context =
13727         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13728       bool IsClassTemplateMember =
13729           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13730           Context->getDescribedClassTemplate();
13731 
13732       Diag(VD->getLocation(),
13733            IsClassTemplateMember
13734                ? diag::warn_attribute_dllimport_static_field_definition
13735                : diag::err_attribute_dllimport_static_field_definition);
13736       Diag(IA->getLocation(), diag::note_attribute);
13737       if (!IsClassTemplateMember)
13738         VD->setInvalidDecl();
13739     }
13740   }
13741 
13742   // dllimport/dllexport variables cannot be thread local, their TLS index
13743   // isn't exported with the variable.
13744   if (DLLAttr && VD->getTLSKind()) {
13745     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13746     if (F && getDLLAttr(F)) {
13747       assert(VD->isStaticLocal());
13748       // But if this is a static local in a dlimport/dllexport function, the
13749       // function will never be inlined, which means the var would never be
13750       // imported, so having it marked import/export is safe.
13751     } else {
13752       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13753                                                                     << DLLAttr;
13754       VD->setInvalidDecl();
13755     }
13756   }
13757 
13758   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13759     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13760       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13761           << Attr;
13762       VD->dropAttr<UsedAttr>();
13763     }
13764   }
13765   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13766     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13767       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13768           << Attr;
13769       VD->dropAttr<RetainAttr>();
13770     }
13771   }
13772 
13773   const DeclContext *DC = VD->getDeclContext();
13774   // If there's a #pragma GCC visibility in scope, and this isn't a class
13775   // member, set the visibility of this variable.
13776   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13777     AddPushedVisibilityAttribute(VD);
13778 
13779   // FIXME: Warn on unused var template partial specializations.
13780   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13781     MarkUnusedFileScopedDecl(VD);
13782 
13783   // Now we have parsed the initializer and can update the table of magic
13784   // tag values.
13785   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13786       !VD->getType()->isIntegralOrEnumerationType())
13787     return;
13788 
13789   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13790     const Expr *MagicValueExpr = VD->getInit();
13791     if (!MagicValueExpr) {
13792       continue;
13793     }
13794     Optional<llvm::APSInt> MagicValueInt;
13795     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13796       Diag(I->getRange().getBegin(),
13797            diag::err_type_tag_for_datatype_not_ice)
13798         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13799       continue;
13800     }
13801     if (MagicValueInt->getActiveBits() > 64) {
13802       Diag(I->getRange().getBegin(),
13803            diag::err_type_tag_for_datatype_too_large)
13804         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13805       continue;
13806     }
13807     uint64_t MagicValue = MagicValueInt->getZExtValue();
13808     RegisterTypeTagForDatatype(I->getArgumentKind(),
13809                                MagicValue,
13810                                I->getMatchingCType(),
13811                                I->getLayoutCompatible(),
13812                                I->getMustBeNull());
13813   }
13814 }
13815 
13816 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13817   auto *VD = dyn_cast<VarDecl>(DD);
13818   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13819 }
13820 
13821 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13822                                                    ArrayRef<Decl *> Group) {
13823   SmallVector<Decl*, 8> Decls;
13824 
13825   if (DS.isTypeSpecOwned())
13826     Decls.push_back(DS.getRepAsDecl());
13827 
13828   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13829   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13830   bool DiagnosedMultipleDecomps = false;
13831   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13832   bool DiagnosedNonDeducedAuto = false;
13833 
13834   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13835     if (Decl *D = Group[i]) {
13836       // For declarators, there are some additional syntactic-ish checks we need
13837       // to perform.
13838       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13839         if (!FirstDeclaratorInGroup)
13840           FirstDeclaratorInGroup = DD;
13841         if (!FirstDecompDeclaratorInGroup)
13842           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13843         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13844             !hasDeducedAuto(DD))
13845           FirstNonDeducedAutoInGroup = DD;
13846 
13847         if (FirstDeclaratorInGroup != DD) {
13848           // A decomposition declaration cannot be combined with any other
13849           // declaration in the same group.
13850           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13851             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13852                  diag::err_decomp_decl_not_alone)
13853                 << FirstDeclaratorInGroup->getSourceRange()
13854                 << DD->getSourceRange();
13855             DiagnosedMultipleDecomps = true;
13856           }
13857 
13858           // A declarator that uses 'auto' in any way other than to declare a
13859           // variable with a deduced type cannot be combined with any other
13860           // declarator in the same group.
13861           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13862             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13863                  diag::err_auto_non_deduced_not_alone)
13864                 << FirstNonDeducedAutoInGroup->getType()
13865                        ->hasAutoForTrailingReturnType()
13866                 << FirstDeclaratorInGroup->getSourceRange()
13867                 << DD->getSourceRange();
13868             DiagnosedNonDeducedAuto = true;
13869           }
13870         }
13871       }
13872 
13873       Decls.push_back(D);
13874     }
13875   }
13876 
13877   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13878     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13879       handleTagNumbering(Tag, S);
13880       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13881           getLangOpts().CPlusPlus)
13882         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13883     }
13884   }
13885 
13886   return BuildDeclaratorGroup(Decls);
13887 }
13888 
13889 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13890 /// group, performing any necessary semantic checking.
13891 Sema::DeclGroupPtrTy
13892 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13893   // C++14 [dcl.spec.auto]p7: (DR1347)
13894   //   If the type that replaces the placeholder type is not the same in each
13895   //   deduction, the program is ill-formed.
13896   if (Group.size() > 1) {
13897     QualType Deduced;
13898     VarDecl *DeducedDecl = nullptr;
13899     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13900       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13901       if (!D || D->isInvalidDecl())
13902         break;
13903       DeducedType *DT = D->getType()->getContainedDeducedType();
13904       if (!DT || DT->getDeducedType().isNull())
13905         continue;
13906       if (Deduced.isNull()) {
13907         Deduced = DT->getDeducedType();
13908         DeducedDecl = D;
13909       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13910         auto *AT = dyn_cast<AutoType>(DT);
13911         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13912                         diag::err_auto_different_deductions)
13913                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13914                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13915                    << D->getDeclName();
13916         if (DeducedDecl->hasInit())
13917           Dia << DeducedDecl->getInit()->getSourceRange();
13918         if (D->getInit())
13919           Dia << D->getInit()->getSourceRange();
13920         D->setInvalidDecl();
13921         break;
13922       }
13923     }
13924   }
13925 
13926   ActOnDocumentableDecls(Group);
13927 
13928   return DeclGroupPtrTy::make(
13929       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13930 }
13931 
13932 void Sema::ActOnDocumentableDecl(Decl *D) {
13933   ActOnDocumentableDecls(D);
13934 }
13935 
13936 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13937   // Don't parse the comment if Doxygen diagnostics are ignored.
13938   if (Group.empty() || !Group[0])
13939     return;
13940 
13941   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13942                       Group[0]->getLocation()) &&
13943       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13944                       Group[0]->getLocation()))
13945     return;
13946 
13947   if (Group.size() >= 2) {
13948     // This is a decl group.  Normally it will contain only declarations
13949     // produced from declarator list.  But in case we have any definitions or
13950     // additional declaration references:
13951     //   'typedef struct S {} S;'
13952     //   'typedef struct S *S;'
13953     //   'struct S *pS;'
13954     // FinalizeDeclaratorGroup adds these as separate declarations.
13955     Decl *MaybeTagDecl = Group[0];
13956     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13957       Group = Group.slice(1);
13958     }
13959   }
13960 
13961   // FIMXE: We assume every Decl in the group is in the same file.
13962   // This is false when preprocessor constructs the group from decls in
13963   // different files (e. g. macros or #include).
13964   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13965 }
13966 
13967 /// Common checks for a parameter-declaration that should apply to both function
13968 /// parameters and non-type template parameters.
13969 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13970   // Check that there are no default arguments inside the type of this
13971   // parameter.
13972   if (getLangOpts().CPlusPlus)
13973     CheckExtraCXXDefaultArguments(D);
13974 
13975   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13976   if (D.getCXXScopeSpec().isSet()) {
13977     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13978       << D.getCXXScopeSpec().getRange();
13979   }
13980 
13981   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13982   // simple identifier except [...irrelevant cases...].
13983   switch (D.getName().getKind()) {
13984   case UnqualifiedIdKind::IK_Identifier:
13985     break;
13986 
13987   case UnqualifiedIdKind::IK_OperatorFunctionId:
13988   case UnqualifiedIdKind::IK_ConversionFunctionId:
13989   case UnqualifiedIdKind::IK_LiteralOperatorId:
13990   case UnqualifiedIdKind::IK_ConstructorName:
13991   case UnqualifiedIdKind::IK_DestructorName:
13992   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13993   case UnqualifiedIdKind::IK_DeductionGuideName:
13994     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13995       << GetNameForDeclarator(D).getName();
13996     break;
13997 
13998   case UnqualifiedIdKind::IK_TemplateId:
13999   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14000     // GetNameForDeclarator would not produce a useful name in this case.
14001     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14002     break;
14003   }
14004 }
14005 
14006 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14007 /// to introduce parameters into function prototype scope.
14008 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14009   const DeclSpec &DS = D.getDeclSpec();
14010 
14011   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14012 
14013   // C++03 [dcl.stc]p2 also permits 'auto'.
14014   StorageClass SC = SC_None;
14015   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14016     SC = SC_Register;
14017     // In C++11, the 'register' storage class specifier is deprecated.
14018     // In C++17, it is not allowed, but we tolerate it as an extension.
14019     if (getLangOpts().CPlusPlus11) {
14020       Diag(DS.getStorageClassSpecLoc(),
14021            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14022                                      : diag::warn_deprecated_register)
14023         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14024     }
14025   } else if (getLangOpts().CPlusPlus &&
14026              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14027     SC = SC_Auto;
14028   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14029     Diag(DS.getStorageClassSpecLoc(),
14030          diag::err_invalid_storage_class_in_func_decl);
14031     D.getMutableDeclSpec().ClearStorageClassSpecs();
14032   }
14033 
14034   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14035     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14036       << DeclSpec::getSpecifierName(TSCS);
14037   if (DS.isInlineSpecified())
14038     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14039         << getLangOpts().CPlusPlus17;
14040   if (DS.hasConstexprSpecifier())
14041     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14042         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14043 
14044   DiagnoseFunctionSpecifiers(DS);
14045 
14046   CheckFunctionOrTemplateParamDeclarator(S, D);
14047 
14048   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14049   QualType parmDeclType = TInfo->getType();
14050 
14051   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14052   IdentifierInfo *II = D.getIdentifier();
14053   if (II) {
14054     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14055                    ForVisibleRedeclaration);
14056     LookupName(R, S);
14057     if (R.isSingleResult()) {
14058       NamedDecl *PrevDecl = R.getFoundDecl();
14059       if (PrevDecl->isTemplateParameter()) {
14060         // Maybe we will complain about the shadowed template parameter.
14061         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14062         // Just pretend that we didn't see the previous declaration.
14063         PrevDecl = nullptr;
14064       } else if (S->isDeclScope(PrevDecl)) {
14065         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14066         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14067 
14068         // Recover by removing the name
14069         II = nullptr;
14070         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14071         D.setInvalidType(true);
14072       }
14073     }
14074   }
14075 
14076   // Temporarily put parameter variables in the translation unit, not
14077   // the enclosing context.  This prevents them from accidentally
14078   // looking like class members in C++.
14079   ParmVarDecl *New =
14080       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14081                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14082 
14083   if (D.isInvalidType())
14084     New->setInvalidDecl();
14085 
14086   assert(S->isFunctionPrototypeScope());
14087   assert(S->getFunctionPrototypeDepth() >= 1);
14088   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14089                     S->getNextFunctionPrototypeIndex());
14090 
14091   // Add the parameter declaration into this scope.
14092   S->AddDecl(New);
14093   if (II)
14094     IdResolver.AddDecl(New);
14095 
14096   ProcessDeclAttributes(S, New, D);
14097 
14098   if (D.getDeclSpec().isModulePrivateSpecified())
14099     Diag(New->getLocation(), diag::err_module_private_local)
14100         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14101         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14102 
14103   if (New->hasAttr<BlocksAttr>()) {
14104     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14105   }
14106 
14107   if (getLangOpts().OpenCL)
14108     deduceOpenCLAddressSpace(New);
14109 
14110   return New;
14111 }
14112 
14113 /// Synthesizes a variable for a parameter arising from a
14114 /// typedef.
14115 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14116                                               SourceLocation Loc,
14117                                               QualType T) {
14118   /* FIXME: setting StartLoc == Loc.
14119      Would it be worth to modify callers so as to provide proper source
14120      location for the unnamed parameters, embedding the parameter's type? */
14121   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14122                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14123                                            SC_None, nullptr);
14124   Param->setImplicit();
14125   return Param;
14126 }
14127 
14128 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14129   // Don't diagnose unused-parameter errors in template instantiations; we
14130   // will already have done so in the template itself.
14131   if (inTemplateInstantiation())
14132     return;
14133 
14134   for (const ParmVarDecl *Parameter : Parameters) {
14135     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14136         !Parameter->hasAttr<UnusedAttr>()) {
14137       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14138         << Parameter->getDeclName();
14139     }
14140   }
14141 }
14142 
14143 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14144     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14145   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14146     return;
14147 
14148   // Warn if the return value is pass-by-value and larger than the specified
14149   // threshold.
14150   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14151     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14152     if (Size > LangOpts.NumLargeByValueCopy)
14153       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14154   }
14155 
14156   // Warn if any parameter is pass-by-value and larger than the specified
14157   // threshold.
14158   for (const ParmVarDecl *Parameter : Parameters) {
14159     QualType T = Parameter->getType();
14160     if (T->isDependentType() || !T.isPODType(Context))
14161       continue;
14162     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14163     if (Size > LangOpts.NumLargeByValueCopy)
14164       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14165           << Parameter << Size;
14166   }
14167 }
14168 
14169 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14170                                   SourceLocation NameLoc, IdentifierInfo *Name,
14171                                   QualType T, TypeSourceInfo *TSInfo,
14172                                   StorageClass SC) {
14173   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14174   if (getLangOpts().ObjCAutoRefCount &&
14175       T.getObjCLifetime() == Qualifiers::OCL_None &&
14176       T->isObjCLifetimeType()) {
14177 
14178     Qualifiers::ObjCLifetime lifetime;
14179 
14180     // Special cases for arrays:
14181     //   - if it's const, use __unsafe_unretained
14182     //   - otherwise, it's an error
14183     if (T->isArrayType()) {
14184       if (!T.isConstQualified()) {
14185         if (DelayedDiagnostics.shouldDelayDiagnostics())
14186           DelayedDiagnostics.add(
14187               sema::DelayedDiagnostic::makeForbiddenType(
14188               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14189         else
14190           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14191               << TSInfo->getTypeLoc().getSourceRange();
14192       }
14193       lifetime = Qualifiers::OCL_ExplicitNone;
14194     } else {
14195       lifetime = T->getObjCARCImplicitLifetime();
14196     }
14197     T = Context.getLifetimeQualifiedType(T, lifetime);
14198   }
14199 
14200   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14201                                          Context.getAdjustedParameterType(T),
14202                                          TSInfo, SC, nullptr);
14203 
14204   // Make a note if we created a new pack in the scope of a lambda, so that
14205   // we know that references to that pack must also be expanded within the
14206   // lambda scope.
14207   if (New->isParameterPack())
14208     if (auto *LSI = getEnclosingLambda())
14209       LSI->LocalPacks.push_back(New);
14210 
14211   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14212       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14213     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14214                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14215 
14216   // Parameters can not be abstract class types.
14217   // For record types, this is done by the AbstractClassUsageDiagnoser once
14218   // the class has been completely parsed.
14219   if (!CurContext->isRecord() &&
14220       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14221                              AbstractParamType))
14222     New->setInvalidDecl();
14223 
14224   // Parameter declarators cannot be interface types. All ObjC objects are
14225   // passed by reference.
14226   if (T->isObjCObjectType()) {
14227     SourceLocation TypeEndLoc =
14228         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14229     Diag(NameLoc,
14230          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14231       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14232     T = Context.getObjCObjectPointerType(T);
14233     New->setType(T);
14234   }
14235 
14236   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14237   // duration shall not be qualified by an address-space qualifier."
14238   // Since all parameters have automatic store duration, they can not have
14239   // an address space.
14240   if (T.getAddressSpace() != LangAS::Default &&
14241       // OpenCL allows function arguments declared to be an array of a type
14242       // to be qualified with an address space.
14243       !(getLangOpts().OpenCL &&
14244         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14245     Diag(NameLoc, diag::err_arg_with_address_space);
14246     New->setInvalidDecl();
14247   }
14248 
14249   // PPC MMA non-pointer types are not allowed as function argument types.
14250   if (Context.getTargetInfo().getTriple().isPPC64() &&
14251       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14252     New->setInvalidDecl();
14253   }
14254 
14255   return New;
14256 }
14257 
14258 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14259                                            SourceLocation LocAfterDecls) {
14260   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14261 
14262   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14263   // for a K&R function.
14264   if (!FTI.hasPrototype) {
14265     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14266       --i;
14267       if (FTI.Params[i].Param == nullptr) {
14268         SmallString<256> Code;
14269         llvm::raw_svector_ostream(Code)
14270             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14271         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14272             << FTI.Params[i].Ident
14273             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14274 
14275         // Implicitly declare the argument as type 'int' for lack of a better
14276         // type.
14277         AttributeFactory attrs;
14278         DeclSpec DS(attrs);
14279         const char* PrevSpec; // unused
14280         unsigned DiagID; // unused
14281         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14282                            DiagID, Context.getPrintingPolicy());
14283         // Use the identifier location for the type source range.
14284         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14285         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14286         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14287         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14288         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14289       }
14290     }
14291   }
14292 }
14293 
14294 Decl *
14295 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14296                               MultiTemplateParamsArg TemplateParameterLists,
14297                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14298   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14299   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14300   Scope *ParentScope = FnBodyScope->getParent();
14301 
14302   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14303   // we define a non-templated function definition, we will create a declaration
14304   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14305   // The base function declaration will have the equivalent of an `omp declare
14306   // variant` annotation which specifies the mangled definition as a
14307   // specialization function under the OpenMP context defined as part of the
14308   // `omp begin declare variant`.
14309   SmallVector<FunctionDecl *, 4> Bases;
14310   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14311     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14312         ParentScope, D, TemplateParameterLists, Bases);
14313 
14314   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14315   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14316   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14317 
14318   if (!Bases.empty())
14319     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14320 
14321   return Dcl;
14322 }
14323 
14324 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14325   Consumer.HandleInlineFunctionDefinition(D);
14326 }
14327 
14328 static bool
14329 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14330                                 const FunctionDecl *&PossiblePrototype) {
14331   // Don't warn about invalid declarations.
14332   if (FD->isInvalidDecl())
14333     return false;
14334 
14335   // Or declarations that aren't global.
14336   if (!FD->isGlobal())
14337     return false;
14338 
14339   // Don't warn about C++ member functions.
14340   if (isa<CXXMethodDecl>(FD))
14341     return false;
14342 
14343   // Don't warn about 'main'.
14344   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14345     if (IdentifierInfo *II = FD->getIdentifier())
14346       if (II->isStr("main") || II->isStr("efi_main"))
14347         return false;
14348 
14349   // Don't warn about inline functions.
14350   if (FD->isInlined())
14351     return false;
14352 
14353   // Don't warn about function templates.
14354   if (FD->getDescribedFunctionTemplate())
14355     return false;
14356 
14357   // Don't warn about function template specializations.
14358   if (FD->isFunctionTemplateSpecialization())
14359     return false;
14360 
14361   // Don't warn for OpenCL kernels.
14362   if (FD->hasAttr<OpenCLKernelAttr>())
14363     return false;
14364 
14365   // Don't warn on explicitly deleted functions.
14366   if (FD->isDeleted())
14367     return false;
14368 
14369   // Don't warn on implicitly local functions (such as having local-typed
14370   // parameters).
14371   if (!FD->isExternallyVisible())
14372     return false;
14373 
14374   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14375        Prev; Prev = Prev->getPreviousDecl()) {
14376     // Ignore any declarations that occur in function or method
14377     // scope, because they aren't visible from the header.
14378     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14379       continue;
14380 
14381     PossiblePrototype = Prev;
14382     return Prev->getType()->isFunctionNoProtoType();
14383   }
14384 
14385   return true;
14386 }
14387 
14388 void
14389 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14390                                    const FunctionDecl *EffectiveDefinition,
14391                                    SkipBodyInfo *SkipBody) {
14392   const FunctionDecl *Definition = EffectiveDefinition;
14393   if (!Definition &&
14394       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14395     return;
14396 
14397   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14398     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14399       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14400         // A merged copy of the same function, instantiated as a member of
14401         // the same class, is OK.
14402         if (declaresSameEntity(OrigFD, OrigDef) &&
14403             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14404                                cast<Decl>(FD->getLexicalDeclContext())))
14405           return;
14406       }
14407     }
14408   }
14409 
14410   if (canRedefineFunction(Definition, getLangOpts()))
14411     return;
14412 
14413   // Don't emit an error when this is redefinition of a typo-corrected
14414   // definition.
14415   if (TypoCorrectedFunctionDefinitions.count(Definition))
14416     return;
14417 
14418   // If we don't have a visible definition of the function, and it's inline or
14419   // a template, skip the new definition.
14420   if (SkipBody && !hasVisibleDefinition(Definition) &&
14421       (Definition->getFormalLinkage() == InternalLinkage ||
14422        Definition->isInlined() ||
14423        Definition->getDescribedFunctionTemplate() ||
14424        Definition->getNumTemplateParameterLists())) {
14425     SkipBody->ShouldSkip = true;
14426     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14427     if (auto *TD = Definition->getDescribedFunctionTemplate())
14428       makeMergedDefinitionVisible(TD);
14429     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14430     return;
14431   }
14432 
14433   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14434       Definition->getStorageClass() == SC_Extern)
14435     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14436         << FD << getLangOpts().CPlusPlus;
14437   else
14438     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14439 
14440   Diag(Definition->getLocation(), diag::note_previous_definition);
14441   FD->setInvalidDecl();
14442 }
14443 
14444 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14445                                    Sema &S) {
14446   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14447 
14448   LambdaScopeInfo *LSI = S.PushLambdaScope();
14449   LSI->CallOperator = CallOperator;
14450   LSI->Lambda = LambdaClass;
14451   LSI->ReturnType = CallOperator->getReturnType();
14452   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14453 
14454   if (LCD == LCD_None)
14455     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14456   else if (LCD == LCD_ByCopy)
14457     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14458   else if (LCD == LCD_ByRef)
14459     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14460   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14461 
14462   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14463   LSI->Mutable = !CallOperator->isConst();
14464 
14465   // Add the captures to the LSI so they can be noted as already
14466   // captured within tryCaptureVar.
14467   auto I = LambdaClass->field_begin();
14468   for (const auto &C : LambdaClass->captures()) {
14469     if (C.capturesVariable()) {
14470       VarDecl *VD = C.getCapturedVar();
14471       if (VD->isInitCapture())
14472         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14473       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14474       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14475           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14476           /*EllipsisLoc*/C.isPackExpansion()
14477                          ? C.getEllipsisLoc() : SourceLocation(),
14478           I->getType(), /*Invalid*/false);
14479 
14480     } else if (C.capturesThis()) {
14481       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14482                           C.getCaptureKind() == LCK_StarThis);
14483     } else {
14484       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14485                              I->getType());
14486     }
14487     ++I;
14488   }
14489 }
14490 
14491 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14492                                     SkipBodyInfo *SkipBody,
14493                                     FnBodyKind BodyKind) {
14494   if (!D) {
14495     // Parsing the function declaration failed in some way. Push on a fake scope
14496     // anyway so we can try to parse the function body.
14497     PushFunctionScope();
14498     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14499     return D;
14500   }
14501 
14502   FunctionDecl *FD = nullptr;
14503 
14504   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14505     FD = FunTmpl->getTemplatedDecl();
14506   else
14507     FD = cast<FunctionDecl>(D);
14508 
14509   // Do not push if it is a lambda because one is already pushed when building
14510   // the lambda in ActOnStartOfLambdaDefinition().
14511   if (!isLambdaCallOperator(FD))
14512     PushExpressionEvaluationContext(
14513         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14514                           : ExprEvalContexts.back().Context);
14515 
14516   // Check for defining attributes before the check for redefinition.
14517   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14518     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14519     FD->dropAttr<AliasAttr>();
14520     FD->setInvalidDecl();
14521   }
14522   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14523     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14524     FD->dropAttr<IFuncAttr>();
14525     FD->setInvalidDecl();
14526   }
14527 
14528   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14529     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14530         Ctor->isDefaultConstructor() &&
14531         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14532       // If this is an MS ABI dllexport default constructor, instantiate any
14533       // default arguments.
14534       InstantiateDefaultCtorDefaultArgs(Ctor);
14535     }
14536   }
14537 
14538   // See if this is a redefinition. If 'will have body' (or similar) is already
14539   // set, then these checks were already performed when it was set.
14540   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14541       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14542     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14543 
14544     // If we're skipping the body, we're done. Don't enter the scope.
14545     if (SkipBody && SkipBody->ShouldSkip)
14546       return D;
14547   }
14548 
14549   // Mark this function as "will have a body eventually".  This lets users to
14550   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14551   // this function.
14552   FD->setWillHaveBody();
14553 
14554   // If we are instantiating a generic lambda call operator, push
14555   // a LambdaScopeInfo onto the function stack.  But use the information
14556   // that's already been calculated (ActOnLambdaExpr) to prime the current
14557   // LambdaScopeInfo.
14558   // When the template operator is being specialized, the LambdaScopeInfo,
14559   // has to be properly restored so that tryCaptureVariable doesn't try
14560   // and capture any new variables. In addition when calculating potential
14561   // captures during transformation of nested lambdas, it is necessary to
14562   // have the LSI properly restored.
14563   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14564     assert(inTemplateInstantiation() &&
14565            "There should be an active template instantiation on the stack "
14566            "when instantiating a generic lambda!");
14567     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14568   } else {
14569     // Enter a new function scope
14570     PushFunctionScope();
14571   }
14572 
14573   // Builtin functions cannot be defined.
14574   if (unsigned BuiltinID = FD->getBuiltinID()) {
14575     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14576         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14577       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14578       FD->setInvalidDecl();
14579     }
14580   }
14581 
14582   // The return type of a function definition must be complete (C99 6.9.1p3),
14583   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14584   QualType ResultType = FD->getReturnType();
14585   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14586       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14587       RequireCompleteType(FD->getLocation(), ResultType,
14588                           diag::err_func_def_incomplete_result))
14589     FD->setInvalidDecl();
14590 
14591   if (FnBodyScope)
14592     PushDeclContext(FnBodyScope, FD);
14593 
14594   // Check the validity of our function parameters
14595   if (BodyKind != FnBodyKind::Delete)
14596     CheckParmsForFunctionDef(FD->parameters(),
14597                              /*CheckParameterNames=*/true);
14598 
14599   // Add non-parameter declarations already in the function to the current
14600   // scope.
14601   if (FnBodyScope) {
14602     for (Decl *NPD : FD->decls()) {
14603       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14604       if (!NonParmDecl)
14605         continue;
14606       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14607              "parameters should not be in newly created FD yet");
14608 
14609       // If the decl has a name, make it accessible in the current scope.
14610       if (NonParmDecl->getDeclName())
14611         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14612 
14613       // Similarly, dive into enums and fish their constants out, making them
14614       // accessible in this scope.
14615       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14616         for (auto *EI : ED->enumerators())
14617           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14618       }
14619     }
14620   }
14621 
14622   // Introduce our parameters into the function scope
14623   for (auto Param : FD->parameters()) {
14624     Param->setOwningFunction(FD);
14625 
14626     // If this has an identifier, add it to the scope stack.
14627     if (Param->getIdentifier() && FnBodyScope) {
14628       CheckShadow(FnBodyScope, Param);
14629 
14630       PushOnScopeChains(Param, FnBodyScope);
14631     }
14632   }
14633 
14634   // Ensure that the function's exception specification is instantiated.
14635   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14636     ResolveExceptionSpec(D->getLocation(), FPT);
14637 
14638   // dllimport cannot be applied to non-inline function definitions.
14639   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14640       !FD->isTemplateInstantiation()) {
14641     assert(!FD->hasAttr<DLLExportAttr>());
14642     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14643     FD->setInvalidDecl();
14644     return D;
14645   }
14646   // We want to attach documentation to original Decl (which might be
14647   // a function template).
14648   ActOnDocumentableDecl(D);
14649   if (getCurLexicalContext()->isObjCContainer() &&
14650       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14651       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14652     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14653 
14654   return D;
14655 }
14656 
14657 /// Given the set of return statements within a function body,
14658 /// compute the variables that are subject to the named return value
14659 /// optimization.
14660 ///
14661 /// Each of the variables that is subject to the named return value
14662 /// optimization will be marked as NRVO variables in the AST, and any
14663 /// return statement that has a marked NRVO variable as its NRVO candidate can
14664 /// use the named return value optimization.
14665 ///
14666 /// This function applies a very simplistic algorithm for NRVO: if every return
14667 /// statement in the scope of a variable has the same NRVO candidate, that
14668 /// candidate is an NRVO variable.
14669 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14670   ReturnStmt **Returns = Scope->Returns.data();
14671 
14672   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14673     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14674       if (!NRVOCandidate->isNRVOVariable())
14675         Returns[I]->setNRVOCandidate(nullptr);
14676     }
14677   }
14678 }
14679 
14680 bool Sema::canDelayFunctionBody(const Declarator &D) {
14681   // We can't delay parsing the body of a constexpr function template (yet).
14682   if (D.getDeclSpec().hasConstexprSpecifier())
14683     return false;
14684 
14685   // We can't delay parsing the body of a function template with a deduced
14686   // return type (yet).
14687   if (D.getDeclSpec().hasAutoTypeSpec()) {
14688     // If the placeholder introduces a non-deduced trailing return type,
14689     // we can still delay parsing it.
14690     if (D.getNumTypeObjects()) {
14691       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14692       if (Outer.Kind == DeclaratorChunk::Function &&
14693           Outer.Fun.hasTrailingReturnType()) {
14694         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14695         return Ty.isNull() || !Ty->isUndeducedType();
14696       }
14697     }
14698     return false;
14699   }
14700 
14701   return true;
14702 }
14703 
14704 bool Sema::canSkipFunctionBody(Decl *D) {
14705   // We cannot skip the body of a function (or function template) which is
14706   // constexpr, since we may need to evaluate its body in order to parse the
14707   // rest of the file.
14708   // We cannot skip the body of a function with an undeduced return type,
14709   // because any callers of that function need to know the type.
14710   if (const FunctionDecl *FD = D->getAsFunction()) {
14711     if (FD->isConstexpr())
14712       return false;
14713     // We can't simply call Type::isUndeducedType here, because inside template
14714     // auto can be deduced to a dependent type, which is not considered
14715     // "undeduced".
14716     if (FD->getReturnType()->getContainedDeducedType())
14717       return false;
14718   }
14719   return Consumer.shouldSkipFunctionBody(D);
14720 }
14721 
14722 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14723   if (!Decl)
14724     return nullptr;
14725   if (FunctionDecl *FD = Decl->getAsFunction())
14726     FD->setHasSkippedBody();
14727   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14728     MD->setHasSkippedBody();
14729   return Decl;
14730 }
14731 
14732 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14733   return ActOnFinishFunctionBody(D, BodyArg, false);
14734 }
14735 
14736 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14737 /// body.
14738 class ExitFunctionBodyRAII {
14739 public:
14740   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14741   ~ExitFunctionBodyRAII() {
14742     if (!IsLambda)
14743       S.PopExpressionEvaluationContext();
14744   }
14745 
14746 private:
14747   Sema &S;
14748   bool IsLambda = false;
14749 };
14750 
14751 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14752   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14753 
14754   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14755     if (EscapeInfo.count(BD))
14756       return EscapeInfo[BD];
14757 
14758     bool R = false;
14759     const BlockDecl *CurBD = BD;
14760 
14761     do {
14762       R = !CurBD->doesNotEscape();
14763       if (R)
14764         break;
14765       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14766     } while (CurBD);
14767 
14768     return EscapeInfo[BD] = R;
14769   };
14770 
14771   // If the location where 'self' is implicitly retained is inside a escaping
14772   // block, emit a diagnostic.
14773   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14774        S.ImplicitlyRetainedSelfLocs)
14775     if (IsOrNestedInEscapingBlock(P.second))
14776       S.Diag(P.first, diag::warn_implicitly_retains_self)
14777           << FixItHint::CreateInsertion(P.first, "self->");
14778 }
14779 
14780 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14781                                     bool IsInstantiation) {
14782   FunctionScopeInfo *FSI = getCurFunction();
14783   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14784 
14785   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14786     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14787 
14788   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14789   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14790 
14791   if (getLangOpts().Coroutines && FSI->isCoroutine())
14792     CheckCompletedCoroutineBody(FD, Body);
14793 
14794   {
14795     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14796     // one is already popped when finishing the lambda in BuildLambdaExpr().
14797     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14798     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14799 
14800     if (FD) {
14801       FD->setBody(Body);
14802       FD->setWillHaveBody(false);
14803 
14804       if (getLangOpts().CPlusPlus14) {
14805         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14806             FD->getReturnType()->isUndeducedType()) {
14807           // For a function with a deduced result type to return void,
14808           // the result type as written must be 'auto' or 'decltype(auto)',
14809           // possibly cv-qualified or constrained, but not ref-qualified.
14810           if (!FD->getReturnType()->getAs<AutoType>()) {
14811             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14812                 << FD->getReturnType();
14813             FD->setInvalidDecl();
14814           } else {
14815             // Falling off the end of the function is the same as 'return;'.
14816             Expr *Dummy = nullptr;
14817             if (DeduceFunctionTypeFromReturnExpr(
14818                     FD, dcl->getLocation(), Dummy,
14819                     FD->getReturnType()->getAs<AutoType>()))
14820               FD->setInvalidDecl();
14821           }
14822         }
14823       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14824         // In C++11, we don't use 'auto' deduction rules for lambda call
14825         // operators because we don't support return type deduction.
14826         auto *LSI = getCurLambda();
14827         if (LSI->HasImplicitReturnType) {
14828           deduceClosureReturnType(*LSI);
14829 
14830           // C++11 [expr.prim.lambda]p4:
14831           //   [...] if there are no return statements in the compound-statement
14832           //   [the deduced type is] the type void
14833           QualType RetType =
14834               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14835 
14836           // Update the return type to the deduced type.
14837           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14838           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14839                                               Proto->getExtProtoInfo()));
14840         }
14841       }
14842 
14843       // If the function implicitly returns zero (like 'main') or is naked,
14844       // don't complain about missing return statements.
14845       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14846         WP.disableCheckFallThrough();
14847 
14848       // MSVC permits the use of pure specifier (=0) on function definition,
14849       // defined at class scope, warn about this non-standard construct.
14850       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14851         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14852 
14853       if (!FD->isInvalidDecl()) {
14854         // Don't diagnose unused parameters of defaulted, deleted or naked
14855         // functions.
14856         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14857             !FD->hasAttr<NakedAttr>())
14858           DiagnoseUnusedParameters(FD->parameters());
14859         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14860                                                FD->getReturnType(), FD);
14861 
14862         // If this is a structor, we need a vtable.
14863         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14864           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14865         else if (CXXDestructorDecl *Destructor =
14866                      dyn_cast<CXXDestructorDecl>(FD))
14867           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14868 
14869         // Try to apply the named return value optimization. We have to check
14870         // if we can do this here because lambdas keep return statements around
14871         // to deduce an implicit return type.
14872         if (FD->getReturnType()->isRecordType() &&
14873             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14874           computeNRVO(Body, FSI);
14875       }
14876 
14877       // GNU warning -Wmissing-prototypes:
14878       //   Warn if a global function is defined without a previous
14879       //   prototype declaration. This warning is issued even if the
14880       //   definition itself provides a prototype. The aim is to detect
14881       //   global functions that fail to be declared in header files.
14882       const FunctionDecl *PossiblePrototype = nullptr;
14883       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14884         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14885 
14886         if (PossiblePrototype) {
14887           // We found a declaration that is not a prototype,
14888           // but that could be a zero-parameter prototype
14889           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14890             TypeLoc TL = TI->getTypeLoc();
14891             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14892               Diag(PossiblePrototype->getLocation(),
14893                    diag::note_declaration_not_a_prototype)
14894                   << (FD->getNumParams() != 0)
14895                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14896                                                     FTL.getRParenLoc(), "void")
14897                                               : FixItHint{});
14898           }
14899         } else {
14900           // Returns true if the token beginning at this Loc is `const`.
14901           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14902                                   const LangOptions &LangOpts) {
14903             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14904             if (LocInfo.first.isInvalid())
14905               return false;
14906 
14907             bool Invalid = false;
14908             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14909             if (Invalid)
14910               return false;
14911 
14912             if (LocInfo.second > Buffer.size())
14913               return false;
14914 
14915             const char *LexStart = Buffer.data() + LocInfo.second;
14916             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14917 
14918             return StartTok.consume_front("const") &&
14919                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14920                     StartTok.startswith("/*") || StartTok.startswith("//"));
14921           };
14922 
14923           auto findBeginLoc = [&]() {
14924             // If the return type has `const` qualifier, we want to insert
14925             // `static` before `const` (and not before the typename).
14926             if ((FD->getReturnType()->isAnyPointerType() &&
14927                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14928                 FD->getReturnType().isConstQualified()) {
14929               // But only do this if we can determine where the `const` is.
14930 
14931               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14932                                getLangOpts()))
14933 
14934                 return FD->getBeginLoc();
14935             }
14936             return FD->getTypeSpecStartLoc();
14937           };
14938           Diag(FD->getTypeSpecStartLoc(),
14939                diag::note_static_for_internal_linkage)
14940               << /* function */ 1
14941               << (FD->getStorageClass() == SC_None
14942                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14943                       : FixItHint{});
14944         }
14945       }
14946 
14947       // If the function being defined does not have a prototype, then we may
14948       // need to diagnose it as changing behavior in C2x because we now know
14949       // whether the function accepts arguments or not. This only handles the
14950       // case where the definition has no prototype but does have parameters
14951       // and either there is no previous potential prototype, or the previous
14952       // potential prototype also has no actual prototype. This handles cases
14953       // like:
14954       //   void f(); void f(a) int a; {}
14955       //   void g(a) int a; {}
14956       // See MergeFunctionDecl() for other cases of the behavior change
14957       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
14958       // type without a prototype.
14959       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
14960           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
14961                                   !PossiblePrototype->isImplicit()))) {
14962         // The function definition has parameters, so this will change behavior
14963         // in C2x. If there is a possible prototype, it comes before the
14964         // function definition.
14965         // FIXME: The declaration may have already been diagnosed as being
14966         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
14967         // there's no way to test for the "changes behavior" condition in
14968         // SemaType.cpp when forming the declaration's function type. So, we do
14969         // this awkward dance instead.
14970         //
14971         // If we have a possible prototype and it declares a function with a
14972         // prototype, we don't want to diagnose it; if we have a possible
14973         // prototype and it has no prototype, it may have already been
14974         // diagnosed in SemaType.cpp as deprecated depending on whether
14975         // -Wstrict-prototypes is enabled. If we already warned about it being
14976         // deprecated, add a note that it also changes behavior. If we didn't
14977         // warn about it being deprecated (because the diagnostic is not
14978         // enabled), warn now that it is deprecated and changes behavior.
14979         bool AddNote = false;
14980         if (PossiblePrototype) {
14981           if (Diags.isIgnored(diag::warn_strict_prototypes,
14982                               PossiblePrototype->getLocation())) {
14983 
14984             PartialDiagnostic PD =
14985                 PDiag(diag::warn_non_prototype_changes_behavior);
14986             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
14987               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
14988                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
14989             }
14990             Diag(PossiblePrototype->getLocation(), PD);
14991           } else {
14992             AddNote = true;
14993           }
14994         }
14995 
14996         // Because this function definition has no prototype and it has
14997         // parameters, it will definitely change behavior in C2x.
14998         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
14999         if (AddNote)
15000           Diag(PossiblePrototype->getLocation(),
15001                diag::note_func_decl_changes_behavior);
15002       }
15003 
15004       // Warn on CPUDispatch with an actual body.
15005       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15006         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15007           if (!CmpndBody->body_empty())
15008             Diag(CmpndBody->body_front()->getBeginLoc(),
15009                  diag::warn_dispatch_body_ignored);
15010 
15011       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15012         const CXXMethodDecl *KeyFunction;
15013         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15014             MD->isVirtual() &&
15015             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15016             MD == KeyFunction->getCanonicalDecl()) {
15017           // Update the key-function state if necessary for this ABI.
15018           if (FD->isInlined() &&
15019               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15020             Context.setNonKeyFunction(MD);
15021 
15022             // If the newly-chosen key function is already defined, then we
15023             // need to mark the vtable as used retroactively.
15024             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15025             const FunctionDecl *Definition;
15026             if (KeyFunction && KeyFunction->isDefined(Definition))
15027               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15028           } else {
15029             // We just defined they key function; mark the vtable as used.
15030             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15031           }
15032         }
15033       }
15034 
15035       assert(
15036           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15037           "Function parsing confused");
15038     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15039       assert(MD == getCurMethodDecl() && "Method parsing confused");
15040       MD->setBody(Body);
15041       if (!MD->isInvalidDecl()) {
15042         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15043                                                MD->getReturnType(), MD);
15044 
15045         if (Body)
15046           computeNRVO(Body, FSI);
15047       }
15048       if (FSI->ObjCShouldCallSuper) {
15049         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15050             << MD->getSelector().getAsString();
15051         FSI->ObjCShouldCallSuper = false;
15052       }
15053       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15054         const ObjCMethodDecl *InitMethod = nullptr;
15055         bool isDesignated =
15056             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15057         assert(isDesignated && InitMethod);
15058         (void)isDesignated;
15059 
15060         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15061           auto IFace = MD->getClassInterface();
15062           if (!IFace)
15063             return false;
15064           auto SuperD = IFace->getSuperClass();
15065           if (!SuperD)
15066             return false;
15067           return SuperD->getIdentifier() ==
15068                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15069         };
15070         // Don't issue this warning for unavailable inits or direct subclasses
15071         // of NSObject.
15072         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15073           Diag(MD->getLocation(),
15074                diag::warn_objc_designated_init_missing_super_call);
15075           Diag(InitMethod->getLocation(),
15076                diag::note_objc_designated_init_marked_here);
15077         }
15078         FSI->ObjCWarnForNoDesignatedInitChain = false;
15079       }
15080       if (FSI->ObjCWarnForNoInitDelegation) {
15081         // Don't issue this warning for unavaialable inits.
15082         if (!MD->isUnavailable())
15083           Diag(MD->getLocation(),
15084                diag::warn_objc_secondary_init_missing_init_call);
15085         FSI->ObjCWarnForNoInitDelegation = false;
15086       }
15087 
15088       diagnoseImplicitlyRetainedSelf(*this);
15089     } else {
15090       // Parsing the function declaration failed in some way. Pop the fake scope
15091       // we pushed on.
15092       PopFunctionScopeInfo(ActivePolicy, dcl);
15093       return nullptr;
15094     }
15095 
15096     if (Body && FSI->HasPotentialAvailabilityViolations)
15097       DiagnoseUnguardedAvailabilityViolations(dcl);
15098 
15099     assert(!FSI->ObjCShouldCallSuper &&
15100            "This should only be set for ObjC methods, which should have been "
15101            "handled in the block above.");
15102 
15103     // Verify and clean out per-function state.
15104     if (Body && (!FD || !FD->isDefaulted())) {
15105       // C++ constructors that have function-try-blocks can't have return
15106       // statements in the handlers of that block. (C++ [except.handle]p14)
15107       // Verify this.
15108       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15109         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15110 
15111       // Verify that gotos and switch cases don't jump into scopes illegally.
15112       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15113         DiagnoseInvalidJumps(Body);
15114 
15115       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15116         if (!Destructor->getParent()->isDependentType())
15117           CheckDestructor(Destructor);
15118 
15119         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15120                                                Destructor->getParent());
15121       }
15122 
15123       // If any errors have occurred, clear out any temporaries that may have
15124       // been leftover. This ensures that these temporaries won't be picked up
15125       // for deletion in some later function.
15126       if (hasUncompilableErrorOccurred() ||
15127           getDiagnostics().getSuppressAllDiagnostics()) {
15128         DiscardCleanupsInEvaluationContext();
15129       }
15130       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15131         // Since the body is valid, issue any analysis-based warnings that are
15132         // enabled.
15133         ActivePolicy = &WP;
15134       }
15135 
15136       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15137           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15138         FD->setInvalidDecl();
15139 
15140       if (FD && FD->hasAttr<NakedAttr>()) {
15141         for (const Stmt *S : Body->children()) {
15142           // Allow local register variables without initializer as they don't
15143           // require prologue.
15144           bool RegisterVariables = false;
15145           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15146             for (const auto *Decl : DS->decls()) {
15147               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15148                 RegisterVariables =
15149                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15150                 if (!RegisterVariables)
15151                   break;
15152               }
15153             }
15154           }
15155           if (RegisterVariables)
15156             continue;
15157           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15158             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15159             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15160             FD->setInvalidDecl();
15161             break;
15162           }
15163         }
15164       }
15165 
15166       assert(ExprCleanupObjects.size() ==
15167                  ExprEvalContexts.back().NumCleanupObjects &&
15168              "Leftover temporaries in function");
15169       assert(!Cleanup.exprNeedsCleanups() &&
15170              "Unaccounted cleanups in function");
15171       assert(MaybeODRUseExprs.empty() &&
15172              "Leftover expressions for odr-use checking");
15173     }
15174   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15175     // the declaration context below. Otherwise, we're unable to transform
15176     // 'this' expressions when transforming immediate context functions.
15177 
15178   if (!IsInstantiation)
15179     PopDeclContext();
15180 
15181   PopFunctionScopeInfo(ActivePolicy, dcl);
15182   // If any errors have occurred, clear out any temporaries that may have
15183   // been leftover. This ensures that these temporaries won't be picked up for
15184   // deletion in some later function.
15185   if (hasUncompilableErrorOccurred()) {
15186     DiscardCleanupsInEvaluationContext();
15187   }
15188 
15189   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15190                                   !LangOpts.OMPTargetTriples.empty())) ||
15191              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15192     auto ES = getEmissionStatus(FD);
15193     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15194         ES == Sema::FunctionEmissionStatus::Unknown)
15195       DeclsToCheckForDeferredDiags.insert(FD);
15196   }
15197 
15198   if (FD && !FD->isDeleted())
15199     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15200 
15201   return dcl;
15202 }
15203 
15204 /// When we finish delayed parsing of an attribute, we must attach it to the
15205 /// relevant Decl.
15206 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15207                                        ParsedAttributes &Attrs) {
15208   // Always attach attributes to the underlying decl.
15209   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15210     D = TD->getTemplatedDecl();
15211   ProcessDeclAttributeList(S, D, Attrs);
15212 
15213   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15214     if (Method->isStatic())
15215       checkThisInStaticMemberFunctionAttributes(Method);
15216 }
15217 
15218 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15219 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15220 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15221                                           IdentifierInfo &II, Scope *S) {
15222   // Find the scope in which the identifier is injected and the corresponding
15223   // DeclContext.
15224   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15225   // In that case, we inject the declaration into the translation unit scope
15226   // instead.
15227   Scope *BlockScope = S;
15228   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15229     BlockScope = BlockScope->getParent();
15230 
15231   Scope *ContextScope = BlockScope;
15232   while (!ContextScope->getEntity())
15233     ContextScope = ContextScope->getParent();
15234   ContextRAII SavedContext(*this, ContextScope->getEntity());
15235 
15236   // Before we produce a declaration for an implicitly defined
15237   // function, see whether there was a locally-scoped declaration of
15238   // this name as a function or variable. If so, use that
15239   // (non-visible) declaration, and complain about it.
15240   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15241   if (ExternCPrev) {
15242     // We still need to inject the function into the enclosing block scope so
15243     // that later (non-call) uses can see it.
15244     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15245 
15246     // C89 footnote 38:
15247     //   If in fact it is not defined as having type "function returning int",
15248     //   the behavior is undefined.
15249     if (!isa<FunctionDecl>(ExternCPrev) ||
15250         !Context.typesAreCompatible(
15251             cast<FunctionDecl>(ExternCPrev)->getType(),
15252             Context.getFunctionNoProtoType(Context.IntTy))) {
15253       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15254           << ExternCPrev << !getLangOpts().C99;
15255       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15256       return ExternCPrev;
15257     }
15258   }
15259 
15260   // Extension in C99.  Legal in C90, but warn about it.
15261   unsigned diag_id;
15262   if (II.getName().startswith("__builtin_"))
15263     diag_id = diag::warn_builtin_unknown;
15264   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15265   else if (getLangOpts().OpenCL)
15266     diag_id = diag::err_opencl_implicit_function_decl;
15267   else if (getLangOpts().C99)
15268     diag_id = diag::ext_implicit_function_decl;
15269   else
15270     diag_id = diag::warn_implicit_function_decl;
15271 
15272   TypoCorrection Corrected;
15273   // Because typo correction is expensive, only do it if the implicit
15274   // function declaration is going to be treated as an error.
15275   //
15276   // Perform the corection before issuing the main diagnostic, as some consumers
15277   // use typo-correction callbacks to enhance the main diagnostic.
15278   if (S && !ExternCPrev &&
15279       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15280     DeclFilterCCC<FunctionDecl> CCC{};
15281     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15282                             S, nullptr, CCC, CTK_NonError);
15283   }
15284 
15285   Diag(Loc, diag_id) << &II;
15286   if (Corrected)
15287     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15288                  /*ErrorRecovery*/ false);
15289 
15290   // If we found a prior declaration of this function, don't bother building
15291   // another one. We've already pushed that one into scope, so there's nothing
15292   // more to do.
15293   if (ExternCPrev)
15294     return ExternCPrev;
15295 
15296   // Set a Declarator for the implicit definition: int foo();
15297   const char *Dummy;
15298   AttributeFactory attrFactory;
15299   DeclSpec DS(attrFactory);
15300   unsigned DiagID;
15301   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15302                                   Context.getPrintingPolicy());
15303   (void)Error; // Silence warning.
15304   assert(!Error && "Error setting up implicit decl!");
15305   SourceLocation NoLoc;
15306   Declarator D(DS, DeclaratorContext::Block);
15307   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15308                                              /*IsAmbiguous=*/false,
15309                                              /*LParenLoc=*/NoLoc,
15310                                              /*Params=*/nullptr,
15311                                              /*NumParams=*/0,
15312                                              /*EllipsisLoc=*/NoLoc,
15313                                              /*RParenLoc=*/NoLoc,
15314                                              /*RefQualifierIsLvalueRef=*/true,
15315                                              /*RefQualifierLoc=*/NoLoc,
15316                                              /*MutableLoc=*/NoLoc, EST_None,
15317                                              /*ESpecRange=*/SourceRange(),
15318                                              /*Exceptions=*/nullptr,
15319                                              /*ExceptionRanges=*/nullptr,
15320                                              /*NumExceptions=*/0,
15321                                              /*NoexceptExpr=*/nullptr,
15322                                              /*ExceptionSpecTokens=*/nullptr,
15323                                              /*DeclsInPrototype=*/None, Loc,
15324                                              Loc, D),
15325                 std::move(DS.getAttributes()), SourceLocation());
15326   D.SetIdentifier(&II, Loc);
15327 
15328   // Insert this function into the enclosing block scope.
15329   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15330   FD->setImplicit();
15331 
15332   AddKnownFunctionAttributes(FD);
15333 
15334   return FD;
15335 }
15336 
15337 /// If this function is a C++ replaceable global allocation function
15338 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15339 /// adds any function attributes that we know a priori based on the standard.
15340 ///
15341 /// We need to check for duplicate attributes both here and where user-written
15342 /// attributes are applied to declarations.
15343 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15344     FunctionDecl *FD) {
15345   if (FD->isInvalidDecl())
15346     return;
15347 
15348   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15349       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15350     return;
15351 
15352   Optional<unsigned> AlignmentParam;
15353   bool IsNothrow = false;
15354   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15355     return;
15356 
15357   // C++2a [basic.stc.dynamic.allocation]p4:
15358   //   An allocation function that has a non-throwing exception specification
15359   //   indicates failure by returning a null pointer value. Any other allocation
15360   //   function never returns a null pointer value and indicates failure only by
15361   //   throwing an exception [...]
15362   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15363     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15364 
15365   // C++2a [basic.stc.dynamic.allocation]p2:
15366   //   An allocation function attempts to allocate the requested amount of
15367   //   storage. [...] If the request succeeds, the value returned by a
15368   //   replaceable allocation function is a [...] pointer value p0 different
15369   //   from any previously returned value p1 [...]
15370   //
15371   // However, this particular information is being added in codegen,
15372   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15373 
15374   // C++2a [basic.stc.dynamic.allocation]p2:
15375   //   An allocation function attempts to allocate the requested amount of
15376   //   storage. If it is successful, it returns the address of the start of a
15377   //   block of storage whose length in bytes is at least as large as the
15378   //   requested size.
15379   if (!FD->hasAttr<AllocSizeAttr>()) {
15380     FD->addAttr(AllocSizeAttr::CreateImplicit(
15381         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15382         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15383   }
15384 
15385   // C++2a [basic.stc.dynamic.allocation]p3:
15386   //   For an allocation function [...], the pointer returned on a successful
15387   //   call shall represent the address of storage that is aligned as follows:
15388   //   (3.1) If the allocation function takes an argument of type
15389   //         std​::​align_­val_­t, the storage will have the alignment
15390   //         specified by the value of this argument.
15391   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15392     FD->addAttr(AllocAlignAttr::CreateImplicit(
15393         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15394   }
15395 
15396   // FIXME:
15397   // C++2a [basic.stc.dynamic.allocation]p3:
15398   //   For an allocation function [...], the pointer returned on a successful
15399   //   call shall represent the address of storage that is aligned as follows:
15400   //   (3.2) Otherwise, if the allocation function is named operator new[],
15401   //         the storage is aligned for any object that does not have
15402   //         new-extended alignment ([basic.align]) and is no larger than the
15403   //         requested size.
15404   //   (3.3) Otherwise, the storage is aligned for any object that does not
15405   //         have new-extended alignment and is of the requested size.
15406 }
15407 
15408 /// Adds any function attributes that we know a priori based on
15409 /// the declaration of this function.
15410 ///
15411 /// These attributes can apply both to implicitly-declared builtins
15412 /// (like __builtin___printf_chk) or to library-declared functions
15413 /// like NSLog or printf.
15414 ///
15415 /// We need to check for duplicate attributes both here and where user-written
15416 /// attributes are applied to declarations.
15417 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15418   if (FD->isInvalidDecl())
15419     return;
15420 
15421   // If this is a built-in function, map its builtin attributes to
15422   // actual attributes.
15423   if (unsigned BuiltinID = FD->getBuiltinID()) {
15424     // Handle printf-formatting attributes.
15425     unsigned FormatIdx;
15426     bool HasVAListArg;
15427     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15428       if (!FD->hasAttr<FormatAttr>()) {
15429         const char *fmt = "printf";
15430         unsigned int NumParams = FD->getNumParams();
15431         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15432             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15433           fmt = "NSString";
15434         FD->addAttr(FormatAttr::CreateImplicit(Context,
15435                                                &Context.Idents.get(fmt),
15436                                                FormatIdx+1,
15437                                                HasVAListArg ? 0 : FormatIdx+2,
15438                                                FD->getLocation()));
15439       }
15440     }
15441     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15442                                              HasVAListArg)) {
15443      if (!FD->hasAttr<FormatAttr>())
15444        FD->addAttr(FormatAttr::CreateImplicit(Context,
15445                                               &Context.Idents.get("scanf"),
15446                                               FormatIdx+1,
15447                                               HasVAListArg ? 0 : FormatIdx+2,
15448                                               FD->getLocation()));
15449     }
15450 
15451     // Handle automatically recognized callbacks.
15452     SmallVector<int, 4> Encoding;
15453     if (!FD->hasAttr<CallbackAttr>() &&
15454         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15455       FD->addAttr(CallbackAttr::CreateImplicit(
15456           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15457 
15458     // Mark const if we don't care about errno and that is the only thing
15459     // preventing the function from being const. This allows IRgen to use LLVM
15460     // intrinsics for such functions.
15461     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15462         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15463       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15464 
15465     // We make "fma" on GNU or Windows const because we know it does not set
15466     // errno in those environments even though it could set errno based on the
15467     // C standard.
15468     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15469     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15470         !FD->hasAttr<ConstAttr>()) {
15471       switch (BuiltinID) {
15472       case Builtin::BI__builtin_fma:
15473       case Builtin::BI__builtin_fmaf:
15474       case Builtin::BI__builtin_fmal:
15475       case Builtin::BIfma:
15476       case Builtin::BIfmaf:
15477       case Builtin::BIfmal:
15478         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15479         break;
15480       default:
15481         break;
15482       }
15483     }
15484 
15485     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15486         !FD->hasAttr<ReturnsTwiceAttr>())
15487       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15488                                          FD->getLocation()));
15489     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15490       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15491     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15492       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15493     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15494       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15495     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15496         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15497       // Add the appropriate attribute, depending on the CUDA compilation mode
15498       // and which target the builtin belongs to. For example, during host
15499       // compilation, aux builtins are __device__, while the rest are __host__.
15500       if (getLangOpts().CUDAIsDevice !=
15501           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15502         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15503       else
15504         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15505     }
15506 
15507     // Add known guaranteed alignment for allocation functions.
15508     switch (BuiltinID) {
15509     case Builtin::BImemalign:
15510     case Builtin::BIaligned_alloc:
15511       if (!FD->hasAttr<AllocAlignAttr>())
15512         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15513                                                    FD->getLocation()));
15514       break;
15515     default:
15516       break;
15517     }
15518 
15519     // Add allocsize attribute for allocation functions.
15520     switch (BuiltinID) {
15521     case Builtin::BIcalloc:
15522       FD->addAttr(AllocSizeAttr::CreateImplicit(
15523           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15524       break;
15525     case Builtin::BImemalign:
15526     case Builtin::BIaligned_alloc:
15527     case Builtin::BIrealloc:
15528       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15529                                                 ParamIdx(), FD->getLocation()));
15530       break;
15531     case Builtin::BImalloc:
15532       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15533                                                 ParamIdx(), FD->getLocation()));
15534       break;
15535     default:
15536       break;
15537     }
15538   }
15539 
15540   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15541 
15542   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15543   // throw, add an implicit nothrow attribute to any extern "C" function we come
15544   // across.
15545   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15546       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15547     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15548     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15549       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15550   }
15551 
15552   IdentifierInfo *Name = FD->getIdentifier();
15553   if (!Name)
15554     return;
15555   if ((!getLangOpts().CPlusPlus &&
15556        FD->getDeclContext()->isTranslationUnit()) ||
15557       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15558        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15559        LinkageSpecDecl::lang_c)) {
15560     // Okay: this could be a libc/libm/Objective-C function we know
15561     // about.
15562   } else
15563     return;
15564 
15565   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15566     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15567     // target-specific builtins, perhaps?
15568     if (!FD->hasAttr<FormatAttr>())
15569       FD->addAttr(FormatAttr::CreateImplicit(Context,
15570                                              &Context.Idents.get("printf"), 2,
15571                                              Name->isStr("vasprintf") ? 0 : 3,
15572                                              FD->getLocation()));
15573   }
15574 
15575   if (Name->isStr("__CFStringMakeConstantString")) {
15576     // We already have a __builtin___CFStringMakeConstantString,
15577     // but builds that use -fno-constant-cfstrings don't go through that.
15578     if (!FD->hasAttr<FormatArgAttr>())
15579       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15580                                                 FD->getLocation()));
15581   }
15582 }
15583 
15584 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15585                                     TypeSourceInfo *TInfo) {
15586   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15587   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15588 
15589   if (!TInfo) {
15590     assert(D.isInvalidType() && "no declarator info for valid type");
15591     TInfo = Context.getTrivialTypeSourceInfo(T);
15592   }
15593 
15594   // Scope manipulation handled by caller.
15595   TypedefDecl *NewTD =
15596       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15597                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15598 
15599   // Bail out immediately if we have an invalid declaration.
15600   if (D.isInvalidType()) {
15601     NewTD->setInvalidDecl();
15602     return NewTD;
15603   }
15604 
15605   if (D.getDeclSpec().isModulePrivateSpecified()) {
15606     if (CurContext->isFunctionOrMethod())
15607       Diag(NewTD->getLocation(), diag::err_module_private_local)
15608           << 2 << NewTD
15609           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15610           << FixItHint::CreateRemoval(
15611                  D.getDeclSpec().getModulePrivateSpecLoc());
15612     else
15613       NewTD->setModulePrivate();
15614   }
15615 
15616   // C++ [dcl.typedef]p8:
15617   //   If the typedef declaration defines an unnamed class (or
15618   //   enum), the first typedef-name declared by the declaration
15619   //   to be that class type (or enum type) is used to denote the
15620   //   class type (or enum type) for linkage purposes only.
15621   // We need to check whether the type was declared in the declaration.
15622   switch (D.getDeclSpec().getTypeSpecType()) {
15623   case TST_enum:
15624   case TST_struct:
15625   case TST_interface:
15626   case TST_union:
15627   case TST_class: {
15628     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15629     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15630     break;
15631   }
15632 
15633   default:
15634     break;
15635   }
15636 
15637   return NewTD;
15638 }
15639 
15640 /// Check that this is a valid underlying type for an enum declaration.
15641 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15642   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15643   QualType T = TI->getType();
15644 
15645   if (T->isDependentType())
15646     return false;
15647 
15648   // This doesn't use 'isIntegralType' despite the error message mentioning
15649   // integral type because isIntegralType would also allow enum types in C.
15650   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15651     if (BT->isInteger())
15652       return false;
15653 
15654   if (T->isBitIntType())
15655     return false;
15656 
15657   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15658 }
15659 
15660 /// Check whether this is a valid redeclaration of a previous enumeration.
15661 /// \return true if the redeclaration was invalid.
15662 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15663                                   QualType EnumUnderlyingTy, bool IsFixed,
15664                                   const EnumDecl *Prev) {
15665   if (IsScoped != Prev->isScoped()) {
15666     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15667       << Prev->isScoped();
15668     Diag(Prev->getLocation(), diag::note_previous_declaration);
15669     return true;
15670   }
15671 
15672   if (IsFixed && Prev->isFixed()) {
15673     if (!EnumUnderlyingTy->isDependentType() &&
15674         !Prev->getIntegerType()->isDependentType() &&
15675         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15676                                         Prev->getIntegerType())) {
15677       // TODO: Highlight the underlying type of the redeclaration.
15678       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15679         << EnumUnderlyingTy << Prev->getIntegerType();
15680       Diag(Prev->getLocation(), diag::note_previous_declaration)
15681           << Prev->getIntegerTypeRange();
15682       return true;
15683     }
15684   } else if (IsFixed != Prev->isFixed()) {
15685     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15686       << Prev->isFixed();
15687     Diag(Prev->getLocation(), diag::note_previous_declaration);
15688     return true;
15689   }
15690 
15691   return false;
15692 }
15693 
15694 /// Get diagnostic %select index for tag kind for
15695 /// redeclaration diagnostic message.
15696 /// WARNING: Indexes apply to particular diagnostics only!
15697 ///
15698 /// \returns diagnostic %select index.
15699 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15700   switch (Tag) {
15701   case TTK_Struct: return 0;
15702   case TTK_Interface: return 1;
15703   case TTK_Class:  return 2;
15704   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15705   }
15706 }
15707 
15708 /// Determine if tag kind is a class-key compatible with
15709 /// class for redeclaration (class, struct, or __interface).
15710 ///
15711 /// \returns true iff the tag kind is compatible.
15712 static bool isClassCompatTagKind(TagTypeKind Tag)
15713 {
15714   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15715 }
15716 
15717 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15718                                              TagTypeKind TTK) {
15719   if (isa<TypedefDecl>(PrevDecl))
15720     return NTK_Typedef;
15721   else if (isa<TypeAliasDecl>(PrevDecl))
15722     return NTK_TypeAlias;
15723   else if (isa<ClassTemplateDecl>(PrevDecl))
15724     return NTK_Template;
15725   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15726     return NTK_TypeAliasTemplate;
15727   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15728     return NTK_TemplateTemplateArgument;
15729   switch (TTK) {
15730   case TTK_Struct:
15731   case TTK_Interface:
15732   case TTK_Class:
15733     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15734   case TTK_Union:
15735     return NTK_NonUnion;
15736   case TTK_Enum:
15737     return NTK_NonEnum;
15738   }
15739   llvm_unreachable("invalid TTK");
15740 }
15741 
15742 /// Determine whether a tag with a given kind is acceptable
15743 /// as a redeclaration of the given tag declaration.
15744 ///
15745 /// \returns true if the new tag kind is acceptable, false otherwise.
15746 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15747                                         TagTypeKind NewTag, bool isDefinition,
15748                                         SourceLocation NewTagLoc,
15749                                         const IdentifierInfo *Name) {
15750   // C++ [dcl.type.elab]p3:
15751   //   The class-key or enum keyword present in the
15752   //   elaborated-type-specifier shall agree in kind with the
15753   //   declaration to which the name in the elaborated-type-specifier
15754   //   refers. This rule also applies to the form of
15755   //   elaborated-type-specifier that declares a class-name or
15756   //   friend class since it can be construed as referring to the
15757   //   definition of the class. Thus, in any
15758   //   elaborated-type-specifier, the enum keyword shall be used to
15759   //   refer to an enumeration (7.2), the union class-key shall be
15760   //   used to refer to a union (clause 9), and either the class or
15761   //   struct class-key shall be used to refer to a class (clause 9)
15762   //   declared using the class or struct class-key.
15763   TagTypeKind OldTag = Previous->getTagKind();
15764   if (OldTag != NewTag &&
15765       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15766     return false;
15767 
15768   // Tags are compatible, but we might still want to warn on mismatched tags.
15769   // Non-class tags can't be mismatched at this point.
15770   if (!isClassCompatTagKind(NewTag))
15771     return true;
15772 
15773   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15774   // by our warning analysis. We don't want to warn about mismatches with (eg)
15775   // declarations in system headers that are designed to be specialized, but if
15776   // a user asks us to warn, we should warn if their code contains mismatched
15777   // declarations.
15778   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15779     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15780                                       Loc);
15781   };
15782   if (IsIgnoredLoc(NewTagLoc))
15783     return true;
15784 
15785   auto IsIgnored = [&](const TagDecl *Tag) {
15786     return IsIgnoredLoc(Tag->getLocation());
15787   };
15788   while (IsIgnored(Previous)) {
15789     Previous = Previous->getPreviousDecl();
15790     if (!Previous)
15791       return true;
15792     OldTag = Previous->getTagKind();
15793   }
15794 
15795   bool isTemplate = false;
15796   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15797     isTemplate = Record->getDescribedClassTemplate();
15798 
15799   if (inTemplateInstantiation()) {
15800     if (OldTag != NewTag) {
15801       // In a template instantiation, do not offer fix-its for tag mismatches
15802       // since they usually mess up the template instead of fixing the problem.
15803       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15804         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15805         << getRedeclDiagFromTagKind(OldTag);
15806       // FIXME: Note previous location?
15807     }
15808     return true;
15809   }
15810 
15811   if (isDefinition) {
15812     // On definitions, check all previous tags and issue a fix-it for each
15813     // one that doesn't match the current tag.
15814     if (Previous->getDefinition()) {
15815       // Don't suggest fix-its for redefinitions.
15816       return true;
15817     }
15818 
15819     bool previousMismatch = false;
15820     for (const TagDecl *I : Previous->redecls()) {
15821       if (I->getTagKind() != NewTag) {
15822         // Ignore previous declarations for which the warning was disabled.
15823         if (IsIgnored(I))
15824           continue;
15825 
15826         if (!previousMismatch) {
15827           previousMismatch = true;
15828           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15829             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15830             << getRedeclDiagFromTagKind(I->getTagKind());
15831         }
15832         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15833           << getRedeclDiagFromTagKind(NewTag)
15834           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15835                TypeWithKeyword::getTagTypeKindName(NewTag));
15836       }
15837     }
15838     return true;
15839   }
15840 
15841   // Identify the prevailing tag kind: this is the kind of the definition (if
15842   // there is a non-ignored definition), or otherwise the kind of the prior
15843   // (non-ignored) declaration.
15844   const TagDecl *PrevDef = Previous->getDefinition();
15845   if (PrevDef && IsIgnored(PrevDef))
15846     PrevDef = nullptr;
15847   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15848   if (Redecl->getTagKind() != NewTag) {
15849     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15850       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15851       << getRedeclDiagFromTagKind(OldTag);
15852     Diag(Redecl->getLocation(), diag::note_previous_use);
15853 
15854     // If there is a previous definition, suggest a fix-it.
15855     if (PrevDef) {
15856       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15857         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15858         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15859              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15860     }
15861   }
15862 
15863   return true;
15864 }
15865 
15866 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15867 /// from an outer enclosing namespace or file scope inside a friend declaration.
15868 /// This should provide the commented out code in the following snippet:
15869 ///   namespace N {
15870 ///     struct X;
15871 ///     namespace M {
15872 ///       struct Y { friend struct /*N::*/ X; };
15873 ///     }
15874 ///   }
15875 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15876                                          SourceLocation NameLoc) {
15877   // While the decl is in a namespace, do repeated lookup of that name and see
15878   // if we get the same namespace back.  If we do not, continue until
15879   // translation unit scope, at which point we have a fully qualified NNS.
15880   SmallVector<IdentifierInfo *, 4> Namespaces;
15881   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15882   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15883     // This tag should be declared in a namespace, which can only be enclosed by
15884     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15885     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15886     if (!Namespace || Namespace->isAnonymousNamespace())
15887       return FixItHint();
15888     IdentifierInfo *II = Namespace->getIdentifier();
15889     Namespaces.push_back(II);
15890     NamedDecl *Lookup = SemaRef.LookupSingleName(
15891         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15892     if (Lookup == Namespace)
15893       break;
15894   }
15895 
15896   // Once we have all the namespaces, reverse them to go outermost first, and
15897   // build an NNS.
15898   SmallString<64> Insertion;
15899   llvm::raw_svector_ostream OS(Insertion);
15900   if (DC->isTranslationUnit())
15901     OS << "::";
15902   std::reverse(Namespaces.begin(), Namespaces.end());
15903   for (auto *II : Namespaces)
15904     OS << II->getName() << "::";
15905   return FixItHint::CreateInsertion(NameLoc, Insertion);
15906 }
15907 
15908 /// Determine whether a tag originally declared in context \p OldDC can
15909 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15910 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15911 /// using-declaration).
15912 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15913                                          DeclContext *NewDC) {
15914   OldDC = OldDC->getRedeclContext();
15915   NewDC = NewDC->getRedeclContext();
15916 
15917   if (OldDC->Equals(NewDC))
15918     return true;
15919 
15920   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15921   // encloses the other).
15922   if (S.getLangOpts().MSVCCompat &&
15923       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15924     return true;
15925 
15926   return false;
15927 }
15928 
15929 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15930 /// former case, Name will be non-null.  In the later case, Name will be null.
15931 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15932 /// reference/declaration/definition of a tag.
15933 ///
15934 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15935 /// trailing-type-specifier) other than one in an alias-declaration.
15936 ///
15937 /// \param SkipBody If non-null, will be set to indicate if the caller should
15938 /// skip the definition of this tag and treat it as if it were a declaration.
15939 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15940                      SourceLocation KWLoc, CXXScopeSpec &SS,
15941                      IdentifierInfo *Name, SourceLocation NameLoc,
15942                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15943                      SourceLocation ModulePrivateLoc,
15944                      MultiTemplateParamsArg TemplateParameterLists,
15945                      bool &OwnedDecl, bool &IsDependent,
15946                      SourceLocation ScopedEnumKWLoc,
15947                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15948                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15949                      SkipBodyInfo *SkipBody) {
15950   // If this is not a definition, it must have a name.
15951   IdentifierInfo *OrigName = Name;
15952   assert((Name != nullptr || TUK == TUK_Definition) &&
15953          "Nameless record must be a definition!");
15954   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15955 
15956   OwnedDecl = false;
15957   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15958   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15959 
15960   // FIXME: Check member specializations more carefully.
15961   bool isMemberSpecialization = false;
15962   bool Invalid = false;
15963 
15964   // We only need to do this matching if we have template parameters
15965   // or a scope specifier, which also conveniently avoids this work
15966   // for non-C++ cases.
15967   if (TemplateParameterLists.size() > 0 ||
15968       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15969     if (TemplateParameterList *TemplateParams =
15970             MatchTemplateParametersToScopeSpecifier(
15971                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15972                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15973       if (Kind == TTK_Enum) {
15974         Diag(KWLoc, diag::err_enum_template);
15975         return nullptr;
15976       }
15977 
15978       if (TemplateParams->size() > 0) {
15979         // This is a declaration or definition of a class template (which may
15980         // be a member of another template).
15981 
15982         if (Invalid)
15983           return nullptr;
15984 
15985         OwnedDecl = false;
15986         DeclResult Result = CheckClassTemplate(
15987             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15988             AS, ModulePrivateLoc,
15989             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15990             TemplateParameterLists.data(), SkipBody);
15991         return Result.get();
15992       } else {
15993         // The "template<>" header is extraneous.
15994         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15995           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15996         isMemberSpecialization = true;
15997       }
15998     }
15999 
16000     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16001         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16002       return nullptr;
16003   }
16004 
16005   // Figure out the underlying type if this a enum declaration. We need to do
16006   // this early, because it's needed to detect if this is an incompatible
16007   // redeclaration.
16008   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16009   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16010 
16011   if (Kind == TTK_Enum) {
16012     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16013       // No underlying type explicitly specified, or we failed to parse the
16014       // type, default to int.
16015       EnumUnderlying = Context.IntTy.getTypePtr();
16016     } else if (UnderlyingType.get()) {
16017       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16018       // integral type; any cv-qualification is ignored.
16019       TypeSourceInfo *TI = nullptr;
16020       GetTypeFromParser(UnderlyingType.get(), &TI);
16021       EnumUnderlying = TI;
16022 
16023       if (CheckEnumUnderlyingType(TI))
16024         // Recover by falling back to int.
16025         EnumUnderlying = Context.IntTy.getTypePtr();
16026 
16027       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16028                                           UPPC_FixedUnderlyingType))
16029         EnumUnderlying = Context.IntTy.getTypePtr();
16030 
16031     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16032       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16033       // of 'int'. However, if this is an unfixed forward declaration, don't set
16034       // the underlying type unless the user enables -fms-compatibility. This
16035       // makes unfixed forward declared enums incomplete and is more conforming.
16036       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16037         EnumUnderlying = Context.IntTy.getTypePtr();
16038     }
16039   }
16040 
16041   DeclContext *SearchDC = CurContext;
16042   DeclContext *DC = CurContext;
16043   bool isStdBadAlloc = false;
16044   bool isStdAlignValT = false;
16045 
16046   RedeclarationKind Redecl = forRedeclarationInCurContext();
16047   if (TUK == TUK_Friend || TUK == TUK_Reference)
16048     Redecl = NotForRedeclaration;
16049 
16050   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16051   /// implemented asks for structural equivalence checking, the returned decl
16052   /// here is passed back to the parser, allowing the tag body to be parsed.
16053   auto createTagFromNewDecl = [&]() -> TagDecl * {
16054     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16055     // If there is an identifier, use the location of the identifier as the
16056     // location of the decl, otherwise use the location of the struct/union
16057     // keyword.
16058     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16059     TagDecl *New = nullptr;
16060 
16061     if (Kind == TTK_Enum) {
16062       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16063                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16064       // If this is an undefined enum, bail.
16065       if (TUK != TUK_Definition && !Invalid)
16066         return nullptr;
16067       if (EnumUnderlying) {
16068         EnumDecl *ED = cast<EnumDecl>(New);
16069         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16070           ED->setIntegerTypeSourceInfo(TI);
16071         else
16072           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16073         ED->setPromotionType(ED->getIntegerType());
16074       }
16075     } else { // struct/union
16076       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16077                                nullptr);
16078     }
16079 
16080     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16081       // Add alignment attributes if necessary; these attributes are checked
16082       // when the ASTContext lays out the structure.
16083       //
16084       // It is important for implementing the correct semantics that this
16085       // happen here (in ActOnTag). The #pragma pack stack is
16086       // maintained as a result of parser callbacks which can occur at
16087       // many points during the parsing of a struct declaration (because
16088       // the #pragma tokens are effectively skipped over during the
16089       // parsing of the struct).
16090       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16091         AddAlignmentAttributesForRecord(RD);
16092         AddMsStructLayoutForRecord(RD);
16093       }
16094     }
16095     New->setLexicalDeclContext(CurContext);
16096     return New;
16097   };
16098 
16099   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16100   if (Name && SS.isNotEmpty()) {
16101     // We have a nested-name tag ('struct foo::bar').
16102 
16103     // Check for invalid 'foo::'.
16104     if (SS.isInvalid()) {
16105       Name = nullptr;
16106       goto CreateNewDecl;
16107     }
16108 
16109     // If this is a friend or a reference to a class in a dependent
16110     // context, don't try to make a decl for it.
16111     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16112       DC = computeDeclContext(SS, false);
16113       if (!DC) {
16114         IsDependent = true;
16115         return nullptr;
16116       }
16117     } else {
16118       DC = computeDeclContext(SS, true);
16119       if (!DC) {
16120         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16121           << SS.getRange();
16122         return nullptr;
16123       }
16124     }
16125 
16126     if (RequireCompleteDeclContext(SS, DC))
16127       return nullptr;
16128 
16129     SearchDC = DC;
16130     // Look-up name inside 'foo::'.
16131     LookupQualifiedName(Previous, DC);
16132 
16133     if (Previous.isAmbiguous())
16134       return nullptr;
16135 
16136     if (Previous.empty()) {
16137       // Name lookup did not find anything. However, if the
16138       // nested-name-specifier refers to the current instantiation,
16139       // and that current instantiation has any dependent base
16140       // classes, we might find something at instantiation time: treat
16141       // this as a dependent elaborated-type-specifier.
16142       // But this only makes any sense for reference-like lookups.
16143       if (Previous.wasNotFoundInCurrentInstantiation() &&
16144           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16145         IsDependent = true;
16146         return nullptr;
16147       }
16148 
16149       // A tag 'foo::bar' must already exist.
16150       Diag(NameLoc, diag::err_not_tag_in_scope)
16151         << Kind << Name << DC << SS.getRange();
16152       Name = nullptr;
16153       Invalid = true;
16154       goto CreateNewDecl;
16155     }
16156   } else if (Name) {
16157     // C++14 [class.mem]p14:
16158     //   If T is the name of a class, then each of the following shall have a
16159     //   name different from T:
16160     //    -- every member of class T that is itself a type
16161     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16162         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16163       return nullptr;
16164 
16165     // If this is a named struct, check to see if there was a previous forward
16166     // declaration or definition.
16167     // FIXME: We're looking into outer scopes here, even when we
16168     // shouldn't be. Doing so can result in ambiguities that we
16169     // shouldn't be diagnosing.
16170     LookupName(Previous, S);
16171 
16172     // When declaring or defining a tag, ignore ambiguities introduced
16173     // by types using'ed into this scope.
16174     if (Previous.isAmbiguous() &&
16175         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16176       LookupResult::Filter F = Previous.makeFilter();
16177       while (F.hasNext()) {
16178         NamedDecl *ND = F.next();
16179         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16180                 SearchDC->getRedeclContext()))
16181           F.erase();
16182       }
16183       F.done();
16184     }
16185 
16186     // C++11 [namespace.memdef]p3:
16187     //   If the name in a friend declaration is neither qualified nor
16188     //   a template-id and the declaration is a function or an
16189     //   elaborated-type-specifier, the lookup to determine whether
16190     //   the entity has been previously declared shall not consider
16191     //   any scopes outside the innermost enclosing namespace.
16192     //
16193     // MSVC doesn't implement the above rule for types, so a friend tag
16194     // declaration may be a redeclaration of a type declared in an enclosing
16195     // scope.  They do implement this rule for friend functions.
16196     //
16197     // Does it matter that this should be by scope instead of by
16198     // semantic context?
16199     if (!Previous.empty() && TUK == TUK_Friend) {
16200       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16201       LookupResult::Filter F = Previous.makeFilter();
16202       bool FriendSawTagOutsideEnclosingNamespace = false;
16203       while (F.hasNext()) {
16204         NamedDecl *ND = F.next();
16205         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16206         if (DC->isFileContext() &&
16207             !EnclosingNS->Encloses(ND->getDeclContext())) {
16208           if (getLangOpts().MSVCCompat)
16209             FriendSawTagOutsideEnclosingNamespace = true;
16210           else
16211             F.erase();
16212         }
16213       }
16214       F.done();
16215 
16216       // Diagnose this MSVC extension in the easy case where lookup would have
16217       // unambiguously found something outside the enclosing namespace.
16218       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16219         NamedDecl *ND = Previous.getFoundDecl();
16220         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16221             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16222       }
16223     }
16224 
16225     // Note:  there used to be some attempt at recovery here.
16226     if (Previous.isAmbiguous())
16227       return nullptr;
16228 
16229     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16230       // FIXME: This makes sure that we ignore the contexts associated
16231       // with C structs, unions, and enums when looking for a matching
16232       // tag declaration or definition. See the similar lookup tweak
16233       // in Sema::LookupName; is there a better way to deal with this?
16234       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16235         SearchDC = SearchDC->getParent();
16236     } else if (getLangOpts().CPlusPlus) {
16237       // Inside ObjCContainer want to keep it as a lexical decl context but go
16238       // past it (most often to TranslationUnit) to find the semantic decl
16239       // context.
16240       while (isa<ObjCContainerDecl>(SearchDC))
16241         SearchDC = SearchDC->getParent();
16242     }
16243   } else if (getLangOpts().CPlusPlus) {
16244     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16245     // TagDecl the same way as we skip it for named TagDecl.
16246     while (isa<ObjCContainerDecl>(SearchDC))
16247       SearchDC = SearchDC->getParent();
16248   }
16249 
16250   if (Previous.isSingleResult() &&
16251       Previous.getFoundDecl()->isTemplateParameter()) {
16252     // Maybe we will complain about the shadowed template parameter.
16253     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16254     // Just pretend that we didn't see the previous declaration.
16255     Previous.clear();
16256   }
16257 
16258   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16259       DC->Equals(getStdNamespace())) {
16260     if (Name->isStr("bad_alloc")) {
16261       // This is a declaration of or a reference to "std::bad_alloc".
16262       isStdBadAlloc = true;
16263 
16264       // If std::bad_alloc has been implicitly declared (but made invisible to
16265       // name lookup), fill in this implicit declaration as the previous
16266       // declaration, so that the declarations get chained appropriately.
16267       if (Previous.empty() && StdBadAlloc)
16268         Previous.addDecl(getStdBadAlloc());
16269     } else if (Name->isStr("align_val_t")) {
16270       isStdAlignValT = true;
16271       if (Previous.empty() && StdAlignValT)
16272         Previous.addDecl(getStdAlignValT());
16273     }
16274   }
16275 
16276   // If we didn't find a previous declaration, and this is a reference
16277   // (or friend reference), move to the correct scope.  In C++, we
16278   // also need to do a redeclaration lookup there, just in case
16279   // there's a shadow friend decl.
16280   if (Name && Previous.empty() &&
16281       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16282     if (Invalid) goto CreateNewDecl;
16283     assert(SS.isEmpty());
16284 
16285     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16286       // C++ [basic.scope.pdecl]p5:
16287       //   -- for an elaborated-type-specifier of the form
16288       //
16289       //          class-key identifier
16290       //
16291       //      if the elaborated-type-specifier is used in the
16292       //      decl-specifier-seq or parameter-declaration-clause of a
16293       //      function defined in namespace scope, the identifier is
16294       //      declared as a class-name in the namespace that contains
16295       //      the declaration; otherwise, except as a friend
16296       //      declaration, the identifier is declared in the smallest
16297       //      non-class, non-function-prototype scope that contains the
16298       //      declaration.
16299       //
16300       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16301       // C structs and unions.
16302       //
16303       // It is an error in C++ to declare (rather than define) an enum
16304       // type, including via an elaborated type specifier.  We'll
16305       // diagnose that later; for now, declare the enum in the same
16306       // scope as we would have picked for any other tag type.
16307       //
16308       // GNU C also supports this behavior as part of its incomplete
16309       // enum types extension, while GNU C++ does not.
16310       //
16311       // Find the context where we'll be declaring the tag.
16312       // FIXME: We would like to maintain the current DeclContext as the
16313       // lexical context,
16314       SearchDC = getTagInjectionContext(SearchDC);
16315 
16316       // Find the scope where we'll be declaring the tag.
16317       S = getTagInjectionScope(S, getLangOpts());
16318     } else {
16319       assert(TUK == TUK_Friend);
16320       // C++ [namespace.memdef]p3:
16321       //   If a friend declaration in a non-local class first declares a
16322       //   class or function, the friend class or function is a member of
16323       //   the innermost enclosing namespace.
16324       SearchDC = SearchDC->getEnclosingNamespaceContext();
16325     }
16326 
16327     // In C++, we need to do a redeclaration lookup to properly
16328     // diagnose some problems.
16329     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16330     // hidden declaration so that we don't get ambiguity errors when using a
16331     // type declared by an elaborated-type-specifier.  In C that is not correct
16332     // and we should instead merge compatible types found by lookup.
16333     if (getLangOpts().CPlusPlus) {
16334       // FIXME: This can perform qualified lookups into function contexts,
16335       // which are meaningless.
16336       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16337       LookupQualifiedName(Previous, SearchDC);
16338     } else {
16339       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16340       LookupName(Previous, S);
16341     }
16342   }
16343 
16344   // If we have a known previous declaration to use, then use it.
16345   if (Previous.empty() && SkipBody && SkipBody->Previous)
16346     Previous.addDecl(SkipBody->Previous);
16347 
16348   if (!Previous.empty()) {
16349     NamedDecl *PrevDecl = Previous.getFoundDecl();
16350     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16351 
16352     // It's okay to have a tag decl in the same scope as a typedef
16353     // which hides a tag decl in the same scope.  Finding this
16354     // with a redeclaration lookup can only actually happen in C++.
16355     //
16356     // This is also okay for elaborated-type-specifiers, which is
16357     // technically forbidden by the current standard but which is
16358     // okay according to the likely resolution of an open issue;
16359     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16360     if (getLangOpts().CPlusPlus) {
16361       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16362         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16363           TagDecl *Tag = TT->getDecl();
16364           if (Tag->getDeclName() == Name &&
16365               Tag->getDeclContext()->getRedeclContext()
16366                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16367             PrevDecl = Tag;
16368             Previous.clear();
16369             Previous.addDecl(Tag);
16370             Previous.resolveKind();
16371           }
16372         }
16373       }
16374     }
16375 
16376     // If this is a redeclaration of a using shadow declaration, it must
16377     // declare a tag in the same context. In MSVC mode, we allow a
16378     // redefinition if either context is within the other.
16379     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16380       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16381       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16382           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16383           !(OldTag && isAcceptableTagRedeclContext(
16384                           *this, OldTag->getDeclContext(), SearchDC))) {
16385         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16386         Diag(Shadow->getTargetDecl()->getLocation(),
16387              diag::note_using_decl_target);
16388         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16389             << 0;
16390         // Recover by ignoring the old declaration.
16391         Previous.clear();
16392         goto CreateNewDecl;
16393       }
16394     }
16395 
16396     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16397       // If this is a use of a previous tag, or if the tag is already declared
16398       // in the same scope (so that the definition/declaration completes or
16399       // rementions the tag), reuse the decl.
16400       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16401           isDeclInScope(DirectPrevDecl, SearchDC, S,
16402                         SS.isNotEmpty() || isMemberSpecialization)) {
16403         // Make sure that this wasn't declared as an enum and now used as a
16404         // struct or something similar.
16405         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16406                                           TUK == TUK_Definition, KWLoc,
16407                                           Name)) {
16408           bool SafeToContinue
16409             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16410                Kind != TTK_Enum);
16411           if (SafeToContinue)
16412             Diag(KWLoc, diag::err_use_with_wrong_tag)
16413               << Name
16414               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16415                                               PrevTagDecl->getKindName());
16416           else
16417             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16418           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16419 
16420           if (SafeToContinue)
16421             Kind = PrevTagDecl->getTagKind();
16422           else {
16423             // Recover by making this an anonymous redefinition.
16424             Name = nullptr;
16425             Previous.clear();
16426             Invalid = true;
16427           }
16428         }
16429 
16430         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16431           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16432           if (TUK == TUK_Reference || TUK == TUK_Friend)
16433             return PrevTagDecl;
16434 
16435           QualType EnumUnderlyingTy;
16436           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16437             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16438           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16439             EnumUnderlyingTy = QualType(T, 0);
16440 
16441           // All conflicts with previous declarations are recovered by
16442           // returning the previous declaration, unless this is a definition,
16443           // in which case we want the caller to bail out.
16444           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16445                                      ScopedEnum, EnumUnderlyingTy,
16446                                      IsFixed, PrevEnum))
16447             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16448         }
16449 
16450         // C++11 [class.mem]p1:
16451         //   A member shall not be declared twice in the member-specification,
16452         //   except that a nested class or member class template can be declared
16453         //   and then later defined.
16454         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16455             S->isDeclScope(PrevDecl)) {
16456           Diag(NameLoc, diag::ext_member_redeclared);
16457           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16458         }
16459 
16460         if (!Invalid) {
16461           // If this is a use, just return the declaration we found, unless
16462           // we have attributes.
16463           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16464             if (!Attrs.empty()) {
16465               // FIXME: Diagnose these attributes. For now, we create a new
16466               // declaration to hold them.
16467             } else if (TUK == TUK_Reference &&
16468                        (PrevTagDecl->getFriendObjectKind() ==
16469                             Decl::FOK_Undeclared ||
16470                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16471                        SS.isEmpty()) {
16472               // This declaration is a reference to an existing entity, but
16473               // has different visibility from that entity: it either makes
16474               // a friend visible or it makes a type visible in a new module.
16475               // In either case, create a new declaration. We only do this if
16476               // the declaration would have meant the same thing if no prior
16477               // declaration were found, that is, if it was found in the same
16478               // scope where we would have injected a declaration.
16479               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16480                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16481                 return PrevTagDecl;
16482               // This is in the injected scope, create a new declaration in
16483               // that scope.
16484               S = getTagInjectionScope(S, getLangOpts());
16485             } else {
16486               return PrevTagDecl;
16487             }
16488           }
16489 
16490           // Diagnose attempts to redefine a tag.
16491           if (TUK == TUK_Definition) {
16492             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16493               // If we're defining a specialization and the previous definition
16494               // is from an implicit instantiation, don't emit an error
16495               // here; we'll catch this in the general case below.
16496               bool IsExplicitSpecializationAfterInstantiation = false;
16497               if (isMemberSpecialization) {
16498                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16499                   IsExplicitSpecializationAfterInstantiation =
16500                     RD->getTemplateSpecializationKind() !=
16501                     TSK_ExplicitSpecialization;
16502                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16503                   IsExplicitSpecializationAfterInstantiation =
16504                     ED->getTemplateSpecializationKind() !=
16505                     TSK_ExplicitSpecialization;
16506               }
16507 
16508               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16509               // not keep more that one definition around (merge them). However,
16510               // ensure the decl passes the structural compatibility check in
16511               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16512               NamedDecl *Hidden = nullptr;
16513               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16514                 // There is a definition of this tag, but it is not visible. We
16515                 // explicitly make use of C++'s one definition rule here, and
16516                 // assume that this definition is identical to the hidden one
16517                 // we already have. Make the existing definition visible and
16518                 // use it in place of this one.
16519                 if (!getLangOpts().CPlusPlus) {
16520                   // Postpone making the old definition visible until after we
16521                   // complete parsing the new one and do the structural
16522                   // comparison.
16523                   SkipBody->CheckSameAsPrevious = true;
16524                   SkipBody->New = createTagFromNewDecl();
16525                   SkipBody->Previous = Def;
16526                   return Def;
16527                 } else {
16528                   SkipBody->ShouldSkip = true;
16529                   SkipBody->Previous = Def;
16530                   makeMergedDefinitionVisible(Hidden);
16531                   // Carry on and handle it like a normal definition. We'll
16532                   // skip starting the definitiion later.
16533                 }
16534               } else if (!IsExplicitSpecializationAfterInstantiation) {
16535                 // A redeclaration in function prototype scope in C isn't
16536                 // visible elsewhere, so merely issue a warning.
16537                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16538                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16539                 else
16540                   Diag(NameLoc, diag::err_redefinition) << Name;
16541                 notePreviousDefinition(Def,
16542                                        NameLoc.isValid() ? NameLoc : KWLoc);
16543                 // If this is a redefinition, recover by making this
16544                 // struct be anonymous, which will make any later
16545                 // references get the previous definition.
16546                 Name = nullptr;
16547                 Previous.clear();
16548                 Invalid = true;
16549               }
16550             } else {
16551               // If the type is currently being defined, complain
16552               // about a nested redefinition.
16553               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16554               if (TD->isBeingDefined()) {
16555                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16556                 Diag(PrevTagDecl->getLocation(),
16557                      diag::note_previous_definition);
16558                 Name = nullptr;
16559                 Previous.clear();
16560                 Invalid = true;
16561               }
16562             }
16563 
16564             // Okay, this is definition of a previously declared or referenced
16565             // tag. We're going to create a new Decl for it.
16566           }
16567 
16568           // Okay, we're going to make a redeclaration.  If this is some kind
16569           // of reference, make sure we build the redeclaration in the same DC
16570           // as the original, and ignore the current access specifier.
16571           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16572             SearchDC = PrevTagDecl->getDeclContext();
16573             AS = AS_none;
16574           }
16575         }
16576         // If we get here we have (another) forward declaration or we
16577         // have a definition.  Just create a new decl.
16578 
16579       } else {
16580         // If we get here, this is a definition of a new tag type in a nested
16581         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16582         // new decl/type.  We set PrevDecl to NULL so that the entities
16583         // have distinct types.
16584         Previous.clear();
16585       }
16586       // If we get here, we're going to create a new Decl. If PrevDecl
16587       // is non-NULL, it's a definition of the tag declared by
16588       // PrevDecl. If it's NULL, we have a new definition.
16589 
16590     // Otherwise, PrevDecl is not a tag, but was found with tag
16591     // lookup.  This is only actually possible in C++, where a few
16592     // things like templates still live in the tag namespace.
16593     } else {
16594       // Use a better diagnostic if an elaborated-type-specifier
16595       // found the wrong kind of type on the first
16596       // (non-redeclaration) lookup.
16597       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16598           !Previous.isForRedeclaration()) {
16599         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16600         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16601                                                        << Kind;
16602         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16603         Invalid = true;
16604 
16605       // Otherwise, only diagnose if the declaration is in scope.
16606       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16607                                 SS.isNotEmpty() || isMemberSpecialization)) {
16608         // do nothing
16609 
16610       // Diagnose implicit declarations introduced by elaborated types.
16611       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16612         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16613         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16614         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16615         Invalid = true;
16616 
16617       // Otherwise it's a declaration.  Call out a particularly common
16618       // case here.
16619       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16620         unsigned Kind = 0;
16621         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16622         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16623           << Name << Kind << TND->getUnderlyingType();
16624         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16625         Invalid = true;
16626 
16627       // Otherwise, diagnose.
16628       } else {
16629         // The tag name clashes with something else in the target scope,
16630         // issue an error and recover by making this tag be anonymous.
16631         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16632         notePreviousDefinition(PrevDecl, NameLoc);
16633         Name = nullptr;
16634         Invalid = true;
16635       }
16636 
16637       // The existing declaration isn't relevant to us; we're in a
16638       // new scope, so clear out the previous declaration.
16639       Previous.clear();
16640     }
16641   }
16642 
16643 CreateNewDecl:
16644 
16645   TagDecl *PrevDecl = nullptr;
16646   if (Previous.isSingleResult())
16647     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16648 
16649   // If there is an identifier, use the location of the identifier as the
16650   // location of the decl, otherwise use the location of the struct/union
16651   // keyword.
16652   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16653 
16654   // Otherwise, create a new declaration. If there is a previous
16655   // declaration of the same entity, the two will be linked via
16656   // PrevDecl.
16657   TagDecl *New;
16658 
16659   if (Kind == TTK_Enum) {
16660     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16661     // enum X { A, B, C } D;    D should chain to X.
16662     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16663                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16664                            ScopedEnumUsesClassTag, IsFixed);
16665 
16666     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16667       StdAlignValT = cast<EnumDecl>(New);
16668 
16669     // If this is an undefined enum, warn.
16670     if (TUK != TUK_Definition && !Invalid) {
16671       TagDecl *Def;
16672       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16673         // C++0x: 7.2p2: opaque-enum-declaration.
16674         // Conflicts are diagnosed above. Do nothing.
16675       }
16676       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16677         Diag(Loc, diag::ext_forward_ref_enum_def)
16678           << New;
16679         Diag(Def->getLocation(), diag::note_previous_definition);
16680       } else {
16681         unsigned DiagID = diag::ext_forward_ref_enum;
16682         if (getLangOpts().MSVCCompat)
16683           DiagID = diag::ext_ms_forward_ref_enum;
16684         else if (getLangOpts().CPlusPlus)
16685           DiagID = diag::err_forward_ref_enum;
16686         Diag(Loc, DiagID);
16687       }
16688     }
16689 
16690     if (EnumUnderlying) {
16691       EnumDecl *ED = cast<EnumDecl>(New);
16692       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16693         ED->setIntegerTypeSourceInfo(TI);
16694       else
16695         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16696       ED->setPromotionType(ED->getIntegerType());
16697       assert(ED->isComplete() && "enum with type should be complete");
16698     }
16699   } else {
16700     // struct/union/class
16701 
16702     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16703     // struct X { int A; } D;    D should chain to X.
16704     if (getLangOpts().CPlusPlus) {
16705       // FIXME: Look for a way to use RecordDecl for simple structs.
16706       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16707                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16708 
16709       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16710         StdBadAlloc = cast<CXXRecordDecl>(New);
16711     } else
16712       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16713                                cast_or_null<RecordDecl>(PrevDecl));
16714   }
16715 
16716   // C++11 [dcl.type]p3:
16717   //   A type-specifier-seq shall not define a class or enumeration [...].
16718   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16719       TUK == TUK_Definition) {
16720     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16721       << Context.getTagDeclType(New);
16722     Invalid = true;
16723   }
16724 
16725   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16726       DC->getDeclKind() == Decl::Enum) {
16727     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16728       << Context.getTagDeclType(New);
16729     Invalid = true;
16730   }
16731 
16732   // Maybe add qualifier info.
16733   if (SS.isNotEmpty()) {
16734     if (SS.isSet()) {
16735       // If this is either a declaration or a definition, check the
16736       // nested-name-specifier against the current context.
16737       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16738           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16739                                        isMemberSpecialization))
16740         Invalid = true;
16741 
16742       New->setQualifierInfo(SS.getWithLocInContext(Context));
16743       if (TemplateParameterLists.size() > 0) {
16744         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16745       }
16746     }
16747     else
16748       Invalid = true;
16749   }
16750 
16751   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16752     // Add alignment attributes if necessary; these attributes are checked when
16753     // the ASTContext lays out the structure.
16754     //
16755     // It is important for implementing the correct semantics that this
16756     // happen here (in ActOnTag). The #pragma pack stack is
16757     // maintained as a result of parser callbacks which can occur at
16758     // many points during the parsing of a struct declaration (because
16759     // the #pragma tokens are effectively skipped over during the
16760     // parsing of the struct).
16761     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16762       AddAlignmentAttributesForRecord(RD);
16763       AddMsStructLayoutForRecord(RD);
16764     }
16765   }
16766 
16767   if (ModulePrivateLoc.isValid()) {
16768     if (isMemberSpecialization)
16769       Diag(New->getLocation(), diag::err_module_private_specialization)
16770         << 2
16771         << FixItHint::CreateRemoval(ModulePrivateLoc);
16772     // __module_private__ does not apply to local classes. However, we only
16773     // diagnose this as an error when the declaration specifiers are
16774     // freestanding. Here, we just ignore the __module_private__.
16775     else if (!SearchDC->isFunctionOrMethod())
16776       New->setModulePrivate();
16777   }
16778 
16779   // If this is a specialization of a member class (of a class template),
16780   // check the specialization.
16781   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16782     Invalid = true;
16783 
16784   // If we're declaring or defining a tag in function prototype scope in C,
16785   // note that this type can only be used within the function and add it to
16786   // the list of decls to inject into the function definition scope.
16787   if ((Name || Kind == TTK_Enum) &&
16788       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16789     if (getLangOpts().CPlusPlus) {
16790       // C++ [dcl.fct]p6:
16791       //   Types shall not be defined in return or parameter types.
16792       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16793         Diag(Loc, diag::err_type_defined_in_param_type)
16794             << Name;
16795         Invalid = true;
16796       }
16797     } else if (!PrevDecl) {
16798       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16799     }
16800   }
16801 
16802   if (Invalid)
16803     New->setInvalidDecl();
16804 
16805   // Set the lexical context. If the tag has a C++ scope specifier, the
16806   // lexical context will be different from the semantic context.
16807   New->setLexicalDeclContext(CurContext);
16808 
16809   // Mark this as a friend decl if applicable.
16810   // In Microsoft mode, a friend declaration also acts as a forward
16811   // declaration so we always pass true to setObjectOfFriendDecl to make
16812   // the tag name visible.
16813   if (TUK == TUK_Friend)
16814     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16815 
16816   // Set the access specifier.
16817   if (!Invalid && SearchDC->isRecord())
16818     SetMemberAccessSpecifier(New, PrevDecl, AS);
16819 
16820   if (PrevDecl)
16821     CheckRedeclarationInModule(New, PrevDecl);
16822 
16823   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16824     New->startDefinition();
16825 
16826   ProcessDeclAttributeList(S, New, Attrs);
16827   AddPragmaAttributes(S, New);
16828 
16829   // If this has an identifier, add it to the scope stack.
16830   if (TUK == TUK_Friend) {
16831     // We might be replacing an existing declaration in the lookup tables;
16832     // if so, borrow its access specifier.
16833     if (PrevDecl)
16834       New->setAccess(PrevDecl->getAccess());
16835 
16836     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16837     DC->makeDeclVisibleInContext(New);
16838     if (Name) // can be null along some error paths
16839       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16840         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16841   } else if (Name) {
16842     S = getNonFieldDeclScope(S);
16843     PushOnScopeChains(New, S, true);
16844   } else {
16845     CurContext->addDecl(New);
16846   }
16847 
16848   // If this is the C FILE type, notify the AST context.
16849   if (IdentifierInfo *II = New->getIdentifier())
16850     if (!New->isInvalidDecl() &&
16851         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16852         II->isStr("FILE"))
16853       Context.setFILEDecl(New);
16854 
16855   if (PrevDecl)
16856     mergeDeclAttributes(New, PrevDecl);
16857 
16858   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16859     inferGslOwnerPointerAttribute(CXXRD);
16860 
16861   // If there's a #pragma GCC visibility in scope, set the visibility of this
16862   // record.
16863   AddPushedVisibilityAttribute(New);
16864 
16865   if (isMemberSpecialization && !New->isInvalidDecl())
16866     CompleteMemberSpecialization(New, Previous);
16867 
16868   OwnedDecl = true;
16869   // In C++, don't return an invalid declaration. We can't recover well from
16870   // the cases where we make the type anonymous.
16871   if (Invalid && getLangOpts().CPlusPlus) {
16872     if (New->isBeingDefined())
16873       if (auto RD = dyn_cast<RecordDecl>(New))
16874         RD->completeDefinition();
16875     return nullptr;
16876   } else if (SkipBody && SkipBody->ShouldSkip) {
16877     return SkipBody->Previous;
16878   } else {
16879     return New;
16880   }
16881 }
16882 
16883 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16884   AdjustDeclIfTemplate(TagD);
16885   TagDecl *Tag = cast<TagDecl>(TagD);
16886 
16887   // Enter the tag context.
16888   PushDeclContext(S, Tag);
16889 
16890   ActOnDocumentableDecl(TagD);
16891 
16892   // If there's a #pragma GCC visibility in scope, set the visibility of this
16893   // record.
16894   AddPushedVisibilityAttribute(Tag);
16895 }
16896 
16897 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16898   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16899     return false;
16900 
16901   // Make the previous decl visible.
16902   makeMergedDefinitionVisible(SkipBody.Previous);
16903   return true;
16904 }
16905 
16906 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16907   assert(isa<ObjCContainerDecl>(IDecl) &&
16908          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16909   DeclContext *OCD = cast<DeclContext>(IDecl);
16910   assert(OCD->getLexicalParent() == CurContext &&
16911       "The next DeclContext should be lexically contained in the current one.");
16912   CurContext = OCD;
16913   return IDecl;
16914 }
16915 
16916 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16917                                            SourceLocation FinalLoc,
16918                                            bool IsFinalSpelledSealed,
16919                                            bool IsAbstract,
16920                                            SourceLocation LBraceLoc) {
16921   AdjustDeclIfTemplate(TagD);
16922   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16923 
16924   FieldCollector->StartClass();
16925 
16926   if (!Record->getIdentifier())
16927     return;
16928 
16929   if (IsAbstract)
16930     Record->markAbstract();
16931 
16932   if (FinalLoc.isValid()) {
16933     Record->addAttr(FinalAttr::Create(
16934         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16935         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16936   }
16937   // C++ [class]p2:
16938   //   [...] The class-name is also inserted into the scope of the
16939   //   class itself; this is known as the injected-class-name. For
16940   //   purposes of access checking, the injected-class-name is treated
16941   //   as if it were a public member name.
16942   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16943       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16944       Record->getLocation(), Record->getIdentifier(),
16945       /*PrevDecl=*/nullptr,
16946       /*DelayTypeCreation=*/true);
16947   Context.getTypeDeclType(InjectedClassName, Record);
16948   InjectedClassName->setImplicit();
16949   InjectedClassName->setAccess(AS_public);
16950   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16951       InjectedClassName->setDescribedClassTemplate(Template);
16952   PushOnScopeChains(InjectedClassName, S);
16953   assert(InjectedClassName->isInjectedClassName() &&
16954          "Broken injected-class-name");
16955 }
16956 
16957 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16958                                     SourceRange BraceRange) {
16959   AdjustDeclIfTemplate(TagD);
16960   TagDecl *Tag = cast<TagDecl>(TagD);
16961   Tag->setBraceRange(BraceRange);
16962 
16963   // Make sure we "complete" the definition even it is invalid.
16964   if (Tag->isBeingDefined()) {
16965     assert(Tag->isInvalidDecl() && "We should already have completed it");
16966     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16967       RD->completeDefinition();
16968   }
16969 
16970   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16971     FieldCollector->FinishClass();
16972     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16973       auto *Def = RD->getDefinition();
16974       assert(Def && "The record is expected to have a completed definition");
16975       unsigned NumInitMethods = 0;
16976       for (auto *Method : Def->methods()) {
16977         if (!Method->getIdentifier())
16978             continue;
16979         if (Method->getName() == "__init")
16980           NumInitMethods++;
16981       }
16982       if (NumInitMethods > 1 || !Def->hasInitMethod())
16983         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16984     }
16985   }
16986 
16987   // Exit this scope of this tag's definition.
16988   PopDeclContext();
16989 
16990   if (getCurLexicalContext()->isObjCContainer() &&
16991       Tag->getDeclContext()->isFileContext())
16992     Tag->setTopLevelDeclInObjCContainer();
16993 
16994   // Notify the consumer that we've defined a tag.
16995   if (!Tag->isInvalidDecl())
16996     Consumer.HandleTagDeclDefinition(Tag);
16997 
16998   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16999   // from XLs and instead matches the XL #pragma pack(1) behavior.
17000   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17001       AlignPackStack.hasValue()) {
17002     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17003     // Only diagnose #pragma align(packed).
17004     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17005       return;
17006     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17007     if (!RD)
17008       return;
17009     // Only warn if there is at least 1 bitfield member.
17010     if (llvm::any_of(RD->fields(),
17011                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17012       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17013   }
17014 }
17015 
17016 void Sema::ActOnObjCContainerFinishDefinition() {
17017   // Exit this scope of this interface definition.
17018   PopDeclContext();
17019 }
17020 
17021 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
17022   assert(DC == CurContext && "Mismatch of container contexts");
17023   OriginalLexicalContext = DC;
17024   ActOnObjCContainerFinishDefinition();
17025 }
17026 
17027 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
17028   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
17029   OriginalLexicalContext = nullptr;
17030 }
17031 
17032 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17033   AdjustDeclIfTemplate(TagD);
17034   TagDecl *Tag = cast<TagDecl>(TagD);
17035   Tag->setInvalidDecl();
17036 
17037   // Make sure we "complete" the definition even it is invalid.
17038   if (Tag->isBeingDefined()) {
17039     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17040       RD->completeDefinition();
17041   }
17042 
17043   // We're undoing ActOnTagStartDefinition here, not
17044   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17045   // the FieldCollector.
17046 
17047   PopDeclContext();
17048 }
17049 
17050 // Note that FieldName may be null for anonymous bitfields.
17051 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17052                                 IdentifierInfo *FieldName,
17053                                 QualType FieldTy, bool IsMsStruct,
17054                                 Expr *BitWidth, bool *ZeroWidth) {
17055   assert(BitWidth);
17056   if (BitWidth->containsErrors())
17057     return ExprError();
17058 
17059   // Default to true; that shouldn't confuse checks for emptiness
17060   if (ZeroWidth)
17061     *ZeroWidth = true;
17062 
17063   // C99 6.7.2.1p4 - verify the field type.
17064   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17065   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17066     // Handle incomplete and sizeless types with a specific error.
17067     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17068                                  diag::err_field_incomplete_or_sizeless))
17069       return ExprError();
17070     if (FieldName)
17071       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17072         << FieldName << FieldTy << BitWidth->getSourceRange();
17073     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17074       << FieldTy << BitWidth->getSourceRange();
17075   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17076                                              UPPC_BitFieldWidth))
17077     return ExprError();
17078 
17079   // If the bit-width is type- or value-dependent, don't try to check
17080   // it now.
17081   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17082     return BitWidth;
17083 
17084   llvm::APSInt Value;
17085   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17086   if (ICE.isInvalid())
17087     return ICE;
17088   BitWidth = ICE.get();
17089 
17090   if (Value != 0 && ZeroWidth)
17091     *ZeroWidth = false;
17092 
17093   // Zero-width bitfield is ok for anonymous field.
17094   if (Value == 0 && FieldName)
17095     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17096 
17097   if (Value.isSigned() && Value.isNegative()) {
17098     if (FieldName)
17099       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17100                << FieldName << toString(Value, 10);
17101     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17102       << toString(Value, 10);
17103   }
17104 
17105   // The size of the bit-field must not exceed our maximum permitted object
17106   // size.
17107   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17108     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17109            << !FieldName << FieldName << toString(Value, 10);
17110   }
17111 
17112   if (!FieldTy->isDependentType()) {
17113     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17114     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17115     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17116 
17117     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17118     // ABI.
17119     bool CStdConstraintViolation =
17120         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17121     bool MSBitfieldViolation =
17122         Value.ugt(TypeStorageSize) &&
17123         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17124     if (CStdConstraintViolation || MSBitfieldViolation) {
17125       unsigned DiagWidth =
17126           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17127       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17128              << (bool)FieldName << FieldName << toString(Value, 10)
17129              << !CStdConstraintViolation << DiagWidth;
17130     }
17131 
17132     // Warn on types where the user might conceivably expect to get all
17133     // specified bits as value bits: that's all integral types other than
17134     // 'bool'.
17135     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17136       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17137           << FieldName << toString(Value, 10)
17138           << (unsigned)TypeWidth;
17139     }
17140   }
17141 
17142   return BitWidth;
17143 }
17144 
17145 /// ActOnField - Each field of a C struct/union is passed into this in order
17146 /// to create a FieldDecl object for it.
17147 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17148                        Declarator &D, Expr *BitfieldWidth) {
17149   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17150                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17151                                /*InitStyle=*/ICIS_NoInit, AS_public);
17152   return Res;
17153 }
17154 
17155 /// HandleField - Analyze a field of a C struct or a C++ data member.
17156 ///
17157 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17158                              SourceLocation DeclStart,
17159                              Declarator &D, Expr *BitWidth,
17160                              InClassInitStyle InitStyle,
17161                              AccessSpecifier AS) {
17162   if (D.isDecompositionDeclarator()) {
17163     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17164     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17165       << Decomp.getSourceRange();
17166     return nullptr;
17167   }
17168 
17169   IdentifierInfo *II = D.getIdentifier();
17170   SourceLocation Loc = DeclStart;
17171   if (II) Loc = D.getIdentifierLoc();
17172 
17173   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17174   QualType T = TInfo->getType();
17175   if (getLangOpts().CPlusPlus) {
17176     CheckExtraCXXDefaultArguments(D);
17177 
17178     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17179                                         UPPC_DataMemberType)) {
17180       D.setInvalidType();
17181       T = Context.IntTy;
17182       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17183     }
17184   }
17185 
17186   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17187 
17188   if (D.getDeclSpec().isInlineSpecified())
17189     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17190         << getLangOpts().CPlusPlus17;
17191   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17192     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17193          diag::err_invalid_thread)
17194       << DeclSpec::getSpecifierName(TSCS);
17195 
17196   // Check to see if this name was declared as a member previously
17197   NamedDecl *PrevDecl = nullptr;
17198   LookupResult Previous(*this, II, Loc, LookupMemberName,
17199                         ForVisibleRedeclaration);
17200   LookupName(Previous, S);
17201   switch (Previous.getResultKind()) {
17202     case LookupResult::Found:
17203     case LookupResult::FoundUnresolvedValue:
17204       PrevDecl = Previous.getAsSingle<NamedDecl>();
17205       break;
17206 
17207     case LookupResult::FoundOverloaded:
17208       PrevDecl = Previous.getRepresentativeDecl();
17209       break;
17210 
17211     case LookupResult::NotFound:
17212     case LookupResult::NotFoundInCurrentInstantiation:
17213     case LookupResult::Ambiguous:
17214       break;
17215   }
17216   Previous.suppressDiagnostics();
17217 
17218   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17219     // Maybe we will complain about the shadowed template parameter.
17220     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17221     // Just pretend that we didn't see the previous declaration.
17222     PrevDecl = nullptr;
17223   }
17224 
17225   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17226     PrevDecl = nullptr;
17227 
17228   bool Mutable
17229     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17230   SourceLocation TSSL = D.getBeginLoc();
17231   FieldDecl *NewFD
17232     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17233                      TSSL, AS, PrevDecl, &D);
17234 
17235   if (NewFD->isInvalidDecl())
17236     Record->setInvalidDecl();
17237 
17238   if (D.getDeclSpec().isModulePrivateSpecified())
17239     NewFD->setModulePrivate();
17240 
17241   if (NewFD->isInvalidDecl() && PrevDecl) {
17242     // Don't introduce NewFD into scope; there's already something
17243     // with the same name in the same scope.
17244   } else if (II) {
17245     PushOnScopeChains(NewFD, S);
17246   } else
17247     Record->addDecl(NewFD);
17248 
17249   return NewFD;
17250 }
17251 
17252 /// Build a new FieldDecl and check its well-formedness.
17253 ///
17254 /// This routine builds a new FieldDecl given the fields name, type,
17255 /// record, etc. \p PrevDecl should refer to any previous declaration
17256 /// with the same name and in the same scope as the field to be
17257 /// created.
17258 ///
17259 /// \returns a new FieldDecl.
17260 ///
17261 /// \todo The Declarator argument is a hack. It will be removed once
17262 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17263                                 TypeSourceInfo *TInfo,
17264                                 RecordDecl *Record, SourceLocation Loc,
17265                                 bool Mutable, Expr *BitWidth,
17266                                 InClassInitStyle InitStyle,
17267                                 SourceLocation TSSL,
17268                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17269                                 Declarator *D) {
17270   IdentifierInfo *II = Name.getAsIdentifierInfo();
17271   bool InvalidDecl = false;
17272   if (D) InvalidDecl = D->isInvalidType();
17273 
17274   // If we receive a broken type, recover by assuming 'int' and
17275   // marking this declaration as invalid.
17276   if (T.isNull() || T->containsErrors()) {
17277     InvalidDecl = true;
17278     T = Context.IntTy;
17279   }
17280 
17281   QualType EltTy = Context.getBaseElementType(T);
17282   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17283     if (RequireCompleteSizedType(Loc, EltTy,
17284                                  diag::err_field_incomplete_or_sizeless)) {
17285       // Fields of incomplete type force their record to be invalid.
17286       Record->setInvalidDecl();
17287       InvalidDecl = true;
17288     } else {
17289       NamedDecl *Def;
17290       EltTy->isIncompleteType(&Def);
17291       if (Def && Def->isInvalidDecl()) {
17292         Record->setInvalidDecl();
17293         InvalidDecl = true;
17294       }
17295     }
17296   }
17297 
17298   // TR 18037 does not allow fields to be declared with address space
17299   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17300       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17301     Diag(Loc, diag::err_field_with_address_space);
17302     Record->setInvalidDecl();
17303     InvalidDecl = true;
17304   }
17305 
17306   if (LangOpts.OpenCL) {
17307     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17308     // used as structure or union field: image, sampler, event or block types.
17309     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17310         T->isBlockPointerType()) {
17311       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17312       Record->setInvalidDecl();
17313       InvalidDecl = true;
17314     }
17315     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17316     // is enabled.
17317     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17318                         "__cl_clang_bitfields", LangOpts)) {
17319       Diag(Loc, diag::err_opencl_bitfields);
17320       InvalidDecl = true;
17321     }
17322   }
17323 
17324   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17325   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17326       T.hasQualifiers()) {
17327     InvalidDecl = true;
17328     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17329   }
17330 
17331   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17332   // than a variably modified type.
17333   if (!InvalidDecl && T->isVariablyModifiedType()) {
17334     if (!tryToFixVariablyModifiedVarType(
17335             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17336       InvalidDecl = true;
17337   }
17338 
17339   // Fields can not have abstract class types
17340   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17341                                              diag::err_abstract_type_in_decl,
17342                                              AbstractFieldType))
17343     InvalidDecl = true;
17344 
17345   bool ZeroWidth = false;
17346   if (InvalidDecl)
17347     BitWidth = nullptr;
17348   // If this is declared as a bit-field, check the bit-field.
17349   if (BitWidth) {
17350     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17351                               &ZeroWidth).get();
17352     if (!BitWidth) {
17353       InvalidDecl = true;
17354       BitWidth = nullptr;
17355       ZeroWidth = false;
17356     }
17357   }
17358 
17359   // Check that 'mutable' is consistent with the type of the declaration.
17360   if (!InvalidDecl && Mutable) {
17361     unsigned DiagID = 0;
17362     if (T->isReferenceType())
17363       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17364                                         : diag::err_mutable_reference;
17365     else if (T.isConstQualified())
17366       DiagID = diag::err_mutable_const;
17367 
17368     if (DiagID) {
17369       SourceLocation ErrLoc = Loc;
17370       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17371         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17372       Diag(ErrLoc, DiagID);
17373       if (DiagID != diag::ext_mutable_reference) {
17374         Mutable = false;
17375         InvalidDecl = true;
17376       }
17377     }
17378   }
17379 
17380   // C++11 [class.union]p8 (DR1460):
17381   //   At most one variant member of a union may have a
17382   //   brace-or-equal-initializer.
17383   if (InitStyle != ICIS_NoInit)
17384     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17385 
17386   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17387                                        BitWidth, Mutable, InitStyle);
17388   if (InvalidDecl)
17389     NewFD->setInvalidDecl();
17390 
17391   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17392     Diag(Loc, diag::err_duplicate_member) << II;
17393     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17394     NewFD->setInvalidDecl();
17395   }
17396 
17397   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17398     if (Record->isUnion()) {
17399       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17400         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17401         if (RDecl->getDefinition()) {
17402           // C++ [class.union]p1: An object of a class with a non-trivial
17403           // constructor, a non-trivial copy constructor, a non-trivial
17404           // destructor, or a non-trivial copy assignment operator
17405           // cannot be a member of a union, nor can an array of such
17406           // objects.
17407           if (CheckNontrivialField(NewFD))
17408             NewFD->setInvalidDecl();
17409         }
17410       }
17411 
17412       // C++ [class.union]p1: If a union contains a member of reference type,
17413       // the program is ill-formed, except when compiling with MSVC extensions
17414       // enabled.
17415       if (EltTy->isReferenceType()) {
17416         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17417                                     diag::ext_union_member_of_reference_type :
17418                                     diag::err_union_member_of_reference_type)
17419           << NewFD->getDeclName() << EltTy;
17420         if (!getLangOpts().MicrosoftExt)
17421           NewFD->setInvalidDecl();
17422       }
17423     }
17424   }
17425 
17426   // FIXME: We need to pass in the attributes given an AST
17427   // representation, not a parser representation.
17428   if (D) {
17429     // FIXME: The current scope is almost... but not entirely... correct here.
17430     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17431 
17432     if (NewFD->hasAttrs())
17433       CheckAlignasUnderalignment(NewFD);
17434   }
17435 
17436   // In auto-retain/release, infer strong retension for fields of
17437   // retainable type.
17438   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17439     NewFD->setInvalidDecl();
17440 
17441   if (T.isObjCGCWeak())
17442     Diag(Loc, diag::warn_attribute_weak_on_field);
17443 
17444   // PPC MMA non-pointer types are not allowed as field types.
17445   if (Context.getTargetInfo().getTriple().isPPC64() &&
17446       CheckPPCMMAType(T, NewFD->getLocation()))
17447     NewFD->setInvalidDecl();
17448 
17449   NewFD->setAccess(AS);
17450   return NewFD;
17451 }
17452 
17453 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17454   assert(FD);
17455   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17456 
17457   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17458     return false;
17459 
17460   QualType EltTy = Context.getBaseElementType(FD->getType());
17461   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17462     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17463     if (RDecl->getDefinition()) {
17464       // We check for copy constructors before constructors
17465       // because otherwise we'll never get complaints about
17466       // copy constructors.
17467 
17468       CXXSpecialMember member = CXXInvalid;
17469       // We're required to check for any non-trivial constructors. Since the
17470       // implicit default constructor is suppressed if there are any
17471       // user-declared constructors, we just need to check that there is a
17472       // trivial default constructor and a trivial copy constructor. (We don't
17473       // worry about move constructors here, since this is a C++98 check.)
17474       if (RDecl->hasNonTrivialCopyConstructor())
17475         member = CXXCopyConstructor;
17476       else if (!RDecl->hasTrivialDefaultConstructor())
17477         member = CXXDefaultConstructor;
17478       else if (RDecl->hasNonTrivialCopyAssignment())
17479         member = CXXCopyAssignment;
17480       else if (RDecl->hasNonTrivialDestructor())
17481         member = CXXDestructor;
17482 
17483       if (member != CXXInvalid) {
17484         if (!getLangOpts().CPlusPlus11 &&
17485             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17486           // Objective-C++ ARC: it is an error to have a non-trivial field of
17487           // a union. However, system headers in Objective-C programs
17488           // occasionally have Objective-C lifetime objects within unions,
17489           // and rather than cause the program to fail, we make those
17490           // members unavailable.
17491           SourceLocation Loc = FD->getLocation();
17492           if (getSourceManager().isInSystemHeader(Loc)) {
17493             if (!FD->hasAttr<UnavailableAttr>())
17494               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17495                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17496             return false;
17497           }
17498         }
17499 
17500         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17501                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17502                diag::err_illegal_union_or_anon_struct_member)
17503           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17504         DiagnoseNontrivial(RDecl, member);
17505         return !getLangOpts().CPlusPlus11;
17506       }
17507     }
17508   }
17509 
17510   return false;
17511 }
17512 
17513 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17514 ///  AST enum value.
17515 static ObjCIvarDecl::AccessControl
17516 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17517   switch (ivarVisibility) {
17518   default: llvm_unreachable("Unknown visitibility kind");
17519   case tok::objc_private: return ObjCIvarDecl::Private;
17520   case tok::objc_public: return ObjCIvarDecl::Public;
17521   case tok::objc_protected: return ObjCIvarDecl::Protected;
17522   case tok::objc_package: return ObjCIvarDecl::Package;
17523   }
17524 }
17525 
17526 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17527 /// in order to create an IvarDecl object for it.
17528 Decl *Sema::ActOnIvar(Scope *S,
17529                                 SourceLocation DeclStart,
17530                                 Declarator &D, Expr *BitfieldWidth,
17531                                 tok::ObjCKeywordKind Visibility) {
17532 
17533   IdentifierInfo *II = D.getIdentifier();
17534   Expr *BitWidth = (Expr*)BitfieldWidth;
17535   SourceLocation Loc = DeclStart;
17536   if (II) Loc = D.getIdentifierLoc();
17537 
17538   // FIXME: Unnamed fields can be handled in various different ways, for
17539   // example, unnamed unions inject all members into the struct namespace!
17540 
17541   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17542   QualType T = TInfo->getType();
17543 
17544   if (BitWidth) {
17545     // 6.7.2.1p3, 6.7.2.1p4
17546     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17547     if (!BitWidth)
17548       D.setInvalidType();
17549   } else {
17550     // Not a bitfield.
17551 
17552     // validate II.
17553 
17554   }
17555   if (T->isReferenceType()) {
17556     Diag(Loc, diag::err_ivar_reference_type);
17557     D.setInvalidType();
17558   }
17559   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17560   // than a variably modified type.
17561   else if (T->isVariablyModifiedType()) {
17562     if (!tryToFixVariablyModifiedVarType(
17563             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17564       D.setInvalidType();
17565   }
17566 
17567   // Get the visibility (access control) for this ivar.
17568   ObjCIvarDecl::AccessControl ac =
17569     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17570                                         : ObjCIvarDecl::None;
17571   // Must set ivar's DeclContext to its enclosing interface.
17572   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17573   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17574     return nullptr;
17575   ObjCContainerDecl *EnclosingContext;
17576   if (ObjCImplementationDecl *IMPDecl =
17577       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17578     if (LangOpts.ObjCRuntime.isFragile()) {
17579     // Case of ivar declared in an implementation. Context is that of its class.
17580       EnclosingContext = IMPDecl->getClassInterface();
17581       assert(EnclosingContext && "Implementation has no class interface!");
17582     }
17583     else
17584       EnclosingContext = EnclosingDecl;
17585   } else {
17586     if (ObjCCategoryDecl *CDecl =
17587         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17588       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17589         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17590         return nullptr;
17591       }
17592     }
17593     EnclosingContext = EnclosingDecl;
17594   }
17595 
17596   // Construct the decl.
17597   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17598                                              DeclStart, Loc, II, T,
17599                                              TInfo, ac, (Expr *)BitfieldWidth);
17600 
17601   if (II) {
17602     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17603                                            ForVisibleRedeclaration);
17604     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17605         && !isa<TagDecl>(PrevDecl)) {
17606       Diag(Loc, diag::err_duplicate_member) << II;
17607       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17608       NewID->setInvalidDecl();
17609     }
17610   }
17611 
17612   // Process attributes attached to the ivar.
17613   ProcessDeclAttributes(S, NewID, D);
17614 
17615   if (D.isInvalidType())
17616     NewID->setInvalidDecl();
17617 
17618   // In ARC, infer 'retaining' for ivars of retainable type.
17619   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17620     NewID->setInvalidDecl();
17621 
17622   if (D.getDeclSpec().isModulePrivateSpecified())
17623     NewID->setModulePrivate();
17624 
17625   if (II) {
17626     // FIXME: When interfaces are DeclContexts, we'll need to add
17627     // these to the interface.
17628     S->AddDecl(NewID);
17629     IdResolver.AddDecl(NewID);
17630   }
17631 
17632   if (LangOpts.ObjCRuntime.isNonFragile() &&
17633       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17634     Diag(Loc, diag::warn_ivars_in_interface);
17635 
17636   return NewID;
17637 }
17638 
17639 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17640 /// class and class extensions. For every class \@interface and class
17641 /// extension \@interface, if the last ivar is a bitfield of any type,
17642 /// then add an implicit `char :0` ivar to the end of that interface.
17643 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17644                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17645   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17646     return;
17647 
17648   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17649   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17650 
17651   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17652     return;
17653   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17654   if (!ID) {
17655     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17656       if (!CD->IsClassExtension())
17657         return;
17658     }
17659     // No need to add this to end of @implementation.
17660     else
17661       return;
17662   }
17663   // All conditions are met. Add a new bitfield to the tail end of ivars.
17664   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17665   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17666 
17667   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17668                               DeclLoc, DeclLoc, nullptr,
17669                               Context.CharTy,
17670                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17671                                                                DeclLoc),
17672                               ObjCIvarDecl::Private, BW,
17673                               true);
17674   AllIvarDecls.push_back(Ivar);
17675 }
17676 
17677 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17678                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17679                        SourceLocation RBrac,
17680                        const ParsedAttributesView &Attrs) {
17681   assert(EnclosingDecl && "missing record or interface decl");
17682 
17683   // If this is an Objective-C @implementation or category and we have
17684   // new fields here we should reset the layout of the interface since
17685   // it will now change.
17686   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17687     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17688     switch (DC->getKind()) {
17689     default: break;
17690     case Decl::ObjCCategory:
17691       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17692       break;
17693     case Decl::ObjCImplementation:
17694       Context.
17695         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17696       break;
17697     }
17698   }
17699 
17700   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17701   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17702 
17703   // Start counting up the number of named members; make sure to include
17704   // members of anonymous structs and unions in the total.
17705   unsigned NumNamedMembers = 0;
17706   if (Record) {
17707     for (const auto *I : Record->decls()) {
17708       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17709         if (IFD->getDeclName())
17710           ++NumNamedMembers;
17711     }
17712   }
17713 
17714   // Verify that all the fields are okay.
17715   SmallVector<FieldDecl*, 32> RecFields;
17716 
17717   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17718        i != end; ++i) {
17719     FieldDecl *FD = cast<FieldDecl>(*i);
17720 
17721     // Get the type for the field.
17722     const Type *FDTy = FD->getType().getTypePtr();
17723 
17724     if (!FD->isAnonymousStructOrUnion()) {
17725       // Remember all fields written by the user.
17726       RecFields.push_back(FD);
17727     }
17728 
17729     // If the field is already invalid for some reason, don't emit more
17730     // diagnostics about it.
17731     if (FD->isInvalidDecl()) {
17732       EnclosingDecl->setInvalidDecl();
17733       continue;
17734     }
17735 
17736     // C99 6.7.2.1p2:
17737     //   A structure or union shall not contain a member with
17738     //   incomplete or function type (hence, a structure shall not
17739     //   contain an instance of itself, but may contain a pointer to
17740     //   an instance of itself), except that the last member of a
17741     //   structure with more than one named member may have incomplete
17742     //   array type; such a structure (and any union containing,
17743     //   possibly recursively, a member that is such a structure)
17744     //   shall not be a member of a structure or an element of an
17745     //   array.
17746     bool IsLastField = (i + 1 == Fields.end());
17747     if (FDTy->isFunctionType()) {
17748       // Field declared as a function.
17749       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17750         << FD->getDeclName();
17751       FD->setInvalidDecl();
17752       EnclosingDecl->setInvalidDecl();
17753       continue;
17754     } else if (FDTy->isIncompleteArrayType() &&
17755                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17756       if (Record) {
17757         // Flexible array member.
17758         // Microsoft and g++ is more permissive regarding flexible array.
17759         // It will accept flexible array in union and also
17760         // as the sole element of a struct/class.
17761         unsigned DiagID = 0;
17762         if (!Record->isUnion() && !IsLastField) {
17763           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17764             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17765           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17766           FD->setInvalidDecl();
17767           EnclosingDecl->setInvalidDecl();
17768           continue;
17769         } else if (Record->isUnion())
17770           DiagID = getLangOpts().MicrosoftExt
17771                        ? diag::ext_flexible_array_union_ms
17772                        : getLangOpts().CPlusPlus
17773                              ? diag::ext_flexible_array_union_gnu
17774                              : diag::err_flexible_array_union;
17775         else if (NumNamedMembers < 1)
17776           DiagID = getLangOpts().MicrosoftExt
17777                        ? diag::ext_flexible_array_empty_aggregate_ms
17778                        : getLangOpts().CPlusPlus
17779                              ? diag::ext_flexible_array_empty_aggregate_gnu
17780                              : diag::err_flexible_array_empty_aggregate;
17781 
17782         if (DiagID)
17783           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17784                                           << Record->getTagKind();
17785         // While the layout of types that contain virtual bases is not specified
17786         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17787         // virtual bases after the derived members.  This would make a flexible
17788         // array member declared at the end of an object not adjacent to the end
17789         // of the type.
17790         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17791           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17792               << FD->getDeclName() << Record->getTagKind();
17793         if (!getLangOpts().C99)
17794           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17795             << FD->getDeclName() << Record->getTagKind();
17796 
17797         // If the element type has a non-trivial destructor, we would not
17798         // implicitly destroy the elements, so disallow it for now.
17799         //
17800         // FIXME: GCC allows this. We should probably either implicitly delete
17801         // the destructor of the containing class, or just allow this.
17802         QualType BaseElem = Context.getBaseElementType(FD->getType());
17803         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17804           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17805             << FD->getDeclName() << FD->getType();
17806           FD->setInvalidDecl();
17807           EnclosingDecl->setInvalidDecl();
17808           continue;
17809         }
17810         // Okay, we have a legal flexible array member at the end of the struct.
17811         Record->setHasFlexibleArrayMember(true);
17812       } else {
17813         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17814         // unless they are followed by another ivar. That check is done
17815         // elsewhere, after synthesized ivars are known.
17816       }
17817     } else if (!FDTy->isDependentType() &&
17818                RequireCompleteSizedType(
17819                    FD->getLocation(), FD->getType(),
17820                    diag::err_field_incomplete_or_sizeless)) {
17821       // Incomplete type
17822       FD->setInvalidDecl();
17823       EnclosingDecl->setInvalidDecl();
17824       continue;
17825     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17826       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17827         // A type which contains a flexible array member is considered to be a
17828         // flexible array member.
17829         Record->setHasFlexibleArrayMember(true);
17830         if (!Record->isUnion()) {
17831           // If this is a struct/class and this is not the last element, reject
17832           // it.  Note that GCC supports variable sized arrays in the middle of
17833           // structures.
17834           if (!IsLastField)
17835             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17836               << FD->getDeclName() << FD->getType();
17837           else {
17838             // We support flexible arrays at the end of structs in
17839             // other structs as an extension.
17840             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17841               << FD->getDeclName();
17842           }
17843         }
17844       }
17845       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17846           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17847                                  diag::err_abstract_type_in_decl,
17848                                  AbstractIvarType)) {
17849         // Ivars can not have abstract class types
17850         FD->setInvalidDecl();
17851       }
17852       if (Record && FDTTy->getDecl()->hasObjectMember())
17853         Record->setHasObjectMember(true);
17854       if (Record && FDTTy->getDecl()->hasVolatileMember())
17855         Record->setHasVolatileMember(true);
17856     } else if (FDTy->isObjCObjectType()) {
17857       /// A field cannot be an Objective-c object
17858       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17859         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17860       QualType T = Context.getObjCObjectPointerType(FD->getType());
17861       FD->setType(T);
17862     } else if (Record && Record->isUnion() &&
17863                FD->getType().hasNonTrivialObjCLifetime() &&
17864                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17865                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17866                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17867                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17868       // For backward compatibility, fields of C unions declared in system
17869       // headers that have non-trivial ObjC ownership qualifications are marked
17870       // as unavailable unless the qualifier is explicit and __strong. This can
17871       // break ABI compatibility between programs compiled with ARC and MRR, but
17872       // is a better option than rejecting programs using those unions under
17873       // ARC.
17874       FD->addAttr(UnavailableAttr::CreateImplicit(
17875           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17876           FD->getLocation()));
17877     } else if (getLangOpts().ObjC &&
17878                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17879                !Record->hasObjectMember()) {
17880       if (FD->getType()->isObjCObjectPointerType() ||
17881           FD->getType().isObjCGCStrong())
17882         Record->setHasObjectMember(true);
17883       else if (Context.getAsArrayType(FD->getType())) {
17884         QualType BaseType = Context.getBaseElementType(FD->getType());
17885         if (BaseType->isRecordType() &&
17886             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17887           Record->setHasObjectMember(true);
17888         else if (BaseType->isObjCObjectPointerType() ||
17889                  BaseType.isObjCGCStrong())
17890                Record->setHasObjectMember(true);
17891       }
17892     }
17893 
17894     if (Record && !getLangOpts().CPlusPlus &&
17895         !shouldIgnoreForRecordTriviality(FD)) {
17896       QualType FT = FD->getType();
17897       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17898         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17899         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17900             Record->isUnion())
17901           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17902       }
17903       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17904       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17905         Record->setNonTrivialToPrimitiveCopy(true);
17906         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17907           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17908       }
17909       if (FT.isDestructedType()) {
17910         Record->setNonTrivialToPrimitiveDestroy(true);
17911         Record->setParamDestroyedInCallee(true);
17912         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17913           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17914       }
17915 
17916       if (const auto *RT = FT->getAs<RecordType>()) {
17917         if (RT->getDecl()->getArgPassingRestrictions() ==
17918             RecordDecl::APK_CanNeverPassInRegs)
17919           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17920       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17921         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17922     }
17923 
17924     if (Record && FD->getType().isVolatileQualified())
17925       Record->setHasVolatileMember(true);
17926     // Keep track of the number of named members.
17927     if (FD->getIdentifier())
17928       ++NumNamedMembers;
17929   }
17930 
17931   // Okay, we successfully defined 'Record'.
17932   if (Record) {
17933     bool Completed = false;
17934     if (CXXRecord) {
17935       if (!CXXRecord->isInvalidDecl()) {
17936         // Set access bits correctly on the directly-declared conversions.
17937         for (CXXRecordDecl::conversion_iterator
17938                I = CXXRecord->conversion_begin(),
17939                E = CXXRecord->conversion_end(); I != E; ++I)
17940           I.setAccess((*I)->getAccess());
17941       }
17942 
17943       // Add any implicitly-declared members to this class.
17944       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17945 
17946       if (!CXXRecord->isDependentType()) {
17947         if (!CXXRecord->isInvalidDecl()) {
17948           // If we have virtual base classes, we may end up finding multiple
17949           // final overriders for a given virtual function. Check for this
17950           // problem now.
17951           if (CXXRecord->getNumVBases()) {
17952             CXXFinalOverriderMap FinalOverriders;
17953             CXXRecord->getFinalOverriders(FinalOverriders);
17954 
17955             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17956                                              MEnd = FinalOverriders.end();
17957                  M != MEnd; ++M) {
17958               for (OverridingMethods::iterator SO = M->second.begin(),
17959                                             SOEnd = M->second.end();
17960                    SO != SOEnd; ++SO) {
17961                 assert(SO->second.size() > 0 &&
17962                        "Virtual function without overriding functions?");
17963                 if (SO->second.size() == 1)
17964                   continue;
17965 
17966                 // C++ [class.virtual]p2:
17967                 //   In a derived class, if a virtual member function of a base
17968                 //   class subobject has more than one final overrider the
17969                 //   program is ill-formed.
17970                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17971                   << (const NamedDecl *)M->first << Record;
17972                 Diag(M->first->getLocation(),
17973                      diag::note_overridden_virtual_function);
17974                 for (OverridingMethods::overriding_iterator
17975                           OM = SO->second.begin(),
17976                        OMEnd = SO->second.end();
17977                      OM != OMEnd; ++OM)
17978                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17979                     << (const NamedDecl *)M->first << OM->Method->getParent();
17980 
17981                 Record->setInvalidDecl();
17982               }
17983             }
17984             CXXRecord->completeDefinition(&FinalOverriders);
17985             Completed = true;
17986           }
17987         }
17988       }
17989     }
17990 
17991     if (!Completed)
17992       Record->completeDefinition();
17993 
17994     // Handle attributes before checking the layout.
17995     ProcessDeclAttributeList(S, Record, Attrs);
17996 
17997     // Maybe randomize the field order.
17998     if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() &&
17999         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18000         !Record->isRandomized()) {
18001       SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields());
18002       SmallVector<Decl *, 32> NewFieldOrdering;
18003       if (randstruct::randomizeStructureLayout(
18004               Context, Record->getNameAsString(), OrigFieldOrdering,
18005               NewFieldOrdering))
18006         Record->reorderFields(NewFieldOrdering);
18007     }
18008 
18009     // We may have deferred checking for a deleted destructor. Check now.
18010     if (CXXRecord) {
18011       auto *Dtor = CXXRecord->getDestructor();
18012       if (Dtor && Dtor->isImplicit() &&
18013           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18014         CXXRecord->setImplicitDestructorIsDeleted();
18015         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18016       }
18017     }
18018 
18019     if (Record->hasAttrs()) {
18020       CheckAlignasUnderalignment(Record);
18021 
18022       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18023         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18024                                            IA->getRange(), IA->getBestCase(),
18025                                            IA->getInheritanceModel());
18026     }
18027 
18028     // Check if the structure/union declaration is a type that can have zero
18029     // size in C. For C this is a language extension, for C++ it may cause
18030     // compatibility problems.
18031     bool CheckForZeroSize;
18032     if (!getLangOpts().CPlusPlus) {
18033       CheckForZeroSize = true;
18034     } else {
18035       // For C++ filter out types that cannot be referenced in C code.
18036       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18037       CheckForZeroSize =
18038           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18039           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18040           CXXRecord->isCLike();
18041     }
18042     if (CheckForZeroSize) {
18043       bool ZeroSize = true;
18044       bool IsEmpty = true;
18045       unsigned NonBitFields = 0;
18046       for (RecordDecl::field_iterator I = Record->field_begin(),
18047                                       E = Record->field_end();
18048            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18049         IsEmpty = false;
18050         if (I->isUnnamedBitfield()) {
18051           if (!I->isZeroLengthBitField(Context))
18052             ZeroSize = false;
18053         } else {
18054           ++NonBitFields;
18055           QualType FieldType = I->getType();
18056           if (FieldType->isIncompleteType() ||
18057               !Context.getTypeSizeInChars(FieldType).isZero())
18058             ZeroSize = false;
18059         }
18060       }
18061 
18062       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18063       // allowed in C++, but warn if its declaration is inside
18064       // extern "C" block.
18065       if (ZeroSize) {
18066         Diag(RecLoc, getLangOpts().CPlusPlus ?
18067                          diag::warn_zero_size_struct_union_in_extern_c :
18068                          diag::warn_zero_size_struct_union_compat)
18069           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18070       }
18071 
18072       // Structs without named members are extension in C (C99 6.7.2.1p7),
18073       // but are accepted by GCC.
18074       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18075         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18076                                diag::ext_no_named_members_in_struct_union)
18077           << Record->isUnion();
18078       }
18079     }
18080   } else {
18081     ObjCIvarDecl **ClsFields =
18082       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18083     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18084       ID->setEndOfDefinitionLoc(RBrac);
18085       // Add ivar's to class's DeclContext.
18086       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18087         ClsFields[i]->setLexicalDeclContext(ID);
18088         ID->addDecl(ClsFields[i]);
18089       }
18090       // Must enforce the rule that ivars in the base classes may not be
18091       // duplicates.
18092       if (ID->getSuperClass())
18093         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18094     } else if (ObjCImplementationDecl *IMPDecl =
18095                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18096       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18097       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18098         // Ivar declared in @implementation never belongs to the implementation.
18099         // Only it is in implementation's lexical context.
18100         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18101       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18102       IMPDecl->setIvarLBraceLoc(LBrac);
18103       IMPDecl->setIvarRBraceLoc(RBrac);
18104     } else if (ObjCCategoryDecl *CDecl =
18105                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18106       // case of ivars in class extension; all other cases have been
18107       // reported as errors elsewhere.
18108       // FIXME. Class extension does not have a LocEnd field.
18109       // CDecl->setLocEnd(RBrac);
18110       // Add ivar's to class extension's DeclContext.
18111       // Diagnose redeclaration of private ivars.
18112       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18113       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18114         if (IDecl) {
18115           if (const ObjCIvarDecl *ClsIvar =
18116               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18117             Diag(ClsFields[i]->getLocation(),
18118                  diag::err_duplicate_ivar_declaration);
18119             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18120             continue;
18121           }
18122           for (const auto *Ext : IDecl->known_extensions()) {
18123             if (const ObjCIvarDecl *ClsExtIvar
18124                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18125               Diag(ClsFields[i]->getLocation(),
18126                    diag::err_duplicate_ivar_declaration);
18127               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18128               continue;
18129             }
18130           }
18131         }
18132         ClsFields[i]->setLexicalDeclContext(CDecl);
18133         CDecl->addDecl(ClsFields[i]);
18134       }
18135       CDecl->setIvarLBraceLoc(LBrac);
18136       CDecl->setIvarRBraceLoc(RBrac);
18137     }
18138   }
18139 }
18140 
18141 /// Determine whether the given integral value is representable within
18142 /// the given type T.
18143 static bool isRepresentableIntegerValue(ASTContext &Context,
18144                                         llvm::APSInt &Value,
18145                                         QualType T) {
18146   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18147          "Integral type required!");
18148   unsigned BitWidth = Context.getIntWidth(T);
18149 
18150   if (Value.isUnsigned() || Value.isNonNegative()) {
18151     if (T->isSignedIntegerOrEnumerationType())
18152       --BitWidth;
18153     return Value.getActiveBits() <= BitWidth;
18154   }
18155   return Value.getMinSignedBits() <= BitWidth;
18156 }
18157 
18158 // Given an integral type, return the next larger integral type
18159 // (or a NULL type of no such type exists).
18160 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18161   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18162   // enum checking below.
18163   assert((T->isIntegralType(Context) ||
18164          T->isEnumeralType()) && "Integral type required!");
18165   const unsigned NumTypes = 4;
18166   QualType SignedIntegralTypes[NumTypes] = {
18167     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18168   };
18169   QualType UnsignedIntegralTypes[NumTypes] = {
18170     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18171     Context.UnsignedLongLongTy
18172   };
18173 
18174   unsigned BitWidth = Context.getTypeSize(T);
18175   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18176                                                         : UnsignedIntegralTypes;
18177   for (unsigned I = 0; I != NumTypes; ++I)
18178     if (Context.getTypeSize(Types[I]) > BitWidth)
18179       return Types[I];
18180 
18181   return QualType();
18182 }
18183 
18184 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18185                                           EnumConstantDecl *LastEnumConst,
18186                                           SourceLocation IdLoc,
18187                                           IdentifierInfo *Id,
18188                                           Expr *Val) {
18189   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18190   llvm::APSInt EnumVal(IntWidth);
18191   QualType EltTy;
18192 
18193   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18194     Val = nullptr;
18195 
18196   if (Val)
18197     Val = DefaultLvalueConversion(Val).get();
18198 
18199   if (Val) {
18200     if (Enum->isDependentType() || Val->isTypeDependent() ||
18201         Val->containsErrors())
18202       EltTy = Context.DependentTy;
18203     else {
18204       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18205       // underlying type, but do allow it in all other contexts.
18206       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18207         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18208         // constant-expression in the enumerator-definition shall be a converted
18209         // constant expression of the underlying type.
18210         EltTy = Enum->getIntegerType();
18211         ExprResult Converted =
18212           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18213                                            CCEK_Enumerator);
18214         if (Converted.isInvalid())
18215           Val = nullptr;
18216         else
18217           Val = Converted.get();
18218       } else if (!Val->isValueDependent() &&
18219                  !(Val =
18220                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18221                            .get())) {
18222         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18223       } else {
18224         if (Enum->isComplete()) {
18225           EltTy = Enum->getIntegerType();
18226 
18227           // In Obj-C and Microsoft mode, require the enumeration value to be
18228           // representable in the underlying type of the enumeration. In C++11,
18229           // we perform a non-narrowing conversion as part of converted constant
18230           // expression checking.
18231           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18232             if (Context.getTargetInfo()
18233                     .getTriple()
18234                     .isWindowsMSVCEnvironment()) {
18235               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18236             } else {
18237               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18238             }
18239           }
18240 
18241           // Cast to the underlying type.
18242           Val = ImpCastExprToType(Val, EltTy,
18243                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18244                                                          : CK_IntegralCast)
18245                     .get();
18246         } else if (getLangOpts().CPlusPlus) {
18247           // C++11 [dcl.enum]p5:
18248           //   If the underlying type is not fixed, the type of each enumerator
18249           //   is the type of its initializing value:
18250           //     - If an initializer is specified for an enumerator, the
18251           //       initializing value has the same type as the expression.
18252           EltTy = Val->getType();
18253         } else {
18254           // C99 6.7.2.2p2:
18255           //   The expression that defines the value of an enumeration constant
18256           //   shall be an integer constant expression that has a value
18257           //   representable as an int.
18258 
18259           // Complain if the value is not representable in an int.
18260           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18261             Diag(IdLoc, diag::ext_enum_value_not_int)
18262               << toString(EnumVal, 10) << Val->getSourceRange()
18263               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18264           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18265             // Force the type of the expression to 'int'.
18266             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18267           }
18268           EltTy = Val->getType();
18269         }
18270       }
18271     }
18272   }
18273 
18274   if (!Val) {
18275     if (Enum->isDependentType())
18276       EltTy = Context.DependentTy;
18277     else if (!LastEnumConst) {
18278       // C++0x [dcl.enum]p5:
18279       //   If the underlying type is not fixed, the type of each enumerator
18280       //   is the type of its initializing value:
18281       //     - If no initializer is specified for the first enumerator, the
18282       //       initializing value has an unspecified integral type.
18283       //
18284       // GCC uses 'int' for its unspecified integral type, as does
18285       // C99 6.7.2.2p3.
18286       if (Enum->isFixed()) {
18287         EltTy = Enum->getIntegerType();
18288       }
18289       else {
18290         EltTy = Context.IntTy;
18291       }
18292     } else {
18293       // Assign the last value + 1.
18294       EnumVal = LastEnumConst->getInitVal();
18295       ++EnumVal;
18296       EltTy = LastEnumConst->getType();
18297 
18298       // Check for overflow on increment.
18299       if (EnumVal < LastEnumConst->getInitVal()) {
18300         // C++0x [dcl.enum]p5:
18301         //   If the underlying type is not fixed, the type of each enumerator
18302         //   is the type of its initializing value:
18303         //
18304         //     - Otherwise the type of the initializing value is the same as
18305         //       the type of the initializing value of the preceding enumerator
18306         //       unless the incremented value is not representable in that type,
18307         //       in which case the type is an unspecified integral type
18308         //       sufficient to contain the incremented value. If no such type
18309         //       exists, the program is ill-formed.
18310         QualType T = getNextLargerIntegralType(Context, EltTy);
18311         if (T.isNull() || Enum->isFixed()) {
18312           // There is no integral type larger enough to represent this
18313           // value. Complain, then allow the value to wrap around.
18314           EnumVal = LastEnumConst->getInitVal();
18315           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18316           ++EnumVal;
18317           if (Enum->isFixed())
18318             // When the underlying type is fixed, this is ill-formed.
18319             Diag(IdLoc, diag::err_enumerator_wrapped)
18320               << toString(EnumVal, 10)
18321               << EltTy;
18322           else
18323             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18324               << toString(EnumVal, 10);
18325         } else {
18326           EltTy = T;
18327         }
18328 
18329         // Retrieve the last enumerator's value, extent that type to the
18330         // type that is supposed to be large enough to represent the incremented
18331         // value, then increment.
18332         EnumVal = LastEnumConst->getInitVal();
18333         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18334         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18335         ++EnumVal;
18336 
18337         // If we're not in C++, diagnose the overflow of enumerator values,
18338         // which in C99 means that the enumerator value is not representable in
18339         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18340         // permits enumerator values that are representable in some larger
18341         // integral type.
18342         if (!getLangOpts().CPlusPlus && !T.isNull())
18343           Diag(IdLoc, diag::warn_enum_value_overflow);
18344       } else if (!getLangOpts().CPlusPlus &&
18345                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18346         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18347         Diag(IdLoc, diag::ext_enum_value_not_int)
18348           << toString(EnumVal, 10) << 1;
18349       }
18350     }
18351   }
18352 
18353   if (!EltTy->isDependentType()) {
18354     // Make the enumerator value match the signedness and size of the
18355     // enumerator's type.
18356     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18357     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18358   }
18359 
18360   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18361                                   Val, EnumVal);
18362 }
18363 
18364 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18365                                                 SourceLocation IILoc) {
18366   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18367       !getLangOpts().CPlusPlus)
18368     return SkipBodyInfo();
18369 
18370   // We have an anonymous enum definition. Look up the first enumerator to
18371   // determine if we should merge the definition with an existing one and
18372   // skip the body.
18373   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18374                                          forRedeclarationInCurContext());
18375   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18376   if (!PrevECD)
18377     return SkipBodyInfo();
18378 
18379   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18380   NamedDecl *Hidden;
18381   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18382     SkipBodyInfo Skip;
18383     Skip.Previous = Hidden;
18384     return Skip;
18385   }
18386 
18387   return SkipBodyInfo();
18388 }
18389 
18390 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18391                               SourceLocation IdLoc, IdentifierInfo *Id,
18392                               const ParsedAttributesView &Attrs,
18393                               SourceLocation EqualLoc, Expr *Val) {
18394   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18395   EnumConstantDecl *LastEnumConst =
18396     cast_or_null<EnumConstantDecl>(lastEnumConst);
18397 
18398   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18399   // we find one that is.
18400   S = getNonFieldDeclScope(S);
18401 
18402   // Verify that there isn't already something declared with this name in this
18403   // scope.
18404   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18405   LookupName(R, S);
18406   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18407 
18408   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18409     // Maybe we will complain about the shadowed template parameter.
18410     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18411     // Just pretend that we didn't see the previous declaration.
18412     PrevDecl = nullptr;
18413   }
18414 
18415   // C++ [class.mem]p15:
18416   // If T is the name of a class, then each of the following shall have a name
18417   // different from T:
18418   // - every enumerator of every member of class T that is an unscoped
18419   // enumerated type
18420   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18421     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18422                             DeclarationNameInfo(Id, IdLoc));
18423 
18424   EnumConstantDecl *New =
18425     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18426   if (!New)
18427     return nullptr;
18428 
18429   if (PrevDecl) {
18430     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18431       // Check for other kinds of shadowing not already handled.
18432       CheckShadow(New, PrevDecl, R);
18433     }
18434 
18435     // When in C++, we may get a TagDecl with the same name; in this case the
18436     // enum constant will 'hide' the tag.
18437     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18438            "Received TagDecl when not in C++!");
18439     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18440       if (isa<EnumConstantDecl>(PrevDecl))
18441         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18442       else
18443         Diag(IdLoc, diag::err_redefinition) << Id;
18444       notePreviousDefinition(PrevDecl, IdLoc);
18445       return nullptr;
18446     }
18447   }
18448 
18449   // Process attributes.
18450   ProcessDeclAttributeList(S, New, Attrs);
18451   AddPragmaAttributes(S, New);
18452 
18453   // Register this decl in the current scope stack.
18454   New->setAccess(TheEnumDecl->getAccess());
18455   PushOnScopeChains(New, S);
18456 
18457   ActOnDocumentableDecl(New);
18458 
18459   return New;
18460 }
18461 
18462 // Returns true when the enum initial expression does not trigger the
18463 // duplicate enum warning.  A few common cases are exempted as follows:
18464 // Element2 = Element1
18465 // Element2 = Element1 + 1
18466 // Element2 = Element1 - 1
18467 // Where Element2 and Element1 are from the same enum.
18468 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18469   Expr *InitExpr = ECD->getInitExpr();
18470   if (!InitExpr)
18471     return true;
18472   InitExpr = InitExpr->IgnoreImpCasts();
18473 
18474   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18475     if (!BO->isAdditiveOp())
18476       return true;
18477     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18478     if (!IL)
18479       return true;
18480     if (IL->getValue() != 1)
18481       return true;
18482 
18483     InitExpr = BO->getLHS();
18484   }
18485 
18486   // This checks if the elements are from the same enum.
18487   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18488   if (!DRE)
18489     return true;
18490 
18491   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18492   if (!EnumConstant)
18493     return true;
18494 
18495   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18496       Enum)
18497     return true;
18498 
18499   return false;
18500 }
18501 
18502 // Emits a warning when an element is implicitly set a value that
18503 // a previous element has already been set to.
18504 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18505                                         EnumDecl *Enum, QualType EnumType) {
18506   // Avoid anonymous enums
18507   if (!Enum->getIdentifier())
18508     return;
18509 
18510   // Only check for small enums.
18511   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18512     return;
18513 
18514   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18515     return;
18516 
18517   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18518   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18519 
18520   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18521 
18522   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18523   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18524 
18525   // Use int64_t as a key to avoid needing special handling for map keys.
18526   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18527     llvm::APSInt Val = D->getInitVal();
18528     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18529   };
18530 
18531   DuplicatesVector DupVector;
18532   ValueToVectorMap EnumMap;
18533 
18534   // Populate the EnumMap with all values represented by enum constants without
18535   // an initializer.
18536   for (auto *Element : Elements) {
18537     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18538 
18539     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18540     // this constant.  Skip this enum since it may be ill-formed.
18541     if (!ECD) {
18542       return;
18543     }
18544 
18545     // Constants with initalizers are handled in the next loop.
18546     if (ECD->getInitExpr())
18547       continue;
18548 
18549     // Duplicate values are handled in the next loop.
18550     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18551   }
18552 
18553   if (EnumMap.size() == 0)
18554     return;
18555 
18556   // Create vectors for any values that has duplicates.
18557   for (auto *Element : Elements) {
18558     // The last loop returned if any constant was null.
18559     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18560     if (!ValidDuplicateEnum(ECD, Enum))
18561       continue;
18562 
18563     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18564     if (Iter == EnumMap.end())
18565       continue;
18566 
18567     DeclOrVector& Entry = Iter->second;
18568     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18569       // Ensure constants are different.
18570       if (D == ECD)
18571         continue;
18572 
18573       // Create new vector and push values onto it.
18574       auto Vec = std::make_unique<ECDVector>();
18575       Vec->push_back(D);
18576       Vec->push_back(ECD);
18577 
18578       // Update entry to point to the duplicates vector.
18579       Entry = Vec.get();
18580 
18581       // Store the vector somewhere we can consult later for quick emission of
18582       // diagnostics.
18583       DupVector.emplace_back(std::move(Vec));
18584       continue;
18585     }
18586 
18587     ECDVector *Vec = Entry.get<ECDVector*>();
18588     // Make sure constants are not added more than once.
18589     if (*Vec->begin() == ECD)
18590       continue;
18591 
18592     Vec->push_back(ECD);
18593   }
18594 
18595   // Emit diagnostics.
18596   for (const auto &Vec : DupVector) {
18597     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18598 
18599     // Emit warning for one enum constant.
18600     auto *FirstECD = Vec->front();
18601     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18602       << FirstECD << toString(FirstECD->getInitVal(), 10)
18603       << FirstECD->getSourceRange();
18604 
18605     // Emit one note for each of the remaining enum constants with
18606     // the same value.
18607     for (auto *ECD : llvm::drop_begin(*Vec))
18608       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18609         << ECD << toString(ECD->getInitVal(), 10)
18610         << ECD->getSourceRange();
18611   }
18612 }
18613 
18614 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18615                              bool AllowMask) const {
18616   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18617   assert(ED->isCompleteDefinition() && "expected enum definition");
18618 
18619   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18620   llvm::APInt &FlagBits = R.first->second;
18621 
18622   if (R.second) {
18623     for (auto *E : ED->enumerators()) {
18624       const auto &EVal = E->getInitVal();
18625       // Only single-bit enumerators introduce new flag values.
18626       if (EVal.isPowerOf2())
18627         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18628     }
18629   }
18630 
18631   // A value is in a flag enum if either its bits are a subset of the enum's
18632   // flag bits (the first condition) or we are allowing masks and the same is
18633   // true of its complement (the second condition). When masks are allowed, we
18634   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18635   //
18636   // While it's true that any value could be used as a mask, the assumption is
18637   // that a mask will have all of the insignificant bits set. Anything else is
18638   // likely a logic error.
18639   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18640   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18641 }
18642 
18643 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18644                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18645                          const ParsedAttributesView &Attrs) {
18646   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18647   QualType EnumType = Context.getTypeDeclType(Enum);
18648 
18649   ProcessDeclAttributeList(S, Enum, Attrs);
18650 
18651   if (Enum->isDependentType()) {
18652     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18653       EnumConstantDecl *ECD =
18654         cast_or_null<EnumConstantDecl>(Elements[i]);
18655       if (!ECD) continue;
18656 
18657       ECD->setType(EnumType);
18658     }
18659 
18660     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18661     return;
18662   }
18663 
18664   // TODO: If the result value doesn't fit in an int, it must be a long or long
18665   // long value.  ISO C does not support this, but GCC does as an extension,
18666   // emit a warning.
18667   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18668   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18669   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18670 
18671   // Verify that all the values are okay, compute the size of the values, and
18672   // reverse the list.
18673   unsigned NumNegativeBits = 0;
18674   unsigned NumPositiveBits = 0;
18675 
18676   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18677     EnumConstantDecl *ECD =
18678       cast_or_null<EnumConstantDecl>(Elements[i]);
18679     if (!ECD) continue;  // Already issued a diagnostic.
18680 
18681     const llvm::APSInt &InitVal = ECD->getInitVal();
18682 
18683     // Keep track of the size of positive and negative values.
18684     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18685       NumPositiveBits = std::max(NumPositiveBits,
18686                                  (unsigned)InitVal.getActiveBits());
18687     else
18688       NumNegativeBits = std::max(NumNegativeBits,
18689                                  (unsigned)InitVal.getMinSignedBits());
18690   }
18691 
18692   // Figure out the type that should be used for this enum.
18693   QualType BestType;
18694   unsigned BestWidth;
18695 
18696   // C++0x N3000 [conv.prom]p3:
18697   //   An rvalue of an unscoped enumeration type whose underlying
18698   //   type is not fixed can be converted to an rvalue of the first
18699   //   of the following types that can represent all the values of
18700   //   the enumeration: int, unsigned int, long int, unsigned long
18701   //   int, long long int, or unsigned long long int.
18702   // C99 6.4.4.3p2:
18703   //   An identifier declared as an enumeration constant has type int.
18704   // The C99 rule is modified by a gcc extension
18705   QualType BestPromotionType;
18706 
18707   bool Packed = Enum->hasAttr<PackedAttr>();
18708   // -fshort-enums is the equivalent to specifying the packed attribute on all
18709   // enum definitions.
18710   if (LangOpts.ShortEnums)
18711     Packed = true;
18712 
18713   // If the enum already has a type because it is fixed or dictated by the
18714   // target, promote that type instead of analyzing the enumerators.
18715   if (Enum->isComplete()) {
18716     BestType = Enum->getIntegerType();
18717     if (BestType->isPromotableIntegerType())
18718       BestPromotionType = Context.getPromotedIntegerType(BestType);
18719     else
18720       BestPromotionType = BestType;
18721 
18722     BestWidth = Context.getIntWidth(BestType);
18723   }
18724   else if (NumNegativeBits) {
18725     // If there is a negative value, figure out the smallest integer type (of
18726     // int/long/longlong) that fits.
18727     // If it's packed, check also if it fits a char or a short.
18728     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18729       BestType = Context.SignedCharTy;
18730       BestWidth = CharWidth;
18731     } else if (Packed && NumNegativeBits <= ShortWidth &&
18732                NumPositiveBits < ShortWidth) {
18733       BestType = Context.ShortTy;
18734       BestWidth = ShortWidth;
18735     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18736       BestType = Context.IntTy;
18737       BestWidth = IntWidth;
18738     } else {
18739       BestWidth = Context.getTargetInfo().getLongWidth();
18740 
18741       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18742         BestType = Context.LongTy;
18743       } else {
18744         BestWidth = Context.getTargetInfo().getLongLongWidth();
18745 
18746         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18747           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18748         BestType = Context.LongLongTy;
18749       }
18750     }
18751     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18752   } else {
18753     // If there is no negative value, figure out the smallest type that fits
18754     // all of the enumerator values.
18755     // If it's packed, check also if it fits a char or a short.
18756     if (Packed && NumPositiveBits <= CharWidth) {
18757       BestType = Context.UnsignedCharTy;
18758       BestPromotionType = Context.IntTy;
18759       BestWidth = CharWidth;
18760     } else if (Packed && NumPositiveBits <= ShortWidth) {
18761       BestType = Context.UnsignedShortTy;
18762       BestPromotionType = Context.IntTy;
18763       BestWidth = ShortWidth;
18764     } else if (NumPositiveBits <= IntWidth) {
18765       BestType = Context.UnsignedIntTy;
18766       BestWidth = IntWidth;
18767       BestPromotionType
18768         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18769                            ? Context.UnsignedIntTy : Context.IntTy;
18770     } else if (NumPositiveBits <=
18771                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18772       BestType = Context.UnsignedLongTy;
18773       BestPromotionType
18774         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18775                            ? Context.UnsignedLongTy : Context.LongTy;
18776     } else {
18777       BestWidth = Context.getTargetInfo().getLongLongWidth();
18778       assert(NumPositiveBits <= BestWidth &&
18779              "How could an initializer get larger than ULL?");
18780       BestType = Context.UnsignedLongLongTy;
18781       BestPromotionType
18782         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18783                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18784     }
18785   }
18786 
18787   // Loop over all of the enumerator constants, changing their types to match
18788   // the type of the enum if needed.
18789   for (auto *D : Elements) {
18790     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18791     if (!ECD) continue;  // Already issued a diagnostic.
18792 
18793     // Standard C says the enumerators have int type, but we allow, as an
18794     // extension, the enumerators to be larger than int size.  If each
18795     // enumerator value fits in an int, type it as an int, otherwise type it the
18796     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18797     // that X has type 'int', not 'unsigned'.
18798 
18799     // Determine whether the value fits into an int.
18800     llvm::APSInt InitVal = ECD->getInitVal();
18801 
18802     // If it fits into an integer type, force it.  Otherwise force it to match
18803     // the enum decl type.
18804     QualType NewTy;
18805     unsigned NewWidth;
18806     bool NewSign;
18807     if (!getLangOpts().CPlusPlus &&
18808         !Enum->isFixed() &&
18809         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18810       NewTy = Context.IntTy;
18811       NewWidth = IntWidth;
18812       NewSign = true;
18813     } else if (ECD->getType() == BestType) {
18814       // Already the right type!
18815       if (getLangOpts().CPlusPlus)
18816         // C++ [dcl.enum]p4: Following the closing brace of an
18817         // enum-specifier, each enumerator has the type of its
18818         // enumeration.
18819         ECD->setType(EnumType);
18820       continue;
18821     } else {
18822       NewTy = BestType;
18823       NewWidth = BestWidth;
18824       NewSign = BestType->isSignedIntegerOrEnumerationType();
18825     }
18826 
18827     // Adjust the APSInt value.
18828     InitVal = InitVal.extOrTrunc(NewWidth);
18829     InitVal.setIsSigned(NewSign);
18830     ECD->setInitVal(InitVal);
18831 
18832     // Adjust the Expr initializer and type.
18833     if (ECD->getInitExpr() &&
18834         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18835       ECD->setInitExpr(ImplicitCastExpr::Create(
18836           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18837           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18838     if (getLangOpts().CPlusPlus)
18839       // C++ [dcl.enum]p4: Following the closing brace of an
18840       // enum-specifier, each enumerator has the type of its
18841       // enumeration.
18842       ECD->setType(EnumType);
18843     else
18844       ECD->setType(NewTy);
18845   }
18846 
18847   Enum->completeDefinition(BestType, BestPromotionType,
18848                            NumPositiveBits, NumNegativeBits);
18849 
18850   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18851 
18852   if (Enum->isClosedFlag()) {
18853     for (Decl *D : Elements) {
18854       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18855       if (!ECD) continue;  // Already issued a diagnostic.
18856 
18857       llvm::APSInt InitVal = ECD->getInitVal();
18858       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18859           !IsValueInFlagEnum(Enum, InitVal, true))
18860         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18861           << ECD << Enum;
18862     }
18863   }
18864 
18865   // Now that the enum type is defined, ensure it's not been underaligned.
18866   if (Enum->hasAttrs())
18867     CheckAlignasUnderalignment(Enum);
18868 }
18869 
18870 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18871                                   SourceLocation StartLoc,
18872                                   SourceLocation EndLoc) {
18873   StringLiteral *AsmString = cast<StringLiteral>(expr);
18874 
18875   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18876                                                    AsmString, StartLoc,
18877                                                    EndLoc);
18878   CurContext->addDecl(New);
18879   return New;
18880 }
18881 
18882 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18883                                       IdentifierInfo* AliasName,
18884                                       SourceLocation PragmaLoc,
18885                                       SourceLocation NameLoc,
18886                                       SourceLocation AliasNameLoc) {
18887   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18888                                          LookupOrdinaryName);
18889   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18890                            AttributeCommonInfo::AS_Pragma);
18891   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18892       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18893 
18894   // If a declaration that:
18895   // 1) declares a function or a variable
18896   // 2) has external linkage
18897   // already exists, add a label attribute to it.
18898   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18899     if (isDeclExternC(PrevDecl))
18900       PrevDecl->addAttr(Attr);
18901     else
18902       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18903           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18904   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18905   } else
18906     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18907 }
18908 
18909 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18910                              SourceLocation PragmaLoc,
18911                              SourceLocation NameLoc) {
18912   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18913 
18914   if (PrevDecl) {
18915     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18916   } else {
18917     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18918   }
18919 }
18920 
18921 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18922                                 IdentifierInfo* AliasName,
18923                                 SourceLocation PragmaLoc,
18924                                 SourceLocation NameLoc,
18925                                 SourceLocation AliasNameLoc) {
18926   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18927                                     LookupOrdinaryName);
18928   WeakInfo W = WeakInfo(Name, NameLoc);
18929 
18930   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18931     if (!PrevDecl->hasAttr<AliasAttr>())
18932       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18933         DeclApplyPragmaWeak(TUScope, ND, W);
18934   } else {
18935     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18936   }
18937 }
18938 
18939 Decl *Sema::getObjCDeclContext() const {
18940   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18941 }
18942 
18943 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18944                                                      bool Final) {
18945   assert(FD && "Expected non-null FunctionDecl");
18946 
18947   // SYCL functions can be template, so we check if they have appropriate
18948   // attribute prior to checking if it is a template.
18949   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18950     return FunctionEmissionStatus::Emitted;
18951 
18952   // Templates are emitted when they're instantiated.
18953   if (FD->isDependentContext())
18954     return FunctionEmissionStatus::TemplateDiscarded;
18955 
18956   // Check whether this function is an externally visible definition.
18957   auto IsEmittedForExternalSymbol = [this, FD]() {
18958     // We have to check the GVA linkage of the function's *definition* -- if we
18959     // only have a declaration, we don't know whether or not the function will
18960     // be emitted, because (say) the definition could include "inline".
18961     FunctionDecl *Def = FD->getDefinition();
18962 
18963     return Def && !isDiscardableGVALinkage(
18964                       getASTContext().GetGVALinkageForFunction(Def));
18965   };
18966 
18967   if (LangOpts.OpenMPIsDevice) {
18968     // In OpenMP device mode we will not emit host only functions, or functions
18969     // we don't need due to their linkage.
18970     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18971         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18972     // DevTy may be changed later by
18973     //  #pragma omp declare target to(*) device_type(*).
18974     // Therefore DevTy having no value does not imply host. The emission status
18975     // will be checked again at the end of compilation unit with Final = true.
18976     if (DevTy.hasValue())
18977       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18978         return FunctionEmissionStatus::OMPDiscarded;
18979     // If we have an explicit value for the device type, or we are in a target
18980     // declare context, we need to emit all extern and used symbols.
18981     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18982       if (IsEmittedForExternalSymbol())
18983         return FunctionEmissionStatus::Emitted;
18984     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18985     // we'll omit it.
18986     if (Final)
18987       return FunctionEmissionStatus::OMPDiscarded;
18988   } else if (LangOpts.OpenMP > 45) {
18989     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18990     // function. In 5.0, no_host was introduced which might cause a function to
18991     // be ommitted.
18992     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18993         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18994     if (DevTy.hasValue())
18995       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18996         return FunctionEmissionStatus::OMPDiscarded;
18997   }
18998 
18999   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19000     return FunctionEmissionStatus::Emitted;
19001 
19002   if (LangOpts.CUDA) {
19003     // When compiling for device, host functions are never emitted.  Similarly,
19004     // when compiling for host, device and global functions are never emitted.
19005     // (Technically, we do emit a host-side stub for global functions, but this
19006     // doesn't count for our purposes here.)
19007     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19008     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19009       return FunctionEmissionStatus::CUDADiscarded;
19010     if (!LangOpts.CUDAIsDevice &&
19011         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19012       return FunctionEmissionStatus::CUDADiscarded;
19013 
19014     if (IsEmittedForExternalSymbol())
19015       return FunctionEmissionStatus::Emitted;
19016   }
19017 
19018   // Otherwise, the function is known-emitted if it's in our set of
19019   // known-emitted functions.
19020   return FunctionEmissionStatus::Unknown;
19021 }
19022 
19023 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19024   // Host-side references to a __global__ function refer to the stub, so the
19025   // function itself is never emitted and therefore should not be marked.
19026   // If we have host fn calls kernel fn calls host+device, the HD function
19027   // does not get instantiated on the host. We model this by omitting at the
19028   // call to the kernel from the callgraph. This ensures that, when compiling
19029   // for host, only HD functions actually called from the host get marked as
19030   // known-emitted.
19031   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19032          IdentifyCUDATarget(Callee) == CFT_Global;
19033 }
19034